diff --git a/.github/workflows/lifecycle.yml b/.github/workflows/lifecycle.yml index ccd658a..d36eec3 100644 --- a/.github/workflows/lifecycle.yml +++ b/.github/workflows/lifecycle.yml @@ -91,6 +91,7 @@ jobs: build_data = [ {"dir": "api", "java": "8"}, + {"dir": "1_21_6", "mc": "1.21.6", "lex": "56.0.9", "neo": "19-beta", "java": "21"}, {"dir": "1_21_5", "mc": "1.21.5", "lex": "55.0.3", "neo": "24-beta", "java": "21"}, {"dir": "1_21", "mc": "1.21.4", "lex": "54.0.16", "neo": "50-beta", "java": "21"}, {"dir": "1_21", "mc": "1.21.3", "lex": "53.0.7", "neo": "11-beta", "java": "21"}, @@ -115,6 +116,9 @@ jobs: ] run_data = [ + {"mc": "1.21.6", "type": "lexforge", "modloader": "forge", "regex": ".*forge.*", "java": "21"}, + {"mc": "1.21.6", "type": "neoforge", "modloader": "neoforge", "regex": ".*neoforge.*", "java": "21"}, + {"mc": "1.21.6", "type": "fabric", "modloader": "fabric", "regex": ".*fabric.*", "java": "21"}, {"mc": "1.21.5", "type": "lexforge", "modloader": "forge", "regex": ".*forge.*", "java": "21"}, {"mc": "1.21.5", "type": "neoforge", "modloader": "neoforge", "regex": ".*neoforge.*", "java": "21"}, {"mc": "1.21.5", "type": "fabric", "modloader": "fabric", "regex": ".*fabric.*", "java": "21"}, diff --git a/1_21_5/build.gradle b/1_21_5/build.gradle index 4681d57..14171eb 100644 --- a/1_21_5/build.gradle +++ b/1_21_5/build.gradle @@ -4,7 +4,7 @@ plugins { id 'com.github.johnrengelman.shadow' version '7.1.2' id 'java' id 'maven-publish' - id 'xyz.wagyourtail.unimined' version '1.3.10-SNAPSHOT' + id 'xyz.wagyourtail.unimined' version '1.3.14' } group 'me.earth' diff --git a/1_21_6/.gitignore b/1_21_6/.gitignore new file mode 100644 index 0000000..10db306 --- /dev/null +++ b/1_21_6/.gitignore @@ -0,0 +1,43 @@ +# gradle + +.gradle/ +build/ +out/ +classes/ + +# eclipse + +*.launch + +# idea + +.idea/ +*.iml +*.ipr +*.iws + +# vscode + +.settings/ +.vscode/ +bin/ +.classpath +.project + +# macos + +*.DS_Store + +# fabric + +run/ + +# java + +hs_err_*.log +replay_*.log +*.hprof +*.jfr +/libs/ +/logs/ +/.architectury-transformer/ diff --git a/1_21_6/build.gradle b/1_21_6/build.gradle new file mode 100644 index 0000000..14171eb --- /dev/null +++ b/1_21_6/build.gradle @@ -0,0 +1,251 @@ +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar + +plugins { + id 'com.github.johnrengelman.shadow' version '7.1.2' + id 'java' + id 'maven-publish' + id 'xyz.wagyourtail.unimined' version '1.3.14' +} + +group 'me.earth' +version "$minecraft_version-${project(':api').project_version}" + +base { + archivesName = 'mc-runtime-test' +} + +sourceSets { + fabric + neoforge + lexforge +} + +repositories { + mavenCentral() + maven { + url = "https://maven.neoforged.net/releases" + } + maven { + url = "https://maven.fabricmc.net/" + } + maven { + url = "https://files.minecraftforge.net/maven" + } + maven { + name = "sponge" + url = "https://repo.spongepowered.org/maven" + } + maven { + url = "https://maven.wagyourtail.xyz/releases" + } + + maven { + name = '3arthMaven' + url = 'https://3arthqu4ke.github.io/maven' + } +} + +unimined.minecraft { + version project.minecraft_version + + mappings { + mojmap() + // intermediary() + // yarn(1) + + devFallbackNamespace "mojmap" + + /*stub.withMappings("intermediary", ["yarn"]) { + c("net/minecraft/class_1927", []) { + m("method_55109", "()Lnet/minecraft/class_243;", ["getPos"]) + } + }*/ + } + + defaultRemapJar = false +} + +unimined.minecraft(sourceSets.fabric) { + combineWith(sourceSets.main) + + fabric { + loader project.fabric_version + } + + defaultRemapJar = true +} + +unimined.minecraft(sourceSets.neoforge) { + combineWith(sourceSets.main) + + neoForged { + loader project.neoforge_version + mixinConfig 'mc_runtime_test.mixins.json' + } + + minecraftRemapper.config { + // neoforge adds 1 conflict, where 2 interfaces have a method with the same name on yarn/mojmap, + // but the method has different names in the intermediary mappings. + // this is a conflict because they have a class that extends both interfaces. + // this shouldn't be a problem as long as named mappings don't make the name of those 2 methods different. + ignoreConflicts(true) + } + + defaultRemapJar = true +} + +unimined.minecraft(sourceSets.lexforge) { + combineWith(sourceSets.main) + + minecraftForge { + loader project.lexforge_version + mixinConfig 'mc_runtime_test.mixins.json' + } + + minecraftRemapper.config { + ignoreConflicts(true) + } + + defaultRemapJar = true +} + +configurations { + mainImplementation + lwjglAgent.extendsFrom runtimeOnly + jarLibs + implementation.extendsFrom jarLibs +} + +for (String platform_capitalized : ['Fabric', 'Neoforge', 'Lexforge']) { + def platform = platform_capitalized.toLowerCase() + def remapJarTask = tasks.named("remap${platform_capitalized}Jar", AbstractArchiveTask).get() + def shadowTask = tasks.register("${platform}ShadowJar", ShadowJar) { + dependsOn(remapJarTask) + it.group = 'build' + it.archiveClassifier = "${platform}-release" + from remapJarTask.outputs + it.configurations += [ project.configurations.jarLibs ] + exclude "**/module-info.class" + } + tasks.named('build') { finalizedBy(shadowTask) } +} + +dependencies { + compileOnly 'org.spongepowered:mixin:0.8.5-SNAPSHOT' + compileOnly 'me.earth.headlessmc:headlessmc:1.8.1' + lwjglAgent 'me.earth.headlessmc:headlessmc-lwjgl:1.8.1' + // yes, I actually want this at runtime to use assertions! + jarLibs 'org.junit.jupiter:junit-jupiter-api:5.10.1' + jarLibs project(':api') +} + +afterEvaluate { + fabricRunClient { + standardInput = System.in + if (rootProject.property('hmc.lwjgl').toBoolean()) { + jvmArgs += ["-javaagent:${configurations.lwjglAgent.files.iterator().next()}"] + systemProperties['joml.nounsafe'] = 'true' + systemProperties['fabric.systemLibraries'] = "${configurations.lwjglAgent.files.iterator().next()}" + } + } +} + +processFabricResources { + inputs.property "version", project.version + + filesMatching("fabric.mod.json") { + expand "version": project.version + } +} + +processNeoforgeResources { + inputs.property "version", project.version + + filesMatching("META-INF/neoforge.mods.toml") { + expand "version": project.version + } +} + +processLexforgeResources { + inputs.property "version", project.version + + filesMatching("META-INF/mods.toml") { + expand "version": project.version + } +} + +// Forge Runs seem to have problems running from the build/classes folder +// So instead we just run from the built jar +afterEvaluate { + lexforgeRunClient { + dependsOn(lexforgeJar) + classpath = classpath.filter { + !it.toString().contains('mc-runtime-test/build/classes/java/'.replace('/', File.separator)) + && !it.toString().contains('mc-runtime-test/build/resources/'.replace('/', File.separator)) + } + + classpath += files("${projectDir}/build/libs/mc-runtime-test-${version}-lexforge-dev.jar".replace('/', File.separator)) + } + + neoforgeRunClient { + dependsOn(neoforgeJar) + classpath = classpath.filter { + !it.toString().contains('mc-runtime-test/build/classes/java/'.replace('/', File.separator)) + && !it.toString().contains('mc-runtime-test/build/resources/'.replace('/', File.separator)) + } + + classpath += files("${projectDir}/build/libs/mc-runtime-test-${version}-neoforge-dev.jar".replace('/', File.separator)) + } +} + +tasks.withType(org.gradle.jvm.tasks.Jar).configureEach { + from("LICENSE") { + duplicatesStrategy = DuplicatesStrategy.INCLUDE + rename { "${it}_${project.archivesBaseName}" } + } + + manifest { + attributes( + 'Implementation-Title': 'MC-Runtime-Test', + 'MixinConfigs': "mc_runtime_test.mixins.json", + 'Implementation-Version': project.version, + ) + } +} + +afterEvaluate { + publishing { + publications { + "${name.toLowerCase()}"(MavenPublication) { + ((MavenPublication) it).groupId "${group}" + ((MavenPublication) it).artifactId "${archivesBaseName.toLowerCase()}" + ((MavenPublication) it).version "${version}" + from components.java + for (String platform: ['Fabric', 'Lexforge', 'Neoforge']) { + String platform_lower = platform.toLowerCase() + artifact tasks.named("${platform_lower}Jar").get() + artifact tasks.named("remap${platform}Jar").get() + artifact tasks.named("${platform_lower}ShadowJar").get() + } + } + } + + repositories { + if (System.getenv('DEPLOY_TO_GITHUB_PACKAGES_URL') == null) { + maven { + name = 'BuildDirMaven' + url = rootProject.projectDir.toPath().parent.resolve('build').resolve('maven') + } + } else { + maven { + name = 'GithubPagesMaven' + url = System.getenv('DEPLOY_TO_GITHUB_PACKAGES_URL') + credentials { + username = System.getenv('GITHUB_USER') + password = System.getenv('GITHUB_TOKEN') + } + } + } + } + } +} diff --git a/1_21_6/gradle.properties b/1_21_6/gradle.properties new file mode 100644 index 0000000..05b0ef8 --- /dev/null +++ b/1_21_6/gradle.properties @@ -0,0 +1,10 @@ +org.gradle.jvmargs = -Xmx2G + +minecraft_version = 1.21.6 +# TODO: can this be removed? +mapping_version = 1 +neoforge_version = 19-beta +lexforge_version = 56.0.9 +fabric_version = 0.15.9 +# Whether to use the headlessmc lwjgl agent or not +hmc.lwjgl=false diff --git a/1_21_6/gradle/wrapper/gradle-wrapper.jar b/1_21_6/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 Binary files /dev/null and b/1_21_6/gradle/wrapper/gradle-wrapper.jar differ diff --git a/1_21_6/gradle/wrapper/gradle-wrapper.properties b/1_21_6/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a8382d7 --- /dev/null +++ b/1_21_6/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists \ No newline at end of file diff --git a/1_21_6/gradlew b/1_21_6/gradlew new file mode 100755 index 0000000..79a61d4 --- /dev/null +++ b/1_21_6/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/1_21_6/gradlew.bat b/1_21_6/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/1_21_6/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@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=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +: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 %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/1_21_6/settings.gradle b/1_21_6/settings.gradle new file mode 100644 index 0000000..e17fb98 --- /dev/null +++ b/1_21_6/settings.gradle @@ -0,0 +1,33 @@ +pluginManagement { + repositories { + mavenCentral() + maven { + url = "https://maven.neoforged.net/releases" + } + maven { + url = "https://maven.minecraftforge.net/" + } + maven { + url = "https://maven.fabricmc.net/" + } + maven { + url = "https://maven.wagyourtail.xyz/releases" + } + maven { + url 'https://3arthqu4ke.github.io/maven' + } + maven { + url = "https://maven.wagyourtail.xyz/snapshots" + } + gradlePluginPortal() { + content { + excludeGroup("org.apache.logging.log4j") + } + } + } +} + +include 'api' +project(':api').projectDir = file('../api') + +rootProject.name = 'mc-runtime-test' \ No newline at end of file diff --git a/1_21_6/src/fabric/resources/fabric.mod.json b/1_21_6/src/fabric/resources/fabric.mod.json new file mode 100644 index 0000000..2a0abd8 --- /dev/null +++ b/1_21_6/src/fabric/resources/fabric.mod.json @@ -0,0 +1,28 @@ +{ + "schemaVersion": 1, + "id": "mc_runtime_test", + "version": "${version}", + + "name": "MC-Runtime-Test", + "description": "Run tests on the Minecraft client at runtime", + "authors": [ + "3arthqu4ke" + ], + "contact": { + "homepage": "https://github.com/headlesshq/mc-runtime-test", + "sources": "https://github.com/headlesshq/mc-runtime-test" + }, + + "license": "MIT", + + "environment": "*", + "mixins": [ + "mc_runtime_test.mixins.json" + ], + + "depends": { + "fabricloader": ">=0.14.19", + "minecraft": "~1.21.0", + "java": ">=8" + } +} diff --git a/1_21_6/src/lexforge/java/me/earth/mc_runtime_test/forge/ForgeMod.java b/1_21_6/src/lexforge/java/me/earth/mc_runtime_test/forge/ForgeMod.java new file mode 100644 index 0000000..d21a353 --- /dev/null +++ b/1_21_6/src/lexforge/java/me/earth/mc_runtime_test/forge/ForgeMod.java @@ -0,0 +1,8 @@ +package me.earth.mc_runtime_test.forge; + +import net.minecraftforge.fml.common.Mod; + +@Mod("mc_runtime_test") +public class ForgeMod { + +} diff --git a/1_21_6/src/lexforge/resources/META-INF/mods.toml b/1_21_6/src/lexforge/resources/META-INF/mods.toml new file mode 100644 index 0000000..52a169f --- /dev/null +++ b/1_21_6/src/lexforge/resources/META-INF/mods.toml @@ -0,0 +1,20 @@ +modLoader = "javafml" +loaderVersion = "[1,)" +issueTrackerURL = "https://github.com/headlesshq/mc-runtime-test" +license = "MIT" + +[[mods]] +modId = "mc_runtime_test" +version = "${version}" +displayName = "MC-Runtime-Test" +authors = "3arthqu4ke" +description = ''' + Run tests on the Minecraft client at runtime +''' + +[[dependencies.mc_runtime_test]] +modId = "minecraft" +mandatory = true +versionRange = "[1.21.0,)" +ordering = "NONE" +side = "BOTH" diff --git a/1_21_6/src/lexforge/resources/pack.mcmeta b/1_21_6/src/lexforge/resources/pack.mcmeta new file mode 100644 index 0000000..d2b91b6 --- /dev/null +++ b/1_21_6/src/lexforge/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "mc_runtime_test resources", + "pack_format": 6 + } +} \ No newline at end of file diff --git a/1_21_6/src/main/java/me/earth/mc_runtime_test/McGameTestRunner.java b/1_21_6/src/main/java/me/earth/mc_runtime_test/McGameTestRunner.java new file mode 100644 index 0000000..51bc2ce --- /dev/null +++ b/1_21_6/src/main/java/me/earth/mc_runtime_test/McGameTestRunner.java @@ -0,0 +1,99 @@ +package me.earth.mc_runtime_test; + +import com.mojang.brigadier.Command; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.logging.LogUtils; +import net.minecraft.commands.CommandSource; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.core.Holder; +import net.minecraft.gametest.framework.*; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.block.Rotation; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; + +import java.util.Collection; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; + +/** + * Similar to running the "/test runall" command. + */ +public class McGameTestRunner { + private static final Logger LOGGER = LogUtils.getLogger(); + + /** + * Basically what happens in {@link TestCommand} when "runall" is used. + * We just exit with an error code if a test fails. + * + * @param playerUUID the uuid of the player. + * @param server the server to run the tests on. + */ + public static @Nullable MultipleTestTracker runGameTests(UUID playerUUID, MinecraftServer server) throws ExecutionException, InterruptedException, TimeoutException { + return server.submit(() -> { + Player player = Objects.requireNonNull(server.getPlayerList().getPlayer(playerUUID)); + ServerLevel level = (ServerLevel) player.level(); + GameTestRunner.clearMarkers(level); + + AtomicReference> result = new AtomicReference<>(); + CommandDispatcher dispatcher = new CommandDispatcher<>(); + dispatcher.register(Commands.literal("test").executes(ctx -> { + Collection> testFunctions = TestFinder.builder().allNearby(ctx).findTests().toList(); + LOGGER.info("TestFunctions: " + testFunctions); + if (testFunctions.size() < McRuntimeTest.MIN_GAME_TESTS_TO_FIND) { + LOGGER.error("Failed to find the minimum amount of gametests, expected " + McRuntimeTest.MIN_GAME_TESTS_TO_FIND + ", but found " + testFunctions.size()); + throw new IllegalStateException("Failed to find the minimum amount of gametests, expected " + McRuntimeTest.MIN_GAME_TESTS_TO_FIND + ", but found " + testFunctions.size()); + } else if (testFunctions.isEmpty()) { + result.set(Optional.empty()); + return Command.SINGLE_SUCCESS; + } + + GameTestBatchFactory.TestDecorator testDecorator = (reference, serverLevel) -> Stream.of( + new GameTestInfo(reference, Rotation.NONE, serverLevel, RetryOptions.noRetries()) + ); + Collection batches = GameTestBatchFactory.divideIntoBatches(testFunctions, testDecorator, ctx.getSource().getLevel()); + + + FailedTestTracker.forgetFailedTests(); + + GameTestRunner gameTestRunner = GameTestRunner.Builder.fromBatches(batches, level).build(); + gameTestRunner.start(); + + MultipleTestTracker multipleTestTracker = new MultipleTestTracker(gameTestRunner.getTestInfos()); + multipleTestTracker.addFailureListener(gameTestInfo -> { + LOGGER.error("Test failed: " + gameTestInfo); + if (gameTestInfo.getError() != null) { + LOGGER.error(String.valueOf(gameTestInfo), gameTestInfo.getError()); + } + + if (!gameTestInfo.isOptional() || McRuntimeTest.GAME_TESTS_FAIL_ON_OPTIONAL) { + System.exit(-1); + } + }); + + result.set(Optional.of(multipleTestTracker)); + return Command.SINGLE_SUCCESS; + })); + + try { + dispatcher.execute("test", server.createCommandSourceStack()); + } catch (CommandSyntaxException e) { + throw new RuntimeException(e); + } + + return result.get().orElse(null); + }).get(60, TimeUnit.SECONDS); + } + +} diff --git a/1_21_6/src/main/java/me/earth/mc_runtime_test/mixin/ICreateWorldScreen.java b/1_21_6/src/main/java/me/earth/mc_runtime_test/mixin/ICreateWorldScreen.java new file mode 100644 index 0000000..f350807 --- /dev/null +++ b/1_21_6/src/main/java/me/earth/mc_runtime_test/mixin/ICreateWorldScreen.java @@ -0,0 +1,12 @@ +package me.earth.mc_runtime_test.mixin; + +import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(CreateWorldScreen.class) +public interface ICreateWorldScreen { + @Invoker("onCreate") + void invokeOnCreate(); + +} diff --git a/1_21_6/src/main/java/me/earth/mc_runtime_test/mixin/MixinMinecraft.java b/1_21_6/src/main/java/me/earth/mc_runtime_test/mixin/MixinMinecraft.java new file mode 100644 index 0000000..60ab01c --- /dev/null +++ b/1_21_6/src/main/java/me/earth/mc_runtime_test/mixin/MixinMinecraft.java @@ -0,0 +1,143 @@ +package me.earth.mc_runtime_test.mixin; + +import me.earth.mc_runtime_test.McGameTestRunner; +import me.earth.mc_runtime_test.McRuntimeTest; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.DeathScreen; +import net.minecraft.client.gui.screens.ErrorScreen; +import net.minecraft.client.gui.screens.Overlay; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.server.IntegratedServer; +import net.minecraft.core.SectionPos; +import net.minecraft.gametest.framework.MultipleTestTracker; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.Objects; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; + +@Mixin(Minecraft.class) +public abstract class MixinMinecraft { + @Shadow @Final private static Logger LOGGER; + @Shadow @Nullable public LocalPlayer player; + @Shadow @Nullable public ClientLevel level; + @Shadow @Nullable public Screen screen; + @Shadow @Nullable private IntegratedServer singleplayerServer; + @Shadow private volatile boolean running; + + @Unique + private boolean mcRuntimeTest$startedLoadingSPWorld = false; + @Unique + private boolean mcRuntimeTest$worldCreationStarted = false; + @Unique + private MultipleTestTracker mcRuntimeTest$testTracker = null; + + @Shadow + public abstract @Nullable Overlay getOverlay(); + + @Shadow + public abstract void setScreen(@Nullable Screen screen); + + @Shadow + public abstract void disconnectWithProgressScreen(); + + @Inject(method = "setScreen", at = @At("HEAD")) + private void setScreenHook(Screen screen, CallbackInfo ci) { + if (!McRuntimeTest.screenHook()) { + return; + } + + if (screen instanceof ErrorScreen) { + mcRuntime$stop(); + throw new RuntimeException("Error Screen " + screen); + } else if (screen instanceof DeathScreen && player != null) { + player.respawn(); + } + } + + @Inject(method = "tick", at = @At("HEAD")) + private void tickHook(CallbackInfo ci) throws ExecutionException, InterruptedException, TimeoutException { + if (!McRuntimeTest.tickHook()) { + return; + } + + if (getOverlay() == null) { + if (!mcRuntimeTest$startedLoadingSPWorld && getOverlay() == null) { + CreateWorldScreen.openFresh(Minecraft.class.cast(this), null); + mcRuntimeTest$startedLoadingSPWorld = true; + } else if (!mcRuntimeTest$worldCreationStarted && screen instanceof ICreateWorldScreen createWorldScreen) { + createWorldScreen.invokeOnCreate(); + mcRuntimeTest$worldCreationStarted = true; + } + } else { + LOGGER.info("Waiting for overlay to disappear..."); + } + + // TODO: detect SinglePlayerServer crash where game freezes? + if (player != null && level != null) { + if (screen == null) { + if (!level.getChunk(SectionPos.blockToSectionCoord(player.getBlockX()), SectionPos.blockToSectionCoord(player.getBlockZ())).isEmpty()) { + if (player.tickCount < 100) { + LOGGER.info("Waiting " + (100 - player.tickCount) + " ticks before testing..."); + } else if (mcRuntimeTest$testTracker == null) { + if (McRuntimeTest.RUN_GAME_TESTS) { + LOGGER.info("Running game tests..."); + mcRuntimeTest$testTracker = McGameTestRunner.runGameTests(player.getUUID(), Objects.requireNonNull(singleplayerServer)); + if (mcRuntimeTest$testTracker == null) { + mcRuntimeTest$testTracker = new MultipleTestTracker(); + LOGGER.info("No tests found, Successfully finished."); + mcRuntime$stop(); + } + } else { + LOGGER.info("Successfully finished."); + mcRuntime$stop(); + } + } else if (mcRuntimeTest$testTracker.isDone()) { + if (mcRuntimeTest$testTracker.getFailedRequiredCount() > 0 + || mcRuntimeTest$testTracker.getFailedOptionalCount() > 0 && McRuntimeTest.GAME_TESTS_FAIL_ON_OPTIONAL) { + System.exit(-1); + } + + mcRuntime$stop(); + } else { + LOGGER.info("Waiting for GameTest: " + mcRuntimeTest$testTracker.getProgressBar()); + } + } else { + LOGGER.info("Players chunk not yet loaded, " + player + ": cores: " + Runtime.getRuntime().availableProcessors() + + ", server running: " + (singleplayerServer == null ? "null" : singleplayerServer.isRunning())); + } + } else { + LOGGER.info("Screen not yet null: " + screen); + if (McRuntimeTest.CLOSE_ANY_SCREEN || McRuntimeTest.CLOSE_CREATE_WORLD_SCREEN && screen instanceof CreateWorldScreen) { + LOGGER.info("Closing screen"); + setScreen(null); + } + } + } else { + LOGGER.info("Waiting for player to load..."); + } + } + + @Unique + private void mcRuntime$stop() { + IntegratedServer server = singleplayerServer; + if (server != null) { + server.halt(true); + disconnectWithProgressScreen(); + } + + running = false; + } + +} diff --git a/1_21_6/src/main/resources/mc_runtime_test.mixins.json b/1_21_6/src/main/resources/mc_runtime_test.mixins.json new file mode 100644 index 0000000..3f834e1 --- /dev/null +++ b/1_21_6/src/main/resources/mc_runtime_test.mixins.json @@ -0,0 +1,13 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "me.earth.mc_runtime_test.mixin", + "compatibilityLevel": "JAVA_8", + "client": [ + "ICreateWorldScreen", + "MixinMinecraft" + ], + "injectors": { + "defaultRequire": 1 + } +} \ No newline at end of file diff --git a/1_21_6/src/neoforge/java/me/earth/mc_runtime_test/neoforge/NeoForgeMod.java b/1_21_6/src/neoforge/java/me/earth/mc_runtime_test/neoforge/NeoForgeMod.java new file mode 100644 index 0000000..c8e767c --- /dev/null +++ b/1_21_6/src/neoforge/java/me/earth/mc_runtime_test/neoforge/NeoForgeMod.java @@ -0,0 +1,8 @@ +package me.earth.mc_runtime_test.neoforge; + +import net.neoforged.fml.common.Mod; + +@Mod("mc_runtime_test") +public class NeoForgeMod { + +} diff --git a/1_21_6/src/neoforge/resources/META-INF/neoforge.mods.toml b/1_21_6/src/neoforge/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..52a169f --- /dev/null +++ b/1_21_6/src/neoforge/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,20 @@ +modLoader = "javafml" +loaderVersion = "[1,)" +issueTrackerURL = "https://github.com/headlesshq/mc-runtime-test" +license = "MIT" + +[[mods]] +modId = "mc_runtime_test" +version = "${version}" +displayName = "MC-Runtime-Test" +authors = "3arthqu4ke" +description = ''' + Run tests on the Minecraft client at runtime +''' + +[[dependencies.mc_runtime_test]] +modId = "minecraft" +mandatory = true +versionRange = "[1.21.0,)" +ordering = "NONE" +side = "BOTH" diff --git a/1_21_6/src/neoforge/resources/pack.mcmeta b/1_21_6/src/neoforge/resources/pack.mcmeta new file mode 100644 index 0000000..d2b91b6 --- /dev/null +++ b/1_21_6/src/neoforge/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "mc_runtime_test resources", + "pack_format": 6 + } +} \ No newline at end of file diff --git a/README.md b/README.md index 1d9e301..6bae672 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ This project helps streamline that process by automating the client launch and b ### Supported Minecraft Versions and Modloaders | Version | Forge | Fabric | NeoForge | |-----------------|----------------|----------------|----------------| -| 1.21 - 1.21.5 | ✔️ | ✔️ | ✔️ | +| 1.21 - 1.21.6 | ✔️ | ✔️ | ✔️ | | 1.20.2 - 1.20.6 | ✔️ | ✔️ | ✔️ | | 1.20.1 | ✔️ | ✔️ | ⚠️ | | 1.19 - 1.19.4 | ✔️ | ✔️ | — |