diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..b589d56 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/discord.xml b/.idea/discord.xml new file mode 100644 index 0000000..cf77f1e --- /dev/null +++ b/.idea/discord.xml @@ -0,0 +1,7 @@ + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..7d5105d --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,17 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..7505437 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..fe0b0da --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..a0ec829 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules/Minecraft-Mods-BetterPingDisplay.main.iml b/.idea/modules/Minecraft-Mods-BetterPingDisplay.main.iml new file mode 100644 index 0000000..893b0bd --- /dev/null +++ b/.idea/modules/Minecraft-Mods-BetterPingDisplay.main.iml @@ -0,0 +1,18 @@ + + + + + + + FABRIC + MIXIN + MCP + + 1 + + + + + + \ No newline at end of file diff --git a/.idea/modules/Minecraft-Mods-BetterPingDisplay.test.iml b/.idea/modules/Minecraft-Mods-BetterPingDisplay.test.iml new file mode 100644 index 0000000..893b0bd --- /dev/null +++ b/.idea/modules/Minecraft-Mods-BetterPingDisplay.test.iml @@ -0,0 +1,18 @@ + + + + + + + FABRIC + MIXIN + MCP + + 1 + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations/Minecraft_Client.xml b/.idea/runConfigurations/Minecraft_Client.xml new file mode 100644 index 0000000..3880acd --- /dev/null +++ b/.idea/runConfigurations/Minecraft_Client.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/.idea/runConfigurations/Minecraft_Server.xml b/.idea/runConfigurations/Minecraft_Server.xml new file mode 100644 index 0000000..13fc9e5 --- /dev/null +++ b/.idea/runConfigurations/Minecraft_Server.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..88baff0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Vlad Marica + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index e368a76..171f258 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,32 @@ -# Minecraft-Mods +# Better Ping Display - Fabric Edition -Updated versions of abandoned mods and/or mods that are slow updating. \ No newline at end of file +[![](http://cf.way2muchnoise.eu/full_406343_downloads.svg)](https://curseforge.com/minecraft/mc-mods/better-ping-display-fabric) + +A [Fabric](https://fabricmc.net/) mod for Minecraft to display each player's ping in the player list as a number. + +Go [**here**](https://github.com/vladmarica/better-ping-display) for the Minecraft Forge edition of this mod. + +![](https://i.imgur.com/HTrH0i2.png) + +This is a client-side mod. The server doesn't need to have it installed. It works even when playing on vanilla servers. + +## Configuration +This mod's config file is `betterpingdisplay.json`. It contains the following options: + +| Option | Default Value | Description | +|---|---|---| +| autoColorPingText | `true` | Whether to color a player's ping based on their latency. E.g, low latency = green, high latency = red | +| renderPingBars | `false` | Whether to also draw the default Minecraft ping bars | +| pingTextColor | `#A0A0A0` | The ping text color to use. Only works whens `autoColorPingText` is false | +| pingTextFormatString | `%dms` | The format string for ping text. Must include a `%d`, which will be replaced dynamically by the actual ping value. + +## Supported Minecraft Versions +* **1.15.x** +* **1.16.x** +* **1.17.x** +* **1.18.x** +* **1.19.x** +* **1.20.x** + +## Requirements +* [Fabric](https://fabricmc.net/) diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..dc95a46 --- /dev/null +++ b/build.gradle @@ -0,0 +1,69 @@ +plugins { + id 'fabric-loom' version '1.6-SNAPSHOT' + id 'maven-publish' +} + +sourceCompatibility = JavaVersion.VERSION_17 +targetCompatibility = JavaVersion.VERSION_17 + +archivesBaseName = project.archives_base_name +version = project.mod_version +group = project.maven_group +minecraft_version = project.minecraft_version + +dependencies { + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + testImplementation 'junit:junit:4.13' +} + +processResources { + duplicatesStrategy = 'WARN' + + filesMatching("fabric.mod.json") { + expand "version": project.version, "minecraft_version": minecraft_version + } +} + +tasks.withType(JavaCompile) { + options.encoding = "UTF-8" +} + +tasks.withType(JavaCompile).configureEach { + it.options.release = 17 +} + +jar { + from "LICENSE" +} + +// configure the maven publication +publishing { + publications { + mavenJava(MavenPublication) { + from components.java + } + } + + // select the repositories you want to publish to + repositories { + // uncomment to publish to the local maven + // mavenLocal() + } +} + +sourceSets { + main.java { + include 'com/vladmarica/betterpingdisplay/**/*' + exclude 'net/fabricmc/*' + } + test.java { + include 'com/vladmarica/betterpingdisplay/**/*' + } +} + +test { + useJUnit() +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..9de50fa --- /dev/null +++ b/gradle.properties @@ -0,0 +1,16 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G + +# Fabric Properties +# check these on https://fabricmc.net/use +minecraft_version=1.20.5 +yarn_mappings=1.20.5+build.1 +loader_version=0.15.10 + +# Mod Properties +mod_version = 1.1.2 +maven_group = com.vladmarica +archives_base_name = BetterPingDisplay-Fabric + +# Dependencies +fabric_version=0.97.6+1.20.5 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..c1962a7 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..509c4a2 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..aeb74cb --- /dev/null +++ b/gradlew @@ -0,0 +1,245 @@ +#!/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 + +# 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 + + +# 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, 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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /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. +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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..5b60df3 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +pluginManagement { + repositories { + jcenter() + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } +} diff --git a/src/main/java/com/vladmarica/betterpingdisplay/BetterPingDisplayMod.java b/src/main/java/com/vladmarica/betterpingdisplay/BetterPingDisplayMod.java new file mode 100644 index 0000000..29a4e33 --- /dev/null +++ b/src/main/java/com/vladmarica/betterpingdisplay/BetterPingDisplayMod.java @@ -0,0 +1,52 @@ +package com.vladmarica.betterpingdisplay; + +import com.vladmarica.betterpingdisplay.Config.ConfigData; +import java.io.File; +import java.nio.file.Path; +import net.fabricmc.api.ModInitializer; +import net.fabricmc.loader.api.FabricLoader; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class BetterPingDisplayMod implements ModInitializer { + public static final String MODID = "betterpingdisplay"; + public static final Logger LOGGER = LogManager.getLogger(MODID); + private static final String CONFIG_FILE_NAME = MODID + ".json"; + private static BetterPingDisplayMod INSTANCE; + + private Config config = new Config(); + + @Override + public void onInitialize() { + INSTANCE = this; + + Path configFilePath = FabricLoader.getInstance().getConfigDir().resolve(CONFIG_FILE_NAME); + File configFile = configFilePath.toFile(); + if (configFile.exists()) { + try { + ConfigData data = Config.loadConfigFile(configFile); + config = new Config(data); + Config.writeConfigFile(configFile, data); + } catch (Exception ex) { + LOGGER.error("Failed to load config file, using default. Error: {}", ex.getMessage()); + } + } else { + try { + LOGGER.warn("Could not find config file, creating a default one"); + Config.writeConfigFile(configFile, new ConfigData()); + } catch (Exception ex) { + LOGGER.error("Failed to write default config file. Error: {}", ex.getMessage()); + } + } + + LOGGER.info("BetterPingDisplay mod loaded"); + } + + public Config getConfig() { + return config; + } + + public static BetterPingDisplayMod instance() { + return INSTANCE; + } +} diff --git a/src/main/java/com/vladmarica/betterpingdisplay/Config.java b/src/main/java/com/vladmarica/betterpingdisplay/Config.java new file mode 100644 index 0000000..90373a8 --- /dev/null +++ b/src/main/java/com/vladmarica/betterpingdisplay/Config.java @@ -0,0 +1,105 @@ +package com.vladmarica.betterpingdisplay; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.annotations.Expose; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Serializable; + +public class Config { + private static final int DEFAULT_PING_TEXT_COLOR = 0xA0A0A0; + private static final String DEFAULT_PING_TEXT_FORMAT = "%dms"; + + private final boolean autoColorPingText; + private final boolean renderPingBars; + private int textColor = DEFAULT_PING_TEXT_COLOR; + private String textFormatString = DEFAULT_PING_TEXT_FORMAT; + + public Config(ConfigData configFileFormat) { + if (configFileFormat.pingTextColor.startsWith("#")) { + try { + textColor = Integer.parseInt(configFileFormat.pingTextColor.substring(1), 16); + } + catch (NumberFormatException ex) { + BetterPingDisplayMod.LOGGER.error("Config option 'pingTextColor' is invalid - it must be a hex color code"); + } + } + else { + BetterPingDisplayMod.LOGGER.error("Config option 'pingTextColor' is invalid - it must be a hex color code"); + } + + if (configFileFormat.pingTextFormatString.contains("%d")) { + textFormatString = configFileFormat.pingTextFormatString; + } + else { + BetterPingDisplayMod.LOGGER.error("Config option 'pingTextFormatString' is invalid - it needs to contain %d"); + } + + autoColorPingText = configFileFormat.autoColorPingText; + renderPingBars = configFileFormat.renderPingBars; + } + + public Config() { + this(new ConfigData()); + } + + public int getTextColor() { + return this.textColor; + } + + public String getTextFormatString() { + return this.textFormatString; + } + + public boolean shouldAutoColorPingText() { + return this.autoColorPingText; + } + + public boolean shouldRenderPingBars() { + return this.renderPingBars; + } + + public static ConfigData loadConfigFile(File configFile) throws IOException { + FileReader reader = null; + try { + Gson gson = new Gson(); + reader = new FileReader(configFile); + return gson.fromJson(reader, ConfigData.class); + } + finally { + if (reader != null) { + reader.close(); + } + } + } + + public static void writeConfigFile(File configFile, ConfigData data) throws IOException { + FileWriter writer = null; + try { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + writer = new FileWriter(configFile); + writer.write(gson.toJson(data)); + } finally { + if (writer != null) { + writer.close(); + } + } + } + + public static class ConfigData implements Serializable { + @Expose + private boolean autoColorPingText = true; + + @Expose + private boolean renderPingBars = false; + + @Expose + private String pingTextColor = "#A0A0A0"; + + @Expose + private String pingTextFormatString = "%dms"; + } +} diff --git a/src/main/java/com/vladmarica/betterpingdisplay/hud/ColorUtil.java b/src/main/java/com/vladmarica/betterpingdisplay/hud/ColorUtil.java new file mode 100644 index 0000000..0d2ff9e --- /dev/null +++ b/src/main/java/com/vladmarica/betterpingdisplay/hud/ColorUtil.java @@ -0,0 +1,38 @@ +package com.vladmarica.betterpingdisplay.hud; + +import com.google.common.annotations.VisibleForTesting; + +public final class ColorUtil { + public static int interpolate(int colorStart, int colorEnd, float offset) { + if (offset < 0 || offset > 1) { + throw new IllegalArgumentException("Offset must be between 0.0 and 1.0"); + } + + int redDiff = getRed(colorEnd) - getRed(colorStart); + int greenDiff = getGreen(colorEnd) - getGreen(colorStart); + int blueDiff = getBlue(colorEnd) - getBlue(colorStart); + + int newRed = Math.round(getRed(colorStart) + (redDiff * offset)); + int newGreen = Math.round(getGreen(colorStart) + (greenDiff * offset)); + int newBlue = Math.round(getBlue(colorStart) + (blueDiff * offset)); + + return (newRed << 16) | (newGreen << 8) | newBlue; + } + + @VisibleForTesting + static int getRed(int color) { + return (color >> 16) & 0xFF; + } + + @VisibleForTesting + static int getGreen(int color) { + return (color >> 8) & 0xFF; + } + + @VisibleForTesting + static int getBlue(int color) { + return color & 0xFF; + } + + private ColorUtil() {} +} diff --git a/src/main/java/com/vladmarica/betterpingdisplay/hud/CustomPlayerListHud.java b/src/main/java/com/vladmarica/betterpingdisplay/hud/CustomPlayerListHud.java new file mode 100644 index 0000000..6cef10d --- /dev/null +++ b/src/main/java/com/vladmarica/betterpingdisplay/hud/CustomPlayerListHud.java @@ -0,0 +1,42 @@ +package com.vladmarica.betterpingdisplay.hud; + +import com.mojang.blaze3d.systems.RenderSystem; +import com.vladmarica.betterpingdisplay.BetterPingDisplayMod; +import com.vladmarica.betterpingdisplay.Config; +import com.vladmarica.betterpingdisplay.mixin.PlayerListHudInvoker; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.font.TextRenderer; +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.gui.hud.PlayerListHud; +import net.minecraft.client.network.PlayerListEntry; +import net.minecraft.client.util.math.MatrixStack; + +public final class CustomPlayerListHud { + private static final int PING_TEXT_RENDER_OFFSET = -13; + private static final int PING_BARS_WIDTH = 11; + private static final Config config = BetterPingDisplayMod.instance().getConfig(); + + public static void renderPingDisplay( + MinecraftClient client, PlayerListHud hud, DrawContext context, int width, int x, int y, PlayerListEntry player) { + String pingString = String.format(config.getTextFormatString(), player.getLatency()); + int pingStringWidth = client.textRenderer.getWidth(pingString); + int pingTextColor = config.shouldAutoColorPingText() + ? PingColors.getColor(player.getLatency()) : config.getTextColor(); + int textX = width + x - pingStringWidth + PING_TEXT_RENDER_OFFSET; + + if (!config.shouldRenderPingBars()) { + textX += PING_BARS_WIDTH; + } + + // Draw the ping text for the given player + context.drawTextWithShadow(client.textRenderer, pingString, textX, y, pingTextColor); + + if (config.shouldRenderPingBars()) { + ((PlayerListHudInvoker) hud).invokeRenderLatencyIcon(context, width, x, y, player); + } else { + // If we don't render ping bars, we need to reset the render system color so the rest + // of the player list renders properly + RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); + } + } +} diff --git a/src/main/java/com/vladmarica/betterpingdisplay/hud/PingColors.java b/src/main/java/com/vladmarica/betterpingdisplay/hud/PingColors.java new file mode 100644 index 0000000..578bc66 --- /dev/null +++ b/src/main/java/com/vladmarica/betterpingdisplay/hud/PingColors.java @@ -0,0 +1,39 @@ +package com.vladmarica.betterpingdisplay.hud; + +import net.minecraft.util.math.MathHelper; + +public final class PingColors { + public static final int PING_START = 0; + public static final int PING_MID = 150; + public static final int PING_END = 300; + + public static final int COLOR_GREY = 0x535353; + public static final int COLOR_START = 0x00E676; + public static final int COLOR_MID = 0xD6CD30; + public static final int COLOR_END = 0xE53935; + + public static int getColor(int ping) { + if (ping < PING_START) { + return COLOR_GREY; + } + + if (ping < PING_MID) { + return ColorUtil.interpolate( + COLOR_START, + COLOR_MID, + computeOffset(PING_START, PING_MID, ping)); + } + + return ColorUtil.interpolate( + COLOR_MID, + COLOR_END, + computeOffset(PING_MID, PING_END, Math.min(ping, PING_END))); + } + + private static float computeOffset(int start, int end, int value) { + float offset = (value - start) / (float) ( end - start); + return MathHelper.clamp(offset, 0.0F, 1.0F); + } + + private PingColors() {} +} diff --git a/src/main/java/com/vladmarica/betterpingdisplay/mixin/PlayerListHudInvoker.java b/src/main/java/com/vladmarica/betterpingdisplay/mixin/PlayerListHudInvoker.java new file mode 100644 index 0000000..04e0360 --- /dev/null +++ b/src/main/java/com/vladmarica/betterpingdisplay/mixin/PlayerListHudInvoker.java @@ -0,0 +1,13 @@ +package com.vladmarica.betterpingdisplay.mixin; + +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.gui.hud.PlayerListHud; +import net.minecraft.client.network.PlayerListEntry; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(PlayerListHud.class) +public interface PlayerListHudInvoker { + @Invoker("renderLatencyIcon") + void invokeRenderLatencyIcon(DrawContext context, int width, int x, int y, PlayerListEntry entry); +} diff --git a/src/main/java/com/vladmarica/betterpingdisplay/mixin/PlayerListHudMixin.java b/src/main/java/com/vladmarica/betterpingdisplay/mixin/PlayerListHudMixin.java new file mode 100644 index 0000000..e31ceb0 --- /dev/null +++ b/src/main/java/com/vladmarica/betterpingdisplay/mixin/PlayerListHudMixin.java @@ -0,0 +1,51 @@ +package com.vladmarica.betterpingdisplay.mixin; + +import com.vladmarica.betterpingdisplay.hud.CustomPlayerListHud; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.gui.hud.PlayerListHud; +import net.minecraft.client.network.PlayerListEntry; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.scoreboard.Scoreboard; +import net.minecraft.scoreboard.ScoreboardObjective; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Constant; +import org.spongepowered.asm.mixin.injection.ModifyConstant; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(PlayerListHud.class) +public abstract class PlayerListHudMixin { + @Unique + @Final + private static final int PLAYER_SLOT_EXTRA_WIDTH = 45; + + @Shadow + @Final + private MinecraftClient client; + + /** + * Increases the int constant {@code 13} in the {@link PlayerListHud#render} method by + * {@value #PLAYER_SLOT_EXTRA_WIDTH}. This constant is used to define the width of the "slots" in the player list. + * In order to fit the ping text, this needs to be increased. + */ + @ModifyConstant(method = "render", constant = @Constant(intValue = 13)) + private int modifySlotWidthConstant(int original) { + return original + PLAYER_SLOT_EXTRA_WIDTH; + } + + /** + * Redirects the call to {@code renderLatencyIcon} in {@link PlayerListHud#render} to instead call + * {@link CustomPlayerListHud#renderPingDisplay}. + */ + @Redirect(method = "render", + at = @At(value = "INVOKE", target = "net/minecraft/client/gui/hud/PlayerListHud.renderLatencyIcon(Lnet/minecraft/client/gui/DrawContext;IIILnet/minecraft/client/network/PlayerListEntry;)V")) + private void redirectRenderLatencyIconCall( + PlayerListHud instance, DrawContext context, int width, int x, int y, @NotNull PlayerListEntry entry) { + CustomPlayerListHud.renderPingDisplay(client, instance, context, width, x, y, entry); + } +} diff --git a/src/main/resources/assets/betterpingdisplay/icon.png b/src/main/resources/assets/betterpingdisplay/icon.png new file mode 100644 index 0000000..de82d52 Binary files /dev/null and b/src/main/resources/assets/betterpingdisplay/icon.png differ diff --git a/src/main/resources/betterpingdisplay.mixins.json b/src/main/resources/betterpingdisplay.mixins.json new file mode 100644 index 0000000..9a55f5f --- /dev/null +++ b/src/main/resources/betterpingdisplay.mixins.json @@ -0,0 +1,15 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "com.vladmarica.betterpingdisplay.mixin", + "compatibilityLevel": "JAVA_21", + "mixins": [ + ], + "client": [ + "PlayerListHudInvoker", + "PlayerListHudMixin" + ], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..73a500b --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,36 @@ +{ + "schemaVersion": 1, + "id": "betterpingdisplay", + "version": "${version}", + + "name": "Better Ping Display", + "description": "Shows the actual ping number instead of just bars in the player list!", + "authors": [ + "Quintinity", + "Yuuki2012" + ], + "contact": { + "homepage": "https://git.raiza.dev/Raiza.dev/Minecraft-Mods/src/branch/BetterPingDisplay/", + "sources": "https://git.raiza.dev/Raiza.dev/Minecraft-Mods/src/branch/BetterPingDisplay/", + "issues": "https://git.raiza.dev/Raiza.dev/Minecraft-Mods/issues" + }, + + "license": "MIT", + "icon": "assets/betterpingdisplay/icon.png", + + "environment": "client", + "entrypoints": { + "main": [ + "com.vladmarica.betterpingdisplay.BetterPingDisplayMod" + ] + }, + "mixins": [ + "betterpingdisplay.mixins.json" + ], + + "depends": { + "fabricloader": ">=0.15", + "minecraft": "${minecraft_version}" + }, + "suggests": {} +} diff --git a/src/test/java/com/vladmarica/betterpingdisplay/hud/ColorUtilTest.java b/src/test/java/com/vladmarica/betterpingdisplay/hud/ColorUtilTest.java new file mode 100644 index 0000000..51c4ab2 --- /dev/null +++ b/src/test/java/com/vladmarica/betterpingdisplay/hud/ColorUtilTest.java @@ -0,0 +1,49 @@ +package com.vladmarica.betterpingdisplay.hud; + +import static com.vladmarica.betterpingdisplay.hud.PingColors.COLOR_MID; +import static com.vladmarica.betterpingdisplay.hud.PingColors.COLOR_START; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link ColorUtil} */ +@RunWith(JUnit4.class) +public class ColorUtilTest { + + @Test + public void testExtractComponents() { + int color = 0xD6C130; + assertEquals(0xD6, ColorUtil.getRed(color)); + assertEquals(0xC1, ColorUtil.getGreen(color)); + assertEquals(0x30, ColorUtil.getBlue(color)); + } + + @Test + public void testInterpolation_zero() { + int color = ColorUtil.interpolate(COLOR_START, COLOR_MID, 0F); + assertEquals(COLOR_START, color); + } + + @Test + public void testInterpolation_middle() { + int color = ColorUtil.interpolate(COLOR_START, COLOR_MID, 0.5F); + assertEquals(0x6b, ColorUtil.getRed(color)); + assertEquals(0xda, ColorUtil.getGreen(color)); + assertEquals(0x53, ColorUtil.getBlue(color)); + } + + @Test + public void testInterpolation_one() { + int color = ColorUtil.interpolate(COLOR_START, COLOR_MID, 1F); + assertEquals(COLOR_MID, color); + } + + @Test + public void testInterpolation_invalidOffset() { + assertThrows(IllegalArgumentException.class, () -> ColorUtil.interpolate(0, 1, -0.1F)); + assertThrows(IllegalArgumentException.class, () -> ColorUtil.interpolate(0, 1, 1.1F)); + } +}