diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..4231567 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = tab +insert_final_newline = true +max_line_length = 120 + +[{*.json,pack.mcmeta}] +insert_final_newline = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f811f6a --- /dev/null +++ b/.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/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..1fb4826 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,21 @@ +name: Build + +on: [push, pull_request] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Build with Gradle + uses: gradle/actions/setup-gradle@v3 + with: + arguments: build diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..31d2550 --- /dev/null +++ b/.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/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..fdfa68d --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,49 @@ +plugins { + id("java") + id("net.neoforged.gradle.userdev") version "7.0.134" + id("idea") +} + +base { + archivesName = "${properties["mod_id"]}-neoforge" + version = "${properties["mod_version"]}+mc${properties["minecraft_version"]}" +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(properties["java_version"] as String) + } + + withSourcesJar() + sourceCompatibility = JavaVersion.valueOf("VERSION_${properties["java_version"]}") + targetCompatibility = JavaVersion.valueOf("VERSION_${properties["java_version"]}") +} + +dependencies { + implementation("net.neoforged:neoforge:${properties["neoforge_version"]}") +} + +tasks { + processResources { + filesMatching("META-INF/neoforge.mods.toml") { + expand(project.properties) + } + } + + compileJava { + options.encoding = "UTF-8" + } + + jar { + from("LICENSE") { + rename { "${it}_${project.properties["mod_id"]}" } + } + } +} + +idea { + module { + isDownloadSources = true + isDownloadJavadoc = true + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..79b93bc --- /dev/null +++ b/gradle.properties @@ -0,0 +1,20 @@ +# Gradle Properties +org.gradle.jvmargs=-Xmx1G +org.gradle.daemon=false +org.gradle.debug=false + +# Environment Properties +java_version=21 +minecraft_version=1.20.6 +minecraft_version_range=[1.20.6,1.21) +neoforge_version=20.6.75-beta +neoforge_version_range=[20.6,) +fml_version_range=[2,) + +## Mod Properties +mod_id=skintypefix +mod_name=Skin type fix +mod_version=0.1.0-beta.1 +mod_license=GPL-3.0-or-later +mod_description=Fix wrong skin type for some players. +mod_authors=Puqns67 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..b82aa23 --- /dev/null +++ b/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/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +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/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..ee7dda7 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,17 @@ +pluginManagement { + repositories { + mavenLocal() + gradlePluginPortal() + maven { + name = "Neoforged" + url = uri("https://maven.neoforged.net/releases") + } + mavenCentral() + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" +} + +rootProject.name = "SkinTypeFix" diff --git a/src/main/java/icu/puqns67/skintypefix/Config.java b/src/main/java/icu/puqns67/skintypefix/Config.java new file mode 100644 index 0000000..a118a9e --- /dev/null +++ b/src/main/java/icu/puqns67/skintypefix/Config.java @@ -0,0 +1,27 @@ +package icu.puqns67.skintypefix; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.fml.event.config.ModConfigEvent; +import net.neoforged.neoforge.common.ModConfigSpec; + +@OnlyIn(Dist.CLIENT) +@EventBusSubscriber(modid = SkinTypeFix.MODID, bus = EventBusSubscriber.Bus.MOD) +public class Config { + private static final ModConfigSpec.Builder BUILDER = new ModConfigSpec.Builder(); + + private static final ModConfigSpec.BooleanValue SKIP_FIX_FOR_SLIM_PLAYERS = BUILDER + .comment("Skip fix for SLIM players, default to true") + .define("skipFixForSlimPlayers", true); + + static final ModConfigSpec SPEC = BUILDER.build(); + + public static boolean skipFixForSlimPlayers; + + @SubscribeEvent + static void onLoad(final ModConfigEvent event) { + skipFixForSlimPlayers = SKIP_FIX_FOR_SLIM_PLAYERS.get(); + } +} diff --git a/src/main/java/icu/puqns67/skintypefix/SkinTypeFix.java b/src/main/java/icu/puqns67/skintypefix/SkinTypeFix.java new file mode 100644 index 0000000..cdb04c7 --- /dev/null +++ b/src/main/java/icu/puqns67/skintypefix/SkinTypeFix.java @@ -0,0 +1,27 @@ +package icu.puqns67.skintypefix; + +import com.mojang.logging.LogUtils; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.config.ModConfig; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import org.slf4j.Logger; + +@OnlyIn(Dist.CLIENT) +@Mod(SkinTypeFix.MODID) +public class SkinTypeFix { + public static final String MODID = "skintypefix"; + public static final Logger LOGGER = LogUtils.getLogger(); + + public SkinTypeFix(IEventBus modEventBus, ModContainer modContainer) { + modEventBus.addListener(this::setup); + modContainer.registerConfig(ModConfig.Type.CLIENT, Config.SPEC); + } + + private void setup(final FMLClientSetupEvent event) { + LOGGER.info("Loaded!"); + } +} diff --git a/src/main/java/icu/puqns67/skintypefix/mixin/accessor/HttpTextureAccessor.java b/src/main/java/icu/puqns67/skintypefix/mixin/accessor/HttpTextureAccessor.java new file mode 100644 index 0000000..0cc1d65 --- /dev/null +++ b/src/main/java/icu/puqns67/skintypefix/mixin/accessor/HttpTextureAccessor.java @@ -0,0 +1,9 @@ +package icu.puqns67.skintypefix.mixin.accessor; + +import com.mojang.blaze3d.platform.NativeImage; + +public interface HttpTextureAccessor { + void skinTypeFix$joinLoader(); + + NativeImage skinTypeFix$getImage(); +} diff --git a/src/main/java/icu/puqns67/skintypefix/mixin/patch/HttpTextureMixin.java b/src/main/java/icu/puqns67/skintypefix/mixin/patch/HttpTextureMixin.java new file mode 100644 index 0000000..96b9778 --- /dev/null +++ b/src/main/java/icu/puqns67/skintypefix/mixin/patch/HttpTextureMixin.java @@ -0,0 +1,74 @@ +package icu.puqns67.skintypefix.mixin.patch; + +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.platform.TextureUtil; +import icu.puqns67.skintypefix.SkinTypeFix; +import icu.puqns67.skintypefix.mixin.accessor.HttpTextureAccessor; +import net.minecraft.client.renderer.texture.HttpTexture; +import net.minecraft.client.renderer.texture.SimpleTexture; +import net.minecraft.resources.ResourceLocation; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import org.spongepowered.asm.mixin.*; + +import javax.annotation.Nullable; +import java.io.InputStream; +import java.util.concurrent.CompletableFuture; + +@OnlyIn(Dist.CLIENT) +@Mixin(HttpTexture.class) +public abstract class HttpTextureMixin extends SimpleTexture implements HttpTextureAccessor { + @Unique + @Nullable + protected NativeImage skinTypeFix$image = null; + @Shadow + @Nullable + private CompletableFuture future; + @Shadow + @Final + private boolean processLegacySkin; + + public HttpTextureMixin(ResourceLocation location) { + super(location); + } + + @Shadow + @Nullable + protected abstract NativeImage processLegacySkin(NativeImage image); + + @Unique + public void skinTypeFix$joinLoader() { + if (this.future != null) { + this.future.join(); + } + } + + @Unique + public NativeImage skinTypeFix$getImage() { + return this.skinTypeFix$image; + } + + /** + * @author Puqns67 + * @reason Overwrite the load() function to create another NativeImage at loading, using for check skin. + */ + @Nullable + @Overwrite + private NativeImage load(InputStream stream) { + try { + var buffer = TextureUtil.readResource(stream); + buffer.rewind(); + this.skinTypeFix$image = NativeImage.read(buffer); + buffer.rewind(); + var result = NativeImage.read(buffer); + if (this.processLegacySkin) { + this.skinTypeFix$image = this.processLegacySkin(this.skinTypeFix$image); + result = this.processLegacySkin(result); + } + return result; + } catch (Exception exception) { + SkinTypeFix.LOGGER.warn("Error while loading the skin texture", exception); + } + return null; + } +} diff --git a/src/main/java/icu/puqns67/skintypefix/mixin/patch/SkinManagerMixin.java b/src/main/java/icu/puqns67/skintypefix/mixin/patch/SkinManagerMixin.java new file mode 100644 index 0000000..52c49ce --- /dev/null +++ b/src/main/java/icu/puqns67/skintypefix/mixin/patch/SkinManagerMixin.java @@ -0,0 +1,97 @@ +package icu.puqns67.skintypefix.mixin.patch; + +import com.llamalad7.mixinextras.sugar.Local; +import com.mojang.authlib.SignatureState; +import com.mojang.authlib.minecraft.MinecraftProfileTexture; +import com.mojang.authlib.minecraft.MinecraftProfileTextures; +import icu.puqns67.skintypefix.Config; +import icu.puqns67.skintypefix.SkinTypeFix; +import icu.puqns67.skintypefix.mixin.accessor.HttpTextureAccessor; +import icu.puqns67.skintypefix.util.Utils; +import icu.puqns67.skintypefix.util.image.Places; +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.PlayerSkin; +import net.minecraft.client.resources.SkinManager; +import net.minecraft.resources.ResourceLocation; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@OnlyIn(Dist.CLIENT) +@Mixin(SkinManager.class) +public class SkinManagerMixin { + @Inject(method = "registerTextures", at = @At("TAIL"), cancellable = true) + private void onRegisterTextures( + UUID uuid, + MinecraftProfileTextures textures, + CallbackInfoReturnable> cir, + @Local(ordinal = 0) MinecraftProfileTexture skinTextureOrigin, + @Local(ordinal = 0) CompletableFuture skinFuture, + @Local(ordinal = 1) CompletableFuture capeFuture, + @Local(ordinal = 2) CompletableFuture elytraFuture, + @Local PlayerSkin.Model skinModelOrigin, + @Local String skinUrl + ) { + // Skip fix if using internal skin or uuid is invalid uuid + if (skinTextureOrigin == null || Utils.isInvalidUUID(uuid)) { + return; + } + + // If model is defaults to SLIM, and config `skipFixForSlimPlayers` is set to true, + // checks are skipped because some skins have bad pixels + if (Config.skipFixForSlimPlayers && skinModelOrigin == PlayerSkin.Model.SLIM) { + return; + } + + var textureManager = Minecraft.getInstance().getTextureManager(); + + CompletableFuture modelFuture = skinFuture.thenApply(v -> { + // Get texture from TextureManager + var skinTexture = (HttpTextureAccessor) textureManager.getTexture(skinFuture.join()); + + // Wait skin loading if it needed fetch from web + skinTexture.skinTypeFix$joinLoader(); + + // Get image from PlayerSkinTexture + var skinImage = skinTexture.skinTypeFix$getImage(); + if (skinImage == null) { + SkinTypeFix.LOGGER.warn("[SkinTypeFix] [{}] {GET_IMAGE} An error occurred while getting image!", uuid); + return skinModelOrigin; + } + + // Check skin type + var needFix = switch (skinModelOrigin) { + case SLIM -> !Places.PLAYER.isAllBlack(skinImage); + case WIDE -> Places.PLAYER.isAllBlack(skinImage); + }; + + if (needFix) { + var skinModelFixed = Utils.reverseModelType(skinModelOrigin); + SkinTypeFix.LOGGER.info("[SkinTypeFix] [{}] Fixed skin type: {} -> {}", uuid, skinModelOrigin, skinModelFixed); + return skinModelFixed; + } + + return skinModelOrigin; + }); + + // Return + cir.setReturnValue( + CompletableFuture + .allOf(skinFuture, capeFuture, elytraFuture, modelFuture) + .thenApply(v -> new PlayerSkin( + skinFuture.join(), + skinUrl, + capeFuture.join(), + elytraFuture.join(), + modelFuture.join(), + textures.signatureState() == SignatureState.SIGNED + )) + ); + } +} diff --git a/src/main/java/icu/puqns67/skintypefix/util/Utils.java b/src/main/java/icu/puqns67/skintypefix/util/Utils.java new file mode 100644 index 0000000..9052fe8 --- /dev/null +++ b/src/main/java/icu/puqns67/skintypefix/util/Utils.java @@ -0,0 +1,20 @@ +package icu.puqns67.skintypefix.util; + +import net.minecraft.client.resources.PlayerSkin; + +import java.util.UUID; + +public class Utils { + private static final UUID INVALID_UUID = new UUID(0, 0); + + public static PlayerSkin.Model reverseModelType(PlayerSkin.Model type) { + return switch (type) { + case SLIM -> PlayerSkin.Model.WIDE; + case WIDE -> PlayerSkin.Model.SLIM; + }; + } + + public static boolean isInvalidUUID(UUID uuid) { + return INVALID_UUID.equals(uuid); + } +} diff --git a/src/main/java/icu/puqns67/skintypefix/util/image/Places.java b/src/main/java/icu/puqns67/skintypefix/util/image/Places.java new file mode 100644 index 0000000..6573304 --- /dev/null +++ b/src/main/java/icu/puqns67/skintypefix/util/image/Places.java @@ -0,0 +1,40 @@ +package icu.puqns67.skintypefix.util.image; + +import com.mojang.blaze3d.platform.NativeImage; + +import java.util.ArrayList; + +public class Places { + public static final Places PLAYER = Places.forPlayer(); + private final ArrayList squares = new ArrayList<>(); + + public Places() { + } + + public static Places forPlayer() { + var result = new Places(); + result.add(50, 16, 51, 19); + result.add(50, 16, 51, 19); + result.add(54, 20, 55, 31); + result.add(42, 48, 43, 51); + result.add(46, 52, 47, 63); + return result; + } + + public void add(Square square) { + this.squares.add(square); + } + + public void add(int x1, int y1, int x2, int y2) { + this.add(new Square(x1, y1, x2, y2)); + } + + public boolean isAllBlack(NativeImage image) { + for (var square : this.squares) { + if (!square.isAllBlack(image)) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/icu/puqns67/skintypefix/util/image/Point.java b/src/main/java/icu/puqns67/skintypefix/util/image/Point.java new file mode 100644 index 0000000..9d43b2d --- /dev/null +++ b/src/main/java/icu/puqns67/skintypefix/util/image/Point.java @@ -0,0 +1,15 @@ +package icu.puqns67.skintypefix.util.image; + +import com.mojang.blaze3d.platform.NativeImage; + +public record Point(int x, int y) { + public Point { + if (x < 0 || y < 0) { + throw new IllegalArgumentException(String.format("Invalid position: %d, %d", x, y)); + } + } + + public boolean isBlack(NativeImage image) { + return image.getPixelRGBA(x, y) == 0xff000000; + } +} diff --git a/src/main/java/icu/puqns67/skintypefix/util/image/Square.java b/src/main/java/icu/puqns67/skintypefix/util/image/Square.java new file mode 100644 index 0000000..45c8c1b --- /dev/null +++ b/src/main/java/icu/puqns67/skintypefix/util/image/Square.java @@ -0,0 +1,39 @@ +package icu.puqns67.skintypefix.util.image; + +import com.mojang.blaze3d.platform.NativeImage; + +import java.util.ArrayList; + +public record Square(Point p1, Point p2) { + public Square { + // The point close to (0,0) is p1 + if (p2.x() < p1.x() || p1.x() == p2.x() && p2.y() < p1.y()) { + var tmp = p1; + p1 = p2; + p2 = tmp; + } + } + + public Square(int x1, int y1, int x2, int y2) { + this(new Point(x1, y1), new Point(x2, y2)); + } + + public ArrayList points() { + var result = new ArrayList(); + for (var Y = this.p1.y(); Y <= this.p2.y(); Y++) { + for (var X = this.p1.x(); X <= this.p2.x(); X++) { + result.add(new Point(X, Y)); + } + } + return result; + } + + public boolean isAllBlack(NativeImage image) { + for (var point : this.points()) { + if (!point.isBlack(image)) { + return false; + } + } + return true; + } +} diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..02385cf --- /dev/null +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,30 @@ +modLoader="javafml" +loaderVersion="${fml_version_range}" +license="${mod_license}" +issueTrackerURL="https://github.com/Puqns67/SkinTypeFix/issues" + +[[mods]] +modId="${mod_id}" +displayName="${mod_name}" +version="${mod_version}" +displayURL="https://modrinth.com/mod/skintypefix" +logoFile="logo.png" +authors="${mod_authors}" +description='''${mod_description}''' + +[[mixins]] +config="${mod_id}.mixins.json" + +[[dependencies.${mod_id}]] + modId="minecraft" + type="required" + versionRange="${minecraft_version_range}" + ordering="NONE" + side="CLIENT" + +[[dependencies.${mod_id}]] + modId="neoforge" + type="required" + versionRange="${neoforge_version_range}" + ordering="NONE" + side="CLIENT" diff --git a/src/main/resources/assets/skintypefix/lang/en_us.json b/src/main/resources/assets/skintypefix/lang/en_us.json new file mode 100644 index 0000000..af871fc --- /dev/null +++ b/src/main/resources/assets/skintypefix/lang/en_us.json @@ -0,0 +1,3 @@ +{ + "fml.menu.mods.info.description.skintypefix": "Fix an issue where the skin type of some players did not match the skin type of the actual skin file." +} \ No newline at end of file diff --git a/src/main/resources/assets/skintypefix/lang/zh_cn.json b/src/main/resources/assets/skintypefix/lang/zh_cn.json new file mode 100644 index 0000000..c32eaa6 --- /dev/null +++ b/src/main/resources/assets/skintypefix/lang/zh_cn.json @@ -0,0 +1,3 @@ +{ + "fml.menu.mods.info.description.skintypefix": "修复部分玩家的皮肤类型与实际皮肤文件的实际皮肤类型不匹配的问题。" +} \ No newline at end of file diff --git a/src/main/resources/logo.png b/src/main/resources/logo.png new file mode 100644 index 0000000..bce421d Binary files /dev/null and b/src/main/resources/logo.png differ diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..7405306 --- /dev/null +++ b/src/main/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "skintypefix resources", + "pack_format": 4 + } +} \ No newline at end of file diff --git a/src/main/resources/skintypefix.mixins.json b/src/main/resources/skintypefix.mixins.json new file mode 100644 index 0000000..e85c430 --- /dev/null +++ b/src/main/resources/skintypefix.mixins.json @@ -0,0 +1,12 @@ +{ + "package": "icu.puqns67.skintypefix.mixin.patch", + "client": [ + "HttpTextureMixin", + "SkinManagerMixin" + ], + "compatibilityLevel": "JAVA_21", + "injectors": { + "defaultRequire": 1 + }, + "required": true +} \ No newline at end of file