Initial commit

This commit is contained in:
Semmieboy YT 2022-02-26 01:38:14 +01:00
parent e8b0ac431f
commit 25aeb857cf
23 changed files with 1326 additions and 10 deletions

102
.gitignore vendored
View File

@ -1,3 +1,18 @@
# 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
@ -7,9 +22,6 @@
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
@ -21,4 +33,86 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_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

12
LICENSE
View File

@ -1,6 +1,6 @@
MIT License
The MIT License (MIT)
Copyright (c) 2022 Semmieboy YT
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
@ -9,13 +9,13 @@ 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 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.
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

81
build.gradle Normal file
View File

@ -0,0 +1,81 @@
plugins {
id 'fabric-loom' version '0.11-SNAPSHOT'
id 'maven-publish'
}
version = project.mod_version
group = project.maven_group
repositories {
// Add repositories to retrieve artifacts from in here.
// You should only use this when depending on other mods because
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
// for more information about repositories.
}
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
}
processResources {
inputs.property "version", project.version
filteringCharset "UTF-8"
filesMatching("fabric.mod.json") {
expand "version": project.version
}
}
def targetJavaVersion = 17
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.
}
}

14
gradle.properties Normal file
View File

@ -0,0 +1,14 @@
# 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.18.1
yarn_mappings=1.18.1+build.22
loader_version=0.13.2
# Mod Properties
mod_version=1.0.0
maven_group=semmieboy_yt
archives_base_name=disc_jockey
# Dependencies
# check this on https://modmuss50.me/fabric.html
fabric_version=0.46.4+1.18

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -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" "$@"

89
gradlew.bat vendored Normal file
View File

@ -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

9
settings.gradle Normal file
View File

@ -0,0 +1,9 @@
pluginManagement {
repositories {
maven {
name = 'Fabric'
url = 'https://maven.fabricmc.net/'
}
gradlePluginPortal()
}
}

View File

@ -0,0 +1,65 @@
package semmieboy_yt.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(2)).rewind().getShort();
}
public String readString() throws IOException {
return new String(readBytes(readInt()));
}
public float readFloat() throws IOException {
return buffer.clear().put(readBytes(4)).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 {
return in.readNBytes(length);
}
}

View File

@ -0,0 +1,26 @@
package semmieboy_yt.disc_jockey;
import net.fabricmc.fabric.api.client.command.v1.ClientCommandManager;
import net.minecraft.client.MinecraftClient;
import semmieboy_yt.disc_jockey.gui.screen.DiscJockeyScreen;
import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal;
public class DiscjockeyCommand {
public static void register() {
ClientCommandManager.DISPATCHER.register(
literal("discjockey")
.executes(context -> {
MinecraftClient client = context.getSource().getClient();
client.send(() -> client.setScreen(new DiscJockeyScreen()));
return 1;
})
.then(literal("reload")
.executes(context -> {
SongLoader.loadSongs();
return 1;
})
)
);
}
}

View File

@ -0,0 +1,42 @@
package semmieboy_yt.disc_jockey;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
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 org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import semmieboy_yt.disc_jockey.gui.hud.BlocksOverlay;
import java.io.File;
import java.util.ArrayList;
public class Main implements ClientModInitializer {
public static final String MOD_ID = "disc_jockey";
public static final Logger LOGGER = LogManager.getLogger("Disc Jockey");
public static final ArrayList<ClientTickEvents.StartWorldTick> TICK_LISTENERS = new ArrayList<>();
public static final Previewer PREVIEWER = new Previewer();
public static final SongPlayer SONG_PLAYER = new SongPlayer();
public static File songsFolder;
@Override
public void onInitializeClient() {
songsFolder = new File(FabricLoader.getInstance().getConfigDir()+File.separator+MOD_ID+File.separator+"songs");
if (!songsFolder.isDirectory()) songsFolder.mkdirs();
DiscjockeyCommand.register();
SongLoader.loadSongs();
ClientTickEvents.START_WORLD_TICK.register(world -> {
for (ClientTickEvents.StartWorldTick listener : TICK_LISTENERS) listener.onStartTick(world);
});
ClientLoginConnectionEvents.DISCONNECT.register((handler, client) -> {
PREVIEWER.stop();
SONG_PLAYER.stop();
});
HudRenderCallback.EVENT.register(BlocksOverlay::render);
}
}

View File

@ -0,0 +1,34 @@
package semmieboy_yt.disc_jockey;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.block.enums.Instrument;
import java.util.Map;
public record Note(Instrument instrument, byte note) {
public static final Map<Instrument, Block> INSTRUMENT_BLOCKS = Map.ofEntries(
Map.entry(Instrument.HARP, Blocks.AIR),
Map.entry(Instrument.BASEDRUM, Blocks.STONE),
Map.entry(Instrument.SNARE, Blocks.SAND),
Map.entry(Instrument.HAT, Blocks.GLASS),
Map.entry(Instrument.BASS, Blocks.OAK_PLANKS),
Map.entry(Instrument.FLUTE, Blocks.CLAY),
Map.entry(Instrument.BELL, Blocks.GOLD_BLOCK),
Map.entry(Instrument.GUITAR, Blocks.WHITE_WOOL),
Map.entry(Instrument.CHIME, Blocks.PACKED_ICE),
Map.entry(Instrument.XYLOPHONE, Blocks.BONE_BLOCK),
Map.entry(Instrument.IRON_XYLOPHONE, Blocks.IRON_BLOCK),
Map.entry(Instrument.COW_BELL, Blocks.SOUL_SAND),
Map.entry(Instrument.DIDGERIDOO, Blocks.PUMPKIN),
Map.entry(Instrument.BIT, Blocks.EMERALD_BLOCK),
Map.entry(Instrument.BANJO, Blocks.HAY_BLOCK),
Map.entry(Instrument.PLING, Blocks.GLOWSTONE)
);
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 Instrument[] INSTRUMENTS = Instrument.values();
}

View File

@ -0,0 +1,46 @@
package semmieboy_yt.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;
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)) {
world.playSoundFromEntity(MinecraftClient.getInstance().player, MinecraftClient.getInstance().player, Note.INSTRUMENTS[(byte)(note >> Note.INSTRUMENT_SHIFT)].getSound(), SoundCategory.RECORDS, 3, (float)Math.pow(2.0, ((byte)(note >> Note.NOTE_SHIFT) - 12) / 12.0));
i++;
if (i >= song.notes.length) {
stop();
break;
}
} else {
break;
}
}
tick += song.tempo / 100f / 20f;
}
}

View File

@ -0,0 +1,20 @@
package semmieboy_yt.disc_jockey;
import semmieboy_yt.disc_jockey.gui.SongListWidget;
import java.util.ArrayList;
public class Song {
public final ArrayList<Note> uniqueNotes = new ArrayList<>();
public long[] notes = new long[0];
public short length, height, tempo, loopStartTick;
public String fileName, name, author, originalAuthor, description;
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;
}

View File

@ -0,0 +1,101 @@
package semmieboy_yt.disc_jockey;
import semmieboy_yt.disc_jockey.gui.SongListWidget;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class SongLoader {
public static final ArrayList<Song> SONGS = new ArrayList<>();
public static void loadSongs() {
SONGS.clear();
for (File file : Main.songsFolder.listFiles()) {
if (file.isFile()) {
try {
BinaryReader reader = new BinaryReader(new FileInputStream(file));
Song song = new Song();
song.fileName = file.getName();
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();
song.author = reader.readString();
song.originalAuthor = reader.readString();
song.description = reader.readString();
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();
if (newFormat) {
song.loop = reader.readByte();
song.maxLoopCount = reader.readByte();
song.loopStartTick = reader.readShort();
}
song.entry = new SongListWidget.SongEntry(song.name.isBlank() ? song.fileName : song.name+" ("+song.fileName+")", SONGS.size());
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;
}
}
SONGS.add(song);
} catch (FileNotFoundException ignored) {
// Won't be thrown
} catch (IOException exception) {
Main.LOGGER.error("Unable to read song "+file.getName(), exception);
}
}
}
}
}

View File

@ -0,0 +1,173 @@
package semmieboy_yt.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.Instrument;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.hud.ChatHud;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket;
import net.minecraft.state.property.Properties;
import net.minecraft.text.LiteralText;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Formatting;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.GameMode;
import java.util.ArrayList;
import java.util.HashMap;
public class SongPlayer implements ClientTickEvents.StartWorldTick {
public boolean running;
private int index;
private float tick;
private Song song;
private HashMap<Instrument, HashMap<Byte, BlockPos>> noteBlocks = null;
private boolean tuned;
private int tuneDelay = 5;
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;
index = 0;
tick = 0;
noteBlocks = null;
tuned = false;
}
@Override
public void onStartTick(ClientWorld world) {
if (noteBlocks == null) {
noteBlocks = new HashMap<>();
ClientPlayerEntity player = MinecraftClient.getInstance().player;
ArrayList<Note> capturedNotes = new ArrayList<>();
Vec3d playerPos = player.getEyePos();
for (int x = -7; x <= 7; x++) {
for (int y = -7; y <= 7; y++) {
for (int z = -7; z <= 7; z++) {
Vec3d pos = playerPos.add(x, y, z);
BlockPos blockPos = new BlockPos(pos);
if (playerPos.squaredDistanceTo(pos) < 4.5 * 4.5) {
BlockState blockState = world.getBlockState(blockPos);
if (blockState.isOf(Blocks.NOTE_BLOCK)) {
for (Note note : song.uniqueNotes) {
if (!capturedNotes.contains(note) && blockState.get(Properties.INSTRUMENT) == note.instrument()) {
getNotes(note.instrument()).put(note.note(), blockPos);
capturedNotes.add(note);
break;
}
}
}
}
}
}
}
ArrayList<Note> missingNotes = new ArrayList<>(song.uniqueNotes);
missingNotes.removeAll(capturedNotes);
if (!missingNotes.isEmpty()) {
ChatHud chatHud = MinecraftClient.getInstance().inGameHud.getChatHud();
chatHud.addMessage(new TranslatableText(Main.MOD_ID+".player.invalid_note_blocks").formatted(Formatting.RED));
HashMap<Block, Integer> missing = new HashMap<>();
for (Note note : missingNotes) {
Block block = Note.INSTRUMENT_BLOCKS.get(note.instrument());
Integer got = missing.get(block);
if (got == null) got = 0;
missing.put(block, got + 1);
}
missing.forEach((block, integer) -> chatHud.addMessage(new LiteralText(block.getName().getString()+" × "+integer).formatted(Formatting.RED)));
stop();
}
} else if (!tuned) {
if (tuneDelay > 0) {
tuneDelay--;
return;
}
tuned = true;
MinecraftClient client = MinecraftClient.getInstance();
int tuneAmount = 0;
for (Note note : song.uniqueNotes) {
BlockPos blockPos = noteBlocks.get(note.instrument()).get(note.note());
BlockState blockState = world.getBlockState(blockPos);
if (blockState.contains(Properties.NOTE)) {
if (blockState.get(Properties.NOTE) != note.note()) {
if (client.player.getEyePos().squaredDistanceTo(Vec3d.ofCenter(blockPos, 0.5)) >= 4.5 * 4.5) {
stop();
client.inGameHud.getChatHud().addMessage(new TranslatableText(Main.MOD_ID+".player.to_far").formatted(Formatting.RED));
return;
}
Vec3d unit = Vec3d.ofCenter(blockPos, 0.5).subtract(client.player.getEyePos()).normalize();
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));
client.interactionManager.interactBlock(client.player, world, Hand.MAIN_HAND, new BlockHitResult(Vec3d.of(blockPos), Direction.UP, blockPos, false));
client.player.swingHand(Hand.MAIN_HAND);
tuned = false;
tuneDelay = 5;
if (++tuneAmount == 6) break;
}
} else {
noteBlocks = null;
break;
}
}
} else {
while (running) {
MinecraftClient client = MinecraftClient.getInstance();
GameMode gameMode = client.interactionManager.getCurrentGameMode();
if (!gameMode.isSurvivalLike()) {
client.inGameHud.getChatHud().addMessage(new TranslatableText(Main.MOD_ID+".player.invalid_game_mode", gameMode.getTranslatableName()).formatted(Formatting.RED));
stop();
return;
}
long note = song.notes[index];
if ((short)note == Math.round(tick)) {
BlockPos blockPos = noteBlocks.get(Note.INSTRUMENTS[(byte)(note >> Note.INSTRUMENT_SHIFT)]).get((byte)(note >> Note.NOTE_SHIFT));
if (client.player.getEyePos().squaredDistanceTo(Vec3d.ofCenter(blockPos, 0.5)) >= 4.5 * 4.5) {
stop();
client.inGameHud.getChatHud().addMessage(new TranslatableText(Main.MOD_ID+".player.to_far").formatted(Formatting.RED));
return;
}
Vec3d unit = Vec3d.ofCenter(blockPos, 0.5).subtract(client.player.getEyePos()).normalize();
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));
client.interactionManager.attackBlock(blockPos, Direction.UP);
client.player.swingHand(Hand.MAIN_HAND);
index++;
if (index >= song.notes.length) {
stop();
break;
}
} else {
break;
}
}
tick += song.tempo / 100f / 20f;
}
}
private HashMap<Byte, BlockPos> getNotes(Instrument instrument) {
return noteBlocks.computeIfAbsent(instrument, k -> new HashMap<>());
}
}

View File

@ -0,0 +1,67 @@
package semmieboy_yt.disc_jockey.gui;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder;
import net.minecraft.client.gui.widget.EntryListWidget;
import net.minecraft.client.util.math.MatrixStack;
import org.jetbrains.annotations.Nullable;
public class SongListWidget extends EntryListWidget<SongListWidget.SongEntry> {
public SongListWidget(MinecraftClient client, int width, int height, int top, int bottom, int itemHeight) {
super(client, width, height, top, bottom, itemHeight);
}
@Override
public void appendNarrations(NarrationMessageBuilder builder) {
// Who cares
}
@Override
public int getRowWidth() {
return width - 40;
}
@Override
protected int getScrollbarPositionX() {
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);
}
public static class SongEntry extends Entry<SongEntry> {
public final int index;
public boolean selected;
public SongListWidget songListWidget;
private final String name;
private final MinecraftClient client = MinecraftClient.getInstance();
public SongEntry(String name, int index) {
this.name = name;
this.index = index;
}
@Override
public void render(MatrixStack matrices, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) {
if (selected) {
fill(matrices, x, y, x + entryWidth, y + entryHeight, 0xFFFFFF);
fill(matrices, x + 1, y + 1, x + entryWidth - 1, y + entryHeight - 1, 0x000000);
}
drawCenteredText(matrices, client.textRenderer, name, x + entryWidth / 2, y + 5, selected ? 0xFFFFFF : 0x808080);
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
// it always gets clicked on
songListWidget.setSelected(this);
return true;
}
}
}

View File

@ -0,0 +1,37 @@
package semmieboy_yt.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.DrawableHelper;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.util.math.MatrixStack;
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(MatrixStack matrices, float tickDelta) {
if (itemStacks != null) {
DrawableHelper.fill(matrices, 2, 2, 62, (itemStacks.length + 1) * 20 + 7, ColorHelper.Argb.getArgb(255, 22, 22, 27));
DrawableHelper.fill(matrices, 4, 4, 60, (itemStacks.length + 1) * 20 + 5, ColorHelper.Argb.getArgb(255, 42, 42, 47));
MinecraftClient client = MinecraftClient.getInstance();
TextRenderer textRenderer = client.textRenderer;
ItemRenderer itemRenderer = client.getItemRenderer();
textRenderer.draw(matrices, " × "+amountOfNoteBlocks, 26, 13, 0xFFFFFF);
itemRenderer.renderInGui(NOTE_BLOCK, 6, 6);
for (int i = 0; i < itemStacks.length; i++) {
textRenderer.draw(matrices, " × "+amounts[i], 26, 13 + 20 * (i + 1), 0xFFFFFF);
itemRenderer.renderInGui(itemStacks[i], 6, 6 + 20 * (i + 1));
}
}
}
}

View File

@ -0,0 +1,141 @@
package semmieboy_yt.disc_jockey.gui.screen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.item.ItemStack;
import net.minecraft.text.TranslatableText;
import semmieboy_yt.disc_jockey.Main;
import semmieboy_yt.disc_jockey.Note;
import semmieboy_yt.disc_jockey.Song;
import semmieboy_yt.disc_jockey.SongLoader;
import semmieboy_yt.disc_jockey.gui.SongListWidget;
import semmieboy_yt.disc_jockey.gui.hud.BlocksOverlay;
import java.util.Arrays;
public class DiscJockeyScreen extends Screen {
private static final TranslatableText
SELECT_SONG = new TranslatableText(Main.MOD_ID+".screen.select_song"),
PLAY = new TranslatableText(Main.MOD_ID+".screen.play"),
PLAY_STOP = new TranslatableText(Main.MOD_ID+".screen.play.stop"),
PREVIEW = new TranslatableText(Main.MOD_ID+".screen.preview"),
PREVIEW_STOP = new TranslatableText(Main.MOD_ID+".screen.preview.stop")
;
private SongListWidget songListWidget;
private ButtonWidget playButton, previewButton;
private boolean shouldFilter;
private String query;
public DiscJockeyScreen() {
super(new TranslatableText(Main.MOD_ID+".screen.title"));
}
@Override
protected void init() {
songListWidget = new SongListWidget(client, width, height, 32, height - 64, 20);
addDrawableChild(songListWidget);
for (int i = 0; i < SongLoader.SONGS.size(); i++) {
Song song = SongLoader.SONGS.get(i);
songListWidget.children().add(song.entry);
song.entry.songListWidget = songListWidget;
if (song.entry.selected) songListWidget.setSelected(song.entry);
}
playButton = new ButtonWidget(width / 2 - 160, height - 61, 100, 20, PLAY, button -> {
if (Main.SONG_PLAYER.running) {
Main.SONG_PLAYER.stop();
} else {
SongListWidget.SongEntry entry = songListWidget.getSelectedOrNull();
if (entry != null) {
Main.SONG_PLAYER.start(SongLoader.SONGS.get(entry.index));
client.setScreen(null);
}
}
});
addDrawableChild(playButton);
previewButton = new ButtonWidget(width / 2 - 50, height - 61, 100, 20, PREVIEW, button -> {
if (Main.PREVIEWER.running) {
Main.PREVIEWER.stop();
} else {
SongListWidget.SongEntry entry = songListWidget.getSelectedOrNull();
if (entry != null) Main.PREVIEWER.start(SongLoader.SONGS.get(entry.index));
}
});
addDrawableChild(previewButton);
addDrawableChild(new ButtonWidget(width / 2 + 60, height - 61, 100, 20, new TranslatableText(Main.MOD_ID+".screen.blocks"), button -> {
SongListWidget.SongEntry entry = songListWidget.getSelectedOrNull();
if (entry != null) {
client.setScreen(null);
Song song = SongLoader.SONGS.get(entry.index);
BlocksOverlay.itemStacks = new ItemStack[0];
BlocksOverlay.amounts = new int[0];
BlocksOverlay.amountOfNoteBlocks = song.uniqueNotes.size();
for (Note note : 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;
}
}
}
}));
TextFieldWidget searchBar = new TextFieldWidget(textRenderer, width / 2 - 75, height - 31, 150, 20, new TranslatableText(Main.MOD_ID+".screen.search"));
searchBar.setChangedListener(query -> {
this.query = query.toLowerCase().replaceAll("\\s", "");
shouldFilter = true;
});
addDrawableChild(searchBar);
}
@Override
public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) {
super.render(matrices, mouseX, mouseY, delta);
drawCenteredText(matrices, 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();
for (Song song : SongLoader.SONGS) if (song.searchableFileName.contains(query) || song.searchableName.contains(query)) songListWidget.children().add(song.entry);
}
}
@Override
public boolean shouldPause() {
return false;
}
@Override
public void onClose() {
super.onClose();
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

View File

@ -0,0 +1,14 @@
{
"disc_jockey.screen.title": "Disc Jockey",
"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.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"
}

View File

@ -0,0 +1,24 @@
{
"schemaVersion": 1,
"id": "disc_jockey",
"version": "${version}",
"name": "Disc Jockey",
"description": "Play note block songs in Minecraft",
"authors": [
"Semmieboy YT"
],
"contact": {
"repo": "https://github.com/SemmieboyYT/Disc-Jockey"
},
"license": "MIT",
"icon": "assets/disc_jockey/icon.png",
"environment": "client",
"entrypoints": {
"client": [
"semmieboy_yt.disc_jockey.Main"
]
},
"depends": {
"fabric": "*"
}
}