commit d84e120cca10722aa847f1a2163a215ab60d82e3 Author: BRanulf Date: Sat Apr 19 16:49:41 2025 +0800 仓库搬迁 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c37caf --- /dev/null +++ b/.gitignore @@ -0,0 +1,118 @@ +# User-specific stuff +.idea/ + +*.iml +*.ipr +*.iws + +# IntelliJ +out/ +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Cache of project +.gradletasknamecache + +**/build/ + +# Common working directory +run/ + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a91dff3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Semmieboy_YT + +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 new file mode 100644 index 0000000..9f5b9f1 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +Download the mod at [Modrinth](https://modrinth.com/mod/disc-jockey) or [CurseForge](https://www.curseforge.com/minecraft/mc-mods/disc-jockey) diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..078787e --- /dev/null +++ b/build.gradle @@ -0,0 +1,87 @@ +plugins { + id 'fabric-loom' version '1.9.2' + id 'maven-publish' +} + +version = project.mod_version +group = project.maven_group + +repositories { + maven { url "https://maven.shedaniel.me/" } + maven {url "https://maven.terraformersmc.com/"} +} + +dependencies { + // To change the versions see the gradle.properties file +// implementation files("libs/modmenu-13.0.3.jar") +// implementation files("libs/modmenu-13.0.3.pom") + 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}" + + include modApi("me.shedaniel.cloth:cloth-config-fabric:17.0.142") { + exclude(group: "net.fabricmc.fabric-api") + } + +// modCompileOnly("com.terraformersmc:modmenu:13.0.3")、 + modCompileOnly files("libs/modmenu-13.0.3.jar") +} + +processResources { + inputs.property "version", project.version + filteringCharset "UTF-8" + + filesMatching("fabric.mod.json") { + expand "version": project.version + } +} + +def targetJavaVersion = 21 +tasks.withType(JavaCompile).configureEach { + // ensure that the encoding is set to UTF-8, no matter what the system default is + // this fixes some edge cases with special characters not displaying correctly + // see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html + // If Javadoc is generated, this must be specified in that task too. + it.options.encoding = "UTF-8" + if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { + it.options.release = targetJavaVersion + } +} + +java { + def javaVersion = JavaVersion.toVersion(targetJavaVersion) + if (JavaVersion.current() < javaVersion) { + toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) + } + archivesBaseName = project.archives_base_name + // 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() +} + +jar { + from("LICENSE") { + rename { "${it}_${project.archivesBaseName}" } + } +} + +// 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. + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..2512360 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,18 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G +# Fabric Properties +# check these on https://modmuss50.me/fabric.html +minecraft_version=1.21.4 +yarn_mappings=1.21.4+build.8 +loader_version=0.16.10 +# Mod Properties +mod_version=1.14.514.013 +maven_group=semmiedev +archives_base_name=disc_jockey +# Dependencies +# check this on https://modmuss50.me/fabric.html + +fabric_version=0.119.2+1.21.4 +systemProp.http.sslVerify=false +systemProp.https.sslVerify=false +systemProp.javax.net.ssl.trustStoreType=WINDOWS-ROOT diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 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..d070599 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https://mirrors.aliyun.com/macports/distfiles/gradle/gradle-8.12.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..c53aefa --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/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/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-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*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 \ + "$@" + +# 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..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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=. +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%" == "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%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/libs/modmenu-13.0.3.pom b/libs/modmenu-13.0.3.pom new file mode 100644 index 0000000..4e0cc7a --- /dev/null +++ b/libs/modmenu-13.0.3.pom @@ -0,0 +1,8 @@ + + + 4.0.0 + com.terraformersmc + modmenu + 13.0.3 + diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..f91a4fe --- /dev/null +++ b/settings.gradle @@ -0,0 +1,9 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } +} diff --git a/src/main/java/semmiedev/disc_jockey/BinaryReader.java b/src/main/java/semmiedev/disc_jockey/BinaryReader.java new file mode 100644 index 0000000..9b81853 --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/BinaryReader.java @@ -0,0 +1,67 @@ +package semmiedev.disc_jockey; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class BinaryReader { + private final InputStream in; + private final ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); + + public BinaryReader(InputStream in) { + this.in = in; + } + + public int readInt() throws IOException { + return buffer.clear().put(readBytes(Integer.BYTES)).rewind().getInt(); + } + + public long readUInt() throws IOException { + return readInt() & 0xFFFFFFFFL; + } + + public int readUShort() throws IOException { + return readShort() & 0xFFFF; + } + + public short readShort() throws IOException { + return buffer.clear().put(readBytes(Short.BYTES)).rewind().getShort(); + } + + public String readString() throws IOException { + return new String(readBytes(readInt())); + } + + public float readFloat() throws IOException { + return buffer.clear().put(readBytes(Float.BYTES)).rewind().getFloat(); + } + + /*private int getStringLength() throws IOException { + int count = 0; + int shift = 0; + boolean more = true; + while (more) { + byte b = (byte) in.read(); + count |= (b & 0x7F) << shift; + shift += 7; + if ((b & 0x80) == 0) { + more = false; + } + } + return count; + }*/ + + public byte readByte() throws IOException { + int b = in.read(); + if (b < 0) throw new EOFException(); + return (byte)(b); + } + + public byte[] readBytes(int length) throws IOException { + byte[] bytes = new byte[length]; + for (int i = 0; i < length; i++) bytes[i] = readByte(); + return bytes; + } +} diff --git a/src/main/java/semmiedev/disc_jockey/Config.java b/src/main/java/semmiedev/disc_jockey/Config.java new file mode 100644 index 0000000..b8c8124 --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/Config.java @@ -0,0 +1,43 @@ +package semmiedev.disc_jockey; + +import me.shedaniel.autoconfig.ConfigData; +import me.shedaniel.autoconfig.annotation.ConfigEntry; + +import java.util.ArrayList; + +@me.shedaniel.autoconfig.annotation.Config(name = Main.MOD_ID) +@me.shedaniel.autoconfig.annotation.Config.Gui.Background("textures/block/note_block.png") +public class Config implements ConfigData { + public boolean hideWarning; + @ConfigEntry.Gui.Tooltip(count = 2) public boolean disableAsyncPlayback; + @ConfigEntry.Gui.Tooltip(count = 2) public boolean omnidirectionalNoteBlockSounds = true; + + public enum ExpectedServerVersion { + All, + v1_20_4_Or_Earlier, + v1_20_5_Or_Later; + + @Override + public String toString() { + if(this == All) { + return "All (universal)"; + }else if(this == v1_20_4_Or_Earlier) { + return "≤1.20.4"; + }else if (this == v1_20_5_Or_Later) { + return "≥1.20.5"; + }else { + return super.toString(); + } + } + } + + @ConfigEntry.Gui.EnumHandler(option = ConfigEntry.Gui.EnumHandler.EnumDisplayOption.BUTTON) + @ConfigEntry.Gui.Tooltip(count = 4) + public ExpectedServerVersion expectedServerVersion = ExpectedServerVersion.All; + + @ConfigEntry.Gui.Tooltip(count = 1) + public float delayPlaybackStartBySecs = 0.0f; + + @ConfigEntry.Gui.Excluded + public ArrayList favorites = new ArrayList<>(); +} diff --git a/src/main/java/semmiedev/disc_jockey/DiscjockeyCommand.java b/src/main/java/semmiedev/disc_jockey/DiscjockeyCommand.java new file mode 100644 index 0000000..9c23dbb --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/DiscjockeyCommand.java @@ -0,0 +1,262 @@ +package semmiedev.disc_jockey; + +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.arguments.FloatArgumentType; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.context.CommandContext; +import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; +import net.minecraft.block.enums.NoteBlockInstrument; +import net.minecraft.client.MinecraftClient; +import net.minecraft.command.CommandSource; +import net.minecraft.text.Text; +import org.jetbrains.annotations.Nullable; +import semmiedev.disc_jockey.gui.screen.DiscJockeyScreen; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Map; +import java.util.Optional; + +import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.argument; +import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.literal; + +public class DiscjockeyCommand { + + + public static void register(CommandDispatcher commandDispatcher) { + final ArrayList instrumentNames = new ArrayList<>(); + for (NoteBlockInstrument instrument : NoteBlockInstrument.values()) { + instrumentNames.add(instrument.toString().toLowerCase()); + } + final ArrayList instrumentNamesAndAll = new ArrayList<>(instrumentNames); + instrumentNamesAndAll.add("all"); + final ArrayList instrumentNamesAndNothing = new ArrayList<>(instrumentNames); + instrumentNamesAndNothing.add("nothing"); + + commandDispatcher.register( + literal("discjockey") + .executes(context -> { + FabricClientCommandSource source = context.getSource(); + if (!isLoading(context)) { + MinecraftClient client = source.getClient(); + client.send(() -> client.setScreen(new DiscJockeyScreen())); + return 1; + } + return 0; + }) + .then(literal("reload") + .executes(context -> { + if (!isLoading(context)) { + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID+".reloading")); + SongLoader.loadSongs(); + return 1; + } + return 0; + }) + ) + .then(literal("play") + .then(argument("song", StringArgumentType.greedyString()) + .suggests((context, builder) -> CommandSource.suggestMatching(SongLoader.SONG_SUGGESTIONS, builder)) + .executes(context -> { + if (!isLoading(context)) { + String songName = StringArgumentType.getString(context, "song"); + Optional song = SongLoader.SONGS.stream().filter(input -> input.displayName.equals(songName)).findAny(); + if (song.isPresent()) { + Main.SONG_PLAYER.start(song.get()); + return 1; + } + context.getSource().sendError(Text.translatable(Main.MOD_ID+".song_not_found", songName)); + return 0; + } + return 0; + }) + ) + ) + .then(literal("stop") + .executes(context -> { + if (Main.SONG_PLAYER.running) { + Main.SONG_PLAYER.stop(); + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID+".stopped_playing", Main.SONG_PLAYER.song)); + return 1; + } + context.getSource().sendError(Text.translatable(Main.MOD_ID+".not_playing")); + return 0; + }) + ) + .then(literal("speed") + .then(argument("speed", FloatArgumentType.floatArg(0.0001F, 15.0F)) + .suggests((context, builder) -> CommandSource.suggestMatching(Arrays.asList("0.5", "0.75", "1", "1.25", "1.5", "2"), builder)) + .executes(context -> { + float newSpeed = FloatArgumentType.getFloat(context, "speed"); + Main.SONG_PLAYER.speed = newSpeed; + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".speed_changed", Main.SONG_PLAYER.speed)); + return 0; + }) + ) + ) + .then(literal("info") + .executes(context -> { + + if (!Main.SONG_PLAYER.running) { + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".info_not_running", Main.SONG_PLAYER.speed)); + return 0; + } + if (!Main.SONG_PLAYER.tuned) { + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".info_tuning", Main.SONG_PLAYER.song.displayName, Main.SONG_PLAYER.speed)); + return 0; + }else if(!Main.SONG_PLAYER.didSongReachEnd) { + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".info_playing", formatTimestamp((int) Main.SONG_PLAYER.getSongElapsedSeconds()), formatTimestamp((int) Main.SONG_PLAYER.song.getLengthInSeconds()), Main.SONG_PLAYER.song.displayName, Main.SONG_PLAYER.speed)); + return 0; + }else { + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".info_finished", Main.SONG_PLAYER.song != null ? Main.SONG_PLAYER.song.displayName : "???", Main.SONG_PLAYER.speed)); + return 0; + } + }) + ) + .then(literal("remapInstruments") + .executes(context -> { + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".instrument_info")); + return 0; + }) + .then(literal("map") + .then(argument("originalInstrument", StringArgumentType.word()) + .suggests((context, builder) -> CommandSource.suggestMatching(instrumentNamesAndAll, builder)) + .then(argument("newInstrument", StringArgumentType.word()) + .suggests((context, builder) -> CommandSource.suggestMatching(instrumentNamesAndNothing, builder)) + .executes(context -> { + String originalInstrumentStr = StringArgumentType.getString(context, "originalInstrument"); + String newInstrumentStr = StringArgumentType.getString(context, "newInstrument"); + @Nullable NoteBlockInstrument originalInstrument = null, newInstrument = null; + for(NoteBlockInstrument maybeInstrument : NoteBlockInstrument.values()) { + if(maybeInstrument.toString().equalsIgnoreCase(originalInstrumentStr)) { + originalInstrument = maybeInstrument; + } + if(maybeInstrument.toString().equalsIgnoreCase(newInstrumentStr)) { + newInstrument = maybeInstrument; + } + } + + if(originalInstrument == null && !originalInstrumentStr.equalsIgnoreCase("all")) { + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".invalid_instrument", originalInstrumentStr)); + return 0; + } + + if(newInstrument == null && !newInstrumentStr.equalsIgnoreCase("nothing")) { + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".invalid_instrument", newInstrumentStr)); + return 0; + } + + // (originalInstrument == null) means: all instruments + // (newInstrument == null) means: nothing (represented by null in hashmap, so no special handling below) + + if(originalInstrument == null) { + // All instruments + for(NoteBlockInstrument instrument : NoteBlockInstrument.values()) { + Main.SONG_PLAYER.instrumentMap.put(instrument, newInstrument); + } + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".instrument_mapped_all", newInstrumentStr.toLowerCase())); + }else { + Main.SONG_PLAYER.instrumentMap.put(originalInstrument, newInstrument); + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".instrument_mapped", originalInstrumentStr.toLowerCase(), newInstrumentStr.toLowerCase())); + } + return 1; + }) + ) + ) + ) + .then(literal("unmap") + .then(argument("instrument", StringArgumentType.word()) + .suggests((context, builder) -> CommandSource.suggestMatching(instrumentNames, builder)) + .executes(context -> { + String instrumentStr = StringArgumentType.getString(context, "instrument"); + + NoteBlockInstrument instrument = null; + for(NoteBlockInstrument maybeInstrument : NoteBlockInstrument.values()) { + if(maybeInstrument.toString().equalsIgnoreCase(instrumentStr)) { + instrument = maybeInstrument; + break; + } + } + + if(instrument == null) { + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".invalid_instrument", instrumentStr)); + return 0; + } + + Main.SONG_PLAYER.instrumentMap.remove(instrument); + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".instrument_unmapped", instrumentStr.toLowerCase())); + return 1; + }) + ) + ) + .then(literal("show") + .executes(context -> { + if(Main.SONG_PLAYER.instrumentMap.isEmpty()) { + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".no_mapped_instruments")); + return 1; + } + + StringBuilder maps = new StringBuilder(); + for(Map.Entry entry : Main.SONG_PLAYER.instrumentMap.entrySet()) { + if(maps.length() > 0) { + maps.append(", "); + } + maps + .append(entry.getKey().toString().toLowerCase()) + .append("->") + .append(entry.getValue() == null ? "nothing" : entry.getValue().toString().toLowerCase()); + } + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".mapped_instruments", maps.toString())); + return 1; + }) + ) + .then(literal("clear") + .executes(context -> { + Main.SONG_PLAYER.instrumentMap.clear(); + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".instrument_maps_cleared")); + return 1; + }) + ) + ) + + .then(literal("loop") + .executes(context -> { + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".loop_status", Main.SONG_PLAYER.loopSong ? "yes" : "no")); + return 1; + }) + .then(literal("yes") + .executes(context -> { + Main.SONG_PLAYER.loopSong = true; + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".loop_enabled")); + return 1; + })) + .then(literal("no") + .executes(context -> { + Main.SONG_PLAYER.loopSong = false; + context.getSource().sendFeedback(Text.translatable(Main.MOD_ID + ".loop_disabled")); + return 1; + })) + ) + ); + } + + private static boolean isLoading(CommandContext context) { + if (SongLoader.loadingSongs) { + context.getSource().sendError(Text.translatable(Main.MOD_ID + ".still_loading")); + SongLoader.showToast = true; + return true; + } + return false; + } + + private static String padZeroes(int number, int length) { + StringBuilder builder = new StringBuilder("" + number); + while(builder.length() < length) + builder.insert(0, '0'); + return builder.toString(); + } + + private static String formatTimestamp(int seconds) { + return padZeroes(seconds / 60, 2) + ":" + padZeroes(seconds % 60, 2); + } +} diff --git a/src/main/java/semmiedev/disc_jockey/Main.java b/src/main/java/semmiedev/disc_jockey/Main.java new file mode 100644 index 0000000..19086dd --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/Main.java @@ -0,0 +1,90 @@ +package semmiedev.disc_jockey; + +import me.shedaniel.autoconfig.AutoConfig; +import me.shedaniel.autoconfig.ConfigHolder; +import me.shedaniel.autoconfig.serializer.JanksonConfigSerializer; +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; +import net.fabricmc.fabric.api.client.networking.v1.ClientLoginConnectionEvents; +import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.option.KeyBinding; +import net.minecraft.client.util.InputUtil; +import net.minecraft.client.world.ClientWorld; +import net.minecraft.text.MutableText; +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.glfw.GLFW; +import semmiedev.disc_jockey.gui.hud.BlocksOverlay; +import semmiedev.disc_jockey.gui.screen.DiscJockeyScreen; + +import java.io.File; +import java.util.ArrayList; + +public class Main implements ClientModInitializer { + public static final String MOD_ID = "disc_jockey"; + public static final MutableText NAME = Text.literal("Disc Jockey"); + public static final Logger LOGGER = LogManager.getLogger("Disc Jockey"); + public static final ArrayList TICK_LISTENERS = new ArrayList<>(); + public static final Previewer PREVIEWER = new Previewer(); + public static final SongPlayer SONG_PLAYER = new SongPlayer(); + + public static File songsFolder; + public static Config config; + public static ConfigHolder configHolder; + + @Override + public void onInitializeClient() { + configHolder = AutoConfig.register(Config.class, JanksonConfigSerializer::new); + config = configHolder.getConfig(); + + songsFolder = new File(FabricLoader.getInstance().getConfigDir()+File.separator+MOD_ID+File.separator+"songs"); + if (!songsFolder.isDirectory()) songsFolder.mkdirs(); + + SongLoader.loadSongs(); + + KeyBinding openScreenKeyBind = KeyBindingHelper.registerKeyBinding(new KeyBinding(MOD_ID+".key_bind.open_screen", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_J, "key.category."+MOD_ID)); + + ClientTickEvents.START_CLIENT_TICK.register(new ClientTickEvents.StartTick() { + private ClientWorld prevWorld; + + @Override + public void onStartTick(MinecraftClient client) { + if (prevWorld != client.world) { + PREVIEWER.stop(); + SONG_PLAYER.stop(); + } + prevWorld = client.world; + + if (openScreenKeyBind.wasPressed()) { + if (SongLoader.loadingSongs) { + client.inGameHud.getChatHud().addMessage(Text.translatable(Main.MOD_ID+".still_loading").formatted(Formatting.RED)); + SongLoader.showToast = true; + } else { + client.setScreen(new DiscJockeyScreen()); + } + } + } + }); + + ClientTickEvents.START_WORLD_TICK.register(world -> { + for (ClientTickEvents.StartWorldTick listener : TICK_LISTENERS) listener.onStartTick(world); + }); + + ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + DiscjockeyCommand.register(dispatcher); + }); + + ClientLoginConnectionEvents.DISCONNECT.register((handler, client) -> { + PREVIEWER.stop(); + SONG_PLAYER.stop(); + }); + + HudRenderCallback.EVENT.register(BlocksOverlay::render); + } +} diff --git a/src/main/java/semmiedev/disc_jockey/ModMenuIntegration.java b/src/main/java/semmiedev/disc_jockey/ModMenuIntegration.java new file mode 100644 index 0000000..5b003fe --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/ModMenuIntegration.java @@ -0,0 +1,12 @@ +package semmiedev.disc_jockey; + +import com.terraformersmc.modmenu.api.ConfigScreenFactory; +import com.terraformersmc.modmenu.api.ModMenuApi; +import me.shedaniel.autoconfig.AutoConfig; + +public class ModMenuIntegration implements ModMenuApi { + @Override + public ConfigScreenFactory getModConfigScreenFactory() { + return parent -> AutoConfig.getConfigScreen(Config.class, parent).get(); + } +} diff --git a/src/main/java/semmiedev/disc_jockey/Note.java b/src/main/java/semmiedev/disc_jockey/Note.java new file mode 100644 index 0000000..1653780 --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/Note.java @@ -0,0 +1,54 @@ +package semmiedev.disc_jockey; + +import net.minecraft.block.Block; +import net.minecraft.block.Blocks; +import net.minecraft.block.enums.NoteBlockInstrument; + +import java.util.HashMap; + +public record Note(NoteBlockInstrument instrument, byte note) { + public static final HashMap INSTRUMENT_BLOCKS = new HashMap<>(); + + public static final byte LAYER_SHIFT = Short.SIZE; + public static final byte INSTRUMENT_SHIFT = Short.SIZE * 2; + public static final byte NOTE_SHIFT = Short.SIZE * 2 + Byte.SIZE; + + public static final NoteBlockInstrument[] INSTRUMENTS = new NoteBlockInstrument[]{ + NoteBlockInstrument.HARP, + NoteBlockInstrument.BASS, + NoteBlockInstrument.BASEDRUM, + NoteBlockInstrument.SNARE, + NoteBlockInstrument.HAT, + NoteBlockInstrument.GUITAR, + NoteBlockInstrument.FLUTE, + NoteBlockInstrument.BELL, + NoteBlockInstrument.CHIME, + NoteBlockInstrument.XYLOPHONE, + NoteBlockInstrument.IRON_XYLOPHONE, + NoteBlockInstrument.COW_BELL, + NoteBlockInstrument.DIDGERIDOO, + NoteBlockInstrument.BIT, + NoteBlockInstrument.BANJO, + NoteBlockInstrument.PLING + + }; + + static { + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.HARP, Blocks.AIR); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.BASEDRUM, Blocks.STONE); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.SNARE, Blocks.SAND); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.HAT, Blocks.GLASS); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.BASS, Blocks.OAK_PLANKS); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.FLUTE, Blocks.CLAY); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.BELL, Blocks.GOLD_BLOCK); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.GUITAR, Blocks.WHITE_WOOL); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.CHIME, Blocks.PACKED_ICE); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.XYLOPHONE, Blocks.BONE_BLOCK); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.IRON_XYLOPHONE, Blocks.IRON_BLOCK); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.COW_BELL, Blocks.SOUL_SAND); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.DIDGERIDOO, Blocks.PUMPKIN); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.BIT, Blocks.EMERALD_BLOCK); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.BANJO, Blocks.HAY_BLOCK); + INSTRUMENT_BLOCKS.put(NoteBlockInstrument.PLING, Blocks.GLOWSTONE); + } +} diff --git a/src/main/java/semmiedev/disc_jockey/Previewer.java b/src/main/java/semmiedev/disc_jockey/Previewer.java new file mode 100644 index 0000000..572e716 --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/Previewer.java @@ -0,0 +1,48 @@ +package semmiedev.disc_jockey; + +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.world.ClientWorld; +import net.minecraft.sound.SoundCategory; +import net.minecraft.util.math.Vec3d; + +public class Previewer implements ClientTickEvents.StartWorldTick { + public boolean running; + + private int i; + private float tick; + private Song song; + + public void start(Song song) { + this.song = song; + Main.TICK_LISTENERS.add(this); + running = true; + } + + public void stop() { + MinecraftClient.getInstance().send(() -> Main.TICK_LISTENERS.remove(this)); + running = false; + i = 0; + tick = 0; + } + + @Override + public void onStartTick(ClientWorld world) { + while (running) { + long note = song.notes[i]; + if ((short)note == Math.round(tick)) { + Vec3d pos = MinecraftClient.getInstance().gameRenderer.getCamera().getPos(); + world.playSound(pos.x, pos.y, pos.z, Note.INSTRUMENTS[(byte)(note >> Note.INSTRUMENT_SHIFT)].getSound().value(), SoundCategory.RECORDS, 3, (float)Math.pow(2.0, ((byte)(note >> Note.NOTE_SHIFT) - 12) / 12.0), false); + i++; + if (i >= song.notes.length) { + stop(); + break; + } + } else { + break; + } + } + + tick += song.tempo / 100f / 20f; + } +} diff --git a/src/main/java/semmiedev/disc_jockey/Song.java b/src/main/java/semmiedev/disc_jockey/Song.java new file mode 100644 index 0000000..fae4373 --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/Song.java @@ -0,0 +1,43 @@ +package semmiedev.disc_jockey; + +import semmiedev.disc_jockey.gui.SongListWidget; + +import java.util.ArrayList; + +public class Song { + public final ArrayList uniqueNotes = new ArrayList<>(); + + public long[] notes = new long[0]; + + public short length, height, tempo, loopStartTick; + public String fileName, name, author, originalAuthor, description, displayName; + public byte autoSaving, autoSavingDuration, timeSignature, vanillaInstrumentCount, formatVersion, loop, maxLoopCount; + public int minutesSpent, leftClicks, rightClicks, blocksAdded, blocksRemoved; + public String importFileName; + + public SongListWidget.SongEntry entry; + public String searchableFileName, searchableName; + + @Override + public String toString() { + return displayName; + } + + public double millisecondsToTicks(long milliseconds) { + // From NBS Format: The tempo of the song multiplied by 100 (for example, 1225 instead of 12.25). Measured in ticks per second. + double songSpeed = (tempo / 100.0) / 20.0; // 20 Ticks per second (temp / 100 = 20) would be 1x speed + double oneMsTo20TickFraction = 1.0 / 50.0; + return milliseconds * oneMsTo20TickFraction * songSpeed; + } + + public double ticksToMilliseconds(double ticks) { + double songSpeed = (tempo / 100.0) / 20.0; + double oneMsTo20TickFraction = 1.0 / 50.0; + return ticks / oneMsTo20TickFraction / songSpeed; + } + + public double getLengthInSeconds() { + return ticksToMilliseconds(length) / 1000.0; + } + +} diff --git a/src/main/java/semmiedev/disc_jockey/SongLoader.java b/src/main/java/semmiedev/disc_jockey/SongLoader.java new file mode 100644 index 0000000..5e0e44b --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/SongLoader.java @@ -0,0 +1,130 @@ +package semmiedev.disc_jockey; + +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.toast.SystemToast; +import net.minecraft.text.Text; +import semmiedev.disc_jockey.gui.SongListWidget; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; + +public class SongLoader { + public static final ArrayList SONGS = new ArrayList<>(); + public static final ArrayList SONG_SUGGESTIONS = new ArrayList<>(); + public static volatile boolean loadingSongs; + public static volatile boolean showToast; + + public static void loadSongs() { + if (loadingSongs) return; + new Thread(() -> { + loadingSongs = true; + SONGS.clear(); + SONG_SUGGESTIONS.clear(); + SONG_SUGGESTIONS.add("Songs are loading, please wait"); + for (File file : Main.songsFolder.listFiles()) { + Song song = null; + try { + song = loadSong(file); + } catch (Exception exception) { + Main.LOGGER.error("Unable to read or parse song {}", file.getName(), exception); + } + if (song != null) SONGS.add(song); + } + for (Song song : SONGS) SONG_SUGGESTIONS.add(song.displayName); + Main.config.favorites.removeIf(favorite -> SongLoader.SONGS.stream().map(song -> song.fileName).noneMatch(favorite::equals)); + + if (showToast && MinecraftClient.getInstance().textRenderer != null) SystemToast.add(MinecraftClient.getInstance().getToastManager(), SystemToast.Type.PACK_LOAD_FAILURE, Main.NAME, Text.translatable(Main.MOD_ID+".loading_done")); + showToast = true; + loadingSongs = false; + }).start(); + } + + public static Song loadSong(File file) throws IOException { + if (file.isFile()) { + BinaryReader reader = new BinaryReader(Files.newInputStream(file.toPath())); + Song song = new Song(); + + song.fileName = file.getName().replaceAll("[\\n\\r]", ""); + + song.length = reader.readShort(); + + boolean newFormat = song.length == 0; + if (newFormat) { + song.formatVersion = reader.readByte(); + song.vanillaInstrumentCount = reader.readByte(); + song.length = reader.readShort(); + } + + song.height = reader.readShort(); + song.name = reader.readString().replaceAll("[\\n\\r]", ""); + song.author = reader.readString().replaceAll("[\\n\\r]", ""); + song.originalAuthor = reader.readString().replaceAll("[\\n\\r]", ""); + song.description = reader.readString().replaceAll("[\\n\\r]", ""); + song.tempo = reader.readShort(); + song.autoSaving = reader.readByte(); + song.autoSavingDuration = reader.readByte(); + song.timeSignature = reader.readByte(); + song.minutesSpent = reader.readInt(); + song.leftClicks = reader.readInt(); + song.rightClicks = reader.readInt(); + song.blocksAdded = reader.readInt(); + song.blocksRemoved = reader.readInt(); + song.importFileName = reader.readString().replaceAll("[\\n\\r]", ""); + + if (newFormat) { + song.loop = reader.readByte(); + song.maxLoopCount = reader.readByte(); + song.loopStartTick = reader.readShort(); + } + + song.displayName = song.name.replaceAll("\\s", "").isEmpty() ? song.fileName : song.name+" ("+song.fileName+")"; + song.entry = new SongListWidget.SongEntry(song, SONGS.size()); + song.entry.favorite = Main.config.favorites.contains(song.fileName); + song.searchableFileName = song.fileName.toLowerCase().replaceAll("\\s", ""); + song.searchableName = song.name.toLowerCase().replaceAll("\\s", ""); + + short tick = -1; + short jumps; + while ((jumps = reader.readShort()) != 0) { + tick += jumps; + short layer = -1; + while ((jumps = reader.readShort()) != 0) { + layer += jumps; + + byte instrumentId = reader.readByte(); + byte noteId = (byte)(reader.readByte() - 33); + + if (newFormat) { + // Data that is not needed as it only works with commands + reader.readByte(); // Velocity + reader.readByte(); // Panning + reader.readShort(); // Pitch + } + + if (noteId < 0) { + noteId = 0; + } else if (noteId > 24) { + noteId = 24; + } + + Note note = new Note(Note.INSTRUMENTS[instrumentId], noteId); + if (!song.uniqueNotes.contains(note)) song.uniqueNotes.add(note); + + song.notes = Arrays.copyOf(song.notes, song.notes.length + 1); + song.notes[song.notes.length - 1] = tick | layer << Note.LAYER_SHIFT | (long)instrumentId << Note.INSTRUMENT_SHIFT | (long)noteId << Note.NOTE_SHIFT; + } + } + + return song; + } + return null; + } + + public static void sort() { + SONGS.sort(Comparator.comparing(song -> song.displayName)); + } +} diff --git a/src/main/java/semmiedev/disc_jockey/SongPlayer.java b/src/main/java/semmiedev/disc_jockey/SongPlayer.java new file mode 100644 index 0000000..de45916 --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/SongPlayer.java @@ -0,0 +1,516 @@ +package semmiedev.disc_jockey; + +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.block.enums.NoteBlockInstrument; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.hud.ChatHud; +import net.minecraft.client.network.ClientPlayerEntity; +import net.minecraft.client.network.PlayerListEntry; +import net.minecraft.client.world.ClientWorld; +import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket; +import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket; +import net.minecraft.state.property.Properties; +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; +import net.minecraft.util.Hand; +import net.minecraft.util.Pair; +import net.minecraft.util.hit.BlockHitResult; +import net.minecraft.util.math.*; +import net.minecraft.world.GameMode; +import org.apache.commons.lang3.NotImplementedException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class SongPlayer implements ClientTickEvents.StartWorldTick { + private static boolean warned; + public boolean running; + public Song song; + + private int index; + private double tick; // Aka song position + private HashMap> noteBlocks = null; + public boolean tuned; + private long lastPlaybackTickAt = -1L; + + // Used to check and enforce packet rate limits to not get kicked + private long last100MsSpanAt = -1L; + private int last100MsSpanEstimatedPackets = 0; + // At how many packets/100ms should the player just reduce / stop sending packets for a while + final private int last100MsReducePacketsAfter = 300 / 10, last100MsStopPacketsAfter = 450 / 10; + // If higher than current millis, don't send any packets of this kind (temp disable) + private long reducePacketsUntil = -1L, stopPacketsUntil = -1L; + + // Use to limit swings and look to only each tick. More will not be visually visible anyway due to interpolation + private long lastLookSentAt = -1L, lastSwingSentAt = -1L; + + // The thread executing the tickPlayback method + private Thread playbackThread = null; + public long playbackLoopDelay = 5; + // Just for external debugging purposes + public HashMap missingInstrumentBlocks = new HashMap<>(); + public float speed = 1.0f; // Toy + + private long lastInteractAt = -1; + private float availableInteracts = 8; + private int tuneInitialUntunedBlocks = -1; + private HashMap> notePredictions = new HashMap<>(); + public boolean didSongReachEnd = false; + public boolean loopSong = false; + private long pausePlaybackUntil = -1L; // Set after tuning, if configured + + public SongPlayer() { + Main.TICK_LISTENERS.add(this); + } + + public @NotNull HashMap instrumentMap = new HashMap<>(); // Toy + public synchronized void startPlaybackThread() { + if(Main.config.disableAsyncPlayback) { + playbackThread = null; + return; + } + + this.playbackThread = new Thread(() -> { + Thread ownThread = this.playbackThread; + while(ownThread == this.playbackThread) { + try { + // Accuracy doesn't really matter at this precision imo + Thread.sleep(playbackLoopDelay); + }catch (Exception ex) { + ex.printStackTrace(); + } + tickPlayback(); + } + }); + this.playbackThread.start(); + } + + public synchronized void stopPlaybackThread() { + this.playbackThread = null; // Should stop on its own then + } + + public synchronized void start(Song song) { + if (!Main.config.hideWarning && !warned) { + MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(Text.translatable("disc_jockey.warning").formatted(Formatting.BOLD, Formatting.RED)); + warned = true; + return; + } + if (running) stop(); + this.song = song; + //Main.LOGGER.info("Song length: " + song.length + " and tempo " + song.tempo); + //Main.TICK_LISTENERS.add(this); + if(this.playbackThread == null) startPlaybackThread(); + running = true; + lastPlaybackTickAt = System.currentTimeMillis(); + last100MsSpanAt = System.currentTimeMillis(); + last100MsSpanEstimatedPackets = 0; + reducePacketsUntil = -1L; + stopPacketsUntil = -1L; + lastLookSentAt = -1L; + lastSwingSentAt = -1L; + missingInstrumentBlocks.clear(); + didSongReachEnd = false; + } + + public synchronized void stop() { + //MinecraftClient.getInstance().send(() -> Main.TICK_LISTENERS.remove(this)); + stopPlaybackThread(); + running = false; + index = 0; + tick = 0; + noteBlocks = null; + notePredictions.clear(); + tuned = false; + tuneInitialUntunedBlocks = -1; + lastPlaybackTickAt = -1L; + last100MsSpanAt = -1L; + last100MsSpanEstimatedPackets = 0; + reducePacketsUntil = -1L; + stopPacketsUntil = -1L; + lastLookSentAt = -1L; + lastSwingSentAt = -1L; + didSongReachEnd = false; // Change after running stop() if actually ended cleanly + } + + public synchronized void tickPlayback() { + if (!running) { + lastPlaybackTickAt = -1L; + last100MsSpanAt = -1L; + return; + } + long previousPlaybackTickAt = lastPlaybackTickAt; + lastPlaybackTickAt = System.currentTimeMillis(); + if(last100MsSpanAt != -1L && System.currentTimeMillis() - last100MsSpanAt >= 100) { + last100MsSpanEstimatedPackets = 0; + last100MsSpanAt = System.currentTimeMillis(); + }else if (last100MsSpanAt == -1L) { + last100MsSpanAt = System.currentTimeMillis(); + last100MsSpanEstimatedPackets = 0; + } + if(noteBlocks != null && tuned) { + if(pausePlaybackUntil != -1L && System.currentTimeMillis() <= pausePlaybackUntil) return; + while (running) { + MinecraftClient client = MinecraftClient.getInstance(); + GameMode gameMode = client.interactionManager == null ? null : client.interactionManager.getCurrentGameMode(); + // In the best case, gameMode would only be queried in sync Ticks, no here + if (gameMode == null || !gameMode.isSurvivalLike()) { + client.inGameHud.getChatHud().addMessage(Text.translatable(Main.MOD_ID+".player.invalid_game_mode", gameMode == null ? "unknown" : gameMode.getTranslatableName()).formatted(Formatting.RED)); + stop(); + return; + } + + long note = song.notes[index]; + final long now = System.currentTimeMillis(); + if ((short)note <= Math.round(tick)) { + @Nullable BlockPos blockPos = noteBlocks.get(Note.INSTRUMENTS[(byte)(note >> Note.INSTRUMENT_SHIFT)]).get((byte)(note >> Note.NOTE_SHIFT)); + if(blockPos == null) { + // Instrument got likely mapped to "nothing". Skip it + index++; + continue; + } + if (!canInteractWith(client.player, blockPos)) { + stop(); + client.inGameHud.getChatHud().addMessage(Text.translatable(Main.MOD_ID+".player.to_far").formatted(Formatting.RED)); + return; + } + Vec3d unit = Vec3d.ofCenter(blockPos, 0.5).subtract(client.player.getEyePos()).normalize(); + if((lastLookSentAt == -1L || now - lastLookSentAt >= 50) && last100MsSpanEstimatedPackets < last100MsReducePacketsAfter && (reducePacketsUntil == -1L || reducePacketsUntil < now)) { + client.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.LookAndOnGround(MathHelper.wrapDegrees((float) (MathHelper.atan2(unit.z, unit.x) * 57.2957763671875) - 90.0f), MathHelper.wrapDegrees((float) (-(MathHelper.atan2(unit.y, Math.sqrt(unit.x * unit.x + unit.z * unit.z)) * 57.2957763671875))), true, false)); + last100MsSpanEstimatedPackets++; + lastLookSentAt = now; + }else if(last100MsSpanEstimatedPackets >= last100MsReducePacketsAfter){ + reducePacketsUntil = Math.max(reducePacketsUntil, now + 500); + } + if(last100MsSpanEstimatedPackets < last100MsStopPacketsAfter && (stopPacketsUntil == -1L || stopPacketsUntil < now)) { + // TODO: 5/30/2022 Check if the block needs tuning + //client.interactionManager.attackBlock(blockPos, Direction.UP); + client.player.networkHandler.sendPacket(new PlayerActionC2SPacket(PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, blockPos, Direction.UP, 0)); + last100MsSpanEstimatedPackets++; + }else if(last100MsSpanEstimatedPackets >= last100MsStopPacketsAfter) { + Main.LOGGER.info("Stopping all packets for a bit!"); + stopPacketsUntil = Math.max(stopPacketsUntil, now + 250); + reducePacketsUntil = Math.max(reducePacketsUntil, now + 10000); + } + if(last100MsSpanEstimatedPackets < last100MsReducePacketsAfter && (reducePacketsUntil == -1L || reducePacketsUntil < now)) { + client.player.networkHandler.sendPacket(new PlayerActionC2SPacket(PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, blockPos, Direction.UP, 0)); + last100MsSpanEstimatedPackets++; + }else if(last100MsSpanEstimatedPackets >= last100MsReducePacketsAfter){ + reducePacketsUntil = Math.max(reducePacketsUntil, now + 500); + } + if((lastSwingSentAt == -1L || now - lastSwingSentAt >= 50) &&last100MsSpanEstimatedPackets < last100MsReducePacketsAfter && (reducePacketsUntil == -1L || reducePacketsUntil < now)) { + client.executeSync(() -> client.player.swingHand(Hand.MAIN_HAND)); + lastSwingSentAt = now; + last100MsSpanEstimatedPackets++; + }else if(last100MsSpanEstimatedPackets >= last100MsReducePacketsAfter){ + reducePacketsUntil = Math.max(reducePacketsUntil, now + 500); + } + + index++; + if (index >= song.notes.length) { + stop(); + didSongReachEnd = true; + if(loopSong) { + start(song); + } + break; + } + } else { + break; + } + } + + if(running) { // Might not be running anymore (prevent small offset on song, even if that is not played anymore) + long elapsedMs = previousPlaybackTickAt != -1L && lastPlaybackTickAt != -1L ? lastPlaybackTickAt - previousPlaybackTickAt : (16); // Assume 16ms if unknown + tick += song.millisecondsToTicks(elapsedMs) * speed; + } + } + } + + // TODO: 6/2/2022 Play note blocks every song tick, instead of every tick. That way the song will sound better + // 11/1/2023 Playback now done in separate thread. Not ideal but better especially when FPS are low. + @Override + public void onStartTick(ClientWorld world) { + MinecraftClient client = MinecraftClient.getInstance(); + if(world == null || client.world == null || client.player == null) return; + if(song == null || !running) return; + + // Clear outdated note predictions + ArrayList outdatedPredictions = new ArrayList<>(); + for(Map.Entry> entry : notePredictions.entrySet()) { + if(entry.getValue().getRight() < System.currentTimeMillis()) + outdatedPredictions.add(entry.getKey()); + } + for(BlockPos outdatedPrediction : outdatedPredictions) notePredictions.remove(outdatedPrediction); + + if (noteBlocks == null) { + noteBlocks = new HashMap<>(); + + ClientPlayerEntity player = client.player; + + // Create list of available noteblock positions per used instrument + HashMap> noteblocksForInstrument = new HashMap<>(); + for(NoteBlockInstrument instrument : NoteBlockInstrument.values()) + noteblocksForInstrument.put(instrument, new ArrayList<>()); + final Vec3d playerEyePos = player.getEyePos(); + + final int maxOffset; // Rough estimates, of which blocks could be in reach + if(Main.config.expectedServerVersion == Config.ExpectedServerVersion.v1_20_4_Or_Earlier) { + maxOffset = 7; + }else if(Main.config.expectedServerVersion == Config.ExpectedServerVersion.v1_20_5_Or_Later) { + maxOffset = (int) Math.ceil(player.getBlockInteractionRange() + 1.0 + 1.0); + }else if(Main.config.expectedServerVersion == Config.ExpectedServerVersion.All) { + maxOffset = Math.min(7, (int) Math.ceil(player.getBlockInteractionRange() + 1.0 + 1.0)); + }else { + throw new NotImplementedException("ExpectedServerVersion Value not implemented: " + Main.config.expectedServerVersion.name()); + } + final ArrayList orderedOffsets = new ArrayList<>(); + for(int offset = 0; offset <= maxOffset; offset++) { + orderedOffsets.add(offset); + if(offset != 0) orderedOffsets.add(offset * -1); + } + + for(NoteBlockInstrument instrument : noteblocksForInstrument.keySet().toArray(new NoteBlockInstrument[0])) { + for (int y : orderedOffsets) { + for (int x : orderedOffsets) { + for (int z : orderedOffsets) { + Vec3d vec3d = playerEyePos.add(x, y, z); + BlockPos blockPos = new BlockPos(MathHelper.floor(vec3d.x), MathHelper.floor(vec3d.y), MathHelper.floor(vec3d.z)); + if (!canInteractWith(player, blockPos)) + continue; + BlockState blockState = world.getBlockState(blockPos); + if (!blockState.isOf(Blocks.NOTE_BLOCK) || !world.isAir(blockPos.up())) + continue; + + if (blockState.get(Properties.INSTRUMENT) == instrument) + noteblocksForInstrument.get(instrument).add(blockPos); + } + } + } + } + + // Remap instruments for funzies + if(!instrumentMap.isEmpty()) { + HashMap> newNoteblocksForInstrument = new HashMap<>(); + for(NoteBlockInstrument orig : noteblocksForInstrument.keySet()) { + NoteBlockInstrument mappedInstrument = instrumentMap.getOrDefault(orig, orig); + if(mappedInstrument == null) { + // Instrument got likely mapped to "nothing" + newNoteblocksForInstrument.put(orig, null); + continue; + } + + newNoteblocksForInstrument.put(orig, noteblocksForInstrument.getOrDefault(instrumentMap.getOrDefault(orig, orig), new ArrayList<>())); + } + noteblocksForInstrument = newNoteblocksForInstrument; + } + + // Find fitting noteblocks with the least amount of adjustments required (to reduce tuning time) + ArrayList capturedNotes = new ArrayList<>(); + for(Note note : song.uniqueNotes) { + ArrayList availableBlocks = noteblocksForInstrument.get(note.instrument()); + if(availableBlocks == null) { + // Note was mapped to "nothing". Pretend it got captured, but just ignore it + capturedNotes.add(note); + getNotes(note.instrument()).put(note.note(), null); + continue; + } + BlockPos bestBlockPos = null; + int bestBlockTuningSteps = Integer.MAX_VALUE; + for(BlockPos blockPos : availableBlocks) { + int wantedNote = note.note(); + int currentNote = client.world.getBlockState(blockPos).get(Properties.NOTE); + int tuningSteps = wantedNote >= currentNote ? wantedNote - currentNote : (25 - currentNote) + wantedNote; + + if(tuningSteps < bestBlockTuningSteps) { + bestBlockPos = blockPos; + bestBlockTuningSteps = tuningSteps; + } + } + + if(bestBlockPos != null) { + capturedNotes.add(note); + availableBlocks.remove(bestBlockPos); + getNotes(note.instrument()).put(note.note(), bestBlockPos); + } // else will be a missing note + } + + ArrayList missingNotes = new ArrayList<>(song.uniqueNotes); + missingNotes.removeAll(capturedNotes); + if (!missingNotes.isEmpty()) { + ChatHud chatHud = MinecraftClient.getInstance().inGameHud.getChatHud(); + chatHud.addMessage(Text.translatable(Main.MOD_ID+".player.invalid_note_blocks").formatted(Formatting.RED)); + + HashMap missing = new HashMap<>(); + for (Note note : missingNotes) { + NoteBlockInstrument mappedInstrument = instrumentMap.getOrDefault(note.instrument(), note.instrument()); + if(mappedInstrument == null) continue; // Ignore if mapped to nothing + Block block = Note.INSTRUMENT_BLOCKS.get(mappedInstrument); + Integer got = missing.get(block); + if (got == null) got = 0; + missing.put(block, got + 1); + } + + missingInstrumentBlocks = missing; + missing.forEach((block, integer) -> chatHud.addMessage(Text.literal(block.getName().getString()+" × "+integer).formatted(Formatting.RED))); + stop(); + } + } else if (!tuned) { + //tuned = true; + + int ping = 0; + { + PlayerListEntry playerListEntry; + if (client.getNetworkHandler() != null && (playerListEntry = client.getNetworkHandler().getPlayerListEntry(client.player.getGameProfile().getId())) != null) + ping = playerListEntry.getLatency(); + } + + if(lastInteractAt != -1L) { + // Paper allows 8 interacts per 300 ms (actually 9 it turns out, but lets keep it a bit lower anyway) + availableInteracts += ((System.currentTimeMillis() - lastInteractAt) / (310.0f / 8.0f)); + availableInteracts = Math.min(8f, Math.max(0f, availableInteracts)); + }else { + availableInteracts = 8f; + lastInteractAt = System.currentTimeMillis(); + } + + int fullyTunedBlocks = 0; + HashMap untunedNotes = new HashMap<>(); + for (Note note : song.uniqueNotes) { + if(noteBlocks == null || noteBlocks.get(note.instrument()) == null) + continue; + BlockPos blockPos = noteBlocks.get(note.instrument()).get(note.note()); + if(blockPos == null) continue; + BlockState blockState = world.getBlockState(blockPos); + int assumedNote = notePredictions.containsKey(blockPos) ? notePredictions.get(blockPos).getLeft() : blockState.get(Properties.NOTE); + + if (blockState.contains(Properties.NOTE)) { + if(assumedNote == note.note() && blockState.get(Properties.NOTE) == note.note()) + fullyTunedBlocks++; + if (assumedNote != note.note()) { + if (!canInteractWith(client.player, blockPos)) { + stop(); + client.inGameHud.getChatHud().addMessage(Text.translatable(Main.MOD_ID+".player.to_far").formatted(Formatting.RED)); + return; + } + untunedNotes.put(blockPos, blockState.get(Properties.NOTE)); + } + } else { + noteBlocks = null; + break; + } + } + + if(tuneInitialUntunedBlocks == -1 || tuneInitialUntunedBlocks < untunedNotes.size()) + tuneInitialUntunedBlocks = untunedNotes.size(); + + int existingUniqueNotesCount = 0; + for(Note n : song.uniqueNotes) { + if(noteBlocks.get(n.instrument()).get(n.note()) != null) + existingUniqueNotesCount++; + } + + if(untunedNotes.isEmpty() && fullyTunedBlocks == existingUniqueNotesCount) { + // Wait roundrip + 100ms before considering tuned after changing notes (in case the server rejects an interact) + if(lastInteractAt == -1 || System.currentTimeMillis() - lastInteractAt >= ping * 2 + 100) { + tuned = true; + pausePlaybackUntil = System.currentTimeMillis() + (long) (Math.abs(Main.config.delayPlaybackStartBySecs) * 1000); + tuneInitialUntunedBlocks = -1; + // Tuning finished + } + } + + BlockPos lastBlockPos = null; + int lastTunedNote = Integer.MIN_VALUE; + float roughTuneProgress = 1 - (untunedNotes.size() / Math.max(tuneInitialUntunedBlocks + 0f, 1f)); + while(availableInteracts >= 1f && untunedNotes.size() > 0) { + BlockPos blockPos = null; + int searches = 0; + while(blockPos == null) { + searches++; + // Find higher note + for (Map.Entry entry : untunedNotes.entrySet()) { + if (entry.getValue() > lastTunedNote) { + blockPos = entry.getKey(); + break; + } + } + // Find higher note or equal + if (blockPos == null) { + for (Map.Entry entry : untunedNotes.entrySet()) { + if (entry.getValue() >= lastTunedNote) { + blockPos = entry.getKey(); + break; + } + } + } + // Not found. Reset last note + if(blockPos == null) + lastTunedNote = Integer.MIN_VALUE; + if(blockPos == null && searches > 1) { + // Something went wrong. Take any note (one should at least exist here) + blockPos = untunedNotes.keySet().toArray(new BlockPos[0])[0]; + break; + } + } + if(blockPos == null) return; // Something went very, very wrong! + + lastTunedNote = untunedNotes.get(blockPos); + untunedNotes.remove(blockPos); + int assumedNote = notePredictions.containsKey(blockPos) ? notePredictions.get(blockPos).getLeft() : client.world.getBlockState(blockPos).get(Properties.NOTE); + notePredictions.put(blockPos, new Pair<>((assumedNote + 1) % 25, System.currentTimeMillis() + ping * 2 + 100)); + client.interactionManager.interactBlock(client.player, Hand.MAIN_HAND, new BlockHitResult(Vec3d.of(blockPos), Direction.UP, blockPos, false)); + lastInteractAt = System.currentTimeMillis(); + availableInteracts -= 1f; + lastBlockPos = blockPos; + } + if(lastBlockPos != null) { + // Turn head into spinning with time and lookup up further the further tuning is progressed + //client.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.LookAndOnGround(((float) (System.currentTimeMillis() % 2000)) * (360f/2000f), (1 - roughTuneProgress) * 180 - 90, true)); + client.player.swingHand(Hand.MAIN_HAND); + } + }else if((playbackThread == null || !playbackThread.isAlive()) && running && Main.config.disableAsyncPlayback) { + // Sync playback (off by default). Replacement for playback thread + try { + tickPlayback(); + }catch (Exception ex) { + ex.printStackTrace(); + stop(); + } + } + } + + private HashMap getNotes(NoteBlockInstrument instrument) { + return noteBlocks.computeIfAbsent(instrument, k -> new HashMap<>()); + } + + // Before 1.20.5, the server limits interacts to 6 Blocks from Player Eye to Block Center + // With 1.20.5 and later, the server does a more complex check, to the closest point of a full block hitbox + // (max distance is BlockInteractRange + 1.0). + private boolean canInteractWith(ClientPlayerEntity player, BlockPos blockPos) { + final Vec3d eyePos = player.getEyePos(); + if(Main.config.expectedServerVersion == Config.ExpectedServerVersion.v1_20_4_Or_Earlier) { + return eyePos.squaredDistanceTo(blockPos.toCenterPos()) <= 6.0 * 6.0; + }else if(Main.config.expectedServerVersion == Config.ExpectedServerVersion.v1_20_5_Or_Later) { + double blockInteractRange = player.getBlockInteractionRange() + 1.0; + return new Box(blockPos).squaredMagnitude(eyePos) < blockInteractRange * blockInteractRange; + }else if(Main.config.expectedServerVersion == Config.ExpectedServerVersion.All) { + // Require both checks to succeed (aka use worst distance) + double blockInteractRange = player.getBlockInteractionRange() + 1.0; + return eyePos.squaredDistanceTo(blockPos.toCenterPos()) <= 6.0 * 6.0 + && new Box(blockPos).squaredMagnitude(eyePos) < blockInteractRange * blockInteractRange; + }else { + throw new NotImplementedException("ExpectedServerVersion Value not implemented: " + Main.config.expectedServerVersion.name()); + } + } + + public double getSongElapsedSeconds() { + if(song == null) return 0; + return song.ticksToMilliseconds(tick) / 1000; + } +} diff --git a/src/main/java/semmiedev/disc_jockey/gui/SongListWidget.java b/src/main/java/semmiedev/disc_jockey/gui/SongListWidget.java new file mode 100644 index 0000000..0b2f055 --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/gui/SongListWidget.java @@ -0,0 +1,108 @@ +package semmiedev.disc_jockey.gui; + +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder; +import net.minecraft.client.gui.widget.EntryListWidget; +import net.minecraft.text.Text; +import net.minecraft.util.Identifier; +import org.jetbrains.annotations.Nullable; +import semmiedev.disc_jockey.Main; +import semmiedev.disc_jockey.Song; + +public class SongListWidget extends EntryListWidget { + private static final String FAVORITE_EMOJI = "收藏★"; + private static final String NOT_FAVORITE_EMOJI = "收藏☆"; + + public SongListWidget(MinecraftClient client, int width, int height, int top, int itemHeight) { + super(client, width, height, top, itemHeight); + } + + @Override + public int getRowWidth() { + return width - 40; + } + + @Override + protected int getScrollbarX() { + return width - 12; + } + + @Override + public void setSelected(@Nullable SongListWidget.SongEntry entry) { + SongListWidget.SongEntry selectedEntry = getSelectedOrNull(); + if (selectedEntry != null) selectedEntry.selected = false; + if (entry != null) entry.selected = true; + super.setSelected(entry); + } + + @Override + protected void appendClickableNarrations(NarrationMessageBuilder builder) { + // Who cares + } + + // TODO: 6/2/2022 Add a delete icon + public static class SongEntry extends Entry { + private static final Identifier ICONS = Identifier.of(Main.MOD_ID, "textures/gui/icons.png"); + + public final int index; + public final Song song; + + public boolean selected, favorite; + public SongListWidget songListWidget; + + private final MinecraftClient client = MinecraftClient.getInstance(); + + private int x, y, entryWidth, entryHeight; + + public SongEntry(Song song, int index) { + this.song = song; + this.index = index; + } + + @Override + public void render(DrawContext context, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { + this.x = x; this.y = y; this.entryWidth = entryWidth; this.entryHeight = entryHeight; + + if (selected) { + context.fill(x, y, x + entryWidth, y + entryHeight, 0xFFFFFF); + context.fill(x + 1, y + 1, x + entryWidth - 1, y + entryHeight - 1, 0x000000); + } + + context.drawCenteredTextWithShadow(client.textRenderer, song.displayName, x + entryWidth / 2, y + 5, selected ? 0xFFFFFF : 0x808080); + + String emoji = String.valueOf(favorite ? FAVORITE_EMOJI : NOT_FAVORITE_EMOJI); + context.drawTextWithShadow( + client.textRenderer, + emoji, + x + 2, y + 2, + favorite ? 0xFFD700 : 0x808080 + ); + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + if (isOverFavoriteButton(mouseX, mouseY)) { + favorite = !favorite; + if (favorite) { + Main.config.favorites.add(song.fileName); + } else { + Main.config.favorites.remove(song.fileName); + } + return true; + } + songListWidget.setSelected(this); + return true; + } + + private boolean isOverFavoriteButton(double mouseX, double mouseY) { + int textWidth = client.textRenderer.getWidth(favorite ? FAVORITE_EMOJI : NOT_FAVORITE_EMOJI); + int textHeight = 8; + return mouseX > x + 2 && + mouseX < x + 2 + textWidth && + mouseY > y + 2 && + mouseY < y + 2 + textHeight; + } + } +} diff --git a/src/main/java/semmiedev/disc_jockey/gui/hud/BlocksOverlay.java b/src/main/java/semmiedev/disc_jockey/gui/hud/BlocksOverlay.java new file mode 100644 index 0000000..1e98d1e --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/gui/hud/BlocksOverlay.java @@ -0,0 +1,41 @@ +package semmiedev.disc_jockey.gui.hud; + +import net.minecraft.block.Blocks; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.font.TextRenderer; +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.render.RenderTickCounter; +import net.minecraft.client.render.item.ItemRenderer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.math.ColorHelper; + +public class BlocksOverlay { + public static ItemStack[] itemStacks; + public static int[] amounts; + public static int amountOfNoteBlocks; + + private static final ItemStack NOTE_BLOCK = Blocks.NOTE_BLOCK.asItem().getDefaultStack(); + + public static void render(DrawContext context, RenderTickCounter tickCounter) { + if (itemStacks != null) { + context.fill(2, 2, 62, (itemStacks.length + 1) * 20 + 7, ColorHelper.getArgb(255, 22, 22, 27)); + context.fill(4, 4, 60, (itemStacks.length + 1) * 20 + 5, ColorHelper.getArgb(255, 42, 42, 47)); + + MinecraftClient client = MinecraftClient.getInstance(); + TextRenderer textRenderer = client.textRenderer; + ItemRenderer itemRenderer = client.getItemRenderer(); + + //textRenderer.draw(matrices, " × "+amountOfNoteBlocks, 26, 13, 0xFFFFFF); + context.drawText(textRenderer, " × "+amountOfNoteBlocks, 26, 13, 0xFFFFFF, true); + //itemRenderer.renderInGui(matrices, NOTE_BLOCK, 6, 6); + context.drawItem(NOTE_BLOCK, 6, 6); + + for (int i = 0; i < itemStacks.length; i++) { + //textRenderer.draw(matrices, " × "+amounts[i], 26, 13 + 20 * (i + 1), 0xFFFFFF); + context.drawText(textRenderer, " × "+amounts[i], 26, 13 + 20 * (i + 1), 0xFFFFFF, true); + //itemRenderer.renderInGui(matrices, itemStacks[i], 6, 6 + 20 * (i + 1)); + context.drawItem(itemStacks[i], 6, 6 + 20 * (i + 1)); + } + } + } +} diff --git a/src/main/java/semmiedev/disc_jockey/gui/screen/DiscJockeyScreen.java b/src/main/java/semmiedev/disc_jockey/gui/screen/DiscJockeyScreen.java new file mode 100644 index 0000000..83f7fe8 --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/gui/screen/DiscJockeyScreen.java @@ -0,0 +1,201 @@ +package semmiedev.disc_jockey.gui.screen; + +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.gui.screen.ConfirmScreen; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.client.gui.widget.TextFieldWidget; +import net.minecraft.item.ItemStack; +import net.minecraft.text.MutableText; +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; +import semmiedev.disc_jockey.Main; +import semmiedev.disc_jockey.Note; +import semmiedev.disc_jockey.Song; +import semmiedev.disc_jockey.SongLoader; +import semmiedev.disc_jockey.gui.SongListWidget; +import semmiedev.disc_jockey.gui.hud.BlocksOverlay; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class DiscJockeyScreen extends Screen { + private static final MutableText + SELECT_SONG = Text.translatable(Main.MOD_ID+".screen.select_song"), + PLAY = Text.translatable(Main.MOD_ID+".screen.play"), + PLAY_STOP = Text.translatable(Main.MOD_ID+".screen.play.stop"), + PREVIEW = Text.translatable(Main.MOD_ID+".screen.preview"), + PREVIEW_STOP = Text.translatable(Main.MOD_ID+".screen.preview.stop"), + DROP_HINT = Text.translatable(Main.MOD_ID+".screen.drop_hint").formatted(Formatting.GRAY) + ; + + private SongListWidget songListWidget; + private ButtonWidget playButton, previewButton; + private boolean shouldFilter; + private String query = ""; + + public DiscJockeyScreen() { + super(Main.NAME); + } + + @Override + protected void init() { + shouldFilter = true; + songListWidget = new SongListWidget(client, width, height - 64 - 32, 32, 20); + addDrawableChild(songListWidget); + for (int i = 0; i < SongLoader.SONGS.size(); i++) { + Song song = SongLoader.SONGS.get(i); + song.entry.songListWidget = songListWidget; + if (song.entry.selected) songListWidget.setSelected(song.entry); + } + + playButton = ButtonWidget.builder(PLAY, button -> { + if (Main.SONG_PLAYER.running) { + Main.SONG_PLAYER.stop(); + } else { + SongListWidget.SongEntry entry = songListWidget.getSelectedOrNull(); + if (entry != null) { + Main.SONG_PLAYER.start(entry.song); + client.setScreen(null); + } + } + }).dimensions(width / 2 - 160, height - 61, 100, 20).build(); + addDrawableChild(playButton); + + previewButton = ButtonWidget.builder(PREVIEW, button -> { + if (Main.PREVIEWER.running) { + Main.PREVIEWER.stop(); + } else { + SongListWidget.SongEntry entry = songListWidget.getSelectedOrNull(); + if (entry != null) Main.PREVIEWER.start(entry.song); + } + }).dimensions(width / 2 - 50, height - 61, 100, 20).build(); + addDrawableChild(previewButton); + + addDrawableChild(ButtonWidget.builder(Text.translatable(Main.MOD_ID+".screen.blocks"), button -> { + // TODO: 6/2/2022 Add an auto build mode + if (BlocksOverlay.itemStacks == null) { + SongListWidget.SongEntry entry = songListWidget.getSelectedOrNull(); + if (entry != null) { + client.setScreen(null); + + BlocksOverlay.itemStacks = new ItemStack[0]; + BlocksOverlay.amounts = new int[0]; + BlocksOverlay.amountOfNoteBlocks = entry.song.uniqueNotes.size(); + + for (Note note : entry.song.uniqueNotes) { + ItemStack itemStack = Note.INSTRUMENT_BLOCKS.get(note.instrument()).asItem().getDefaultStack(); + int index = -1; + + for (int i = 0; i < BlocksOverlay.itemStacks.length; i++) { + if (BlocksOverlay.itemStacks[i].getItem() == itemStack.getItem()) { + index = i; + break; + } + } + + if (index == -1) { + BlocksOverlay.itemStacks = Arrays.copyOf(BlocksOverlay.itemStacks, BlocksOverlay.itemStacks.length + 1); + BlocksOverlay.amounts = Arrays.copyOf(BlocksOverlay.amounts, BlocksOverlay.amounts.length + 1); + + BlocksOverlay.itemStacks[BlocksOverlay.itemStacks.length - 1] = itemStack; + BlocksOverlay.amounts[BlocksOverlay.amounts.length - 1] = 1; + } else { + BlocksOverlay.amounts[index] = BlocksOverlay.amounts[index] + 1; + } + } + } + } else { + BlocksOverlay.itemStacks = null; + client.setScreen(null); + } + }).dimensions(width / 2 + 60, height - 61, 100, 20).build()); + + TextFieldWidget searchBar = new TextFieldWidget(textRenderer, width / 2 - 75, height - 31, 150, 20, Text.translatable(Main.MOD_ID+".screen.search")); + searchBar.setChangedListener(query -> { + query = query.toLowerCase().replaceAll("\\s", ""); + if (this.query.equals(query)) return; + this.query = query; + shouldFilter = true; + }); + addDrawableChild(searchBar); + + // TODO: 6/2/2022 Add a reload button + } + + @Override + public void render(DrawContext context, int mouseX, int mouseY, float delta) { + super.render(context, mouseX, mouseY, delta); + + context.drawCenteredTextWithShadow(textRenderer, DROP_HINT, width / 2, 5, 0xFFFFFF); + context.drawCenteredTextWithShadow(textRenderer, SELECT_SONG, width / 2, 20, 0xFFFFFF); + } + + @Override + public void tick() { + previewButton.setMessage(Main.PREVIEWER.running ? PREVIEW_STOP : PREVIEW); + playButton.setMessage(Main.SONG_PLAYER.running ? PLAY_STOP : PLAY); + + if (shouldFilter) { + shouldFilter = false; +// songListWidget.setScrollAmount(0); + songListWidget.children().clear(); + boolean empty = query.isEmpty(); + int favoriteIndex = 0; + for (Song song : SongLoader.SONGS) { + if (empty || song.searchableFileName.contains(query) || song.searchableName.contains(query)) { + if (song.entry.favorite) { + songListWidget.children().add(favoriteIndex++, song.entry); + } else { + songListWidget.children().add(song.entry); + } + } + } + } + } + + @Override + public void onFilesDropped(List paths) { + String string = paths.stream().map(Path::getFileName).map(Path::toString).collect(Collectors.joining(", ")); + if (string.length() > 300) string = string.substring(0, 300)+"..."; + + client.setScreen(new ConfirmScreen(confirmed -> { + if (confirmed) { + paths.forEach(path -> { + try { + File file = path.toFile(); + + if (SongLoader.SONGS.stream().anyMatch(input -> input.fileName.equalsIgnoreCase(file.getName()))) return; + + Song song = SongLoader.loadSong(file); + if (song != null) { + Files.copy(path, Main.songsFolder.toPath().resolve(file.getName())); + SongLoader.SONGS.add(song); + } + } catch (IOException exception) { + Main.LOGGER.warn("Failed to copy song file from {} to {}", path, Main.songsFolder.toPath(), exception); + } + }); + + SongLoader.sort(); + } + client.setScreen(this); + }, Text.translatable(Main.MOD_ID+".screen.drop_confirm"), Text.literal(string))); + } + + @Override + public boolean shouldPause() { + return false; + } + + @Override + public void close() { + super.close(); + new Thread(() -> Main.configHolder.save()).start(); + } +} diff --git a/src/main/java/semmiedev/disc_jockey/mixin/ClientWorldMixin.java b/src/main/java/semmiedev/disc_jockey/mixin/ClientWorldMixin.java new file mode 100644 index 0000000..2df4843 --- /dev/null +++ b/src/main/java/semmiedev/disc_jockey/mixin/ClientWorldMixin.java @@ -0,0 +1,56 @@ +package semmiedev.disc_jockey.mixin; + +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.sound.PositionedSoundInstance; +import net.minecraft.client.sound.SoundInstance; +import net.minecraft.client.world.ClientWorld; +import net.minecraft.sound.SoundCategory; +import net.minecraft.sound.SoundEvent; +import net.minecraft.util.math.random.Random; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import semmiedev.disc_jockey.Main; + +@Mixin(ClientWorld.class) +public class ClientWorldMixin { + @Shadow @Final private MinecraftClient client; + + @Inject( + method = "playSound(DDDLnet/minecraft/sound/SoundEvent;Lnet/minecraft/sound/SoundCategory;FFZJ)V", + at = @At("HEAD"), + cancellable = true + ) + private void makeNoteBlockSoundsOmnidirectional( + double x, double y, double z, + SoundEvent event, + SoundCategory category, + float volume, float pitch, + boolean useDistance, long seed, + CallbackInfo ci + ) { + if ( + ((Main.config.omnidirectionalNoteBlockSounds && Main.SONG_PLAYER.running) || Main.PREVIEWER.running) && + event.id().getPath().startsWith("block.note_block") + ) { + ci.cancel(); + client.getSoundManager().play( + new PositionedSoundInstance( + event.id(), + category, + volume, + pitch, + Random.create(seed), + false, + 0, + SoundInstance.AttenuationType.NONE, + 0, 0, 0, + true + ) + ); + } + } +} diff --git a/src/main/resources/assets/disc_jockey/icon.png b/src/main/resources/assets/disc_jockey/icon.png new file mode 100644 index 0000000..e3f52d1 Binary files /dev/null and b/src/main/resources/assets/disc_jockey/icon.png differ diff --git a/src/main/resources/assets/disc_jockey/lang/en_us.json b/src/main/resources/assets/disc_jockey/lang/en_us.json new file mode 100644 index 0000000..e4e0f1c --- /dev/null +++ b/src/main/resources/assets/disc_jockey/lang/en_us.json @@ -0,0 +1,55 @@ +{ + "disc_jockey.screen.select_song": "Select A Song", + "disc_jockey.screen.play": "Play", + "disc_jockey.screen.play.stop": "Stop Playing", + "disc_jockey.screen.preview": "Preview", + "disc_jockey.screen.preview.stop": "Stop Previewing", + "disc_jockey.screen.blocks.title": "Blocks", + "disc_jockey.screen.blocks": "Blocks", + "disc_jockey.screen.search": "Search For Songs", + "disc_jockey.screen.drop_hint": "Drag and drop song files into this window to add them", + "disc_jockey.screen.drop_confirm": "Do you want to add the following songs to Disc Jockey?", + "disc_jockey.player.invalid_note_blocks": "The Note Blocks near you are not in the correct configuration. Missing:", + "disc_jockey.player.invalid_game_mode": "You can't play in %s", + "disc_jockey.player.to_far": "You went to far away", + "disc_jockey.still_loading": "The songs are still loading", + "disc_jockey.reloading": "Reloading all songs", + "disc_jockey.loading_done": "All songs are loaded", + "disc_jockey.song_not_found": " Song '%s' does not exist", + "disc_jockey.not_playing": "Not playing any song", + "disc_jockey.speed_changed": "Changed playback speed to %s", + "disc_jockey.stopped_playing": "Stopped playing '%s'", + "disc_jockey.info_not_running": "No song is playing (Speed: %s)", + "disc_jockey.info_tuning": "Tuning: (Speed: %s)", + "disc_jockey.info_playing": "Playing: [%s/%s] %s (Speed: %s)", + "disc_jockey.info_finished": "Finished: %s (Speed: %s)", + "disc_jockey.instrument_info": "This maps instruments to be played by noteblocks for a different instrument instead.", + "disc_jockey.invalid_instrument": "Invalid instrument: %s", + "disc_jockey.instrument_mapped": "Mapped %s to %s", + "disc_jockey.instrument_mapped_all": "Mapped all instruments to %s", + "disc_jockey.instrument_unmapped": "Unmapped %s", + "disc_jockey.mapped_instruments": "Mapped instruments: %s", + "disc_jockey.no_mapped_instruments": "No instruments mapped, yet.", + "disc_jockey.instrument_maps_cleared": "Instrument mappings cleared.", + "disc_jockey.loop_status": "Loop song: %s", + "disc_jockey.loop_enabled": "Enabled looping of current song.", + "disc_jockey.loop_disabled": "Disabled looping of current song.", + "disc_jockey.warning": "WARNING!!! This mod is very likely to get false flagged as hacks, please contact a server administrator before using this mod! (You can disable this warning in the mod settings)", + "key.category.disc_jockey": "Disc Jockey", + "disc_jockey.key_bind.open_screen": "Open song selection screen", + "text.autoconfig.disc_jockey.title": "Disc Jockey", + "text.autoconfig.disc_jockey.option.hideWarning": "Hide Warning", + "text.autoconfig.disc_jockey.option.disableAsyncPlayback": "Disable Async Playback", + "text.autoconfig.disc_jockey.option.disableAsyncPlayback.@Tooltip[0]": "Will force notes to play synchronously with client ticks instead of in a separate thread.", + "text.autoconfig.disc_jockey.option.disableAsyncPlayback.@Tooltip[1]": "This can lead to performance loss, especially when you client has low or inconsistent fps but can fix issues when playback does not happen at all.", + "text.autoconfig.disc_jockey.option.omnidirectionalNoteBlockSounds": "Omnidirectional Note Block Sounds (clientside)", + "text.autoconfig.disc_jockey.option.omnidirectionalNoteBlockSounds.@Tooltip[0]": "Makes all note block sounds when playing a song omnidirectional, creating a more pleasing listening experience", + "text.autoconfig.disc_jockey.option.omnidirectionalNoteBlockSounds.@Tooltip[1]": "If you don't know what that means, I recommend you just try it and hear the difference", + "text.autoconfig.disc_jockey.option.expectedServerVersion": "Expected Server Version", + "text.autoconfig.disc_jockey.option.expectedServerVersion.@Tooltip[0]": "Select the server version, you expect this mod to be used on.", + "text.autoconfig.disc_jockey.option.expectedServerVersion.@Tooltip[1]": "This affects how reachable NoteBlocks are determined.", + "text.autoconfig.disc_jockey.option.expectedServerVersion.@Tooltip[2]": "Selecting the wrong version could cause you not to be able to play some distant note blocks which could break/worsen playback", + "text.autoconfig.disc_jockey.option.expectedServerVersion.@Tooltip[3]": "If you're unsure, or play on many different server versions and don't mind not reaching every possible note block, select \"All\"", + "text.autoconfig.disc_jockey.option.delayPlaybackStartBySecs": "Delay playback by (seconds)", + "text.autoconfig.disc_jockey.option.delayPlaybackStartBySecs.@Tooltip": "Delays playback for specified seconds, after tuning finished, if any (e.g. 0.5 for half a second delay)." +} \ No newline at end of file diff --git a/src/main/resources/assets/disc_jockey/lang/zh_cn.json b/src/main/resources/assets/disc_jockey/lang/zh_cn.json new file mode 100644 index 0000000..8a69068 --- /dev/null +++ b/src/main/resources/assets/disc_jockey/lang/zh_cn.json @@ -0,0 +1,55 @@ +{ + "disc_jockey.screen.select_song": "选择歌曲", + "disc_jockey.screen.play": "播放", + "disc_jockey.screen.play.stop": "停止播放", + "disc_jockey.screen.preview": "试听", + "disc_jockey.screen.preview.stop": "停止试听", + "disc_jockey.screen.blocks.title": "音符盒", + "disc_jockey.screen.blocks": "音符盒", + "disc_jockey.screen.search": "搜索歌曲", + "disc_jockey.screen.drop_hint": "将歌曲文件拖入此窗口以添加", + "disc_jockey.screen.drop_confirm": "是否将以下歌曲添加到 Disc Jockey?", + "disc_jockey.player.invalid_note_blocks": "附近的音符盒配置不正确。缺失:", + "disc_jockey.player.invalid_game_mode": "无法在 %s 模式下播放", + "disc_jockey.player.to_far": "你距离太远了", + "disc_jockey.still_loading": "歌曲仍在加载中", + "disc_jockey.reloading": "正在重新加载所有歌曲", + "disc_jockey.loading_done": "所有歌曲已加载完成", + "disc_jockey.song_not_found": "歌曲“%s”不存在", + "disc_jockey.not_playing": "未播放任何歌曲", + "disc_jockey.speed_changed": "播放速度已调整为 %s", + "disc_jockey.stopped_playing": "已停止播放“%s”", + "disc_jockey.info_not_running": "未播放歌曲(速度:%s)", + "disc_jockey.info_tuning": "调音中(速度:%s)", + "disc_jockey.info_playing": "播放中:[%s/%s] %s(速度:%s)", + "disc_jockey.info_finished": "已播放:%s(速度:%s)", + "disc_jockey.instrument_info": "此功能可将音符盒的乐器映射为其他乐器音色。", + "disc_jockey.invalid_instrument": "无效乐器:%s", + "disc_jockey.instrument_mapped": "已将 %s 映射为 %s", + "disc_jockey.instrument_mapped_all": "已将全部乐器映射为 %s", + "disc_jockey.instrument_unmapped": "已取消 %s 的映射", + "disc_jockey.mapped_instruments": "已映射乐器:%s", + "disc_jockey.no_mapped_instruments": "当前未映射任何乐器", + "disc_jockey.instrument_maps_cleared": "已清除所有乐器映射", + "disc_jockey.loop_status": "循环播放:%s", + "disc_jockey.loop_enabled": "已启用当前歌曲循环播放", + "disc_jockey.loop_disabled": "已禁用当前歌曲循环播放", + "disc_jockey.warning": "警告!此模组极易被误判为作弊工具,使用前请联系服务器管理员!(可在模组设置中关闭此警告)\n当前版本:1.14.514(1.21.4)为非官方版本,由BRanulf改版,翻译也是这家伙提供的。\n仅供学习参考,请支持官方,别找我XD", + "key.category.disc_jockey": "Disc Jockey", + "disc_jockey.key_bind.open_screen": "打开歌曲选择界面", + "text.autoconfig.disc_jockey.title": "Disc Jockey", + "text.autoconfig.disc_jockey.option.hideWarning": "隐藏警告", + "text.autoconfig.disc_jockey.option.disableAsyncPlayback": "禁用异步播放", + "text.autoconfig.disc_jockey.option.disableAsyncPlayback.@Tooltip[0]": "强制音符与客户端刻同步播放,而非使用独立线程。", + "text.autoconfig.disc_jockey.option.disableAsyncPlayback.@Tooltip[1]": "可能导致性能下降(尤其在低帧率时),但可解决某些情况下无法播放的问题。", + "text.autoconfig.disc_jockey.option.omnidirectionalNoteBlockSounds": "全向音符盒音效(客户端)", + "text.autoconfig.disc_jockey.option.omnidirectionalNoteBlockSounds.@Tooltip[0]": "使音符盒音效全向传播,提升听觉体验", + "text.autoconfig.disc_jockey.option.omnidirectionalNoteBlockSounds.@Tooltip[1]": "若不确定效果,建议直接试听对比", + "text.autoconfig.disc_jockey.option.expectedServerVersion": "预期服务器版本", + "text.autoconfig.disc_jockey.option.expectedServerVersion.@Tooltip[0]": "选择你预计使用此模组的服务器版本。", + "text.autoconfig.disc_jockey.option.expectedServerVersion.@Tooltip[1]": "此设置影响音符盒可触达范围的判定逻辑。", + "text.autoconfig.disc_jockey.option.expectedServerVersion.@Tooltip[2]": "版本选择错误可能导致无法触发部分音符盒,影响播放效果", + "text.autoconfig.disc_jockey.option.expectedServerVersion.@Tooltip[3]": "若不确认版本,或需兼容多版本服务器,请选择“全部”", + "text.autoconfig.disc_jockey.option.delayPlaybackStartBySecs": "播放延迟(秒)", + "text.autoconfig.disc_jockey.option.delayPlaybackStartBySecs.@Tooltip": "调音完成后延迟指定秒数再开始播放(如 0.5 表示延迟半秒)。" +} \ No newline at end of file diff --git a/src/main/resources/assets/disc_jockey/textures/gui/icons.png b/src/main/resources/assets/disc_jockey/textures/gui/icons.png new file mode 100644 index 0000000..6442038 Binary files /dev/null and b/src/main/resources/assets/disc_jockey/textures/gui/icons.png differ diff --git a/src/main/resources/disc_jockey.mixins.json b/src/main/resources/disc_jockey.mixins.json new file mode 100644 index 0000000..f907fc6 --- /dev/null +++ b/src/main/resources/disc_jockey.mixins.json @@ -0,0 +1,12 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "semmiedev.disc_jockey.mixin", + "compatibilityLevel": "JAVA_21", + "mixins": [ + "ClientWorldMixin" + ], + "injectors": { + "defaultRequire": 1 + } +} \ No newline at end of file diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..1cc0f82 --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,35 @@ +{ + "schemaVersion": 1, + "id": "disc_jockey", + "version": "${version}", + "name": "Disc Jockey", + "description": "在游戏中播放音符盒(打碟机)", + "authors": [ + "SemmieDev", + "EnderKill98", + "BRanulf(仅限该版本,请支持上面两个原作者)" + ], + "contact": { + "repo": "http://git.branulf.top/BRanulf/DJ_BR" + }, + "license": "MIT", + "icon": "assets/disc_jockey/icon.png", + "environment": "client", + "entrypoints": { + "client": [ + "semmiedev.disc_jockey.Main" + ], + "modmenu": [ + "semmiedev.disc_jockey.ModMenuIntegration" + ] + }, + "mixins": [ + "disc_jockey.mixins.json" + ], + "depends": { + "fabric": "*", + "minecraft": "~1.21.4", + "java": ">=21", + "cloth-config": "*" + } +}