diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 96913dd..1aeac74 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -156,7 +156,7 @@ jobs: fail-fast: false matrix: mod-loader: ['fabric', 'forge'] - mc-version: ["1.20.6"] + mc-version: ["1.20.6", "1.21"] #exclude: # - mod-loader: 'forge' # mc-version: '1.17' diff --git a/MinecraftMod/fabric/1.21/.gitignore b/MinecraftMod/fabric/1.21/.gitignore new file mode 100644 index 0000000..09cd281 --- /dev/null +++ b/MinecraftMod/fabric/1.21/.gitignore @@ -0,0 +1,33 @@ +# gradle + +.gradle/ +build/ +out/ +classes/ + +# eclipse + +*.launch + +# idea + +.idea/ +*.iml +*.ipr +*.iws + +# vscode + +.settings/ +.vscode/ +bin/ +.classpath +.project + +# macos + +*.DS_Store + +# fabric + +run/ diff --git a/MinecraftMod/fabric/1.21/build.gradle b/MinecraftMod/fabric/1.21/build.gradle new file mode 100644 index 0000000..91fe319 --- /dev/null +++ b/MinecraftMod/fabric/1.21/build.gradle @@ -0,0 +1,95 @@ +plugins { + id 'fabric-loom' version '1.6-SNAPSHOT' + id 'maven-publish' +} + +version = project.mod_version +group = project.maven_group + +base { + archivesName = project.archives_base_name +} + +repositories { + // Add repositories to retrieve artifacts from in here. + // You should only use this when depending on other mods because + // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. + // See https://docs.gradle.org/current/userguide/declaring_repositories.html + // for more information about repositories. + + mavenLocal() +} + +loom { + splitEnvironmentSourceSets() + + mods { + "effectmc" { + sourceSet sourceSets.main + sourceSet sourceSets.client + } + } + +} + +dependencies { + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + + // Fabric API. This is technically optional, but you probably want it anyway. + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + + // Uncomment the following line to enable the deprecated Fabric API modules. + // These are included in the Fabric API production distribution and allow you to update your mod to the latest modules at a later more convenient time. + + // modImplementation "net.fabricmc.fabric-api:fabric-api-deprecated:${project.fabric_version}" + + implementation "com.mosadie.effectmc:core:${project.effectmc_core_version}" + include "com.mosadie.effectmc:core:${project.effectmc_core_version}" +} +processResources { + inputs.property "version", project.version + + filesMatching("fabric.mod.json") { + expand "version": project.version + } +} + +tasks.withType(JavaCompile).configureEach { + it.options.release = 17 +} + +java { + // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task + // if it is present. + // If you remove this line, sources will not be generated. + withSourcesJar() + + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +jar { + from("LICENSE") { + rename { "${it}_${project.base.archivesName.get()}"} + } +} + +// configure the maven publication +publishing { + publications { + mavenJava(MavenPublication) { + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + // Notice: This block does NOT have the same function as the block in the top level. + // The repositories here will be used for publishing your artifact, not for + // retrieving dependencies. + } +} \ No newline at end of file diff --git a/MinecraftMod/fabric/1.21/gradle.properties b/MinecraftMod/fabric/1.21/gradle.properties new file mode 100644 index 0000000..fbce15f --- /dev/null +++ b/MinecraftMod/fabric/1.21/gradle.properties @@ -0,0 +1,18 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G + +# Fabric Properties + # check these on https://fabricmc.net/develop + minecraft_version=1.21 + yarn_mappings=1.21+build.2 + loader_version=0.15.11 + +# Mod Properties + mod_version = 2.3.0 + maven_group = com.mosadie.effectmc + archives_base_name = effectmc-fabric-1.21 + +# Dependencies + fabric_version=0.100.1+1.21 + + effectmc_core_version=2.3 diff --git a/MinecraftMod/fabric/1.21/gradle/wrapper/gradle-wrapper.jar b/MinecraftMod/fabric/1.21/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/MinecraftMod/fabric/1.21/gradle/wrapper/gradle-wrapper.jar differ diff --git a/MinecraftMod/fabric/1.21/gradle/wrapper/gradle-wrapper.properties b/MinecraftMod/fabric/1.21/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..b82aa23 --- /dev/null +++ b/MinecraftMod/fabric/1.21/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/MinecraftMod/fabric/1.21/gradlew b/MinecraftMod/fabric/1.21/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/MinecraftMod/fabric/1.21/gradlew @@ -0,0 +1,249 @@ +#!/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##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +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=SC2039,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=SC2039,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 + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +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/MinecraftMod/fabric/1.21/gradlew.bat b/MinecraftMod/fabric/1.21/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/MinecraftMod/fabric/1.21/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/MinecraftMod/fabric/1.21/settings.gradle b/MinecraftMod/fabric/1.21/settings.gradle new file mode 100644 index 0000000..f91a4fe --- /dev/null +++ b/MinecraftMod/fabric/1.21/settings.gradle @@ -0,0 +1,9 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } +} diff --git a/MinecraftMod/fabric/1.21/src/client/java/com/mosadie/effectmc/EffectMC.java b/MinecraftMod/fabric/1.21/src/client/java/com/mosadie/effectmc/EffectMC.java new file mode 100644 index 0000000..7932d93 --- /dev/null +++ b/MinecraftMod/fabric/1.21/src/client/java/com/mosadie/effectmc/EffectMC.java @@ -0,0 +1,773 @@ +package com.mosadie.effectmc; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.datafixers.util.Pair; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.JsonOps; +import com.mojang.text2speech.Narrator; +import com.mosadie.effectmc.core.EffectExecutor; +import com.mosadie.effectmc.core.EffectMCCore; +import com.mosadie.effectmc.core.WorldState; +import com.mosadie.effectmc.core.handler.*; +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.api.ModInitializer; +import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; +import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; +import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.screen.ConfirmScreen; +import net.minecraft.client.gui.screen.DisconnectedScreen; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.screen.TitleScreen; +import net.minecraft.client.gui.screen.ingame.BookScreen; +import net.minecraft.client.gui.screen.multiplayer.ConnectScreen; +import net.minecraft.client.gui.screen.multiplayer.DirectConnectScreen; +import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen; +import net.minecraft.client.gui.screen.world.CreateWorldScreen; +import net.minecraft.client.gui.screen.world.SelectWorldScreen; +import net.minecraft.client.network.ServerAddress; +import net.minecraft.client.network.ServerInfo; +import net.minecraft.client.option.GameOptions; +import net.minecraft.client.option.Perspective; +import net.minecraft.client.sound.PositionedSoundInstance; +import net.minecraft.client.sound.SoundInstance; +import net.minecraft.client.toast.SystemToast; +import net.minecraft.command.CommandRegistryAccess; +import net.minecraft.component.Component; +import net.minecraft.component.DataComponentTypes; +import net.minecraft.component.type.WrittenBookContentComponent; +import net.minecraft.entity.player.PlayerModelPart; +import net.minecraft.item.ItemStack; +import net.minecraft.item.Items; +import net.minecraft.network.message.ChatVisibility; +import net.minecraft.registry.RegistryOps; +import net.minecraft.server.integrated.IntegratedServer; +import net.minecraft.sound.SoundCategory; +import net.minecraft.text.Text; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.random.Random; +import org.apache.commons.io.IOUtils; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class EffectMC implements ModInitializer, ClientModInitializer, EffectExecutor { + + public static String MODID = "effectmc"; + + private EffectMCCore core; + + public static Logger LOGGER = LogManager.getLogger(); + + private static Narrator narrator = Narrator.getNarrator(); + private static Random random = Random.create(); + private static ServerInfo serverInfo = new ServerInfo("", "", ServerInfo.ServerType.OTHER); // Used to hold data during Open Screen + + private HttpClient authedClient; + + @Override + public void onInitialize() { + System.out.println("Hello Fabric world!"); + } + + @Override + public void onInitializeClient() { + File configDir = FabricLoader.getInstance().getConfigDir().resolve("../" + MODID + "/").toFile(); + if (!configDir.exists()) { + if (!configDir.mkdirs()) { + LOGGER.error("Something went wrong creating the config directory! The mod will not work until this is fixed!"); + return; + } + } + File trustFile = configDir.toPath().resolve("trust.json").toFile(); + File configFile = configDir.toPath().resolve("config.json").toFile(); + + + + LOGGER.info("Starting Core"); + core = new EffectMCCore(configFile, trustFile,this); + LOGGER.info("Core Started"); + + LOGGER.info("Starting Server"); + boolean result; + try { + result = core.initServer(); + } catch (URISyntaxException e) { + LOGGER.error("Failed to initialize server due to internal error, please report this!", e); + result = false; + } + LOGGER.info("Server start result: " + result); + + // Register command + ClientCommandRegistrationCallback.EVENT.register(this::registerClientCommand); + + Header authHeader = new BasicHeader("Authorization", "Bearer " + MinecraftClient.getInstance().getSession().getAccessToken()); + List
headers = new ArrayList<>(); + headers.add(authHeader); + authedClient = HttpClientBuilder.create().setDefaultHeaders(headers).build(); + } + + private void registerClientCommand(CommandDispatcher dispatcher, CommandRegistryAccess registryAccess) { + LOGGER.info("Registering Client Command"); + dispatcher.register(ClientCommandManager.literal("effectmc") + .then(ClientCommandManager.literal("trust").executes((context -> { + MinecraftClient.getInstance().send(core::setTrustNextRequest); + receiveChatMessage("[EffectMC] Now prompting to trust the next request sent."); + return 0; + }))) + .then(ClientCommandManager.literal("exportbook").executes((context -> { + if (MinecraftClient.getInstance().player == null) { + return 0; + } + + ItemStack mainHand = MinecraftClient.getInstance().player.getMainHandStack(); + ItemStack offHand = MinecraftClient.getInstance().player.getOffHandStack(); + + ItemStack bookStack = null; + if (mainHand.getItem().equals(Items.WRITTEN_BOOK)) { + bookStack = mainHand; + } else if (offHand.getItem().equals(Items.WRITTEN_BOOK)) { + bookStack = offHand; + } + + if (bookStack == null) { + receiveChatMessage("[EffectMC] Failed to export book: Not holding a book!"); + return 0; + } + + if (!bookStack.getComponents().contains(DataComponentTypes.WRITTEN_BOOK_CONTENT)) { + receiveChatMessage("[EffectMC] Failed to export book: Missing component."); + return 0; + } + + DataResult dataResult = WrittenBookContentComponent.CODEC.encodeStart(JsonOps.INSTANCE, bookStack.get(DataComponentTypes.WRITTEN_BOOK_CONTENT)); + + if (dataResult.isError()) { + receiveChatMessage("[EffectMC] Failed to export book: Error encoding JSON."); + if (dataResult.error().isPresent()) { + LOGGER.warn("Error encoding JSON: " + dataResult.error().get().message()); + } else { + LOGGER.warn("Error encoding JSON: Unknown error."); + } + return 0; + } + + if (dataResult.result().isEmpty()) { + receiveChatMessage("[EffectMC] Failed to export book: No JSON result."); + return 0; + } + + String json = dataResult.result().get().toString(); + + LOGGER.info("Exported Book JSON: " + json); + receiveChatMessage("[EffectMC] Exported the held book to the current log file."); + return 0; + }))).then(ClientCommandManager.literal("exportitem").executes((context -> { + if (MinecraftClient.getInstance().player == null) { + LOGGER.info("Null player running exportitem, this shouldn't happen!"); + return 0; + } + + if (MinecraftClient.getInstance().world == null) { + LOGGER.info("Null world running exportitem, this shouldn't happen!"); + return 0; + } + + DataResult dataResult = ItemStack.CODEC.encodeStart(RegistryOps.of(JsonOps.INSTANCE, MinecraftClient.getInstance().world.getRegistryManager()), MinecraftClient.getInstance().player.getMainHandStack()); + + if (dataResult.isError()) { + receiveChatMessage("[EffectMC] Failed to export held item data: Error encoding JSON."); + if (dataResult.error().isPresent()) { + LOGGER.warn("Error encoding JSON: " + dataResult.error().get().message()); + } else { + LOGGER.warn("Error encoding JSON: Unknown error."); + } + return 0; + } + + if (dataResult.result().isEmpty()) { + receiveChatMessage("[EffectMC] Failed to export held item data: No JSON result."); + return 0; + } + + String json = dataResult.result().get().toString(); + + LOGGER.info("Held Item JSON: " + json); + showItemToast(json, "Exported", MinecraftClient.getInstance().player.getMainHandStack().getName().getString()); + receiveChatMessage("[EffectMC] Exported held item data to log file!"); + return 0; + }))).executes((context -> { + receiveChatMessage("[EffectMC] Available subcommands: exportbook, exportitem, trust"); + return 0; + }))); + } + + @Override + public void log(String message) { + LOGGER.info(message); + } + + @Override + public boolean joinServer(String serverIp) { + MinecraftClient.getInstance().send(() -> { + leaveIfNeeded(); + + if (!ServerAddress.isValid(serverIp)) { + LOGGER.warn("Invalid server address: " + serverIp); + return; + } + + ServerAddress address = ServerAddress.parse(serverIp); + ServerInfo info = new ServerInfo("EffectMC", serverIp, ServerInfo.ServerType.OTHER); + + + LOGGER.info("Connecting to " + serverIp); + + // Connect to server + + ConnectScreen.connect(new TitleScreen(), MinecraftClient.getInstance(), address, info, false, null); + }); + return true; + } + + @Override + public boolean setSkinLayer(SkinLayerHandler.SKIN_SECTION section, boolean visibility) { + GameOptions options = MinecraftClient.getInstance().options; + + switch (section) { + case ALL: + options.togglePlayerModelPart(PlayerModelPart.CAPE, visibility); + // Fall to ALL_BODY + case ALL_BODY: + options.togglePlayerModelPart(PlayerModelPart.HAT, visibility); + options.togglePlayerModelPart(PlayerModelPart.JACKET, visibility); + options.togglePlayerModelPart(PlayerModelPart.LEFT_SLEEVE, visibility); + options.togglePlayerModelPart(PlayerModelPart.LEFT_PANTS_LEG, visibility); + options.togglePlayerModelPart(PlayerModelPart.RIGHT_SLEEVE, visibility); + options.togglePlayerModelPart(PlayerModelPart.RIGHT_PANTS_LEG, visibility); + break; + case CAPE: + options.togglePlayerModelPart(PlayerModelPart.CAPE, visibility); + break; + case JACKET: + options.togglePlayerModelPart(PlayerModelPart.JACKET, visibility); + break; + case LEFT_SLEEVE: + options.togglePlayerModelPart(PlayerModelPart.LEFT_SLEEVE, visibility); + break; + case RIGHT_SLEEVE: + options.togglePlayerModelPart(PlayerModelPart.RIGHT_SLEEVE, visibility); + break; + case LEFT_PANTS_LEG: + options.togglePlayerModelPart(PlayerModelPart.LEFT_PANTS_LEG, visibility); + break; + case RIGHT_PANTS_LEG: + options.togglePlayerModelPart(PlayerModelPart.RIGHT_PANTS_LEG, visibility); + break; + case HAT: + options.togglePlayerModelPart(PlayerModelPart.HAT, visibility); + break; + } + + return true; + } + + @Override + public boolean toggleSkinLayer(SkinLayerHandler.SKIN_SECTION section) { + GameOptions options = MinecraftClient.getInstance().options; + + switch (section) { + case ALL: + trueTogglePlayerModelPart(options, PlayerModelPart.CAPE); + // Fall to ALL_BODY + case ALL_BODY: + trueTogglePlayerModelPart(options, PlayerModelPart.HAT); + trueTogglePlayerModelPart(options, PlayerModelPart.JACKET); + trueTogglePlayerModelPart(options, PlayerModelPart.LEFT_SLEEVE); + trueTogglePlayerModelPart(options, PlayerModelPart.LEFT_PANTS_LEG); + trueTogglePlayerModelPart(options, PlayerModelPart.RIGHT_SLEEVE); + trueTogglePlayerModelPart(options, PlayerModelPart.RIGHT_PANTS_LEG); + break; + case CAPE: + trueTogglePlayerModelPart(options, PlayerModelPart.CAPE); + break; + case JACKET: + trueTogglePlayerModelPart(options, PlayerModelPart.JACKET); + break; + case LEFT_SLEEVE: + trueTogglePlayerModelPart(options, PlayerModelPart.LEFT_SLEEVE); + break; + case RIGHT_SLEEVE: + trueTogglePlayerModelPart(options, PlayerModelPart.RIGHT_SLEEVE); + break; + case LEFT_PANTS_LEG: + trueTogglePlayerModelPart(options, PlayerModelPart.LEFT_PANTS_LEG); + break; + case RIGHT_PANTS_LEG: + trueTogglePlayerModelPart(options, PlayerModelPart.RIGHT_PANTS_LEG); + break; + case HAT: + trueTogglePlayerModelPart(options, PlayerModelPart.HAT); + break; + } + + return true; + } + + private void trueTogglePlayerModelPart(GameOptions options, PlayerModelPart part) { + options.togglePlayerModelPart(part, !options.isPlayerModelPartEnabled(part)); + } + + @Override + public boolean sendChatMessage(String message) { + if (MinecraftClient.getInstance().player != null) { + if (message.startsWith("/")) { + LOGGER.info("Sending command message: " + message); + MinecraftClient.getInstance().player.networkHandler.sendCommand(message.substring(1)); + } else { + LOGGER.info("Sending chat message: " + message); + MinecraftClient.getInstance().player.networkHandler.sendChatMessage(message); + } + + return true; + } + + return false; + } + + @Override + public boolean receiveChatMessage(String message) { + if (MinecraftClient.getInstance().player != null) { + LOGGER.info("Showing chat message: " + message); + MinecraftClient.getInstance().player.sendMessage(Text.of(message), false); + + return true; + } + + return false; + } + + @Override + public boolean showTitle(String title, String subtitle) { + LOGGER.info("Showing Title: " + title + " Subtitle: " + subtitle); + MinecraftClient.getInstance().inGameHud.setDefaultTitleFade(); + MinecraftClient.getInstance().inGameHud.setSubtitle(Text.of(subtitle)); + MinecraftClient.getInstance().inGameHud.setTitle(Text.of(title)); + return true; + } + + @Override + public boolean showActionMessage(String message) { + LOGGER.info("Showing ActionBar message: " + message); + MinecraftClient.getInstance().inGameHud.setOverlayMessage(Text.of(message), false); + return true; + } + + @Override + public void showTrustPrompt(String device) { + MinecraftClient.getInstance().send(() -> { + ConfirmScreen screen = new ConfirmScreen(new EffectMCCore.TrustBooleanConsumer(device, core), Text.of("EffectMC - Trust Prompt"), Text.of("Do you want to trust this device? (" + device + ")")); + MinecraftClient.getInstance().setScreen(screen); + }); + } + + @Override + public boolean triggerDisconnect(DisconnectHandler.NEXT_SCREEN nextScreenType, String title, String message) { + MinecraftClient.getInstance().send(() -> { + leaveIfNeeded(); + + Screen nextScreen; + + switch (nextScreenType) { + default: + case MAIN_MENU: + nextScreen = new TitleScreen(); + break; + + case SERVER_SELECT: + nextScreen = new MultiplayerScreen(new TitleScreen()); + break; + + case WORLD_SELECT: + nextScreen = new SelectWorldScreen(new TitleScreen()); + break; + } + + DisconnectedScreen screen = new DisconnectedScreen(nextScreen, Text.of(title), Text.of(message)); + MinecraftClient.getInstance().setScreen(screen); + }); + return true; + } + + @Override + public boolean playSound(String soundID, String categoryName, float volume, float pitch, boolean repeat, int repeatDelay, String attenuationType, double x, double y, double z, boolean relative, boolean global) { + MinecraftClient.getInstance().send(() -> { + Identifier sound = Identifier.tryParse(soundID); + + if (sound == null) { + LOGGER.info("Invalid sound Identifier"); + } + + SoundCategory category; + try { + category = SoundCategory.valueOf(categoryName.toUpperCase()); + } catch (IllegalArgumentException e) { + category = SoundCategory.MASTER; + } + + SoundInstance.AttenuationType attenuation; + try { + attenuation = SoundInstance.AttenuationType.valueOf(attenuationType.toUpperCase()); + } catch (IllegalArgumentException e) { + attenuation = SoundInstance.AttenuationType.NONE; + } + + double trueX = x; + double trueY = y; + double trueZ = z; + + if (relative && MinecraftClient.getInstance().world != null && MinecraftClient.getInstance().player != null) { + trueX += MinecraftClient.getInstance().player.getX(); + trueY += MinecraftClient.getInstance().player.getY(); + trueZ += MinecraftClient.getInstance().player.getZ(); + } + + MinecraftClient.getInstance().getSoundManager().play(new PositionedSoundInstance(sound, category, volume, pitch, random, repeat, repeatDelay, attenuation, trueX, trueY, trueZ, global)); + }); + + return true; + } + + @Override + public void resetScreen() { + MinecraftClient.getInstance().send(() -> MinecraftClient.getInstance().setScreen(null)); + } + + @Override + public boolean stopSound(String sound, String categoryName) { + MinecraftClient.getInstance().send(() -> { + Identifier location = sound == null ? null : Identifier.tryParse(sound); + SoundCategory category = null; + + try { + category = SoundCategory.valueOf(categoryName); + } catch (IllegalArgumentException | NullPointerException e) { + // Do nothing, if soundId is non-null Minecraft will auto-search, otherwise Minecraft stops all sounds. + } + + MinecraftClient.getInstance().getSoundManager().stopSounds(location, category); + }); + + return true; + } + + @Override + public boolean showToast(String title, String subtitle) { + MinecraftClient.getInstance().send(() -> MinecraftClient.getInstance().getToastManager().add(new SystemToast(SystemToast.Type.NARRATOR_TOGGLE, Text.of(title), Text.of(subtitle)))); + + return true; + } + + @Override + public boolean showItemToast(String itemData, String title, String subtitle) { + MinecraftClient.getInstance().send(() -> MinecraftClient.getInstance().getToastManager().add(new ItemToast(itemData, Text.of(title), Text.of(subtitle), core))); + + return true; + } + + @Override + public boolean openBook(JsonObject bookJSON) { + MinecraftClient.getInstance().send(() -> { + DataResult> dataResult = WrittenBookContentComponent.CODEC.decode(JsonOps.INSTANCE, bookJSON); + + if (dataResult.isError()) { + if (dataResult.error().isPresent()) { + LOGGER.error("Error decoding book JSON: " + dataResult.error().get().message()); + } else { + LOGGER.error("Error decoding book JSON: Unknown error."); + } + return; + } + + if (dataResult.result().isEmpty()) { + LOGGER.error("No result from decoding book JSON."); + return; + } + + ItemStack bookStack = new ItemStack(Items.WRITTEN_BOOK); + bookStack.set(DataComponentTypes.WRITTEN_BOOK_CONTENT, dataResult.result().get().getFirst()); + + BookScreen.Contents bookContents = BookScreen.Contents.create(bookStack); + + BookScreen screen = new BookScreen(bookContents); + + MinecraftClient.getInstance().setScreen(screen); + }); + + return true; + } + + @Override + public boolean narrate(String message, boolean interrupt) { + if (narrator.active()) { + MinecraftClient.getInstance().send(() -> narrator.say(message, interrupt)); + return true; + } + + LOGGER.error("Narrator is unavailable!"); + + return false; + } + + @Override + public boolean loadWorld(String worldName) { + MinecraftClient.getInstance().send(() -> { + if (MinecraftClient.getInstance().getLevelStorage().levelExists(worldName)) { + if (MinecraftClient.getInstance().world != null) { + LOGGER.info("Disconnecting from world..."); + + MinecraftClient.getInstance().world.disconnect(); + MinecraftClient.getInstance().disconnect(); + } + + LOGGER.info("Loading world..."); + MinecraftClient.getInstance().createIntegratedServerLoader().start(worldName, () -> { + LOGGER.info("World load cancelled!"); + MinecraftClient.getInstance().setScreen(new TitleScreen()); + }); + } else { + LOGGER.warn("World " + worldName + " does not exist!"); + } + }); + + return true; + } + + @Override + public boolean setSkin(URL skinUrl, SetSkinHandler.SKIN_TYPE skinType) { + if (skinUrl == null) { + LOGGER.warn("Skin URL is null!"); + return false; + } + + try { + JsonObject payload = new JsonObject(); + + payload.add("variant", new JsonPrimitive(skinType.getValue())); + payload.add("url", new JsonPrimitive(skinUrl.toString())); + + HttpPost request = new HttpPost("https://api.minecraftservices.com/minecraft/profile/skins"); + request.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON)); + + HttpResponse response = authedClient.execute(request); + + if (response.getEntity() != null && response.getEntity().getContentLength() > 0) { + JsonObject responseJSON = core.fromJson(IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8)); + if (responseJSON.has("errorMessage")) { + LOGGER.warn("Failed to update skin! " + responseJSON); + return false; + } + + LOGGER.debug("Skin Update Response: " + responseJSON); + } + + LOGGER.info("Skin updated!"); + return true; + } catch (IOException e) { + LOGGER.warn("Failed to update skin!", e); + return false; + } + } + + public void leaveIfNeeded() { + if (MinecraftClient.getInstance().world != null) { + LOGGER.info("Disconnecting from world..."); + + MinecraftClient.getInstance().world.disconnect(); + MinecraftClient.getInstance().disconnect(); + } + } + + @Override + public boolean openScreen(OpenScreenHandler.SCREEN screen) { + MinecraftClient.getInstance().execute(() -> { + leaveIfNeeded(); + + switch (screen) { + case MAIN_MENU: + MinecraftClient.getInstance().setScreen(new TitleScreen()); + break; + case SERVER_SELECT: + MinecraftClient.getInstance().setScreen(new MultiplayerScreen(new TitleScreen())); + break; + case SERVER_DIRECT_CONNECT: + MinecraftClient.getInstance().setScreen(new DirectConnectScreen(new MultiplayerScreen(new TitleScreen()), this::connectIfTrue, serverInfo)); + break; + case WORLD_SELECT: + MinecraftClient.getInstance().setScreen(new SelectWorldScreen(new TitleScreen())); + break; + case WORLD_CREATE: + CreateWorldScreen.create(MinecraftClient.getInstance(), new SelectWorldScreen(new TitleScreen())); + break; + default: + LOGGER.error("Unknown screen."); + } + }); + return true; + } + + @Override + public boolean setFOV(int fov) { + MinecraftClient.getInstance().execute(() -> MinecraftClient.getInstance().options.getFov().setValue(fov)); + return true; + } + + @Override + public boolean setPOV(SetPovHandler.POV pov) { + Perspective mcPov; + + switch (pov) { + default: + case FIRST_PERSON: + mcPov = Perspective.FIRST_PERSON; + break; + + case THIRD_PERSON_BACK: + mcPov = Perspective.THIRD_PERSON_BACK; + break; + + case THIRD_PERSON_FRONT: + mcPov = Perspective.THIRD_PERSON_FRONT; + break; + } + + MinecraftClient.getInstance().execute(() -> MinecraftClient.getInstance().options.setPerspective(mcPov)); + return true; + } + + @Override + public boolean setGuiScale(int scale) { + if (MinecraftClient.getInstance().options.getGuiScale().getValue().equals(scale)) { + return true; + } + + MinecraftClient.getInstance().execute(() -> { + MinecraftClient.getInstance().options.getGuiScale().setValue(scale); + MinecraftClient.getInstance().options.write(); + MinecraftClient.getInstance().onResolutionChanged(); + }); + return true; + } + + @Override + public boolean setGamma(double gamma) { + MinecraftClient.getInstance().execute(() -> { + MinecraftClient.getInstance().options.getGamma().setValue(gamma); + MinecraftClient.getInstance().options.write(); + }); + return true; + } + + @Override + public boolean setChatVisibility(ChatVisibilityHandler.VISIBILITY visibility) { + ChatVisibility result; + switch (visibility) { + case SHOW: + result = ChatVisibility.FULL; + break; + + case COMMANDS_ONLY: + result = ChatVisibility.SYSTEM; + break; + + case HIDE: + result = ChatVisibility.HIDDEN; + break; + + default: + return false; + } + + MinecraftClient.getInstance().execute(() -> { + MinecraftClient.getInstance().options.getChatVisibility().setValue(result); + MinecraftClient.getInstance().options.write(); + }); + return true; + } + + @Override + public boolean setRenderDistance(int chunks) { + MinecraftClient.getInstance().execute(() -> { + MinecraftClient.getInstance().options.getViewDistance().setValue(chunks); + MinecraftClient.getInstance().options.write(); + }); + return true; + } + + @Override + public WorldState getWorldState() { + if (MinecraftClient.getInstance().world == null) { + return WorldState.OTHER; + } + + return MinecraftClient.getInstance().isConnectedToLocalServer() ? WorldState.SINGLEPLAYER : WorldState.MULTIPLAYER; + } + + @Override + public String getSPWorldName() { + if (getWorldState() != WorldState.SINGLEPLAYER) { + return null; + } + + IntegratedServer server = MinecraftClient.getInstance().getServer(); + + if (server != null) { + return server.getSaveProperties().getLevelName(); + } + + LOGGER.info("Attempted to get SP World Name, but no integrated server was found!"); + return null; + } + + @Override + public String getServerIP() { + if (getWorldState() != WorldState.MULTIPLAYER) { + return null; + } + + if (MinecraftClient.getInstance().getCurrentServerEntry() != null) { + return MinecraftClient.getInstance().getCurrentServerEntry().address; + } + + LOGGER.info("Failed to get Server IP!"); + return null; + } + + private void connectIfTrue(boolean connect) { + if (connect) { + joinServer(serverInfo.address); + } else { + MinecraftClient.getInstance().setScreen(new MultiplayerScreen(new TitleScreen())); + } + } +} diff --git a/MinecraftMod/fabric/1.21/src/client/java/com/mosadie/effectmc/ItemToast.java b/MinecraftMod/fabric/1.21/src/client/java/com/mosadie/effectmc/ItemToast.java new file mode 100644 index 0000000..d6c5483 --- /dev/null +++ b/MinecraftMod/fabric/1.21/src/client/java/com/mosadie/effectmc/ItemToast.java @@ -0,0 +1,64 @@ +package com.mosadie.effectmc; + +import com.google.gson.JsonElement; +import com.mojang.datafixers.util.Pair; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.JsonOps; +import com.mosadie.effectmc.core.EffectMCCore; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.toast.Toast; +import net.minecraft.client.toast.ToastManager; +import net.minecraft.item.ItemStack; +import net.minecraft.item.Items; +import net.minecraft.registry.RegistryOps; +import net.minecraft.text.Text; +import net.minecraft.util.Identifier; + +public class ItemToast implements Toast { + + private static final Identifier TEXTURE = Identifier.tryParse("toast/recipe"); + private ItemStack item; + private Text title; + private Text body; + + private long lastChanged; + private boolean changed = true; + + public ItemToast(String itemData, Text title, Text body, EffectMCCore core) { + if (MinecraftClient.getInstance().world == null) { + EffectMC.LOGGER.warn("Error decoding item data: No level"); + item = new ItemStack(Items.AIR); + this.title = title; + this.body = body; + return; + } + DataResult> dataResult = ItemStack.CODEC.decode(RegistryOps.of(JsonOps.INSTANCE, MinecraftClient.getInstance().world.getRegistryManager()), core.fromJson(itemData)); + + if (dataResult.error().isPresent()) { + EffectMC.LOGGER.warn("Error decoding item data: " + dataResult.error().get()); + item = new ItemStack(Items.AIR); + } else if (dataResult.result().isPresent()) { + item = dataResult.result().get().getFirst(); + } else { + EffectMC.LOGGER.warn("Error decoding item data: No item data"); + item = new ItemStack(Items.AIR); + } + + this.title = title; + this.body = body; + } + @Override + public Visibility draw(DrawContext context, ToastManager manager, long time) { + if (changed) { + lastChanged = time; + changed = false; + } + + context.drawGuiTexture(TEXTURE, 0, 0, this.getWidth(), this.getHeight()); + context.drawText(manager.getClient().textRenderer, title, 30, 7, -16777216, false); + context.drawText(manager.getClient().textRenderer, body, 30, 18, -16777216, false); + context.drawItemWithoutEntity(item, 8, 8); + return (double)(time - this.lastChanged) >= 5000.0D ? Visibility.HIDE : Visibility.SHOW; + } +} diff --git a/MinecraftMod/fabric/1.21/src/main/resources/assets/effectmc/icon.png b/MinecraftMod/fabric/1.21/src/main/resources/assets/effectmc/icon.png new file mode 100644 index 0000000..ce915be Binary files /dev/null and b/MinecraftMod/fabric/1.21/src/main/resources/assets/effectmc/icon.png differ diff --git a/MinecraftMod/fabric/1.21/src/main/resources/fabric.mod.json b/MinecraftMod/fabric/1.21/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..dda339b --- /dev/null +++ b/MinecraftMod/fabric/1.21/src/main/resources/fabric.mod.json @@ -0,0 +1,31 @@ +{ + "schemaVersion": 1, + "id": "effectmc", + "version": "${version}", + "name": "EffectMC", + "description": "Various vanilla-themed live special effects for you to control!", + "authors": [ + "MoSadie" + ], + "contact": { + "homepage": "https://github.com/MoSadie/EffectMC", + "sources": "https://github.com/MoSadie/EffectMC" + }, + + "license": "GNU LGPL v3", + "icon": "assets/effectmc/icon.png", + + "environment": "client", + "entrypoints": { + "client": [ + "com.mosadie.effectmc.EffectMC" + ] + }, + + "depends": { + "fabricloader": ">=0.15", + "fabric": "*", + "minecraft": "~1.21", + "java": ">=21" + } +} diff --git a/MinecraftMod/forge/1.21/.gitattributes b/MinecraftMod/forge/1.21/.gitattributes new file mode 100644 index 0000000..f811f6a --- /dev/null +++ b/MinecraftMod/forge/1.21/.gitattributes @@ -0,0 +1,5 @@ +# Disable autocrlf on generated files, they always generate with LF +# Add any extra files or paths here to make git stop saying they +# are changed when only line endings change. +src/generated/**/.cache/cache text eol=lf +src/generated/**/*.json text eol=lf diff --git a/MinecraftMod/forge/1.21/.gitignore b/MinecraftMod/forge/1.21/.gitignore new file mode 100644 index 0000000..31d2550 --- /dev/null +++ b/MinecraftMod/forge/1.21/.gitignore @@ -0,0 +1,26 @@ +# eclipse +bin +*.launch +.settings +.metadata +.classpath +.project + +# idea +out +*.ipr +*.iws +*.iml +.idea + +# gradle +build +.gradle + +# other +eclipse +run +runs +run-data + +repo \ No newline at end of file diff --git a/MinecraftMod/forge/1.21/build.gradle b/MinecraftMod/forge/1.21/build.gradle new file mode 100644 index 0000000..9a846ef --- /dev/null +++ b/MinecraftMod/forge/1.21/build.gradle @@ -0,0 +1,166 @@ +plugins { + id 'java-library' + id 'eclipse' + id 'idea' + id 'maven-publish' + id 'net.neoforged.gradle.userdev' version '7.0.142' +} + +version = mod_version +group = mod_group_id + +repositories { + mavenLocal() +} + +base { + archivesName = mod_id + "-neoforge-" + minecraft_version +} + +// Mojang ships Java 21 to end users starting in 1.20.5, so mods should target Java 21. +java.toolchain.languageVersion = JavaLanguageVersion.of(21) + +jarJar.enable() + +//minecraft.accessTransformers.file rootProject.file('src/main/resources/META-INF/accesstransformer.cfg') +//minecraft.accessTransformers.entry public net.minecraft.client.Minecraft textureManager # textureManager + +// Default run configurations. +// These can be tweaked, removed, or duplicated as needed. +runs { + // applies to all the run configs below + configureEach { + // Recommended logging data for a userdev environment + // The markers can be added/remove as needed separated by commas. + // "SCAN": For mods scan. + // "REGISTRIES": For firing of registry events. + // "REGISTRYDUMP": For getting the contents of all registries. + systemProperty 'forge.logging.markers', 'REGISTRIES' + + // Recommended logging level for the console + // You can set various levels here. + // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels + systemProperty 'forge.logging.console.level', 'debug' + + modSource project.sourceSets.main + } + + client { + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + systemProperty 'forge.enabledGameTestNamespaces', project.mod_id + } + + server { + systemProperty 'forge.enabledGameTestNamespaces', project.mod_id + programArgument '--nogui' + } + + // This run config launches GameTestServer and runs all registered gametests, then exits. + // By default, the server will crash when no gametests are provided. + // The gametest system is also enabled by default for other run configs under the /test command. + gameTestServer { + systemProperty 'forge.enabledGameTestNamespaces', project.mod_id + } + + data { + // example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it + // workingDirectory project.file('run-data') + + // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. + programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath() + } +} + +// Include resources generated by data generators. +sourceSets.main.resources { srcDir 'src/generated/resources' } + +repositories { + mavenLocal() +} + + +dependencies { + // Specify the version of Minecraft to use. + // Depending on the plugin applied there are several options. We will assume you applied the userdev plugin as shown above. + // The group for userdev is net.neoforged, the module name is neoforge, and the version is the same as the neoforge version. + // You can however also use the vanilla plugin (net.neoforged.gradle.vanilla) to use a version of Minecraft without the neoforge loader. + // And its provides the option to then use net.minecraft as the group, and one of; client, server or joined as the module name, plus the game version as version. + // For all intends and purposes: You can treat this dependency as if it is a normal library you would use. + implementation "net.neoforged:neoforge:${neo_version}" + + // Example mod dependency with JEI + // The JEI API is declared for compile time use, while the full JEI artifact is used at runtime + // compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}" + // compileOnly "mezz.jei:jei-${mc_version}-forge-api:${jei_version}" + // runtimeOnly "mezz.jei:jei-${mc_version}-forge:${jei_version}" + + // Example mod dependency using a mod jar from ./libs with a flat dir repository + // This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar + // The group id is ignored when searching -- in this case, it is "blank" + // implementation "blank:coolmod-${mc_version}:${coolmod_version}" + + // Example mod dependency using a file as dependency + // implementation files("libs/coolmod-${mc_version}-${coolmod_version}.jar") + + // Example project dependency using a sister or child project: + // implementation project(":myproject") + + implementation("com.mosadie.effectmc:core:${effectmc_core_version}") + jarJar("com.mosadie.effectmc:core:${effectmc_core_version_range}") + + // For more info: + // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html + // http://www.gradle.org/docs/current/userguide/dependency_management.html +} + +// This block of code expands all declared replace properties in the specified resource targets. +// A missing property will result in an error. Properties are expanded using ${} Groovy notation. +// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments. +// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html +tasks.withType(ProcessResources).configureEach { + var replaceProperties = [ + minecraft_version : minecraft_version, + minecraft_version_range: minecraft_version_range, + neo_version : neo_version, + neo_version_range : neo_version_range, + loader_version_range : loader_version_range, + mod_id : mod_id, + mod_name : mod_name, + mod_license : mod_license, + mod_version : mod_version, + mod_authors : mod_authors, + mod_description : mod_description, + pack_format_number : pack_format_number, + ] + inputs.properties replaceProperties + + filesMatching(['META-INF/neoforge.mods.toml', 'pack.mcmeta']) { + expand replaceProperties + [project: project] + } +} + +// Example configuration to allow publishing using the maven-publish plugin +publishing { + publications { + register('mavenJava', MavenPublication) { + from components.java + } + } + repositories { + maven { + url "file://${project.projectDir}/repo" + } + } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation +} + +// IDEA no longer automatically downloads sources/javadoc jars for dependencies, so we need to explicitly enable the behavior. +idea { + module { + downloadSources = true + downloadJavadoc = true + } +} \ No newline at end of file diff --git a/MinecraftMod/forge/1.21/gradle.properties b/MinecraftMod/forge/1.21/gradle.properties new file mode 100644 index 0000000..5ec87ec --- /dev/null +++ b/MinecraftMod/forge/1.21/gradle.properties @@ -0,0 +1,50 @@ +# Sets default memory used for gradle commands. Can be overridden by user or command line properties. +org.gradle.jvmargs=-Xmx1G +org.gradle.daemon=false +org.gradle.debug=false + +#read more on this at https://github.com/neoforged/NeoGradle/blob/NG_7.0/README.md#apply-parchment-mappings +# you can also find the latest versions at: https://parchmentmc.org/docs/getting-started +neogradle.subsystems.parchment.minecraftVersion=1.21 +neogradle.subsystems.parchment.mappingsVersion=2024.07.07 + +## Environment Properties + +# The Minecraft version must agree with the Neo version to get a valid artifact +minecraft_version=1.21 +# The Minecraft version range can use any release version of Minecraft as bounds. +# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly +# as they do not follow standard versioning conventions. +minecraft_version_range=[1.21,1.22) +# The Neo version must agree with the Minecraft version to get a valid artifact +neo_version=21.0.140-beta +# The Neo version range can use any version of Neo as bounds or match the loader version range +neo_version_range=[21,) +# The loader version range can only use the major version of Neo/FML as bounds +loader_version_range=[2,) + +# The version of the EffectMC Core to use +effectmc_core_version=2.3 +effectmc_core_version_range=[2.3,3.0) + +## Mod Properties + +# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63} +# Must match the String constant located in the main mod class annotated with @Mod. +mod_id=effectmc +# The human-readable display name for the mod. +mod_name=EffectMC +# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default. +mod_license=GNU LGPL v3 +# The mod version. See https://semver.org/ +mod_version=2.3.0 +# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository. +# This should match the base package used for the mod sources. +# See https://maven.apache.org/guides/mini/guide-naming-conventions.html +mod_group_id=com.mosadie.effectmc +# The authors of the mod. This is a simple text string that is used for display purposes in the mod list. +mod_authors=MoSadie +# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list. +mod_description=Various vanilla-themed live special effects for you to control! +# Pack version - this changes each minecraft release, in general. +pack_format_number=34 diff --git a/MinecraftMod/forge/1.21/gradle/wrapper/gradle-wrapper.jar b/MinecraftMod/forge/1.21/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..943f0cb Binary files /dev/null and b/MinecraftMod/forge/1.21/gradle/wrapper/gradle-wrapper.jar differ diff --git a/MinecraftMod/forge/1.21/gradle/wrapper/gradle-wrapper.properties b/MinecraftMod/forge/1.21/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..20db9ad --- /dev/null +++ b/MinecraftMod/forge/1.21/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/MinecraftMod/forge/1.21/gradlew b/MinecraftMod/forge/1.21/gradlew new file mode 100755 index 0000000..65dcd68 --- /dev/null +++ b/MinecraftMod/forge/1.21/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/MinecraftMod/forge/1.21/gradlew.bat b/MinecraftMod/forge/1.21/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/MinecraftMod/forge/1.21/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/MinecraftMod/forge/1.21/settings.gradle b/MinecraftMod/forge/1.21/settings.gradle new file mode 100644 index 0000000..b359a59 --- /dev/null +++ b/MinecraftMod/forge/1.21/settings.gradle @@ -0,0 +1,11 @@ +pluginManagement { + repositories { + mavenLocal() + gradlePluginPortal() + maven { url = 'https://maven.neoforged.net/releases' } + } +} + +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0' +} diff --git a/MinecraftMod/forge/1.21/src/main/java/com/mosadie/effectmc/EffectMC.java b/MinecraftMod/forge/1.21/src/main/java/com/mosadie/effectmc/EffectMC.java new file mode 100644 index 0000000..c9866c3 --- /dev/null +++ b/MinecraftMod/forge/1.21/src/main/java/com/mosadie/effectmc/EffectMC.java @@ -0,0 +1,773 @@ +package com.mosadie.effectmc; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.datafixers.util.Pair; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.JsonOps; +import com.mojang.text2speech.Narrator; +import com.mosadie.effectmc.core.EffectExecutor; +import com.mosadie.effectmc.core.EffectMCCore; +import com.mosadie.effectmc.core.WorldState; +import com.mosadie.effectmc.core.handler.*; +import net.minecraft.client.CameraType; +import net.minecraft.client.Minecraft; +import net.minecraft.client.Options; +import net.minecraft.client.gui.components.toasts.SystemToast; +import net.minecraft.client.gui.screens.*; +import net.minecraft.client.gui.screens.inventory.BookViewScreen; +import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen; +import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen; +import net.minecraft.client.gui.screens.worldselection.SelectWorldScreen; +import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.client.multiplayer.resolver.ServerAddress; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.client.resources.sounds.SoundInstance; +import net.minecraft.client.server.IntegratedServer; +import net.minecraft.commands.Commands; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtUtils; +import net.minecraft.nbt.TagParser; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.player.ChatVisiblity; +import net.minecraft.world.entity.player.PlayerModelPart; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.WrittenBookItem; +import net.minecraft.world.item.component.WrittenBookContent; +import net.minecraft.world.item.enchantment.Enchantment; +import net.neoforged.fml.ModList; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.client.event.RegisterClientCommandsEvent; +import net.neoforged.neoforge.common.NeoForge; +import org.apache.commons.io.IOUtils; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@Mod(EffectMC.MODID) +public class EffectMC implements EffectExecutor { + public final static String MODID = "effectmc"; + + private final EffectMCCore core; + + public static Logger LOGGER = LogManager.getLogger(); + + private static Narrator narrator = Narrator.getNarrator(); + private static RandomSource randomSource = RandomSource.create(); + private static ServerData serverData = new ServerData("", "", ServerData.Type.OTHER); // Used to hold data during Open Screen + + private final HttpClient authedClient; + + public EffectMC() throws IOException { + File configDir = ModList.get().getModFileById(MODID).getFile().getFilePath().resolve("../" + MODID + "/").toFile(); + if (!configDir.exists()) { + if (!configDir.mkdirs()) { + LOGGER.error("Something went wrong creating the config directory!"); + throw new IOException("Failed to create config directory!"); + } + } + File trustFile = configDir.toPath().resolve("trust.json").toFile(); + File configFile = configDir.toPath().resolve("config.json").toFile(); + + + + LOGGER.info("Starting Core"); + core = new EffectMCCore(configFile, trustFile,this); + LOGGER.info("Core Started"); + + LOGGER.info("Starting Server"); + boolean result; + try { + result = core.initServer(); + } catch (URISyntaxException e) { + LOGGER.error("Failed to initialize server due to internal error, please report this!", e); + result = false; + } + LOGGER.info("Server start result: " + result); + + NeoForge.EVENT_BUS.addListener(this::registerClientCommand); + + Header authHeader = new BasicHeader("Authorization", "Bearer " + Minecraft.getInstance().getUser().getAccessToken()); + List
headers = new ArrayList<>(); + headers.add(authHeader); + authedClient = HttpClientBuilder.create().setDefaultHeaders(headers).build(); + } + + public void registerClientCommand(RegisterClientCommandsEvent event) { + LOGGER.info("Registering effectmc command."); + event.getDispatcher().register(Commands.literal("effectmc") + .then(Commands.literal("trust").executes((context -> { + Minecraft.getInstance().execute(core::setTrustNextRequest); + receiveChatMessage("[EffectMC] Now prompting to trust the next request sent."); + return 0; + }))) + .then(Commands.literal("exportbook").executes((context -> { + if (Minecraft.getInstance().player == null) { + return 0; + } + + ItemStack mainHand = Minecraft.getInstance().player.getMainHandItem(); + ItemStack offHand = Minecraft.getInstance().player.getOffhandItem(); + + ItemStack bookStack = null; + if (mainHand.getItem().equals(Items.WRITTEN_BOOK)) { + bookStack = mainHand; + } else if (offHand.getItem().equals(Items.WRITTEN_BOOK)) { + bookStack = offHand; + } + + if (bookStack == null) { + receiveChatMessage("[EffectMC] Failed to export book: Not holding a book!"); + return 0; + } + + if (!bookStack.getComponents().has(DataComponents.WRITTEN_BOOK_CONTENT)) { + receiveChatMessage("[EffectMC] Failed to export book: Missing component."); + return 0; + } + + DataResult dataResult = WrittenBookContent.CODEC.encodeStart(JsonOps.INSTANCE, bookStack.get(DataComponents.WRITTEN_BOOK_CONTENT)); + + if (dataResult.isError()) { + receiveChatMessage("[EffectMC] Failed to export book: Error encoding JSON."); + if (dataResult.error().isPresent()) { + LOGGER.warn("Error encoding JSON: " + dataResult.error().get().message()); + } else { + LOGGER.warn("Error encoding JSON: Unknown error."); + } + return 0; + } + + if (dataResult.result().isEmpty()) { + receiveChatMessage("[EffectMC] Failed to export book: No JSON result."); + return 0; + } + + String json = dataResult.result().get().toString(); + + LOGGER.info("Exported Book JSON: " + json); + receiveChatMessage("[EffectMC] Exported the held book to the current log file."); + return 0; + }))).then(Commands.literal("exportitem").executes((context -> { + if (Minecraft.getInstance().player == null) { + LOGGER.info("Null player running exportitem, this shouldn't happen!"); + return 0; + } + if (Minecraft.getInstance().level == null) { + LOGGER.info("Null level running exportitem, this shouldn't happen!"); + return 0; + } + + try { + DataResult dataResult = ItemStack.CODEC.encodeStart(RegistryOps.create(JsonOps.INSTANCE, Minecraft.getInstance().level.registryAccess()), Minecraft.getInstance().player.getMainHandItem()); + + if (dataResult.isError()) { + receiveChatMessage("[EffectMC] Failed to export held item data: Error encoding JSON."); + if (dataResult.error().isPresent()) { + LOGGER.warn("Error encoding JSON: " + dataResult.error().get().message()); + } else { + LOGGER.warn("Error encoding JSON: Unknown error."); + } + return 0; + } + + if (dataResult.result().isEmpty()) { + receiveChatMessage("[EffectMC] Failed to export held item data: No JSON result."); + return 0; + } + + String json = dataResult.result().get().toString(); + + LOGGER.info("Held Item JSON: " + json); + showItemToast(json, "Exported", Minecraft.getInstance().player.getMainHandItem().getDisplayName().getString()); + receiveChatMessage("[EffectMC] Exported held item data to log file!"); + return 0; + } catch (Exception e) { + LOGGER.error("Failed to export item data!", e); + receiveChatMessage("[EffectMC] Failed to export held item data: Internal error."); + return 0; + } + }))).executes((context -> { + receiveChatMessage("[EffectMC] Available subcommands: exportbook, exportitem, trust"); + return 0; + }))); + LOGGER.info("Registered effectmc command."); + } + + @Override + public void log(String message) { + LOGGER.info(message); + } + + @Override + public boolean joinServer(String serverIp) { + Minecraft.getInstance().execute(() -> { + leaveIfNeeded(); + + // Create ServerAddress + if (!ServerAddress.isValidAddress(serverIp)) { + LOGGER.error("Invalid server IP!"); + + DisconnectedScreen errorScreen = new DisconnectedScreen(new JoinMultiplayerScreen(new TitleScreen()), Component.literal("Failed to join server!"), Component.literal("Invalid server IP!")); + Minecraft.getInstance().setScreen(errorScreen); + + return; + } + + ServerAddress serverAddress = ServerAddress.parseString(serverIp); + ServerData serverData = new ServerData("EffectMC", serverIp, ServerData.Type.OTHER); + + + LOGGER.info("Connecting to " + serverAddress.getHost()); + // Connect to server + + ConnectScreen.startConnecting(new TitleScreen(), Minecraft.getInstance(), serverAddress, serverData, false, null); + }); + return true; + } + + @Override + public boolean setSkinLayer(SkinLayerHandler.SKIN_SECTION section, boolean visibility) { + Options options = Minecraft.getInstance().options; + + switch (section) { + + case ALL: + options.toggleModelPart(PlayerModelPart.CAPE, visibility); + // Fall to ALL_BODY + case ALL_BODY: + options.toggleModelPart(PlayerModelPart.HAT, visibility); + options.toggleModelPart(PlayerModelPart.JACKET, visibility); + options.toggleModelPart(PlayerModelPart.LEFT_SLEEVE, visibility); + options.toggleModelPart(PlayerModelPart.LEFT_PANTS_LEG, visibility); + options.toggleModelPart(PlayerModelPart.RIGHT_SLEEVE, visibility); + options.toggleModelPart(PlayerModelPart.RIGHT_PANTS_LEG, visibility); + break; + case CAPE: + options.toggleModelPart(PlayerModelPart.CAPE, visibility); + break; + case JACKET: + options.toggleModelPart(PlayerModelPart.JACKET, visibility); + break; + case LEFT_SLEEVE: + options.toggleModelPart(PlayerModelPart.LEFT_SLEEVE, visibility); + break; + case RIGHT_SLEEVE: + options.toggleModelPart(PlayerModelPart.RIGHT_SLEEVE, visibility); + break; + case LEFT_PANTS_LEG: + options.toggleModelPart(PlayerModelPart.LEFT_PANTS_LEG, visibility); + break; + case RIGHT_PANTS_LEG: + options.toggleModelPart(PlayerModelPart.RIGHT_PANTS_LEG, visibility); + break; + case HAT: + options.toggleModelPart(PlayerModelPart.HAT, visibility); + break; + } + + return true; + } + + @Override + public boolean toggleSkinLayer(SkinLayerHandler.SKIN_SECTION section) { + Options options = Minecraft.getInstance().options; + switch (section) { + + case ALL: + options.toggleModelPart(PlayerModelPart.CAPE, !options.isModelPartEnabled(PlayerModelPart.CAPE)); + // Fall to ALL_BODY + case ALL_BODY: + options.toggleModelPart(PlayerModelPart.HAT, !options.isModelPartEnabled(PlayerModelPart.HAT)); + options.toggleModelPart(PlayerModelPart.JACKET, !options.isModelPartEnabled(PlayerModelPart.JACKET)); + options.toggleModelPart(PlayerModelPart.LEFT_SLEEVE, !options.isModelPartEnabled(PlayerModelPart.LEFT_SLEEVE)); + options.toggleModelPart(PlayerModelPart.LEFT_PANTS_LEG, !options.isModelPartEnabled(PlayerModelPart.LEFT_PANTS_LEG)); + options.toggleModelPart(PlayerModelPart.RIGHT_SLEEVE, !options.isModelPartEnabled(PlayerModelPart.RIGHT_SLEEVE)); + options.toggleModelPart(PlayerModelPart.RIGHT_PANTS_LEG, !options.isModelPartEnabled(PlayerModelPart.RIGHT_PANTS_LEG)); + break; + case CAPE: + options.toggleModelPart(PlayerModelPart.CAPE, !options.isModelPartEnabled(PlayerModelPart.CAPE)); + break; + case JACKET: + options.toggleModelPart(PlayerModelPart.JACKET, !options.isModelPartEnabled(PlayerModelPart.JACKET)); + break; + case LEFT_SLEEVE: + options.toggleModelPart(PlayerModelPart.LEFT_SLEEVE, !options.isModelPartEnabled(PlayerModelPart.LEFT_SLEEVE)); + break; + case RIGHT_SLEEVE: + options.toggleModelPart(PlayerModelPart.RIGHT_SLEEVE, !options.isModelPartEnabled(PlayerModelPart.RIGHT_SLEEVE)); + break; + case LEFT_PANTS_LEG: + options.toggleModelPart(PlayerModelPart.LEFT_PANTS_LEG, !options.isModelPartEnabled(PlayerModelPart.LEFT_PANTS_LEG)); + break; + case RIGHT_PANTS_LEG: + options.toggleModelPart(PlayerModelPart.RIGHT_PANTS_LEG, !options.isModelPartEnabled(PlayerModelPart.RIGHT_PANTS_LEG)); + break; + case HAT: + options.toggleModelPart(PlayerModelPart.HAT, !options.isModelPartEnabled(PlayerModelPart.HAT)); + break; + } + + return true; + } + + @Override + public boolean sendChatMessage(String message) { + if (Minecraft.getInstance().player != null) { + if (message.startsWith("/")) { + LOGGER.info("Sending command message: " + message); + Minecraft.getInstance().player.connection.sendCommand(message.substring(1)); + } else { + LOGGER.info("Sending chat message: " + message); + Minecraft.getInstance().player.connection.sendChat(message); + } + + return true; + } + + return false; + } + + @Override + public boolean receiveChatMessage(String message) { + if (Minecraft.getInstance().player != null) { + LOGGER.info("Showing chat message: " + message); + Minecraft.getInstance().player.displayClientMessage(Component.literal(message), false);//.sendMessage(Component.literal(message), Minecraft.getInstance().player.getUUID()); + + return true; + } + + return false; + } + + @Override + public boolean showTitle(String title, String subtitle) { + LOGGER.info("Showing Title: " + title + " Subtitle: " + subtitle); + Minecraft.getInstance().gui.resetTitleTimes(); + Minecraft.getInstance().gui.setSubtitle(Component.literal(subtitle)); + Minecraft.getInstance().gui.setTitle(Component.literal(title)); + + return true; + } + + @Override + public boolean showActionMessage(String message) { + LOGGER.info("Showing ActionBar message: " + message); + Minecraft.getInstance().gui.setOverlayMessage(Component.literal(message), false); + + return true; + } + + @Override + public boolean triggerDisconnect(DisconnectHandler.NEXT_SCREEN nextScreenType, String title, String message) { + Minecraft.getInstance().execute(() -> { + leaveIfNeeded(); + + Screen nextScreen; + + switch (nextScreenType) { + default: + case MAIN_MENU: + nextScreen = new TitleScreen(); + break; + + case SERVER_SELECT: + nextScreen = new JoinMultiplayerScreen(new TitleScreen()); + break; + + case WORLD_SELECT: + nextScreen = new SelectWorldScreen(new TitleScreen()); + break; + } + + DisconnectedScreen screen = new DisconnectedScreen(nextScreen, Component.literal(title), Component.literal(message)); + Minecraft.getInstance().setScreen(screen); + }); + + return true; + } + + @Override + public boolean playSound(String soundID, String categoryName, float volume, float pitch, boolean repeat, int repeatDelay, String attenuationType, double x, double y, double z, boolean relative, boolean global) { + Minecraft.getInstance().execute(() -> { + ResourceLocation sound = ResourceLocation.tryParse(soundID); + + if (sound == null) { + LOGGER.info("Invalid sound ResourceLocation"); + return; + } + + SoundSource category; + try { + category = SoundSource.valueOf(categoryName.toUpperCase()); + } catch (IllegalArgumentException e) { + category = SoundSource.MASTER; + } + + SoundInstance.Attenuation attenuation; + try { + attenuation = SoundInstance.Attenuation.valueOf(attenuationType.toUpperCase()); + } catch (IllegalArgumentException e) { + attenuation = SoundInstance.Attenuation.NONE; + } + + double trueX = x; + double trueY = y; + double trueZ = z; + + if (relative && Minecraft.getInstance().level != null && Minecraft.getInstance().player != null) { + trueX += Minecraft.getInstance().player.getX(); + trueY += Minecraft.getInstance().player.getY(); + trueZ += Minecraft.getInstance().player.getZ(); + } + + Minecraft.getInstance().getSoundManager().play(new SimpleSoundInstance(sound, category, volume, pitch, randomSource, repeat, repeatDelay, attenuation, trueX, trueY, trueZ, global)); + }); + + return true; + } + + @Override + public void showTrustPrompt(String device) { + Minecraft.getInstance().execute(() -> { + ConfirmScreen screen = new ConfirmScreen(new EffectMCCore.TrustBooleanConsumer(device, core), Component.literal("EffectMC - Trust Prompt"), Component.literal("Do you want to trust this device? (" + device + ")")); + Minecraft.getInstance().setScreen(screen); + }); + } + + @Override + public void resetScreen() { + Minecraft.getInstance().execute(() -> Minecraft.getInstance().setScreen(null)); + } + + @Override + public boolean stopSound(String sound, String categoryName) { + Minecraft.getInstance().execute(() -> { + ResourceLocation location = sound == null ? null : ResourceLocation.tryParse(sound); + SoundSource category = null; + + try { + category = SoundSource.valueOf(categoryName); + } catch (IllegalArgumentException | NullPointerException e) { + // Do nothing, if soundId is non-null Minecraft will auto-search, otherwise Minecraft stops all sounds. + } + + Minecraft.getInstance().getSoundManager().stop(location, category); + }); + + return true; + } + + @Override + public boolean showToast(String title, String subtitle) { + Minecraft.getInstance().execute(() -> Minecraft.getInstance().getToasts().addToast(new SystemToast(SystemToast.SystemToastId.NARRATOR_TOGGLE, Component.literal(title), Component.literal(subtitle)))); + + return true; + } + + @Override + public boolean showItemToast(String itemData, String title, String subtitle) { + Minecraft.getInstance().execute(() -> Minecraft.getInstance().getToasts().addToast(new ItemToast(itemData, Component.literal(title), Component.literal(subtitle), core))); + + return true; + } + + @Override + public boolean openBook(JsonObject bookJSON) { + Minecraft.getInstance().execute(() -> { + DataResult> dataResult = WrittenBookContent.CODEC.decode(JsonOps.INSTANCE, bookJSON); + + if (dataResult.isError()) { + if (dataResult.error().isPresent()) { + LOGGER.error("Error decoding book JSON: " + dataResult.error().get().message()); + } else { + LOGGER.error("Error decoding book JSON: Unknown error."); + } + return; + } + + if (dataResult.result().isEmpty()) { + LOGGER.error("No result from decoding book JSON."); + return; + } + + ItemStack bookStack = new ItemStack(Items.WRITTEN_BOOK); + bookStack.set(DataComponents.WRITTEN_BOOK_CONTENT, dataResult.result().get().getFirst()); + + BookViewScreen.BookAccess bookInfo = BookViewScreen.BookAccess.fromItem(bookStack); + + BookViewScreen screen = new BookViewScreen(bookInfo); + + Minecraft.getInstance().setScreen(screen); + }); + + return true; + } + + @Override + public boolean narrate(String message, boolean interrupt) { + if (narrator.active()) { + Minecraft.getInstance().execute(() -> narrator.say(message, interrupt)); + return true; + } + LOGGER.error("Narrator is unavailable!"); + return false; + } + + @Override + public boolean loadWorld(String worldName) { + Minecraft.getInstance().execute(() -> { + if (Minecraft.getInstance().getLevelSource().levelExists(worldName)) { + leaveIfNeeded(); + + LOGGER.info("Loading world..."); + Minecraft.getInstance().createWorldOpenFlows().openWorld(worldName, () -> { + LOGGER.info("World load cancelled!"); + Minecraft.getInstance().setScreen(new TitleScreen()); + }); + } else { + LOGGER.warn("World " + worldName + " does not exist!"); + } + }); + + return true; + } + + @Override + public boolean setSkin(URL skinUrl, SetSkinHandler.SKIN_TYPE skinType) { + if (skinUrl == null) { + LOGGER.warn("Skin URL is null!"); + return false; + } + + try { + JsonObject payload = new JsonObject(); + + payload.add("variant", new JsonPrimitive(skinType.getValue())); + payload.add("url", new JsonPrimitive(skinUrl.toString())); + + HttpPost request = new HttpPost("https://api.minecraftservices.com/minecraft/profile/skins"); + request.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON)); + + HttpResponse response = authedClient.execute(request); + + if (response.getEntity() != null && response.getEntity().getContentLength() > 0) { + JsonObject responseJSON = core.fromJson(IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8)); + if (responseJSON.has("errorMessage")) { + LOGGER.warn("Failed to update skin! " + responseJSON); + return false; + } + + LOGGER.debug("Skin Update Response: " + responseJSON); + } + + LOGGER.info("Skin updated!"); + return true; + } catch (IOException e) { + LOGGER.warn("Failed to update skin!", e); + return false; + } + } + + public void leaveIfNeeded() { + if (Minecraft.getInstance().level != null) { + LOGGER.info("Disconnecting from world..."); + + Minecraft.getInstance().level.disconnect(); + Minecraft.getInstance().disconnect(); +// Minecraft.getInstance().clearClientLevel(new ProgressScreen(true)); + } + } + + @Override + public boolean openScreen(OpenScreenHandler.SCREEN screen) { + Minecraft.getInstance().execute(() -> { + leaveIfNeeded(); + + switch (screen) { + case MAIN_MENU: + Minecraft.getInstance().setScreen(new TitleScreen()); + break; + case SERVER_SELECT: + Minecraft.getInstance().setScreen(new JoinMultiplayerScreen(new TitleScreen())); + break; + case SERVER_DIRECT_CONNECT: + Minecraft.getInstance().setScreen(new DirectJoinServerScreen(new JoinMultiplayerScreen(new TitleScreen()), this::connectIfTrue, serverData)); + break; + case WORLD_SELECT: + Minecraft.getInstance().setScreen(new SelectWorldScreen(new TitleScreen())); + break; + case WORLD_CREATE: + CreateWorldScreen.openFresh(Minecraft.getInstance(), new SelectWorldScreen(new TitleScreen())); + break; + default: + LOGGER.error("Unknown screen."); + } + }); + return true; + } + + @Override + public boolean setFOV(int fov) { + Minecraft.getInstance().execute(() -> Minecraft.getInstance().options.fov().set(fov)); + return true; + } + + @Override + public boolean setPOV(SetPovHandler.POV pov) { + CameraType mcPov; + + switch (pov) { + default: + case FIRST_PERSON: + mcPov = CameraType.FIRST_PERSON; + break; + + case THIRD_PERSON_BACK: + mcPov = CameraType.THIRD_PERSON_BACK; + break; + + case THIRD_PERSON_FRONT: + mcPov = CameraType.THIRD_PERSON_FRONT; + break; + } + + Minecraft.getInstance().execute(() -> Minecraft.getInstance().options.setCameraType(mcPov)); + return true; + } + + @Override + public boolean setGuiScale(int scale) { + if (Minecraft.getInstance().options.guiScale().get().equals(scale)) { + return true; + } + + Minecraft.getInstance().execute(() -> { + Minecraft.getInstance().options.guiScale().set(scale); + Minecraft.getInstance().options.save(); + Minecraft.getInstance().resizeDisplay(); + }); + return true; + } + + @Override + public boolean setGamma(double gamma) { + Minecraft.getInstance().execute(() -> { + Minecraft.getInstance().options.gamma().set(gamma); + Minecraft.getInstance().options.save(); + }); + return true; + } + + @Override + public boolean setChatVisibility(ChatVisibilityHandler.VISIBILITY visibility) { + ChatVisiblity result; + switch (visibility) { + case SHOW: + result = ChatVisiblity.FULL; + break; + + case COMMANDS_ONLY: + result = ChatVisiblity.SYSTEM; + break; + + case HIDE: + result = ChatVisiblity.HIDDEN; + break; + + default: + return false; + } + + Minecraft.getInstance().execute(() -> { + Minecraft.getInstance().options.chatVisibility().set(result); + Minecraft.getInstance().options.save(); + }); + return true; + } + + @Override + public boolean setRenderDistance(int chunks) { + Minecraft.getInstance().execute(() -> { + Minecraft.getInstance().options.renderDistance().set(chunks); + Minecraft.getInstance().options.save(); + }); + return true; + } + + @Override + public WorldState getWorldState() { + if (Minecraft.getInstance().level == null) { + return WorldState.OTHER; + } + + return Minecraft.getInstance().isLocalServer() ? WorldState.SINGLEPLAYER : WorldState.MULTIPLAYER; + } + + @Override + public String getSPWorldName() { + if (getWorldState() != WorldState.SINGLEPLAYER) { + return null; + } + + IntegratedServer server = Minecraft.getInstance().getSingleplayerServer(); + + if (server != null) { + return server.getWorldData().getLevelName(); + } + + LOGGER.info("Attempted to get SP World Name, but no integrated server was found!"); + return null; + } + + @Override + public String getServerIP() { + if (getWorldState() != WorldState.MULTIPLAYER) { + return null; + } + + if (Minecraft.getInstance().getCurrentServer() != null) { + return Minecraft.getInstance().getCurrentServer().ip; + } + + LOGGER.info("Failed to get Server IP!"); + return null; + } + + private void connectIfTrue(boolean connect) { + if (connect) { + joinServer(serverData.ip); + } else { + Minecraft.getInstance().setScreen(new JoinMultiplayerScreen(new TitleScreen())); + } + } +} diff --git a/MinecraftMod/forge/1.21/src/main/java/com/mosadie/effectmc/ItemToast.java b/MinecraftMod/forge/1.21/src/main/java/com/mosadie/effectmc/ItemToast.java new file mode 100644 index 0000000..8f66edd --- /dev/null +++ b/MinecraftMod/forge/1.21/src/main/java/com/mosadie/effectmc/ItemToast.java @@ -0,0 +1,67 @@ +package com.mosadie.effectmc; + +import com.google.gson.JsonElement; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.datafixers.util.Pair; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.JsonOps; +import com.mosadie.effectmc.core.EffectMCCore; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.toasts.RecipeToast; +import net.minecraft.client.gui.components.toasts.Toast; +import net.minecraft.client.gui.components.toasts.ToastComponent; +import net.minecraft.nbt.TagParser; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +public class ItemToast implements Toast { + private final static ResourceLocation TEXTURE = ResourceLocation.tryParse("toast/recipe"); + private ItemStack item; + private Component title; + private Component body; + + private long lastChanged; + private boolean changed = true; + + public ItemToast(String itemData, Component title, Component body, EffectMCCore core) { + if (Minecraft.getInstance().level == null) { + EffectMC.LOGGER.warn("Error decoding item data: No level"); + item = new ItemStack(Items.AIR); + this.title = title; + this.body = body; + return; + } + DataResult> dataResult = ItemStack.CODEC.decode(RegistryOps.create(JsonOps.INSTANCE, Minecraft.getInstance().level.registryAccess()), core.fromJson(itemData)); + + if (dataResult.error().isPresent()) { + EffectMC.LOGGER.warn("Error decoding item data: " + dataResult.error().get()); + item = new ItemStack(Items.AIR); + } else if (dataResult.result().isPresent()) { + item = dataResult.result().get().getFirst(); + } else { + EffectMC.LOGGER.warn("Error decoding item data: No item data"); + item = new ItemStack(Items.AIR); + } + + this.title = title; + this.body = body; + } + @Override + public Visibility render(GuiGraphics guiGraphics, ToastComponent toastComponent, long time) { + if (changed) { + lastChanged = time; + changed = false; + } + + + guiGraphics.blitSprite(TEXTURE, 0, 0, this.width(), this.height()); + guiGraphics.drawString(toastComponent.getMinecraft().font, title, 30, 7, -16777216, false); + guiGraphics.drawString(toastComponent.getMinecraft().font, body, 30, 18, -16777216, false); + guiGraphics.renderFakeItem(item, 8, 8); + return (double)(time - this.lastChanged) >= 5000.0D * toastComponent.getNotificationDisplayTimeMultiplier() ? Visibility.HIDE : Visibility.SHOW; + } +} diff --git a/MinecraftMod/forge/1.21/src/main/resources/META-INF/neoforge.mods.toml b/MinecraftMod/forge/1.21/src/main/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..8d42371 --- /dev/null +++ b/MinecraftMod/forge/1.21/src/main/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,70 @@ +# This is an example neoforge.mods.toml file. It contains the data relating to the loading mods. +# There are several mandatory fields (#mandatory), and many more that are optional (#optional). +# The overall format is standard TOML format, v0.5.0. +# Note that there are a couple of TOML lists in this file. +# Find more information on toml format here: https://github.com/toml-lang/toml +# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml +modLoader="javafml" #mandatory +# A version range to match for said mod loader - for regular FML @Mod it will be the the FML version. This is currently 47. +loaderVersion="${loader_version_range}" #mandatory +# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties. +# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here. +license="${mod_license}" +# A URL to refer people to when problems occur with this mod +#issueTrackerURL="https://github.com/mosadie/effectmc/issues" #optional +# A list of mods - how many allowed here is determined by the individual mod loader +[[mods]] #mandatory +# The modid of the mod +modId="${mod_id}" #mandatory +# The version number of the mod +version="${mod_version}" #mandatory +# A display name for the mod +displayName="${mod_name}" #mandatory +# A URL to query for updates for this mod. See the JSON update specification https://docs.neoforged.net/docs/misc/updatechecker/ +updateJSONURL="https://raw.githubusercontent.com/MoSadie/EffectMC/main/MinecraftMod/forge/update.json" #optional +# A URL for the "homepage" for this mod, displayed in the mod UI +displayURL="https://modrinth.com/mod/effectmc" #optional +# A file name (in the root of the mod JAR) containing a logo for display +#logoFile="examplemod.png" #optional +# A text field displayed in the mod UI +#credits="" #optional +# A text field displayed in the mod UI +authors="${mod_authors}" #optional +# Display Test controls the display for your mod in the server connection screen +# MATCH_VERSION means that your mod will cause a red X if the versions on client and server differ. This is the default behaviour and should be what you choose if you have server and client elements to your mod. +# IGNORE_SERVER_VERSION means that your mod will not cause a red X if it's present on the server but not on the client. This is what you should use if you're a server only mod. +# IGNORE_ALL_VERSION means that your mod will not cause a red X if it's present on the client or the server. This is a special case and should only be used if your mod has no server component. +# NONE means that no display test is set on your mod. You need to do this yourself, see IExtensionPoint.DisplayTest for more information. You can define any scheme you wish with this value. +# IMPORTANT NOTE: this is NOT an instruction as to which environments (CLIENT or DEDICATED SERVER) your mod loads on. Your mod should load (and maybe do nothing!) whereever it finds itself. +#displayTest="IGNORE_ALL_VERSION" # MATCH_VERSION is the default if nothing is specified (#optional) + +# The description text for the mod (multi line!) (#mandatory) +description='''${mod_description}''' +# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional. +[[dependencies.${mod_id}]] #optional + # the modid of the dependency + modId="neoforge" #mandatory + # Does this dependency have to exist - if not, ordering below must be specified + mandatory=true #mandatory + # The version range of the dependency + versionRange="${neo_version_range}" #mandatory + # An ordering relationship for the dependency - BEFORE or AFTER required if the dependency is not mandatory + # BEFORE - This mod is loaded BEFORE the dependency + # AFTER - This mod is loaded AFTER the dependency + ordering="NONE" + # Side this dependency is applied on - BOTH, CLIENT, or SERVER + side="BOTH" +# Here's another dependency +[[dependencies.${mod_id}]] + modId="minecraft" + mandatory=true + # This version range declares a minimum of the current minecraft version up to but not including the next major version + versionRange="${minecraft_version_range}" + ordering="NONE" + side="BOTH" + +# Features are specific properties of the game environment, that you may want to declare you require. This example declares +# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't +# stop your mod loading on the server for example. +#[features.${mod_id}] +#openGLVersion="[3.2,)" diff --git a/MinecraftMod/forge/1.21/src/main/resources/pack.mcmeta b/MinecraftMod/forge/1.21/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..59c5240 --- /dev/null +++ b/MinecraftMod/forge/1.21/src/main/resources/pack.mcmeta @@ -0,0 +1,8 @@ +{ + "pack": { + "description": { + "text": "${mod_id} resources" + }, + "pack_format": ${pack_format_number} + } +} diff --git a/MinecraftMod/forge/update.json b/MinecraftMod/forge/update.json index 8ac3d0f..3d5cef4 100644 --- a/MinecraftMod/forge/update.json +++ b/MinecraftMod/forge/update.json @@ -1,5 +1,8 @@ { "homepage": "https://github.com/MoSadie/EffectMC", + "1.21": { + "2.3.0": "See https://github.com/MoSadie/EffectMC/releases/tag/v2.3.0" + }, "1.20.6": { "2.3.0": "See https://github.com/MoSadie/EffectMC/releases/tag/v2.3.0" }, @@ -72,6 +75,8 @@ "1.0.0": "See https://github.com/MoSadie/EffectMC/releases/tag/v1.0.0" }, "promos": { + "1.21-latest": "2.3.0", + "1.21-recommended": "2.3.0", "1.20.6-latest": "2.3.0", "1.20.6-recommended": "2.3.0", "1.20.4-latest": "2.3.0",