From 845b5f68c72e4add4baa5a7c73f77a55af680fa5 Mon Sep 17 00:00:00 2001 From: Raven Szewczyk Date: Thu, 19 Jan 2023 15:33:54 +0000 Subject: [PATCH 1/3] Update buildscript --- .gitattributes | 44 ++++ build.gradle | 675 +++++++++++++++++++++++++++++++++++++----------- settings.gradle | 10 + 3 files changed, 578 insertions(+), 151 deletions(-) create mode 100644 .gitattributes create mode 100644 settings.gradle 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 c09bee2..2dc32c9 100644 --- a/build.gradle +++ b/build.gradle @@ -1,25 +1,40 @@ -//version: 1652851397 +//version: 1673027205 /* -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/master/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' } + maven { + // GTNH ForgeGradle and ASM Fork + name = "GTNH Maven" + url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + } maven { name 'sonatype' url 'https://oss.sonatype.org/content/repositories/snapshots/' @@ -28,31 +43,41 @@ buildscript { name 'Scala CI dependencies' url 'https://repo1.maven.org/maven2/' } - maven { - name 'jitpack' - url 'https://jitpack.io' - } } dependencies { - classpath 'com.github.GTNewHorizons:ForgeGradle:1.2.7' + //Overwrite the current ASM version to fix shading newer than java 8 applicatations. + classpath 'org.ow2.asm:asm-debug-all-custom:5.0.3' + classpath 'net.minecraftforge.gradle:ForgeGradle:1.2.13' } } - plugins { id 'java-library' id 'idea' id 'eclipse' id 'scala' id 'maven-publish' - 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 '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.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' @@ -78,7 +103,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()) } @@ -103,63 +135,79 @@ checkPropertyExists("containsMixinsAndOrCoreModOnly") checkPropertyExists("usesShadowedDependencies") checkPropertyExists("developmentEnvironmentUserName") -boolean noPublishedSources = project.findProperty("noPublishedSources") ? project.noPublishedSources.toBoolean() : false -boolean usesMixinDebug = project.findProperty('usesMixinDebug') ?: project.usesMixins.toBoolean() +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!") + } + 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) } - 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) - } - - 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) } } @@ -189,7 +237,7 @@ try { 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' + + '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' @@ -200,22 +248,21 @@ ext { modVersion = identifiedVersion } -if(identifiedVersion == versionOverride) { +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" ] @@ -233,17 +280,19 @@ minecraft { runDir = 'run' if (replaceGradleTokenInFile) { - replaceIn replaceGradleTokenInFile - if(gradleTokenModId) { + for (f in replaceGradleTokenInFile.split(',')) { + replaceIn f + } + 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 } } @@ -252,7 +301,7 @@ minecraft { args(arguments) jvmArgs(jvmArguments) - if(developmentEnvironmentUserName) { + if (developmentEnvironmentUserName) { args("--username", developmentEnvironmentUserName) } } @@ -263,16 +312,20 @@ minecraft { } } -if(file('addon.gradle').exists()) { +if (file('addon.gradle').exists()) { apply from: 'addon.gradle' } apply from: 'repositories.gradle' configurations { - implementation.extendsFrom(shadowImplementation) // TODO: remove after all uses are refactored - implementation.extendsFrom(shadowCompile) - implementation.extendsFrom(shadeCompile) + // TODO: remove Compile after all uses are refactored to Implementation + for (config in [shadowImplementation, shadowCompile, shadeCompile]) { + compileClasspath.extendsFrom(config) + runtimeClasspath.extendsFrom(config) + testCompileClasspath.extendsFrom(config) + testRuntimeClasspath.extendsFrom(config) + } } repositories { @@ -280,33 +333,33 @@ repositories { name 'Overmind forge repo mirror' url 'https://gregtech.overminddl1.com/' } - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { maven { - name 'sponge' - url 'https://repo.spongepowered.org/repository/maven-public' + name = "GTNH Maven" + url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" } - maven { - url 'https://jitpack.io' + if (usesMixinDebug.toBoolean()) { + maven { + name = "Fabric Maven" + url = "https://maven.fabricmc.net/" + } } } } dependencies { - if(usesMixins.toBoolean()) { + 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' + annotationProcessor('com.gtnewhorizon:gtnhmixins:2.1.3:processor') + if (usesMixinDebug.toBoolean()) { + runtimeClasspath('org.jetbrains:intellij-fernflower:1.2.1.16') + testRuntimeClasspath('org.jetbrains:intellij-fernflower:1.2.1.16') } - compile('com.github.GTNewHorizons:SpongeMixins:1.5.0') + } + if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { + compile('com.gtnewhorizon:gtnhmixins:2.1.3') } } @@ -318,13 +371,18 @@ def mixinSrg = "${tasks.reobf.temporaryDir}" + File.separator + "mixins.srg" task generateAssets { if (usesMixins.toBoolean()) { - def mixinConfigFile = getFile("/src/main/resources/mixins." + modId + ".json"); + 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", @@ -354,7 +412,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) } @@ -369,38 +430,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 ] } @@ -415,9 +476,9 @@ runServer { tasks.withType(JavaExec).configureEach { javaLauncher.set( - javaToolchains.launcherFor { - languageVersion = projectJavaVersion - } + javaToolchains.launcherFor { + languageVersion = projectJavaVersion + } ) } @@ -425,6 +486,7 @@ 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) { @@ -437,43 +499,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() && (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() + "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", + "MixinConfigs" : "mixins." + modId + ".json", + "ForceLoadAsMod": !containsMixinsAndOrCoreModOnly.toBoolean() ] } return manifestAttributes } task sourcesJar(type: Jar) { - from (sourceSets.main.allSource) - from (file("$projectDir/LICENSE")) + from(sourceSets.main.allSource) + from(file("$projectDir/LICENSE")) getArchiveClassifier().set('sources') } @@ -492,7 +555,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) { @@ -520,22 +586,22 @@ task devJar(type: Jar) { attributes(getManifestAttributes()) } - if(usesShadowedDependencies.toBoolean()) { + if (usesShadowedDependencies.toBoolean()) { dependsOn(circularResolverJar) enabled = false } } task apiJar(type: Jar) { - from (sourceSets.main.allSource) { - 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") } @@ -543,11 +609,11 @@ task apiJar(type: Jar) { } artifacts { - if(!noPublishedSources) { + if (!noPublishedSources) { archives sourcesJar } archives devJar - if(apiPackage) { + if (apiPackage) { archives apiJar } } @@ -565,10 +631,10 @@ publishing { publications { maven(MavenPublication) { from components.java - if(usesShadowedDependencies.toBoolean()) { + if (usesShadowedDependencies.toBoolean()) { artifact source: shadowJar, classifier: "" } - if(!noPublishedSources) { + if (!noPublishedSources) { artifact source: sourcesJar, classifier: "sources" } artifact source: usesShadowedDependencies.toBoolean() ? shadowDevJar : devJar, classifier: "dev" @@ -583,8 +649,11 @@ publishing { // remove extra garbage from minecraft and minecraftDeps configuration pom.withXml { - def badArtifacts = [:].withDefault {[] as Set} - for (configuration in [projectConfigs.minecraft, projectConfigs.minecraftDeps]) { + 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 } @@ -613,6 +682,113 @@ 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]) + } + } + if (usesMixins.toBoolean()) { + addModrinthDep("required", "project", "gtnhmixins") + } + 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]) + } + } + if (usesMixins.toBoolean()) { + addCurseForgeRelation("requiredDependency", "gtnhmixins") + } + 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 { @@ -622,7 +798,7 @@ task updateBuildScript { } } -if (isNewBuildScriptVersionAvailable(projectDir.toString())) { +if (!project.getGradle().startParameter.isOffline() && isNewBuildScriptVersionAvailable(projectDir.toString())) { if (autoUpdateBuildScript.toBoolean()) { performBuildScriptUpdate(projectDir.toString()) } else { @@ -631,7 +807,40 @@ if (isNewBuildScriptVersionAvailable(projectDir.toString())) { } 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) { @@ -639,6 +848,10 @@ boolean performBuildScriptUpdate(String projectDir) { def buildscriptFile = getFile("build.gradle") availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } } 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 @@ -658,7 +871,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 "" @@ -669,7 +882,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 { @@ -678,42 +987,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" +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()) { + 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 @@ -727,14 +1051,48 @@ 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) { @@ -743,6 +1101,21 @@ def checkPropertyExists(String propertyName) { } } +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/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 +} From ed155c644c5b13b04b42005e60f5acfe9f902d44 Mon Sep 17 00:00:00 2001 From: Raven Szewczyk Date: Thu, 19 Jan 2023 15:34:07 +0000 Subject: [PATCH 2/3] Apply spotless --- .../codechicken/core/launch/DepLoader.java | 175 ++++++------ .../scala/codechicken/multipart/PartMap.java | 142 +++++----- .../multipart/minecraft/ButtonPart.java | 190 ++++++------- .../multipart/minecraft/Content.java | 72 +++-- .../multipart/minecraft/EventHandler.java | 116 ++++---- .../multipart/minecraft/IPartMeta.java | 9 +- .../multipart/minecraft/LeverPart.java | 133 ++++----- .../multipart/minecraft/McBlockPart.java | 76 +++-- .../multipart/minecraft/McMetaPart.java | 64 ++--- .../multipart/minecraft/McMultipartCPH.java | 15 +- .../multipart/minecraft/McMultipartSPH.java | 7 +- .../multipart/minecraft/McSidedMetaPart.java | 61 ++--- .../minecraft/MinecraftMultipartMod.java | 16 +- .../multipart/minecraft/PartMetaAccess.java | 9 +- .../minecraft/RedstoneTorchPart.java | 259 ++++++++---------- .../multipart/minecraft/TorchPart.java | 113 +++----- .../multipart/nei/NEI_MicroblockConfig.java | 19 +- 17 files changed, 631 insertions(+), 845 deletions(-) diff --git a/src/main/scala/codechicken/core/launch/DepLoader.java b/src/main/scala/codechicken/core/launch/DepLoader.java index 0032ed5..91c56fc 100644 --- a/src/main/scala/codechicken/core/launch/DepLoader.java +++ b/src/main/scala/codechicken/core/launch/DepLoader.java @@ -8,13 +8,6 @@ import cpw.mods.fml.relauncher.FMLInjectionData; import cpw.mods.fml.relauncher.FMLLaunchHandler; import cpw.mods.fml.relauncher.IFMLCallHook; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; -import net.minecraft.launchwrapper.LaunchClassLoader; -import sun.misc.URLClassPath; -import sun.net.util.URLUtil; - -import javax.swing.*; -import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkListener; import java.awt.*; import java.awt.Dialog.ModalityType; import java.awt.event.WindowAdapter; @@ -35,6 +28,12 @@ import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; +import javax.swing.*; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; +import net.minecraft.launchwrapper.LaunchClassLoader; +import sun.misc.URLClassPath; +import sun.net.util.URLUtil; /** * For autodownloading stuff. @@ -72,10 +71,12 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { private Box makeProgressPanel() { Box box = Box.createVerticalBox(); box.add(Box.createRigidArea(new Dimension(0, 10))); - JLabel welcomeLabel = new JLabel("" + owner + " is setting up your minecraft environment"); + JLabel welcomeLabel = new JLabel("" + owner + + " is setting up your minecraft environment"); box.add(welcomeLabel); welcomeLabel.setAlignmentY(LEFT_ALIGNMENT); - welcomeLabel = new JLabel("Please wait, " + owner + " has some tasks to do before you can play"); + welcomeLabel = + new JLabel("Please wait, " + owner + " has some tasks to do before you can play"); welcomeLabel.setAlignmentY(LEFT_ALIGNMENT); box.add(welcomeLabel); box.add(Box.createRigidArea(new Dimension(0, 10))); @@ -91,12 +92,11 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { @Override public JDialog makeDialog() { - if (container != null) - return container; + if (container != null) return container; setMessageType(JOptionPane.INFORMATION_MESSAGE); setMessage(makeProgressPanel()); - setOptions(new Object[]{"Stop"}); + setOptions(new Object[] {"Stop"}); addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { @@ -117,39 +117,40 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { container.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { - requestClose("Closing this window will stop minecraft from launching\nAre you sure you wish to do this?"); + requestClose( + "Closing this window will stop minecraft from launching\nAre you sure you wish to do this?"); } }); return container; } protected void requestClose(String message) { - int shouldClose = JOptionPane.showConfirmDialog(container, message, "Are you sure you want to stop?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); - if (shouldClose == JOptionPane.YES_OPTION) - container.dispose(); + int shouldClose = JOptionPane.showConfirmDialog( + container, + message, + "Are you sure you want to stop?", + JOptionPane.YES_NO_OPTION, + JOptionPane.WARNING_MESSAGE); + if (shouldClose == JOptionPane.YES_OPTION) container.dispose(); stopIt = true; - if (pokeThread != null) - pokeThread.interrupt(); + if (pokeThread != null) pokeThread.interrupt(); } @Override public void updateProgressString(String progressUpdate, Object... data) { - //FMLLog.finest(progressUpdate, data); - if (currentActivity != null) - currentActivity.setText(String.format(progressUpdate, data)); + // FMLLog.finest(progressUpdate, data); + if (currentActivity != null) currentActivity.setText(String.format(progressUpdate, data)); } @Override public void resetProgress(int sizeGuess) { - if (progress != null) - progress.getModel().setRangeProperties(0, 0, 0, sizeGuess, false); + if (progress != null) progress.getModel().setRangeProperties(0, 0, 0, sizeGuess, false); } @Override public void updateProgress(int fullLength) { - if (progress != null) - progress.getModel().setValue(fullLength); + if (progress != null) progress.getModel().setValue(fullLength); } @Override @@ -164,12 +165,13 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { @Override public void showErrorDialog(String name, String url) { - JEditorPane ep = new JEditorPane("text/html", - "" + - owner + " was unable to download required library " + name + - "
Check your internet connection and try restarting or download it manually from" + - "
" + url + " and put it in your mods folder" + - ""); + JEditorPane ep = new JEditorPane( + "text/html", + "" + owner + + " was unable to download required library " + name + + "
Check your internet connection and try restarting or download it manually from" + + "
" + url + " and put it in your mods folder" + ""); ep.setEditable(false); ep.setOpaque(false); @@ -190,16 +192,13 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { public static class DummyDownloader implements IDownloadDisplay { @Override - public void resetProgress(int sizeGuess) { - } + public void resetProgress(int sizeGuess) {} @Override - public void setPokeThread(Thread currentThread) { - } + public void setPokeThread(Thread currentThread) {} @Override - public void updateProgress(int fullLength) { - } + public void updateProgress(int fullLength) {} @Override public boolean shouldStopIt() { @@ -207,8 +206,7 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { } @Override - public void updateProgressString(String string, Object... data) { - } + public void updateProgressString(String string, Object... data) {} @Override public Object makeDialog() { @@ -216,12 +214,10 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { } @Override - public void showErrorDialog(String name, String url) { - } + public void showErrorDialog(String name, String url) {} } - public static class VersionedFile - { + public static class VersionedFile { public final Pattern pattern; public final String filename; public final ComparableVersion version; @@ -231,11 +227,10 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { this.pattern = pattern; this.filename = filename; Matcher m = pattern.matcher(filename); - if(m.matches()) { + if (m.matches()) { name = m.group(1); version = new ComparableVersion(m.group(2)); - } - else { + } else { name = null; version = null; } @@ -246,8 +241,7 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { } } - public static class Dependency - { + public static class Dependency { public String url; public VersionedFile file; @@ -279,21 +273,20 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { modsDir = new File(mcDir, "mods"); v_modsDir = new File(mcDir, "mods/" + mcVer); - if (!v_modsDir.exists()) - v_modsDir.mkdirs(); + if (!v_modsDir.exists()) v_modsDir.mkdirs(); } private void addClasspath(String name) { try { - ((LaunchClassLoader) DepLoader.class.getClassLoader()).addURL(new File(v_modsDir, name).toURI().toURL()); + ((LaunchClassLoader) DepLoader.class.getClassLoader()) + .addURL(new File(v_modsDir, name).toURI().toURL()); } catch (MalformedURLException e) { throw new RuntimeException(e); } } private void deleteMod(File mod) { - if (mod.delete()) - return; + if (mod.delete()) return; try { ClassLoader cl = DepLoader.class.getClassLoader(); @@ -317,7 +310,8 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { if (!mod.delete()) { mod.deleteOnExit(); - String msg = owner + " was unable to delete file " + mod.getPath() + " the game will now try to delete it on exit. If this dialog appears again, delete it manually."; + String msg = owner + " was unable to delete file " + mod.getPath() + + " the game will now try to delete it on exit. If this dialog appears again, delete it manually."; System.err.println(msg); if (!GraphicsEnvironment.isHeadless()) JOptionPane.showMessageDialog(null, msg, "An update error has occured", JOptionPane.ERROR_MESSAGE); @@ -357,7 +351,9 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { private void download(InputStream is, int sizeGuess, File target) throws Exception { if (sizeGuess > downloadBuffer.capacity()) - throw new Exception(String.format("The file %s is too large to be downloaded by " + owner + " - the download is invalid", target.getName())); + throw new Exception(String.format( + "The file %s is too large to be downloaded by " + owner + " - the download is invalid", + target.getName())); downloadBuffer.clear(); @@ -391,9 +387,7 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { /*String cksum = generateChecksum(downloadBuffer); if (cksum.equals(validationHash)) {*/ - if (!target.exists()) - target.createNewFile(); - + if (!target.exists()) target.createNewFile(); downloadBuffer.position(0); FileOutputStream fos = new FileOutputStream(target); @@ -412,19 +406,16 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { private String checkExisting(Dependency dep) { for (File f : modsDir.listFiles()) { VersionedFile vfile = new VersionedFile(f.getName(), dep.file.pattern); - if (!vfile.matches() || !vfile.name.equals(dep.file.name)) - continue; + if (!vfile.matches() || !vfile.name.equals(dep.file.name)) continue; - if (f.renameTo(new File(v_modsDir, f.getName()))) - continue; + if (f.renameTo(new File(v_modsDir, f.getName()))) continue; deleteMod(f); } for (File f : v_modsDir.listFiles()) { VersionedFile vfile = new VersionedFile(f.getName(), dep.file.pattern); - if (!vfile.matches() || !vfile.name.equals(dep.file.name)) - continue; + if (!vfile.matches() || !vfile.name.equals(dep.file.name)) continue; int cmp = vfile.version.compareTo(dep.file.version); if (cmp < 0) { @@ -433,27 +424,25 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { return null; } if (cmp > 0) { - System.err.println("Warning: version of " + dep.file.name + ", " + vfile.version + " is newer than request " + dep.file.version); + System.err.println("Warning: version of " + dep.file.name + ", " + vfile.version + + " is newer than request " + dep.file.version); return f.getName(); } - return f.getName();//found dependency + return f.getName(); // found dependency } return null; } public void load() { scanDepInfos(); - if (depMap.isEmpty()) - return; + if (depMap.isEmpty()) return; loadDeps(); activateDeps(); } private void activateDeps() { - for (Dependency dep : depMap.values()) - if (dep.coreLib) - addClasspath(dep.existing); + for (Dependency dep : depMap.values()) if (dep.coreLib) addClasspath(dep.existing); } private void loadDeps() { @@ -475,7 +464,7 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { private void load(Dependency dep) { dep.existing = checkExisting(dep); - if (dep.existing == null)//download dep + if (dep.existing == null) // download dep { download(dep); dep.existing = dep.file.filename; @@ -491,8 +480,7 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { private void scanDepInfos() { for (File file : modFiles()) { - if (!file.getName().endsWith(".jar") && !file.getName().endsWith(".zip")) - continue; + if (!file.getName().endsWith(".jar") && !file.getName().endsWith(".zip")) continue; scanDepInfo(file); } @@ -503,8 +491,7 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { ZipFile zip = new ZipFile(file); ZipEntry e = zip.getEntry("dependancies.info"); if (e == null) e = zip.getEntry("dependencies.info"); - if (e != null) - loadJSon(zip.getInputStream(e)); + if (e != null) loadJSon(zip.getInputStream(e)); zip.close(); } catch (Exception e) { System.err.println("Failed to load dependencies.info from " + file.getName() + " as JSON"); @@ -515,47 +502,41 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { private void loadJSon(InputStream input) throws IOException { InputStreamReader reader = new InputStreamReader(input); JsonElement root = new JsonParser().parse(reader); - if (root.isJsonArray()) - loadJSonArr(root); - else - loadJson(root.getAsJsonObject()); + if (root.isJsonArray()) loadJSonArr(root); + else loadJson(root.getAsJsonObject()); reader.close(); } private void loadJSonArr(JsonElement root) throws IOException { - for (JsonElement node : root.getAsJsonArray()) - loadJson(node.getAsJsonObject()); + for (JsonElement node : root.getAsJsonArray()) loadJson(node.getAsJsonObject()); } private void loadJson(JsonObject node) throws IOException { - boolean obfuscated = ((LaunchClassLoader) DepLoader.class.getClassLoader()) - .getClassBytes("net.minecraft.world.World") == null; + boolean obfuscated = + ((LaunchClassLoader) DepLoader.class.getClassLoader()).getClassBytes("net.minecraft.world.World") + == null; String testClass = node.get("class").getAsString(); - if (DepLoader.class.getResource("/" + testClass.replace('.', '/') + ".class") != null) - return; + if (DepLoader.class.getResource("/" + testClass.replace('.', '/') + ".class") != null) return; String repo = node.get("repo").getAsString(); String filename = node.get("file").getAsString(); - if (!obfuscated && node.has("dev")) - filename = node.get("dev").getAsString(); + if (!obfuscated && node.has("dev")) filename = node.get("dev").getAsString(); boolean coreLib = node.has("coreLib") && node.get("coreLib").getAsBoolean(); Pattern pattern = null; try { - if(node.has("pattern")) + if (node.has("pattern")) pattern = Pattern.compile(node.get("pattern").getAsString()); } catch (PatternSyntaxException e) { - System.err.println("Invalid filename pattern: "+node.get("pattern")); + System.err.println("Invalid filename pattern: " + node.get("pattern")); e.printStackTrace(); } - if(pattern == null) - pattern = Pattern.compile("(\\w+).*?([\\d\\.]+)[-\\w]*\\.[^\\d]+"); + if (pattern == null) pattern = Pattern.compile("(\\w+).*?([\\d\\.]+)[-\\w]*\\.[^\\d]+"); VersionedFile file = new VersionedFile(filename, pattern); - if (!file.matches()) - throw new RuntimeException("Invalid filename format for dependency: " + filename); + if (!file.matches()) throw new RuntimeException("Invalid filename format for dependency: " + filename); addDep(new Dependency(repo, file, coreLib)); } @@ -568,8 +549,7 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { } private boolean mergeNew(Dependency oldDep, Dependency newDep) { - if (oldDep == null) - return true; + if (oldDep == null) return true; Dependency newest = newDep.file.version.compareTo(oldDep.file.version) > 0 ? newDep : oldDep; newest.coreLib = newDep.coreLib || oldDep.coreLib; @@ -601,8 +581,7 @@ public class DepLoader implements IFMLLoadingPlugin, IFMLCallHook { } @Override - public void injectData(Map data) { - } + public void injectData(Map data) {} @Override public Void call() { diff --git a/src/main/scala/codechicken/multipart/PartMap.java b/src/main/scala/codechicken/multipart/PartMap.java index 9100ec9..4bc8e10 100644 --- a/src/main/scala/codechicken/multipart/PartMap.java +++ b/src/main/scala/codechicken/multipart/PartMap.java @@ -4,8 +4,7 @@ package codechicken.multipart; * Defines what each slot in a multipart tile corresponds to and provides some utility functions. * For performance reasons, it is recommended that integer constants be useds as opposed to this enum */ -public enum PartMap -{ +public enum PartMap { BOTTOM(0), TOP(1), NORTH(2), @@ -13,122 +12,119 @@ public enum PartMap WEST(4), EAST(5), CENTER(6), - CORNER_NNN(7),//0 - CORNER_NPN(8),//1 - CORNER_NNP(9),//2 - CORNER_NPP(10),//3 - CORNER_PNN(11),//4 - CORNER_PPN(12),//5 - CORNER_PNP(13),//6 - CORNER_PPP(14),//7 - EDGE_NYN(15),//0 - EDGE_NYP(16),//1 - EDGE_PYN(17),//2 - EDGE_PYP(18),//3 - EDGE_NNZ(19),//4 - EDGE_PNZ(20),//5 - EDGE_NPZ(21),//6 - EDGE_PPZ(22),//7 - EDGE_XNN(23),//8 - EDGE_XPN(24),//9 - EDGE_XNP(25),//10 - EDGE_XPP(26);//11 - + CORNER_NNN(7), // 0 + CORNER_NPN(8), // 1 + CORNER_NNP(9), // 2 + CORNER_NPP(10), // 3 + CORNER_PNN(11), // 4 + CORNER_PPN(12), // 5 + CORNER_PNP(13), // 6 + CORNER_PPP(14), // 7 + EDGE_NYN(15), // 0 + EDGE_NYP(16), // 1 + EDGE_PYN(17), // 2 + EDGE_PYP(18), // 3 + EDGE_NNZ(19), // 4 + EDGE_PNZ(20), // 5 + EDGE_NPZ(21), // 6 + EDGE_PPZ(22), // 7 + EDGE_XNN(23), // 8 + EDGE_XPN(24), // 9 + EDGE_XNP(25), // 10 + EDGE_XPP(26); // 11 + public final int i; public final int mask; - - private PartMap(int i) - { + + private PartMap(int i) { this.i = i; - mask = 1<>2) - { - case 0: return 6; - case 1: return 5; - case 2: return 3; + public static int edgeAxisMask(int e) { + switch (e >> 2) { + case 0: + return 6; + case 1: + return 5; + case 2: + return 3; } throw new IllegalArgumentException("Switch Falloff"); } - + /** * Unpacks an edge index, to a mask where high values indicate positive positions in that axis. * Note the parameter e is relative to the first edge slot and can range from 0-11 * For example, edge 1 (slot 16), is EDGE_NYP so the mask returned would be 010 as z is positive. */ - public static int unpackEdgeBits(int e) - { - switch(e>>2) - { - case 0: return (e&3)<<1; - case 1: return (e&2)>>1|(e&1)<<2; - case 2: return (e&3); + public static int unpackEdgeBits(int e) { + switch (e >> 2) { + case 0: + return (e & 3) << 1; + case 1: + return (e & 2) >> 1 | (e & 1) << 2; + case 2: + return (e & 3); } throw new IllegalArgumentException("Switch Falloff"); } - + /** * Repacks a mask of axis bits indicating positive positions, into an edge in along the same axis as e. * Note the parameter e is relative to the first edge slot and can range from 0-11 */ - public static int packEdgeBits(int e, int bits) - { - switch(e>>2) - { - case 0: return e&0xC|bits>>1; - case 1: return e&0xC|(bits&4)>>2|(bits&1)<<1; - case 2: return e&0xC|bits&3; + public static int packEdgeBits(int e, int bits) { + switch (e >> 2) { + case 0: + return e & 0xC | bits >> 1; + case 1: + return e & 0xC | (bits & 4) >> 2 | (bits & 1) << 1; + case 2: + return e & 0xC | bits & 3; } throw new IllegalArgumentException("Switch Falloff"); } - - private static int[] edgeBetweenMap = new int[]{ + + private static int[] edgeBetweenMap = new int[] { -1, -1, 8, 10, 4, 5, -1, -1, 9, 11, 6, 7, - -1, -1,-1, -1, 0, 2, - -1, -1,-1, -1, 1, 3}; - + -1, -1, -1, -1, 0, 2, + -1, -1, -1, -1, 1, 3 + }; + /** * Returns the slot of the edge between 2 sides. */ - public static int edgeBetween(int s1, int s2) - { - if(s2 < s1) - return edgeBetween(s2, s1); - if((s1&6) == (s2&6)) - throw new IllegalArgumentException("Faces "+s1+" and "+s2+" are opposites"); - return 15+edgeBetweenMap[s1*6+s2]; + public static int edgeBetween(int s1, int s2) { + if (s2 < s1) return edgeBetween(s2, s1); + if ((s1 & 6) == (s2 & 6)) throw new IllegalArgumentException("Faces " + s1 + " and " + s2 + " are opposites"); + return 15 + edgeBetweenMap[s1 * 6 + s2]; } } diff --git a/src/main/scala/codechicken/multipart/minecraft/ButtonPart.java b/src/main/scala/codechicken/multipart/minecraft/ButtonPart.java index af82f33..e582da2 100644 --- a/src/main/scala/codechicken/multipart/minecraft/ButtonPart.java +++ b/src/main/scala/codechicken/multipart/minecraft/ButtonPart.java @@ -4,7 +4,6 @@ import codechicken.lib.vec.BlockCoord; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; import codechicken.multipart.IFaceRedstonePart; -import codechicken.multipart.TickScheduler; import net.minecraft.block.Block; import net.minecraft.block.BlockButton; import net.minecraft.entity.Entity; @@ -16,169 +15,136 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -public class ButtonPart extends McSidedMetaPart implements IFaceRedstonePart -{ +public class ButtonPart extends McSidedMetaPart implements IFaceRedstonePart { public static BlockButton stoneButton = (BlockButton) Blocks.stone_button; public static BlockButton woodenButton = (BlockButton) Blocks.wooden_button; - public static int[] metaSideMap = new int[]{-1, 4, 5, 2, 3}; - public static int[] sideMetaMap = new int[]{-1, -1, 3, 4, 1, 2}; - - public static BlockButton getButton(int meta) - { - return (meta&0x10) > 0 ? woodenButton : stoneButton; + public static int[] metaSideMap = new int[] {-1, 4, 5, 2, 3}; + public static int[] sideMetaMap = new int[] {-1, -1, 3, 4, 1, 2}; + + public static BlockButton getButton(int meta) { + return (meta & 0x10) > 0 ? woodenButton : stoneButton; } - - public ButtonPart() - { - } - - public ButtonPart(int meta) - { + + public ButtonPart() {} + + public ButtonPart(int meta) { super(meta); } - + @Override - public int sideForMeta(int meta) - { - return metaSideMap[meta&7]; + public int sideForMeta(int meta) { + return metaSideMap[meta & 7]; } @Override - public Block getBlock() - { + public Block getBlock() { return getButton(meta); } - + @Override - public String getType() - { + public String getType() { return "mc_button"; } - - public int delay() - { + + public int delay() { return sensitive() ? 30 : 20; } - - public boolean sensitive() - { - return (meta&0x10) > 0; + + public boolean sensitive() { + return (meta & 0x10) > 0; } - + @Override - public Cuboid6 getBounds() - { + public Cuboid6 getBounds() { int m = meta & 7; double d = pressed() ? 0.0625 : 0.125; - - if (m == 1) - return new Cuboid6(0.0, 0.375, 0.5 - 0.1875, d, 0.625, 0.5 + 0.1875); - if (m == 2) - return new Cuboid6(1.0 - d, 0.375, 0.5 - 0.1875, 1.0, 0.625, 0.5 + 0.1875); - if (m == 3) - return new Cuboid6(0.5 - 0.1875, 0.375, 0.0, 0.5 + 0.1875, 0.625, d); - if (m == 4) - return new Cuboid6(0.5 - 0.1875, 0.375, 1.0 - d, 0.5 + 0.1875, 0.625, 1.0); - - return null;//falloff + + if (m == 1) return new Cuboid6(0.0, 0.375, 0.5 - 0.1875, d, 0.625, 0.5 + 0.1875); + if (m == 2) return new Cuboid6(1.0 - d, 0.375, 0.5 - 0.1875, 1.0, 0.625, 0.5 + 0.1875); + if (m == 3) return new Cuboid6(0.5 - 0.1875, 0.375, 0.0, 0.5 + 0.1875, 0.625, d); + if (m == 4) return new Cuboid6(0.5 - 0.1875, 0.375, 1.0 - d, 0.5 + 0.1875, 0.625, 1.0); + + return null; // falloff } - public static McBlockPart placement(World world, BlockCoord pos, int side, int type) - { - if(side == 0 || side == 1) - return null; - - pos = pos.copy().offset(side^1); - if(!world.isSideSolid(pos.x, pos.y, pos.z, ForgeDirection.getOrientation(side))) - return null; - - return new ButtonPart(sideMetaMap[side^1]|type<<4); + public static McBlockPart placement(World world, BlockCoord pos, int side, int type) { + if (side == 0 || side == 1) return null; + + pos = pos.copy().offset(side ^ 1); + if (!world.isSideSolid(pos.x, pos.y, pos.z, ForgeDirection.getOrientation(side))) return null; + + return new ButtonPart(sideMetaMap[side ^ 1] | type << 4); } @Override - public boolean activate(EntityPlayer player, MovingObjectPosition part, ItemStack item) - { - if(pressed()) - return false; - - if(!world().isRemote) - toggle(); - + public boolean activate(EntityPlayer player, MovingObjectPosition part, ItemStack item) { + if (pressed()) return false; + + if (!world().isRemote) toggle(); + return true; } - + @Override - public void scheduledTick() - { - if(pressed()) - updateState(); - } - - public boolean pressed() - { - return (meta&8) > 0; - } - - @Override - public void onEntityCollision(Entity entity) - { - if(!pressed() && !world().isRemote && entity instanceof EntityArrow) - updateState(); + public void scheduledTick() { + if (pressed()) updateState(); } - private void toggle() - { + public boolean pressed() { + return (meta & 8) > 0; + } + + @Override + public void onEntityCollision(Entity entity) { + if (!pressed() && !world().isRemote && entity instanceof EntityArrow) updateState(); + } + + private void toggle() { boolean in = !pressed(); - meta^=8; + meta ^= 8; world().playSoundEffect(x() + 0.5, y() + 0.5, z() + 0.5, "random.click", 0.3F, in ? 0.6F : 0.5F); - if(in) - scheduleTick(delay()); - + if (in) scheduleTick(delay()); + sendDescUpdate(); tile().notifyPartChange(this); - tile().notifyNeighborChange(metaSideMap[meta&7]); + tile().notifyNeighborChange(metaSideMap[meta & 7]); tile().markDirty(); } - private void updateState() - { - boolean arrows = sensitive() && !world().getEntitiesWithinAABB(EntityArrow.class, - getBounds().add(Vector3.fromTileEntity(tile())).toAABB()).isEmpty(); + private void updateState() { + boolean arrows = sensitive() + && !world().getEntitiesWithinAABB( + EntityArrow.class, + getBounds().add(Vector3.fromTileEntity(tile())).toAABB()) + .isEmpty(); boolean pressed = pressed(); - - if(arrows != pressed) - toggle(); - if(arrows && pressed) - scheduleTick(delay()); + + if (arrows != pressed) toggle(); + if (arrows && pressed) scheduleTick(delay()); } - + @Override - public void onRemoved() - { - if(pressed()) - tile().notifyNeighborChange(metaSideMap[meta&7]); + public void onRemoved() { + if (pressed()) tile().notifyNeighborChange(metaSideMap[meta & 7]); } - + @Override - public int weakPowerLevel(int side) - { + public int weakPowerLevel(int side) { return pressed() ? 15 : 0; } @Override - public int strongPowerLevel(int side) - { - return pressed() && side == metaSideMap[meta&7] ? 15 : 0; + public int strongPowerLevel(int side) { + return pressed() && side == metaSideMap[meta & 7] ? 15 : 0; } @Override - public boolean canConnectRedstone(int side) - { + public boolean canConnectRedstone(int side) { return true; } - + @Override public int getFace() { - return metaSideMap[meta&7]; + return metaSideMap[meta & 7]; } } diff --git a/src/main/scala/codechicken/multipart/minecraft/Content.java b/src/main/scala/codechicken/multipart/minecraft/Content.java index 89e50da..2fd8154 100644 --- a/src/main/scala/codechicken/multipart/minecraft/Content.java +++ b/src/main/scala/codechicken/multipart/minecraft/Content.java @@ -1,63 +1,53 @@ package codechicken.multipart.minecraft; +import codechicken.lib.vec.BlockCoord; +import codechicken.multipart.MultiPartRegistry; +import codechicken.multipart.MultiPartRegistry.IPartConverter; +import codechicken.multipart.MultiPartRegistry.IPartFactory; +import codechicken.multipart.TMultiPart; +import java.util.Arrays; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.world.World; -import codechicken.lib.vec.BlockCoord; -import codechicken.multipart.MultiPartRegistry.IPartConverter; -import codechicken.multipart.MultiPartRegistry.IPartFactory; -import codechicken.multipart.MultiPartRegistry; -import codechicken.multipart.TMultiPart; -import java.util.Arrays; - -public class Content implements IPartFactory, IPartConverter -{ +public class Content implements IPartFactory, IPartConverter { @Override - public TMultiPart createPart(String name, boolean client) - { - if(name.equals("mc_torch")) return new TorchPart(); - if(name.equals("mc_lever")) return new LeverPart(); - if(name.equals("mc_button")) return new ButtonPart(); - if(name.equals("mc_redtorch")) return new RedstoneTorchPart(); - + public TMultiPart createPart(String name, boolean client) { + if (name.equals("mc_torch")) return new TorchPart(); + if (name.equals("mc_lever")) return new LeverPart(); + if (name.equals("mc_button")) return new ButtonPart(); + if (name.equals("mc_redtorch")) return new RedstoneTorchPart(); + return null; } - - public void init() - { + + public void init() { MultiPartRegistry.registerConverter(this); - MultiPartRegistry.registerParts(this, new String[]{ - "mc_torch", - "mc_lever", - "mc_button", - "mc_redtorch" - }); + MultiPartRegistry.registerParts(this, new String[] {"mc_torch", "mc_lever", "mc_button", "mc_redtorch"}); } @Override public Iterable blockTypes() { - return Arrays.asList(Blocks.torch, Blocks.lever, Blocks.stone_button, Blocks.wooden_button, Blocks.redstone_torch, Blocks.unlit_redstone_torch); + return Arrays.asList( + Blocks.torch, + Blocks.lever, + Blocks.stone_button, + Blocks.wooden_button, + Blocks.redstone_torch, + Blocks.unlit_redstone_torch); } @Override - public TMultiPart convert(World world, BlockCoord pos) - { + public TMultiPart convert(World world, BlockCoord pos) { Block b = world.getBlock(pos.x, pos.y, pos.z); int meta = world.getBlockMetadata(pos.x, pos.y, pos.z); - if(b == Blocks.torch) - return new TorchPart(meta); - if(b == Blocks.lever) - return new LeverPart(meta); - if(b == Blocks.stone_button) - return new ButtonPart(meta); - if(b == Blocks.wooden_button) - return new ButtonPart(meta|0x10); - if(b == Blocks.redstone_torch) - return new RedstoneTorchPart(meta); - if(b == Blocks.unlit_redstone_torch) - return new RedstoneTorchPart(meta|0x10); - + if (b == Blocks.torch) return new TorchPart(meta); + if (b == Blocks.lever) return new LeverPart(meta); + if (b == Blocks.stone_button) return new ButtonPart(meta); + if (b == Blocks.wooden_button) return new ButtonPart(meta | 0x10); + if (b == Blocks.redstone_torch) return new RedstoneTorchPart(meta); + if (b == Blocks.unlit_redstone_torch) return new RedstoneTorchPart(meta | 0x10); + return null; } } diff --git a/src/main/scala/codechicken/multipart/minecraft/EventHandler.java b/src/main/scala/codechicken/multipart/minecraft/EventHandler.java index 791b42d..4896e92 100644 --- a/src/main/scala/codechicken/multipart/minecraft/EventHandler.java +++ b/src/main/scala/codechicken/multipart/minecraft/EventHandler.java @@ -6,6 +6,7 @@ import codechicken.lib.vec.BlockCoord; import codechicken.lib.vec.Vector3; import codechicken.multipart.TileMultipart; import cpw.mods.fml.common.eventhandler.EventPriority; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.entity.player.EntityPlayer; @@ -15,97 +16,94 @@ import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; -public class EventHandler -{ +public class EventHandler { private ThreadLocal placing = new ThreadLocal(); - + @SubscribeEvent(priority = EventPriority.LOW) - public void playerInteract(PlayerInteractEvent event) - { - if(event.action == Action.RIGHT_CLICK_BLOCK && event.entityPlayer.worldObj.isRemote) - { - if(placing.get() != null) - return;//for mods that do dumb stuff and call this event like MFR + public void playerInteract(PlayerInteractEvent event) { + if (event.action == Action.RIGHT_CLICK_BLOCK && event.entityPlayer.worldObj.isRemote) { + if (placing.get() != null) return; // for mods that do dumb stuff and call this event like MFR placing.set(event); - if(place(event.entityPlayer, event.entityPlayer.worldObj)) - event.setCanceled(true); + if (place(event.entityPlayer, event.entityPlayer.worldObj)) event.setCanceled(true); placing.set(null); } } - - public static boolean place(EntityPlayer player, World world) - { + + public static boolean place(EntityPlayer player, World world) { MovingObjectPosition hit = RayTracer.reTrace(world, player); - if(hit == null) - return false; - + if (hit == null) return false; + BlockCoord pos = new BlockCoord(hit.blockX, hit.blockY, hit.blockZ).offset(hit.sideHit); ItemStack held = player.getHeldItem(); McBlockPart part = null; - if(held == null) - return false; + if (held == null) return false; Block heldBlock = Block.getBlockFromItem(held.getItem()); - if(heldBlock == Blocks.air) - return false; + if (heldBlock == Blocks.air) return false; - if(heldBlock == Blocks.torch) - part = TorchPart.placement(world, pos, hit.sideHit); - else if(heldBlock == Blocks.lever) - part = LeverPart.placement(world, pos, player, hit.sideHit); - else if(heldBlock == Blocks.stone_button) - part = ButtonPart.placement(world, pos, hit.sideHit, 0); - else if(heldBlock == Blocks.wooden_button) - part = ButtonPart.placement(world, pos, hit.sideHit, 1); - else if(heldBlock == Blocks.redstone_torch) - part = RedstoneTorchPart.placement(world, pos, hit.sideHit); - - if(part == null) - return false; + if (heldBlock == Blocks.torch) part = TorchPart.placement(world, pos, hit.sideHit); + else if (heldBlock == Blocks.lever) part = LeverPart.placement(world, pos, player, hit.sideHit); + else if (heldBlock == Blocks.stone_button) part = ButtonPart.placement(world, pos, hit.sideHit, 0); + else if (heldBlock == Blocks.wooden_button) part = ButtonPart.placement(world, pos, hit.sideHit, 1); + else if (heldBlock == Blocks.redstone_torch) part = RedstoneTorchPart.placement(world, pos, hit.sideHit); - if(world.isRemote && !player.isSneaking())//attempt to use block activated like normal and tell the server the right stuff + if (part == null) return false; + + if (world.isRemote + && !player + .isSneaking()) // attempt to use block activated like normal and tell the server the right stuff { Vector3 f = new Vector3(hit.hitVec).add(-hit.blockX, -hit.blockY, -hit.blockZ); Block block = world.getBlock(hit.blockX, hit.blockY, hit.blockZ); - if(!ignoreActivate(block) && block.onBlockActivated(world, hit.blockX, hit.blockY, hit.blockZ, player, hit.sideHit, (float)f.x, (float)f.y, (float)f.z)) - { + if (!ignoreActivate(block) + && block.onBlockActivated( + world, + hit.blockX, + hit.blockY, + hit.blockZ, + player, + hit.sideHit, + (float) f.x, + (float) f.y, + (float) f.z)) { player.swingItem(); PacketCustom.sendToServer(new C08PacketPlayerBlockPlacement( - hit.blockX, hit.blockY, hit.blockZ, hit.sideHit, - player.inventory.getCurrentItem(), - (float)f.x, (float)f.y, (float)f.z)); + hit.blockX, + hit.blockY, + hit.blockZ, + hit.sideHit, + player.inventory.getCurrentItem(), + (float) f.x, + (float) f.y, + (float) f.z)); return true; } } - + TileMultipart tile = TileMultipart.getOrConvertTile(world, pos); - if(tile == null || !tile.canAddPart(part)) - return false; - - if(!world.isRemote) - { + if (tile == null || !tile.canAddPart(part)) return false; + + if (!world.isRemote) { TileMultipart.addPart(world, pos, part); - world.playSoundEffect(pos.x + 0.5, pos.y + 0.5, pos.z + 0.5, + world.playSoundEffect( + pos.x + 0.5, + pos.y + 0.5, + pos.z + 0.5, part.getBlock().stepSound.func_150496_b(), - (part.getBlock().stepSound.getVolume() + 1.0F) / 2.0F, + (part.getBlock().stepSound.getVolume() + 1.0F) / 2.0F, part.getBlock().stepSound.getPitch() * 0.8F); - if(!player.capabilities.isCreativeMode) - { + if (!player.capabilities.isCreativeMode) { held.stackSize--; - if (held.stackSize == 0) - { + if (held.stackSize == 0) { player.inventory.mainInventory[player.inventory.currentItem] = null; MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, held)); } } - } - else - { + } else { player.swingItem(); new PacketCustom(McMultipartSPH.channel, 1).sendToServer(); } @@ -115,10 +113,8 @@ public class EventHandler /** * Because vanilla is weird. */ - private static boolean ignoreActivate(Block block) - { - if(block instanceof BlockFence) - return true; + private static boolean ignoreActivate(Block block) { + if (block instanceof BlockFence) return true; return false; } } diff --git a/src/main/scala/codechicken/multipart/minecraft/IPartMeta.java b/src/main/scala/codechicken/multipart/minecraft/IPartMeta.java index c9e62a5..4b7cdbc 100644 --- a/src/main/scala/codechicken/multipart/minecraft/IPartMeta.java +++ b/src/main/scala/codechicken/multipart/minecraft/IPartMeta.java @@ -4,13 +4,12 @@ import codechicken.lib.vec.BlockCoord; import net.minecraft.block.Block; import net.minecraft.world.World; -public interface IPartMeta -{ +public interface IPartMeta { public int getMetadata(); - + public World getWorld(); public Block getBlock(); - + public BlockCoord getPos(); -} \ No newline at end of file +} diff --git a/src/main/scala/codechicken/multipart/minecraft/LeverPart.java b/src/main/scala/codechicken/multipart/minecraft/LeverPart.java index 422d7f5..171171d 100644 --- a/src/main/scala/codechicken/multipart/minecraft/LeverPart.java +++ b/src/main/scala/codechicken/multipart/minecraft/LeverPart.java @@ -1,6 +1,9 @@ package codechicken.multipart.minecraft; import codechicken.lib.math.MathHelper; +import codechicken.lib.vec.BlockCoord; +import codechicken.lib.vec.Cuboid6; +import codechicken.multipart.IFaceRedstonePart; import net.minecraft.block.Block; import net.minecraft.block.BlockLever; import net.minecraft.client.renderer.RenderBlocks; @@ -11,103 +14,80 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import codechicken.lib.vec.BlockCoord; -import codechicken.lib.vec.Cuboid6; -import codechicken.multipart.IFaceRedstonePart; -public class LeverPart extends McSidedMetaPart implements IFaceRedstonePart -{ +public class LeverPart extends McSidedMetaPart implements IFaceRedstonePart { public static BlockLever lever = (BlockLever) Blocks.lever; - public static int[] metaSideMap = new int[]{1, 4, 5, 2, 3, 0, 0, 1}; - public static int[] sideMetaMap = new int[]{6, 0, 3, 4, 1, 2}; - public static int[] metaSwapMap = new int[]{5, 7}; - - public LeverPart() - { - } - - public LeverPart(int meta) - { + public static int[] metaSideMap = new int[] {1, 4, 5, 2, 3, 0, 0, 1}; + public static int[] sideMetaMap = new int[] {6, 0, 3, 4, 1, 2}; + public static int[] metaSwapMap = new int[] {5, 7}; + + public LeverPart() {} + + public LeverPart(int meta) { super(meta); } - + @Override - public Block getBlock() - { + public Block getBlock() { return lever; } - + @Override - public String getType() - { + public String getType() { return "mc_lever"; } - - public boolean active() - { - return (meta&8) > 0; + + public boolean active() { + return (meta & 8) > 0; } - + @Override - public Cuboid6 getBounds() - { + public Cuboid6 getBounds() { int m = meta & 7; double d = 0.1875; - if (m == 1) - return new Cuboid6(0, 0.2, 0.5 - d, d * 2, 0.8, 0.5 + d); - if (m == 2) - return new Cuboid6(1 - d * 2, 0.2, 0.5 - d, 1, 0.8, 0.5 + d); - if (m == 3) - return new Cuboid6(0.5 - d, 0.2, 0, 0.5 + d, 0.8, d * 2); - if (m == 4) - return new Cuboid6(0.5 - d, 0.2, 1 - d * 2, 0.5 + d, 0.8, 1); + if (m == 1) return new Cuboid6(0, 0.2, 0.5 - d, d * 2, 0.8, 0.5 + d); + if (m == 2) return new Cuboid6(1 - d * 2, 0.2, 0.5 - d, 1, 0.8, 0.5 + d); + if (m == 3) return new Cuboid6(0.5 - d, 0.2, 0, 0.5 + d, 0.8, d * 2); + if (m == 4) return new Cuboid6(0.5 - d, 0.2, 1 - d * 2, 0.5 + d, 0.8, 1); d = 0.25; - if (m == 0 || m == 7) - return new Cuboid6(0.5 - d, 0.4, 0.5 - d, 0.5 + d, 1, 0.5 + d); - + if (m == 0 || m == 7) return new Cuboid6(0.5 - d, 0.4, 0.5 - d, 0.5 + d, 1, 0.5 + d); + return new Cuboid6(0.5 - d, 0, 0.5 - d, 0.5 + d, 0.6, 0.5 + d); } - + @Override - public int sideForMeta(int meta) - { - return metaSideMap[meta&7]; + public int sideForMeta(int meta) { + return metaSideMap[meta & 7]; } - public static McBlockPart placement(World world, BlockCoord pos, EntityPlayer player, int side) - { - pos = pos.copy().offset(side^1); - if(!world.isSideSolid(pos.x, pos.y, pos.z, ForgeDirection.getOrientation(side))) - return null; - - int meta = sideMetaMap[side^1]; - if(side < 2 && (MathHelper.floor_double(player.rotationYaw / 90 + 0.5) & 1) == 0) - meta = metaSwapMap[side^1]; - + public static McBlockPart placement(World world, BlockCoord pos, EntityPlayer player, int side) { + pos = pos.copy().offset(side ^ 1); + if (!world.isSideSolid(pos.x, pos.y, pos.z, ForgeDirection.getOrientation(side))) return null; + + int meta = sideMetaMap[side ^ 1]; + if (side < 2 && (MathHelper.floor_double(player.rotationYaw / 90 + 0.5) & 1) == 0) meta = metaSwapMap[side ^ 1]; + return new LeverPart(meta); } @Override - public boolean activate(EntityPlayer player, MovingObjectPosition part, ItemStack item) - { + public boolean activate(EntityPlayer player, MovingObjectPosition part, ItemStack item) { World world = world(); - if(world.isRemote) - return true; + if (world.isRemote) return true; world.playSoundEffect(x() + 0.5, y() + 0.5, z() + 0.5, "random.click", 0.3F, !active() ? 0.6F : 0.5F); meta ^= 8; sendDescUpdate(); tile().notifyPartChange(this); - tile().notifyNeighborChange(metaSideMap[meta&7]); + tile().notifyNeighborChange(metaSideMap[meta & 7]); tile().markDirty(); return true; } @Override - public void drawBreaking(RenderBlocks renderBlocks) - { + public void drawBreaking(RenderBlocks renderBlocks) { IBlockAccess actual = renderBlocks.blockAccess; renderBlocks.blockAccess = new PartMetaAccess(this); renderBlocks.renderBlockLever(lever, x(), y(), z()); @@ -115,39 +95,32 @@ public class LeverPart extends McSidedMetaPart implements IFaceRedstonePart } @Override - public void onRemoved() - { - if(active()) - tile().notifyNeighborChange(metaSideMap[meta&7]); - } - - @Override - public void onConverted() - { - if(active()) - tile().notifyNeighborChange(metaSideMap[meta&7]); + public void onRemoved() { + if (active()) tile().notifyNeighborChange(metaSideMap[meta & 7]); } @Override - public int weakPowerLevel(int side) - { + public void onConverted() { + if (active()) tile().notifyNeighborChange(metaSideMap[meta & 7]); + } + + @Override + public int weakPowerLevel(int side) { return active() ? 15 : 0; } @Override - public int strongPowerLevel(int side) - { - return active() && side == metaSideMap[meta&7] ? 15 : 0; + public int strongPowerLevel(int side) { + return active() && side == metaSideMap[meta & 7] ? 15 : 0; } @Override - public boolean canConnectRedstone(int side) - { + public boolean canConnectRedstone(int side) { return true; } - + @Override public int getFace() { - return metaSideMap[meta&7]; + return metaSideMap[meta & 7]; } } diff --git a/src/main/scala/codechicken/multipart/minecraft/McBlockPart.java b/src/main/scala/codechicken/multipart/minecraft/McBlockPart.java index 9a43b43..b0ea4cd 100644 --- a/src/main/scala/codechicken/multipart/minecraft/McBlockPart.java +++ b/src/main/scala/codechicken/multipart/minecraft/McBlockPart.java @@ -1,14 +1,5 @@ package codechicken.multipart.minecraft; -import java.util.Arrays; -import java.util.Collections; - -import net.minecraft.block.Block; -import net.minecraft.client.particle.EffectRenderer; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.util.MovingObjectPosition; import codechicken.lib.vec.Cuboid6; import codechicken.multipart.IconHitEffects; import codechicken.multipart.JCuboidPart; @@ -18,75 +9,72 @@ import codechicken.multipart.NormalOcclusionTest; import codechicken.multipart.TMultiPart; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Arrays; +import java.util.Collections; +import net.minecraft.block.Block; +import net.minecraft.client.particle.EffectRenderer; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.util.MovingObjectPosition; -public abstract class McBlockPart extends JCuboidPart implements JNormalOcclusion, JIconHitEffects -{ +public abstract class McBlockPart extends JCuboidPart implements JNormalOcclusion, JIconHitEffects { public abstract Block getBlock(); - + @Override - public boolean occlusionTest(TMultiPart npart) - { + public boolean occlusionTest(TMultiPart npart) { return NormalOcclusionTest.apply(this, npart); } @Override - public Iterable getOcclusionBoxes() - { + public Iterable getOcclusionBoxes() { return Arrays.asList(getBounds()); } - + @Override - public Iterable getCollisionBoxes() - { + public Iterable getCollisionBoxes() { return Collections.emptyList(); } - + @Override - public Iterable getDrops() - { + public Iterable getDrops() { return Arrays.asList(new ItemStack(getBlock())); } - + @Override - public ItemStack pickItem(MovingObjectPosition hit) - { + public ItemStack pickItem(MovingObjectPosition hit) { return new ItemStack(getBlock()); } - + @Override - public float getStrength(MovingObjectPosition hit, EntityPlayer player) - { - return getBlock().getPlayerRelativeBlockHardness(player, player.worldObj, hit.blockX, hit.blockY, hit.blockZ)*30; + public float getStrength(MovingObjectPosition hit, EntityPlayer player) { + return getBlock().getPlayerRelativeBlockHardness(player, player.worldObj, hit.blockX, hit.blockY, hit.blockZ) + * 30; } - + @Override - public IIcon getBreakingIcon(Object subPart, int side) - { + public IIcon getBreakingIcon(Object subPart, int side) { return getBlock().getIcon(0, 0); } - + @Override @SideOnly(Side.CLIENT) - public IIcon getBrokenIcon(int side) - { + public IIcon getBrokenIcon(int side) { return getBlock().getIcon(0, 0); } - + @Override - public void addHitEffects(MovingObjectPosition hit, EffectRenderer effectRenderer) - { + public void addHitEffects(MovingObjectPosition hit, EffectRenderer effectRenderer) { IconHitEffects.addHitEffects(this, hit, effectRenderer); } - + @Override - public void addDestroyEffects(MovingObjectPosition hit, EffectRenderer effectRenderer) - { + public void addDestroyEffects(MovingObjectPosition hit, EffectRenderer effectRenderer) { IconHitEffects.addDestroyEffects(this, effectRenderer, false); } - + @Override - public int getLightValue() - { + public int getLightValue() { return getBlock().getLightValue(); } } diff --git a/src/main/scala/codechicken/multipart/minecraft/McMetaPart.java b/src/main/scala/codechicken/multipart/minecraft/McMetaPart.java index a520d38..f8b6608 100644 --- a/src/main/scala/codechicken/multipart/minecraft/McMetaPart.java +++ b/src/main/scala/codechicken/multipart/minecraft/McMetaPart.java @@ -2,78 +2,64 @@ package codechicken.multipart.minecraft; import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; -import codechicken.lib.lighting.LightMatrix; import codechicken.lib.vec.BlockCoord; import codechicken.lib.vec.Vector3; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -public abstract class McMetaPart extends McBlockPart implements IPartMeta -{ +public abstract class McMetaPart extends McBlockPart implements IPartMeta { public byte meta; - - public McMetaPart() - { + + public McMetaPart() {} + + public McMetaPart(int meta) { + this.meta = (byte) meta; } - - public McMetaPart(int meta) - { - this.meta = (byte)meta; - } - + @Override - public void save(NBTTagCompound tag) - { + public void save(NBTTagCompound tag) { tag.setByte("meta", meta); } - + @Override - public void load(NBTTagCompound tag) - { + public void load(NBTTagCompound tag) { meta = tag.getByte("meta"); } - + @Override - public void writeDesc(MCDataOutput packet) - { + public void writeDesc(MCDataOutput packet) { packet.writeByte(meta); } - + @Override - public void readDesc(MCDataInput packet) - { + public void readDesc(MCDataInput packet) { meta = packet.readByte(); } - + @Override - public World getWorld() - { + public World getWorld() { return world(); } - + @Override - public int getMetadata() - { + public int getMetadata() { return meta; } - + @Override - public BlockCoord getPos() - { + public BlockCoord getPos() { return new BlockCoord(tile()); } - + @Override - public boolean doesTick() - { + public boolean doesTick() { return false; } - + @Override - public boolean renderStatic(Vector3 pos, int pass) - { - if(pass == 0) { + public boolean renderStatic(Vector3 pos, int pass) { + if (pass == 0) { new RenderBlocks(new PartMetaAccess(this)).renderBlockByRenderType(getBlock(), x(), y(), z()); return true; } diff --git a/src/main/scala/codechicken/multipart/minecraft/McMultipartCPH.java b/src/main/scala/codechicken/multipart/minecraft/McMultipartCPH.java index ebe9bc5..fbb9590 100644 --- a/src/main/scala/codechicken/multipart/minecraft/McMultipartCPH.java +++ b/src/main/scala/codechicken/multipart/minecraft/McMultipartCPH.java @@ -1,14 +1,13 @@ package codechicken.multipart.minecraft; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.WorldClient; import codechicken.lib.packet.PacketCustom; import codechicken.lib.packet.PacketCustom.IClientPacketHandler; import codechicken.lib.vec.BlockCoord; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.network.play.INetHandlerPlayClient; -public class McMultipartCPH implements IClientPacketHandler -{ +public class McMultipartCPH implements IClientPacketHandler { public static Object channel = MinecraftMultipartMod.instance; @Override @@ -22,9 +21,13 @@ public class McMultipartCPH implements IClientPacketHandler private void spawnBurnoutSmoke(WorldClient world, BlockCoord pos) { for (int l = 0; l < 5; l++) - world.spawnParticle("smoke", + world.spawnParticle( + "smoke", pos.x + world.rand.nextDouble() * 0.6 + 0.2, pos.y + world.rand.nextDouble() * 0.6 + 0.2, - pos.z + world.rand.nextDouble() * 0.6 + 0.2, 0, 0, 0); + pos.z + world.rand.nextDouble() * 0.6 + 0.2, + 0, + 0, + 0); } } diff --git a/src/main/scala/codechicken/multipart/minecraft/McMultipartSPH.java b/src/main/scala/codechicken/multipart/minecraft/McMultipartSPH.java index c812d7f..c86d79a 100644 --- a/src/main/scala/codechicken/multipart/minecraft/McMultipartSPH.java +++ b/src/main/scala/codechicken/multipart/minecraft/McMultipartSPH.java @@ -1,13 +1,12 @@ package codechicken.multipart.minecraft; +import codechicken.lib.packet.PacketCustom; +import codechicken.lib.packet.PacketCustom.IServerPacketHandler; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraft.world.World; -import codechicken.lib.packet.PacketCustom; -import codechicken.lib.packet.PacketCustom.IServerPacketHandler; -public class McMultipartSPH implements IServerPacketHandler -{ +public class McMultipartSPH implements IServerPacketHandler { public static Object channel = MinecraftMultipartMod.instance; @Override diff --git a/src/main/scala/codechicken/multipart/minecraft/McSidedMetaPart.java b/src/main/scala/codechicken/multipart/minecraft/McSidedMetaPart.java index 34d83c7..8372488 100644 --- a/src/main/scala/codechicken/multipart/minecraft/McSidedMetaPart.java +++ b/src/main/scala/codechicken/multipart/minecraft/McSidedMetaPart.java @@ -1,69 +1,56 @@ package codechicken.multipart.minecraft; -import net.minecraft.item.ItemStack; -import net.minecraftforge.common.util.ForgeDirection; import codechicken.lib.vec.BlockCoord; import codechicken.lib.vec.Vector3; import codechicken.multipart.TFacePart; import codechicken.multipart.TileMultipart; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.util.ForgeDirection; -public abstract class McSidedMetaPart extends McMetaPart implements TFacePart -{ - public McSidedMetaPart() - { - } - - public McSidedMetaPart(int meta) - { +public abstract class McSidedMetaPart extends McMetaPart implements TFacePart { + public McSidedMetaPart() {} + + public McSidedMetaPart(int meta) { super(meta); } - + public abstract int sideForMeta(int meta); - + @Override - public void onNeighborChanged() - { - if(!world().isRemote) - dropIfCantStay(); + public void onNeighborChanged() { + if (!world().isRemote) dropIfCantStay(); } - - public boolean canStay() - { + + public boolean canStay() { BlockCoord pos = new BlockCoord(tile()).offset(sideForMeta(meta)); - return world().isSideSolid(pos.x, pos.y, pos.z, ForgeDirection.getOrientation(sideForMeta(meta)^1)); + return world().isSideSolid(pos.x, pos.y, pos.z, ForgeDirection.getOrientation(sideForMeta(meta) ^ 1)); } - - public boolean dropIfCantStay() - { - if(!canStay()) - { + + public boolean dropIfCantStay() { + if (!canStay()) { drop(); return true; } return false; } - public void drop() - { + public void drop() { TileMultipart.dropItem(new ItemStack(getBlock()), world(), Vector3.fromTileEntityCenter(tile())); tile().remPart(this); } - + @Override - public int getSlotMask() - { - return 1< 0; + + public boolean active() { + return (meta & 0x10) > 0; } - + @Override - public String getType() - { + public String getType() { return "mc_redtorch"; } - + @Override - public int sideForMeta(int meta) - { - return super.sideForMeta(meta&7); + public int sideForMeta(int meta) { + return super.sideForMeta(meta & 7); } - + @Override - public Cuboid6 getBounds() - { - return getBounds(meta&7); + public Cuboid6 getBounds() { + return getBounds(meta & 7); } - - public static McBlockPart placement(World world, BlockCoord pos, int side) - { - if(side == 0) - return null; - pos = pos.copy().offset(side^1); - if(!world.isSideSolid(pos.x, pos.y, pos.z, ForgeDirection.getOrientation(side))) - return null; - - return new RedstoneTorchPart(sideMetaMap[side^1]|0x10); + + public static McBlockPart placement(World world, BlockCoord pos, int side) { + if (side == 0) return null; + pos = pos.copy().offset(side ^ 1); + if (!world.isSideSolid(pos.x, pos.y, pos.z, ForgeDirection.getOrientation(side))) return null; + + return new RedstoneTorchPart(sideMetaMap[side ^ 1] | 0x10); } - + @Override - public void randomDisplayTick(Random random) - { - if(!active()) - return; - + public void randomDisplayTick(Random random) { + if (!active()) return; + double d0 = x() + 0.5 + (random.nextFloat() - 0.5) * 0.2; double d1 = y() + 0.7 + (random.nextFloat() - 0.5) * 0.2; double d2 = z() + 0.5 + (random.nextFloat() - 0.5) * 0.2; double d3 = 0.22D; double d4 = 0.27D; - + World world = world(); - int m = meta&7; - if (m == 1) - world.spawnParticle("reddust", d0 - d4, d1 + d3, d2, 0, 0, 0); - else if (m == 2) - world.spawnParticle("reddust", d0 + d4, d1 + d3, d2, 0, 0, 0); - else if (m == 3) - world.spawnParticle("reddust", d0, d1 + d3, d2 - d4, 0, 0, 0); - else if (m == 4) - world.spawnParticle("reddust", d0, d1 + d3, d2 + d4, 0, 0, 0); - else - world.spawnParticle("reddust", d0, d1, d2, 0, 0, 0); - } - - @Override - public ItemStack pickItem(MovingObjectPosition hit) - { - return new ItemStack(torchActive); - } - - @Override - public void onNeighborChanged() - { - if(!world().isRemote) - { - if(!dropIfCantStay() && isBeingPowered() == active()) - scheduleTick(2); - } - } - - public boolean isBeingPowered() - { - int side = metaSideMap[meta&7]; - return RedstoneInteractions.getPowerTo(this, side) > 0; - } - - @Override - public void scheduledTick() - { - if(!world().isRemote && isBeingPowered() == active()) - toggle(); + int m = meta & 7; + if (m == 1) world.spawnParticle("reddust", d0 - d4, d1 + d3, d2, 0, 0, 0); + else if (m == 2) world.spawnParticle("reddust", d0 + d4, d1 + d3, d2, 0, 0, 0); + else if (m == 3) world.spawnParticle("reddust", d0, d1 + d3, d2 - d4, 0, 0, 0); + else if (m == 4) world.spawnParticle("reddust", d0, d1 + d3, d2 + d4, 0, 0, 0); + else world.spawnParticle("reddust", d0, d1, d2, 0, 0, 0); } @Override - public void randomUpdate() - { + public ItemStack pickItem(MovingObjectPosition hit) { + return new ItemStack(torchActive); + } + + @Override + public void onNeighborChanged() { + if (!world().isRemote) { + if (!dropIfCantStay() && isBeingPowered() == active()) scheduleTick(2); + } + } + + public boolean isBeingPowered() { + int side = metaSideMap[meta & 7]; + return RedstoneInteractions.getPowerTo(this, side) > 0; + } + + @Override + public void scheduledTick() { + if (!world().isRemote && isBeingPowered() == active()) toggle(); + } + + @Override + public void randomUpdate() { scheduledTick(); } @@ -149,104 +119,91 @@ public class RedstoneTorchPart extends TorchPart implements IFaceRedstonePart, T TickScheduler.loadRandomTick(this); } - private boolean burnedOut(boolean add) - { + private boolean burnedOut(boolean add) { long time = world().getTotalWorldTime(); - while(burnout != null && burnout.timeout <= time) - burnout = burnout.next; - - if(add) - { - BurnoutEntry e = new BurnoutEntry(world().getTotalWorldTime()+60); - if(burnout == null) - burnout = e; - else - { + while (burnout != null && burnout.timeout <= time) burnout = burnout.next; + + if (add) { + BurnoutEntry e = new BurnoutEntry(world().getTotalWorldTime() + 60); + if (burnout == null) burnout = e; + else { BurnoutEntry b = burnout; - while(b.next != null) - b = b.next; + while (b.next != null) b = b.next; b.next = e; } } - if(burnout == null) - return false; - + if (burnout == null) return false; + int i = 0; BurnoutEntry b = burnout; - while(b != null) - { + while (b != null) { i++; b = b.next; } return i >= 8; } - - private void toggle() - { - if(active())//deactivating + + private void toggle() { + if (active()) // deactivating { - if(burnedOut(true)) - { + if (burnedOut(true)) { World world = world(); Random rand = world.rand; - world.playSoundEffect(x()+0.5, y()+0.5, z()+0.5, "random.fizz", 0.5F, 2.6F + (rand.nextFloat() - rand.nextFloat()) * 0.8F); + world.playSoundEffect( + x() + 0.5, + y() + 0.5, + z() + 0.5, + "random.fizz", + 0.5F, + 2.6F + (rand.nextFloat() - rand.nextFloat()) * 0.8F); McMultipartSPH.spawnBurnoutSmoke(world, x(), y(), z()); } - } - else if(burnedOut(false)) - { + } else if (burnedOut(false)) { return; } - + meta ^= 0x10; sendDescUpdate(); tile().markDirty(); tile().notifyPartChange(this); tile().notifyNeighborChange(1); } - + @Override public void drop() { - meta|=0x10;//set state to on for drop + meta |= 0x10; // set state to on for drop super.drop(); } @Override - public void onRemoved() - { - if(active()) - tile().notifyNeighborChange(1); + public void onRemoved() { + if (active()) tile().notifyNeighborChange(1); } - + @Override - public void onAdded() - { - if(active()) - tile().notifyNeighborChange(1); + public void onAdded() { + if (active()) tile().notifyNeighborChange(1); onNeighborChanged(); } @Override - public int strongPowerLevel(int side) - { + public int strongPowerLevel(int side) { return side == 1 && active() ? 15 : 0; } @Override - public int weakPowerLevel(int side) - { - return active() && side != metaSideMap[meta&7] ? 15 : 0; + public int weakPowerLevel(int side) { + return active() && side != metaSideMap[meta & 7] ? 15 : 0; } - + @Override - public boolean canConnectRedstone(int side) - { + public boolean canConnectRedstone(int side) { return true; } - + @Override public int getFace() { - return metaSideMap[meta&7]; + return metaSideMap[meta & 7]; } } diff --git a/src/main/scala/codechicken/multipart/minecraft/TorchPart.java b/src/main/scala/codechicken/multipart/minecraft/TorchPart.java index 425896f..ec83126 100644 --- a/src/main/scala/codechicken/multipart/minecraft/TorchPart.java +++ b/src/main/scala/codechicken/multipart/minecraft/TorchPart.java @@ -1,121 +1,96 @@ package codechicken.multipart.minecraft; +import codechicken.lib.vec.BlockCoord; +import codechicken.lib.vec.Cuboid6; +import codechicken.multipart.IRandomDisplayTick; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.block.BlockTorch; import net.minecraft.init.Blocks; import net.minecraft.world.World; -import codechicken.multipart.IRandomDisplayTick; -import codechicken.lib.vec.BlockCoord; -import codechicken.lib.vec.Cuboid6; import net.minecraftforge.common.util.ForgeDirection; -public class TorchPart extends McSidedMetaPart implements IRandomDisplayTick -{ +public class TorchPart extends McSidedMetaPart implements IRandomDisplayTick { public static BlockTorch torch = (BlockTorch) Blocks.torch; - public static int[] metaSideMap = new int[]{-1, 4, 5, 2, 3, 0}; - public static int[] sideMetaMap = new int[]{5, 0, 3, 4, 1, 2}; - - public TorchPart() - { - } - - public TorchPart(int meta) - { + public static int[] metaSideMap = new int[] {-1, 4, 5, 2, 3, 0}; + public static int[] sideMetaMap = new int[] {5, 0, 3, 4, 1, 2}; + + public TorchPart() {} + + public TorchPart(int meta) { super(meta); } - + @Override - public Block getBlock() - { + public Block getBlock() { return torch; } - + @Override - public String getType() - { + public String getType() { return "mc_torch"; } - + @Override - public Cuboid6 getBounds() - { + public Cuboid6 getBounds() { return getBounds(meta); } - - public Cuboid6 getBounds(int meta) - { + + public Cuboid6 getBounds(int meta) { double d = 0.15; - if (meta == 1) - return new Cuboid6(0, 0.2, 0.5 - d, d * 2, 0.8, 0.5 + d); - if (meta == 2) - return new Cuboid6(1 - d * 2, 0.2, 0.5 - d, 1, 0.8, 0.5 + d); - if (meta == 3) - return new Cuboid6(0.5 - d, 0.2, 0, 0.5 + d, 0.8, d * 2); - if (meta == 4) - return new Cuboid6(0.5 - d, 0.2, 1 - d * 2, 0.5 + d, 0.8, 1); - + if (meta == 1) return new Cuboid6(0, 0.2, 0.5 - d, d * 2, 0.8, 0.5 + d); + if (meta == 2) return new Cuboid6(1 - d * 2, 0.2, 0.5 - d, 1, 0.8, 0.5 + d); + if (meta == 3) return new Cuboid6(0.5 - d, 0.2, 0, 0.5 + d, 0.8, d * 2); + if (meta == 4) return new Cuboid6(0.5 - d, 0.2, 1 - d * 2, 0.5 + d, 0.8, 1); + d = 0.1; return new Cuboid6(0.5 - d, 0, 0.5 - d, 0.5 + d, 0.6, 0.5 + d); } - + @Override - public int sideForMeta(int meta) - { + public int sideForMeta(int meta) { return metaSideMap[meta]; } - + @Override - public boolean canStay() - { - return sideForMeta(meta) == 0 && world().getBlock(x(), y() - 1, z()).canPlaceTorchOnTop(world(), x(), y() - 1, z()) || super.canStay(); + public boolean canStay() { + return sideForMeta(meta) == 0 + && world().getBlock(x(), y() - 1, z()).canPlaceTorchOnTop(world(), x(), y() - 1, z()) + || super.canStay(); } - - public static McBlockPart placement(World world, BlockCoord pos, int side) - { - if(side == 0) - return null; - pos = pos.copy().offset(side^1); + + public static McBlockPart placement(World world, BlockCoord pos, int side) { + if (side == 0) return null; + pos = pos.copy().offset(side ^ 1); Block block = world.getBlock(pos.x, pos.y, pos.z); - if(!block.isSideSolid(world, pos.x, pos.y, pos.z, ForgeDirection.getOrientation(side)) && (side != 1 || block.canPlaceTorchOnTop(world, pos.x, pos.y, pos.z))) - return null; + if (!block.isSideSolid(world, pos.x, pos.y, pos.z, ForgeDirection.getOrientation(side)) + && (side != 1 || block.canPlaceTorchOnTop(world, pos.x, pos.y, pos.z))) return null; - return new TorchPart(sideMetaMap[side^1]); + return new TorchPart(sideMetaMap[side ^ 1]); } @Override - public void randomDisplayTick(Random random) - { + public void randomDisplayTick(Random random) { double d0 = x() + 0.5; double d1 = y() + 0.7; double d2 = z() + 0.5; double d3 = 0.22D; double d4 = 0.27D; - + World world = world(); - if (meta == 1) - { + if (meta == 1) { world.spawnParticle("smoke", d0 - d4, d1 + d3, d2, 0, 0, 0); world.spawnParticle("flame", d0 - d4, d1 + d3, d2, 0, 0, 0); - } - else if (meta == 2) - { + } else if (meta == 2) { world.spawnParticle("smoke", d0 + d4, d1 + d3, d2, 0, 0, 0); world.spawnParticle("flame", d0 + d4, d1 + d3, d2, 0, 0, 0); - } - else if (meta == 3) - { + } else if (meta == 3) { world.spawnParticle("smoke", d0, d1 + d3, d2 - d4, 0, 0, 0); world.spawnParticle("flame", d0, d1 + d3, d2 - d4, 0, 0, 0); - } - else if (meta == 4) - { + } else if (meta == 4) { world.spawnParticle("smoke", d0, d1 + d3, d2 + d4, 0, 0, 0); world.spawnParticle("flame", d0, d1 + d3, d2 + d4, 0, 0, 0); - } - else - { + } else { world.spawnParticle("smoke", d0, d1, d2, 0, 0, 0); world.spawnParticle("flame", d0, d1, d2, 0, 0, 0); } diff --git a/src/main/scala/codechicken/multipart/nei/NEI_MicroblockConfig.java b/src/main/scala/codechicken/multipart/nei/NEI_MicroblockConfig.java index 89b5f27..fb5f922 100644 --- a/src/main/scala/codechicken/multipart/nei/NEI_MicroblockConfig.java +++ b/src/main/scala/codechicken/multipart/nei/NEI_MicroblockConfig.java @@ -1,25 +1,22 @@ package codechicken.multipart.nei; import codechicken.lib.inventory.InventoryUtils; -import codechicken.microblock.MicroblockClass; import codechicken.microblock.CommonMicroClass; +import codechicken.microblock.MicroblockClass; import codechicken.microblock.handler.MicroblockProxy; import codechicken.nei.ItemStackMap; import codechicken.nei.api.API; import codechicken.nei.api.IConfigureNEI; +import java.util.Arrays; import net.minecraft.util.StatCollector; -import java.util.Arrays; - -public class NEI_MicroblockConfig implements IConfigureNEI -{ +public class NEI_MicroblockConfig implements IConfigureNEI { @Override public void loadConfig() { MicroblockClass[] microClasses = CommonMicroClass.classes(); for (int c = 0; c < microClasses.length; c++) { MicroblockClass mcrClass = microClasses[c]; - if (mcrClass == null) - continue; + if (mcrClass == null) continue; addSubset(mcrClass, c << 8 | 1); addSubset(mcrClass, c << 8 | 2); @@ -28,8 +25,10 @@ public class NEI_MicroblockConfig implements IConfigureNEI } private void addSubset(MicroblockClass mcrClass, int i) { - API.addSubset("Microblocks." + StatCollector.translateToLocal(mcrClass.getName() + "." + (i & 0xFF) + ".subset"), - Arrays.asList(InventoryUtils.newItemStack(MicroblockProxy.itemMicro(), 1, i, ItemStackMap.WILDCARD_TAG))); + API.addSubset( + "Microblocks." + StatCollector.translateToLocal(mcrClass.getName() + "." + (i & 0xFF) + ".subset"), + Arrays.asList( + InventoryUtils.newItemStack(MicroblockProxy.itemMicro(), 1, i, ItemStackMap.WILDCARD_TAG))); } @Override @@ -41,4 +40,4 @@ public class NEI_MicroblockConfig implements IConfigureNEI public String getVersion() { return "1.0.0.0"; } -} \ No newline at end of file +} From 1ba2172e8a788a54d0c59b05ed9dbd1945b1399e Mon Sep 17 00:00:00 2001 From: Raven Szewczyk Date: Thu, 19 Jan 2023 17:12:21 +0000 Subject: [PATCH 3/3] Fix wrong asm types being used for TypeInsnNodes --- dependencies.gradle | 4 ++-- .../codechicken/multipart/asm/ASMMixinCompiler.scala | 4 ++-- .../scala/codechicken/multipart/asm/StackAnalyser.scala | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index 7a21ea2..908a5a2 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -1,6 +1,6 @@ // Add your dependencies here dependencies { - compile("com.github.GTNewHorizons:CodeChickenLib:1.1.5.5:dev") - compile("com.github.GTNewHorizons:NotEnoughItems:2.3.5-GTNH:dev") + compile("com.github.GTNewHorizons:CodeChickenLib:1.1.5.7:dev") + compile("com.github.GTNewHorizons:NotEnoughItems:2.3.20-GTNH:dev") } diff --git a/src/main/scala/codechicken/multipart/asm/ASMMixinCompiler.scala b/src/main/scala/codechicken/multipart/asm/ASMMixinCompiler.scala index c0f9eca..047525e 100644 --- a/src/main/scala/codechicken/multipart/asm/ASMMixinCompiler.scala +++ b/src/main/scala/codechicken/multipart/asm/ASMMixinCompiler.scala @@ -446,7 +446,7 @@ object ASMMixinCompiler } def staticTransform(mnode: MethodNode, base: MethodNode) { - val stack = new StackAnalyser(getType(cnode.name), base) + val stack = new StackAnalyser(getType(Type.getObjectType(cnode.name).getDescriptor), base) val insnList = mnode.instructions var insn = insnList.getFirst @@ -478,7 +478,7 @@ object ASMMixinCompiler //cast to parent class and call val mType = Type.getMethodType(minsn.desc) val instanceEntry = stack.peek(width(mType.getArgumentTypes)) - insnList.insert(instanceEntry.insn, new TypeInsnNode(CHECKCAST, cnode.superName)) + insnList.insert(instanceEntry.insn, new TypeInsnNode(CHECKCAST, Type.getObjectType(cnode.superName).getDescriptor)) minsn.owner = cnode.superName } } diff --git a/src/main/scala/codechicken/multipart/asm/StackAnalyser.scala b/src/main/scala/codechicken/multipart/asm/StackAnalyser.scala index 444e778..a34ed68 100644 --- a/src/main/scala/codechicken/multipart/asm/StackAnalyser.scala +++ b/src/main/scala/codechicken/multipart/asm/StackAnalyser.scala @@ -283,10 +283,10 @@ class StackAnalyser(val owner:Type, val m:MethodNode) } case tinsn:TypeInsnNode => ainsn.getOpcode match { - case NEW => push(New(getType(tinsn.desc))) - case NEWARRAY => push(NewArray(pop(), getType(tinsn.desc))) - case ANEWARRAY => push(NewArray(pop(), getType("["+tinsn.desc))) - case CHECKCAST => push(Cast(pop(), getType(tinsn.desc))) + case NEW => push(New(getObjectType(tinsn.desc))) + case NEWARRAY => push(NewArray(pop(), getObjectType(tinsn.desc))) + case ANEWARRAY => push(NewArray(pop(), getObjectType("["+tinsn.desc))) + case CHECKCAST => push(Cast(pop(), getObjectType(tinsn.desc))) case INSTANCEOF => push(UnaryOp(INSTANCEOF, pop())) } case mainsn:MultiANewArrayInsnNode =>