From 9333b91f5c4104e5c52e0af4d2a4aa80da87294b Mon Sep 17 00:00:00 2001 From: thedarkcolour <30441001+thedarkcolour@users.noreply.github.com> Date: Sun, 3 Nov 2019 13:59:32 -0800 Subject: Initial 1.14 release --- .gitignore | 25 +++ build.gradle | 137 ++++++++++++++++ file/1.14/kotlinforforge-0.1.14-sources.jar | Bin 0 -> 5809 bytes file/1.14/kotlinforforge-0.1.14.jar | Bin 0 -> 5761321 bytes gradle.properties | 7 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 54708 bytes gradle/wrapper/gradle-wrapper.properties | 6 + gradlew | 172 +++++++++++++++++++++ gradlew.bat | 84 ++++++++++ .../kotlinforforge/AutoKotlinEventBusSubscriber.kt | 90 +++++++++++ .../thedarkcolour/kotlinforforge/KotlinForForge.kt | 13 ++ .../kotlinforforge/KotlinLanguageProvider.kt | 42 +++++ .../kotlinforforge/KotlinModContainer.kt | 103 ++++++++++++ .../kotlinforforge/KotlinModLoadingContext.kt | 17 ++ src/main/resources/META-INF/mods.toml | 39 +++++ ...aftforge.forgespi.language.IModLanguageProvider | 1 + src/main/resources/pack.mcmeta | 7 + src/main/resources/patcher.js | 50 ++++++ 18 files changed, 793 insertions(+) create mode 100644 .gitignore create mode 100644 build.gradle create mode 100644 file/1.14/kotlinforforge-0.1.14-sources.jar create mode 100644 file/1.14/kotlinforforge-0.1.14.jar create mode 100644 gradle.properties create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 src/main/kotlin/thedarkcolour/kotlinforforge/AutoKotlinEventBusSubscriber.kt create mode 100644 src/main/kotlin/thedarkcolour/kotlinforforge/KotlinForForge.kt create mode 100644 src/main/kotlin/thedarkcolour/kotlinforforge/KotlinLanguageProvider.kt create mode 100644 src/main/kotlin/thedarkcolour/kotlinforforge/KotlinModContainer.kt create mode 100644 src/main/kotlin/thedarkcolour/kotlinforforge/KotlinModLoadingContext.kt create mode 100644 src/main/resources/META-INF/mods.toml create mode 100644 src/main/resources/META-INF/services/net.minecraftforge.forgespi.language.IModLanguageProvider create mode 100644 src/main/resources/pack.mcmeta create mode 100644 src/main/resources/patcher.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..12f8644 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +# eclipse +bin +*.launch +.settings +.metadata +.classpath +.project + +# idea +out +*.ipr +*.iws +*.iml +.idea + +# gradle +build +.gradle + +# other +eclipse +run + +# Files from Forge MDK +forge*changelog.txt diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..13de264 --- /dev/null +++ b/build.gradle @@ -0,0 +1,137 @@ +buildscript { + repositories { + maven { url = 'https://files.minecraftforge.net/maven' } + jcenter() + mavenCentral() + } + dependencies { + classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '3.+', changing: true + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlin_version}" + } +} +plugins { + id "org.jetbrains.kotlin.jvm" version "1.3.50" + id "com.github.johnrengelman.shadow" version "4.0.4" +} + +apply plugin: 'net.minecraftforge.gradle' +// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup. +apply plugin: 'maven-publish' +apply plugin: 'eclipse' +apply plugin: 'idea' +apply plugin: 'kotlin' + +version = '0.1.14' +group = 'thedarkcolour.kotlinforforge' // http://maven.apache.org/guides/mini/guide-naming-conventions.html +archivesBaseName = 'kotlinforforge' + +sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' + +tasks.build.dependsOn kotlinSourcesJar +tasks.build.dependsOn shadowJar + +minecraft { + mappings channel: 'snapshot', version: '20191019-1.14.3' + + runs { + client { + workingDirectory project.file('run') + + // Recommended logging data for a userdev environment + property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP' + + // Recommended logging level for the console + property 'forge.logging.console.level', 'debug' + + mods { + examplemod { + source sourceSets.main + } + } + } + + server { + workingDirectory project.file('run') + + // Recommended logging data for a userdev environment + property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP' + + // Recommended logging level for the console + property 'forge.logging.console.level', 'debug' + + mods { + examplemod { + source sourceSets.main + } + } + } + + data { + workingDirectory project.file('run') + + // Recommended logging data for a userdev environment + property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP' + + // Recommended logging level for the console + property 'forge.logging.console.level', 'debug' + + args '--mod', 'examplemod', '--all', '--output', file('src/generated/resources/') + + mods { + examplemod { + source sourceSets.main + } + } + } + } +} + +repositories { + +} + +dependencies { + minecraft 'net.minecraftforge:forge:1.14.4-28.1.74' + compile group: "org.jetbrains.kotlin", name: "kotlin-stdlib", version: kotlin_version + compile group: "org.jetbrains.kotlin", name: "kotlin-stdlib-jdk7", version: kotlin_version + compile group: "org.jetbrains.kotlin", name: "kotlin-stdlib-jdk8", version: kotlin_version + compile group: "org.jetbrains.kotlin", name: "kotlin-reflect", version: kotlin_version + compile group: "org.jetbrains", name: "annotations", version: annotations_version + compile group: "org.jetbrains.kotlinx", name: "kotlinx-coroutines-core", version: coroutines_version + compile group: "org.jetbrains.kotlinx", name: "kotlinx-coroutines-jdk8", version: coroutines_version +} + +shadowJar { + classifier = "" + dependencies { + include(dependency("org.jetbrains.kotlin:kotlin-stdlib:${kotlin_version}")) + include(dependency("org.jetbrains.kotlin:kotlin-stdlib-jdk7:${kotlin_version}")) + include(dependency("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlin_version}")) + include(dependency("org.jetbrains.kotlin:kotlin-reflect:${kotlin_version}")) + include(dependency("org.jetbrains:annotations:${annotations_version}")) + include(dependency("org.jetbrains.kotlinx:kotlinx-coroutines-core:${coroutines_version}")) + include(dependency("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:${coroutines_version}")) + } +} + +// Example configuration to allow publishing using the maven-publish task +// we define a custom artifact that is sourced from the reobfJar output task +// and then declare that to be published +// Note you'll need to add a repository hereI +def reobfFile = file("$buildDir/reobfJar/output.jar") +def reobfArtifact = artifacts.add('default', reobfFile) { + type 'jar' + builtBy 'reobfJar' +} +publishing { + publications { + mavenJava(MavenPublication) { + artifact reobfArtifact + } + } + repositories { + maven { + url "file:///${project.projectDir}/mcmodsrepo" + } + } +} \ No newline at end of file diff --git a/file/1.14/kotlinforforge-0.1.14-sources.jar b/file/1.14/kotlinforforge-0.1.14-sources.jar new file mode 100644 index 0000000..1feb9be Binary files /dev/null and b/file/1.14/kotlinforforge-0.1.14-sources.jar differ diff --git a/file/1.14/kotlinforforge-0.1.14.jar b/file/1.14/kotlinforforge-0.1.14.jar new file mode 100644 index 0000000..7cec72c Binary files /dev/null and b/file/1.14/kotlinforforge-0.1.14.jar differ diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..4a0ea15 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,7 @@ +# Sets default memory used for gradle commands. Can be overridden by user or command line properties. +# This is required to provide enough memory for the Minecraft decompilation process. +org.gradle.jvmargs=-Xmx3G +org.gradle.daemon=false +kotlin_version=1.3.50 +coroutines_version = 1.3.1 +annotations_version = 16.0.3 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7a3265e Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c7a095a --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Oct 19 12:21:43 PDT 2019 +distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..cccdd3d --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/kotlin/thedarkcolour/kotlinforforge/AutoKotlinEventBusSubscriber.kt b/src/main/kotlin/thedarkcolour/kotlinforforge/AutoKotlinEventBusSubscriber.kt new file mode 100644 index 0000000..b77a567 --- /dev/null +++ b/src/main/kotlin/thedarkcolour/kotlinforforge/AutoKotlinEventBusSubscriber.kt @@ -0,0 +1,90 @@ +package thedarkcolour.kotlinforforge + +import net.minecraftforge.api.distmarker.Dist +import net.minecraftforge.fml.Logging +import net.minecraftforge.fml.ModContainer +import net.minecraftforge.fml.common.Mod +import net.minecraftforge.fml.loading.FMLEnvironment +import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation +import net.minecraftforge.forgespi.language.ModFileScanData +import org.objectweb.asm.Type +import thedarkcolour.kotlinforforge.KotlinForForge.logger +import java.util.* +import java.util.stream.Collectors +import kotlin.reflect.full.companionObjectInstance + +/** + * Handles [net.minecraftforge.fml.common.Mod.EventBusSubscriber] + */ +@Suppress("unused") +object AutoKotlinEventBusSubscriber { + private val EVENT_BUS_SUBSCRIBER: Type = Type.getType(Mod.EventBusSubscriber::class.java) + + /** + * Registers Kotlin objects that are annotated with [Mod.EventBusSubscriber] + * This allows you to declare an object that subscribes to the event bus + * without making all the [net.minecraftforge.eventbus.api.SubscribeEvent] annotated with [JvmStatic] + * + * Example Usage: + * + * @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) + * public object ExampleSubscriber { + * @SubscribeEvent + * public fun onItemRegistry(event: RegistryEvent.Register) { + * println("Look! We're in items :)") + * } + * } + * + * This also works with companion objects. + * You must define the [net.minecraftforge.eventbus.api.SubscribeEvent] methods inside the companion object. + * Example Usage: + * + * @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) + * public class ExampleSubscriberClass { + * + * companion object ExampleSubscriberCompanion { + * @SubscribeEvent + * public fun onItemRegistry(event: RegistryEvent.Register) { + * println("Look! We're in items :)") + * } + * } + * } + */ + @Suppress("UNCHECKED_CAST", "unused") + fun inject(mod: ModContainer, scanData: ModFileScanData, classLoader: ClassLoader) { + logger.debug(Logging.LOADING, "Attempting to inject @EventBusSubscriber kotlin objects in to the event bus for {}", mod.modId) + val data: ArrayList = scanData.annotations.stream() + .filter { annotationData -> + EVENT_BUS_SUBSCRIBER == annotationData.annotationType + } + .collect(Collectors.toList()) as ArrayList + data.forEach { annotationData -> + val sidesValue: List = annotationData.annotationData.getOrDefault("value", listOf(ModAnnotation.EnumHolder(null, "CLIENT"), ModAnnotation.EnumHolder(null, "DEDICATED_SERVER"))) as List + val sides: EnumSet = sidesValue.stream().map { eh -> Dist.valueOf(eh.value) } + .collect(Collectors.toCollection { EnumSet.noneOf(Dist::class.java) }) + val modid = annotationData.annotationData.getOrDefault("modid", mod.modId) + val busTargetHolder: ModAnnotation.EnumHolder = annotationData.annotationData.getOrDefault("bus", ModAnnotation.EnumHolder(null, "FORGE")) as ModAnnotation.EnumHolder + val busTarget = Mod.EventBusSubscriber.Bus.valueOf(busTargetHolder.value) + val clazz = Class.forName(annotationData.classType.className, true, classLoader) + val ktClass = clazz.kotlin + val ktObject = ktClass.objectInstance + if (ktObject != null && mod.modId == modid && sides.contains(FMLEnvironment.dist)) { + try { + logger.debug(Logging.LOADING, "Auto-subscribing kotlin object {} to {}", annotationData.classType.className, busTarget) + busTarget.bus().get().register(ktObject) + } catch (e: Throwable) { + logger.fatal(Logging.LOADING, "Failed to load mod class {} for @EventBusSubscriber annotation", annotationData.classType, e) + throw RuntimeException(e) + } + } else if (ktClass.companionObjectInstance != null) { + try { + logger.debug(Logging.LOADING, "Auto-subscribing kotlin companion object from {} to {}", ktClass.simpleName, busTarget) + busTarget.bus().get().register(ktClass.companionObjectInstance) + } catch (e: Throwable) { + logger.fatal(Logging.LOADING, "Failed to load kotlin companion object {} for @EventBusSubscriber annotation", annotationData.classType, e) + throw RuntimeException(e) + } + } + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinForForge.kt b/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinForForge.kt new file mode 100644 index 0000000..e697f10 --- /dev/null +++ b/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinForForge.kt @@ -0,0 +1,13 @@ +package thedarkcolour.kotlinforforge + +import net.minecraftforge.fml.common.Mod +import org.apache.logging.log4j.LogManager +import org.apache.logging.log4j.Logger + +/** + * Set 'modLoader' in mods.toml to "kotlinforforge". + */ +@Mod("kotlinforforge") +object KotlinForForge { + internal val logger: Logger = LogManager.getLogger() +} \ No newline at end of file diff --git a/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinLanguageProvider.kt b/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinLanguageProvider.kt new file mode 100644 index 0000000..e860497 --- /dev/null +++ b/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinLanguageProvider.kt @@ -0,0 +1,42 @@ +package thedarkcolour.kotlinforforge + +import net.minecraftforge.fml.Logging +import net.minecraftforge.fml.javafmlmod.FMLJavaModLanguageProvider +import net.minecraftforge.forgespi.language.ILifecycleEvent +import net.minecraftforge.forgespi.language.IModInfo +import net.minecraftforge.forgespi.language.IModLanguageProvider +import net.minecraftforge.forgespi.language.ModFileScanData +import java.util.function.BinaryOperator +import java.util.function.Consumer +import java.util.function.Function +import java.util.function.Supplier +import java.util.stream.Collectors + +class KotlinLanguageProvider : FMLJavaModLanguageProvider() { + override fun getFileVisitor(): Consumer { + return Consumer { scanResult -> + val target = scanResult.annotations.stream() + .filter {data -> data.annotationType == MODANNOTATION } + .peek { data -> KotlinForForge.logger.debug(Logging.SCAN, "Found @Mod class {} with id {}", data.classType.className, data.annotationData["value"]) } + .map { data -> KotlinModTarget(data.classType.className, data.annotationData["value"] as String) } + .collect(Collectors.toMap(Function { target: KotlinModTarget -> return@Function target.modId }, Function {return@Function it}, BinaryOperator { a, _ -> a })) + scanResult.addLanguageLoader(target) + } + } + + override fun ?> consumeLifecycleEvent(consumeEvent: Supplier?) {} + + override fun name(): String { + return "kotlinforforge" + } + + internal class KotlinModTarget internal constructor(private val className: String, val modId: String) : IModLanguageProvider.IModLanguageLoader { + @Suppress("UNCHECKED_CAST") + override fun loadMod(info: IModInfo, modClassLoader: ClassLoader, modFileScanResults: ModFileScanData): T { + val ktContainer = Class.forName("thedarkcolour.kotlinforforge.KotlinModContainer", true, Thread.currentThread().contextClassLoader) + KotlinForForge.logger.debug(Logging.LOADING, "Loading KotlinModContainer from classloader {} - got {}", Thread.currentThread().contextClassLoader, ktContainer.classLoader) + val constructor = ktContainer.getConstructor(IModInfo::class.java, String::class.java, ClassLoader::class.java, ModFileScanData::class.java)!! + return constructor.newInstance(info, className, modClassLoader, modFileScanResults) as T + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinModContainer.kt b/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinModContainer.kt new file mode 100644 index 0000000..26a65ea --- /dev/null +++ b/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinModContainer.kt @@ -0,0 +1,103 @@ +package thedarkcolour.kotlinforforge + +import net.minecraftforge.eventbus.EventBusErrorMessage +import net.minecraftforge.eventbus.api.BusBuilder +import net.minecraftforge.eventbus.api.Event +import net.minecraftforge.eventbus.api.IEventBus +import net.minecraftforge.eventbus.api.IEventListener +import net.minecraftforge.fml.* +import net.minecraftforge.forgespi.language.IModInfo +import net.minecraftforge.forgespi.language.ModFileScanData +import org.apache.logging.log4j.LogManager +import java.util.* +import java.util.function.Consumer +import java.util.function.Supplier + +@Suppress("UNUSED_PARAMETER") +class KotlinModContainer(info: IModInfo, className: String, loader: ClassLoader, private val scanData: ModFileScanData) : ModContainer(info) { + private lateinit var modInstance: Any + private val modClass: Class<*> + val eventBus: IEventBus + + // Use a separate logger because KotlinForForge.logger isn't initialized yet + private val logger = LogManager.getLogger() + + init { + logger.debug(Logging.LOADING, "Creating KotlinModContainer instance for {} with classLoader {} & {}", className, loader, javaClass.classLoader) + triggerMap[ModLoadingStage.CONSTRUCT] = dummy().andThen { beforeEvent(it) }.andThen { constructMod(it) }.andThen{ afterEvent(it) } + triggerMap[ModLoadingStage.CREATE_REGISTRIES] = dummy().andThen { beforeEvent(it) }.andThen { fireEvent(it) }.andThen{ afterEvent(it) } + triggerMap[ModLoadingStage.LOAD_REGISTRIES] = dummy().andThen { beforeEvent(it) }.andThen { fireEvent(it) }.andThen{ afterEvent(it) } + triggerMap[ModLoadingStage.COMMON_SETUP] = dummy().andThen { beforeEvent(it) }.andThen { preinitMod(it) }.andThen{ fireEvent(it) }.andThen { this.afterEvent(it) } + triggerMap[ModLoadingStage.SIDED_SETUP] = dummy().andThen { beforeEvent(it)}.andThen { fireEvent(it) }.andThen { afterEvent(it) } + triggerMap[ModLoadingStage.ENQUEUE_IMC] = dummy().andThen { beforeEvent(it)}.andThen { initMod(it) }.andThen{ fireEvent(it) }.andThen{ this.afterEvent(it) } + triggerMap[ModLoadingStage.PROCESS_IMC] = dummy().andThen { beforeEvent(it) }.andThen { fireEvent(it) }.andThen{ afterEvent(it) } + triggerMap[ModLoadingStage.COMPLETE] = dummy().andThen { beforeEvent(it) }.andThen { completeLoading(it) }.andThen{ fireEvent(it) }.andThen { this.afterEvent(it) } + triggerMap[ModLoadingStage.GATHERDATA] = dummy().andThen { beforeEvent(it) }.andThen { fireEvent(it) }.andThen{ afterEvent(it) } + eventBus = BusBuilder.builder().setExceptionHandler{ bus, event, listeners, index, throwable -> onEventFailed(bus, event, listeners, index, throwable) }.setTrackPhases(false).build() + configHandler = Optional.of(Consumer {event -> eventBus.post(event)}) + val ctx = KotlinModLoadingContext(this) + contextExtension = Supplier { return@Supplier ctx} + try { + modClass = Class.forName(className, true, loader) + logger.debug(Logging.LOADING, "Loaded kotlin modclass {} with {}", modClass.name, modClass.classLoader) + } catch (e: Throwable) { + logger.error(Logging.LOADING, "Failed to load kotlin class {}", className, e) + throw ModLoadingException(info, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmodclass", e) + } + } + + private fun completeLoading(lifecycleEvent: LifecycleEventProvider.LifecycleEvent) {} + private fun initMod(lifecycleEvent: LifecycleEventProvider.LifecycleEvent) {} + private fun dummy(): Consumer = Consumer {} + private fun onEventFailed(iEventBus: IEventBus, event: Event, iEventListeners: Array, i: Int, throwable: Throwable) = logger.error(EventBusErrorMessage(event, i, iEventListeners, throwable)) + private fun beforeEvent(lifecycleEvent: LifecycleEventProvider.LifecycleEvent) {} + + private fun fireEvent(lifecycleEvent: LifecycleEventProvider.LifecycleEvent) { + val event = lifecycleEvent.getOrBuildEvent(this) + logger.debug(Logging.LOADING, "Firing event for modid {} : {}", this.getModId(), event) + try { + + } catch (e: Throwable) { + logger.error(Logging.LOADING,"An error occurred while dispatching event {} to {}", lifecycleEvent.fromStage(), modId) + throw ModLoadingException(modInfo, lifecycleEvent.fromStage(), "fml.modloading.errorduringevent", e) + } + } + + private fun afterEvent(lifecycleEvent: LifecycleEventProvider.LifecycleEvent) { + if (currentState == ModLoadingStage.ERROR) { + logger.error(Logging.LOADING, "An error occurred while dispatching event {} to {}", lifecycleEvent.fromStage(), modId) + } + } + + private fun preinitMod(lifecycleEvent: LifecycleEventProvider.LifecycleEvent) {} + + private fun constructMod(lifecycleEvent: LifecycleEventProvider.LifecycleEvent) { + try { + logger.debug(Logging.LOADING, "Loading mod instance {} of type {}", getModId(), modClass.name) + modInstance = modClass.kotlin.objectInstance ?: modClass.newInstance() + logger.debug(Logging.LOADING, "Loaded mod instance {} of type {}", getModId(), modClass.name) + } catch (e: Throwable) { + logger.error(Logging.LOADING, "Failed to create mod instance. ModID: {}, class {}", getModId(), modClass.name, e) + throw ModLoadingException(modInfo, lifecycleEvent.fromStage(), "fml.modloading.failedtoloadmod", e, modClass) + } + + try { + logger.debug(Logging.LOADING, "Injecting Automatic event subscribers for {}", getModId()) + // Inject into object EventBusSubscribers + AutoKotlinEventBusSubscriber.inject(this, scanData, modClass.classLoader) + logger.debug(Logging.LOADING, "Completed Automatic event subscribers for {}", getModId()) + } catch (e: Throwable) { + logger.error(Logging.LOADING, "Failed to register automatic subscribers. ModID: {}, class {}", getModId(), modClass.name, e) + throw ModLoadingException(modInfo, lifecycleEvent.fromStage(), "fml.modloading.failedtoloadmod", e, modClass) + } + + } + + override fun getMod(): Any { + return modInstance + } + + override fun matches(mod: Any?): Boolean { + return mod == modInstance + } +} \ No newline at end of file diff --git a/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinModLoadingContext.kt b/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinModLoadingContext.kt new file mode 100644 index 0000000..4b7edc0 --- /dev/null +++ b/src/main/kotlin/thedarkcolour/kotlinforforge/KotlinModLoadingContext.kt @@ -0,0 +1,17 @@ +package thedarkcolour.kotlinforforge + +import net.minecraftforge.eventbus.api.IEventBus +import net.minecraftforge.fml.ModLoadingContext + +class KotlinModLoadingContext internal constructor(private val container: KotlinModContainer) { + fun getEventBus(): IEventBus { + return container.eventBus + } + + companion object { + @JvmStatic + fun get() { + return ModLoadingContext.get().extension() + } + } +} \ No newline at end of file diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml new file mode 100644 index 0000000..ff8cd97 --- /dev/null +++ b/src/main/resources/META-INF/mods.toml @@ -0,0 +1,39 @@ +modLoader="kotlinforforge" # IModLanguageProvider +loaderVersion="[25,)" # IModLanguageProvider version + +issueTrackerURL="https://github.com/thedarkcolour/Future-MC/issues" # Issues page + + +#displayURL="https://minecraft.curseforge.com/projects/kotlinforforge" #optional + +description=''' +Kotlin for Forge. Allows mods to use the Kotlin programming language. +''' # A description + +# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional. +[[dependencies.kotlinforforge]] #optional + modId="forge" #mandatory + mandatory=true #mandatory + versionRange="[25,)" #mandatory + # An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory + ordering="NONE" + + side="BOTH" +# Dependency +[[dependencies.kotlinforforge]] + modId="minecraft" + mandatory=true + versionRange="[1.14.4]" + ordering="NONE" + side="BOTH" + +# --------------------------------------------------------- # +# --------------------------------------------------------- # +# --------------------------------------------------------- # + +[[mods]] #mandatory +displayName="Kotlin for Forge" # Name of mod +modId="kotlinforforge" # Modid +version="1.0.0" # Version of kotlinforforge +authors="TheDarkColour" # Author +credits="Herobrine knows all." # Credits \ No newline at end of file diff --git a/src/main/resources/META-INF/services/net.minecraftforge.forgespi.language.IModLanguageProvider b/src/main/resources/META-INF/services/net.minecraftforge.forgespi.language.IModLanguageProvider new file mode 100644 index 0000000..c78667e --- /dev/null +++ b/src/main/resources/META-INF/services/net.minecraftforge.forgespi.language.IModLanguageProvider @@ -0,0 +1 @@ +thedarkcolour.kotlinforforge.KotlinLanguageProvider diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..167eba8 --- /dev/null +++ b/src/main/resources/pack.mcmeta @@ -0,0 +1,7 @@ +{ + "pack": { + "description": "kotlinforforge resources", + "pack_format": 4, + "_comment": "A pack_format of 4 requires json lang files. Note: we require v4 pack meta for all mods." + } +} \ No newline at end of file diff --git a/src/main/resources/patcher.js b/src/main/resources/patcher.js new file mode 100644 index 0000000..fcfe312 --- /dev/null +++ b/src/main/resources/patcher.js @@ -0,0 +1,50 @@ +function initializeCoreMod() { +// Unused, remove + return { + 'KotlinPatcher': { + 'target': { + 'type': 'METHOD', + 'class': 'net.minecraftforge.fml.javafmlmod.FMLModContainer', + 'methodName': 'constructMod', + 'methodDesc': '(Lnet/minecraftforge/fml/LifecycleEventProvider$LifecycleEvent;)V' + }, + 'transformer': function (methodNode) { + var VarInsnNode = Java.type('org.objectweb.asm.tree.VarInsnNode'); + var FieldInsnNode = Java.type('org.objectweb.asm.tree.FieldInsnNode'); + var MethodInsnNode = Java.type('org.objectweb.asm.tree.MethodInsnNode'); + var InsnList = Java.type('org.objectweb.asm.tree.InsnList'); + var Opcodes = Java.type('org.objectweb.asm.Opcodes'); + var list = new InsnList(); + list.add(new FieldInsnNode(Opcodes.GETSTATIC, "thedarkcolour/kotlinforforge/AutoKotlinEventBusSubscriber", "INSTANCE", "Lthedarkcolour/kotlinforforge/AutoKotlinEventBusSubscriber;")); + list.add(new VarInsnNode(Opcodes.ALOAD, 0)); + list.add(new VarInsnNode(Opcodes.ALOAD, 0)); + list.add(new FieldInsnNode(Opcodes.GETFIELD, 'net/minecraftforge/fml/javafmlmod/FMLModContainer', 'scanResults', 'Lnet/minecraftforge/forgespi/language/ModFileScanData;')); + list.add(new VarInsnNode(Opcodes.ALOAD, 0)); + list.add(new FieldInsnNode(Opcodes.GETFIELD, 'net/minecraftforge/fml/javafmlmod/FMLModContainer', 'modClass', 'Ljava/lang/Class;')); + list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, 'java/lang/Class', 'getClassLoader', '()Ljava/lang/ClassLoader;', false)); + list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "thedarkcolour/kotlinforforge/AutoKotlinEventBusSubscriber", "inject", "(Lnet/minecraftforge/fml/ModContainer;Lnet/minecraftforge/forgespi/language/ModFileScanData;Ljava/lang/ClassLoader;)V", false)); + + for (var i = 0; i < 1000; ++i) { + var insn = methodNode.instructions.get(i); + //print('bruh moment'); + if (insn instanceof MethodInsnNode) { + //print('FOUND A METHODINSNNODE'); + if (insn.desc === '(Lnet/minecraftforge/fml/ModContainer;Lnet/minecraftforge/forgespi/language/ModFileScanData;Ljava/lang/ClassLoader;)V') { + methodNode.instructions.insertBefore(insn.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getPrevious(), list); + //print('PATCHED FMLMODCONTAINER'); + break; + } + } + } + + //var writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); + //methodNode.accept(writer); + //var reader = new ClassReader(writer.toByteArray()); + //var cn = new ClassNode(); + //reader.accept(cn, 0); + + return methodNode; + } + } + } +} \ No newline at end of file -- cgit