initial commit

This commit is contained in:
りき萌 2022-11-18 18:13:03 +01:00
commit 684cec7c6e
51 changed files with 2450 additions and 0 deletions

37
.gitignore vendored Normal file
View file

@ -0,0 +1,37 @@
# gradle
.gradle/
build/
out/
classes/
# eclipse
*.launch
# idea
.idea/
*.iml
*.ipr
*.iws
# vscode
.settings/
.vscode/
bin/
.classpath
.project
# macos
*.DS_Store
# fabric
run/
# Rust
target/

3
README.md Normal file
View file

@ -0,0 +1,3 @@
# dawd³
dawd³ (dawd cubed) - Minecraft audio experiments.

81
build.gradle.kts Normal file
View file

@ -0,0 +1,81 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("fabric-loom")
kotlin("jvm").version(System.getProperty("kotlin_version"))
id("fr.stardustenterprises.rust.wrapper") version "3.2.5" apply false
id("fr.stardustenterprises.rust.importer") version "3.2.5"
}
base { archivesName.set(project.extra["archives_base_name"] as String) }
version = project.extra["mod_version"] as String
group = project.extra["maven_group"] as String
repositories {}
dependencies {
minecraft("com.mojang", "minecraft", project.extra["minecraft_version"] as String)
mappings("net.fabricmc", "yarn", project.extra["yarn_mappings"] as String, null, "v2")
modImplementation("net.fabricmc", "fabric-loader", project.extra["loader_version"] as String)
modImplementation("net.fabricmc.fabric-api", "fabric-api", project.extra["fabric_version"] as String)
modImplementation(
"net.fabricmc",
"fabric-language-kotlin",
project.extra["fabric_language_kotlin_version"] as String
)
rust(project(":d3r"))
}
subprojects {
group = "net.liquidev.d3r"
version = "0.1.0"
}
rustImport {
baseDir.set("/d3r")
layout.set("flat")
}
tasks {
val javaVersion = JavaVersion.toVersion((project.extra["java_version"] as String).toInt())
withType<JavaCompile> {
options.encoding = "UTF-8"
sourceCompatibility = javaVersion.toString()
targetCompatibility = javaVersion.toString()
options.release.set(javaVersion.toString().toInt())
}
withType<KotlinCompile> {
kotlinOptions {
jvmTarget = javaVersion.toString()
}
}
jar {
from("LICENSE") { rename { "${it}_${base.archivesName}" } }
}
processResources {
filesMatching("fabric.mod.json") {
expand(
mutableMapOf(
"version" to project.extra["mod_version"] as String,
"fabricloader" to project.extra["loader_version"] as String,
"fabric_api" to project.extra["fabric_version"] as String,
"fabric_language_kotlin" to project.extra["fabric_language_kotlin_version"] as String,
"minecraft" to project.extra["minecraft_version"] as String,
"java" to project.extra["java_version"] as String
)
)
}
filesMatching("*.mixins.json") { expand(mutableMapOf("java" to project.extra["java_version"] as String)) }
}
java {
toolchain { languageVersion.set(JavaLanguageVersion.of(javaVersion.toString())) }
sourceCompatibility = javaVersion
targetCompatibility = javaVersion
withSourcesJar()
}
}

1106
d3r/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

16
d3r/Cargo.toml Normal file
View file

@ -0,0 +1,16 @@
[package]
name = "d3r"
description = "dawd³ audio runtime"
version = "0.1.0"
edition = "2021"
[lib]
name = "dawd3_d3r"
crate-type = ["cdylib"]
[dependencies]
bitvec = "1.0.1"
cpal = "0.14.1"
env_logger = "0.9.3"
jni = "0.20.0"
log = "0.4.17"

8
d3r/README.md Normal file
View file

@ -0,0 +1,8 @@
# d3r
**d3r** is a low-level realtime sound output library for Java, developed as the audio backend of dawd³.
The Java sources can be found [here](../src/main/java/net/liquidev/d3r).
d3r exposes the API of [CPAL] to Java through the use of JNI.
[CPAL]: https://lib.rs/crates/cpal

13
d3r/build.gradle.kts Normal file
View file

@ -0,0 +1,13 @@
plugins {
id("fr.stardustenterprises.rust.wrapper")
}
rust {
command.set("cargo")
cargoInstallTargets.set(true)
release.set(true)
// targets += target("x86_64-pc-windows-gnu", "dawd3_d3r.dll")
targets += target("x86_64-unknown-linux-gnu", "libdawd3_d3r.so")
}

214
d3r/src/lib.rs Normal file
View file

@ -0,0 +1,214 @@
use std::cell::RefCell;
use std::fmt::Display;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{BufferSize, Device, Host, SampleRate, Stream, StreamConfig};
use jni::objects::{JClass, JMethodID, JObject};
use jni::signature::ReturnType;
use jni::sys::jvalue;
use jni::JNIEnv;
use log::{error, info, warn, LevelFilter};
use crate::registry::Registry;
mod registry;
struct GlobalState {
host: Option<Host>,
devices: Registry<Device>,
streams: Registry<Stream>,
}
thread_local! {
static STATE: RefCell<GlobalState> = RefCell::new(GlobalState {
host: None,
devices: Registry::new(),
streams: Registry::new(),
});
}
fn with_global_state<T>(f: impl FnOnce(&mut GlobalState) -> T) -> T {
STATE.with(|state| {
let mut state = state.borrow_mut();
f(&mut state)
})
}
fn try_with_global_state<T, E>(env: JNIEnv, f: impl FnOnce(&mut GlobalState) -> Result<T, E>) -> T
where
T: Default,
E: Display,
{
let result = with_global_state(|state| f(state));
match result {
Ok(value) => value,
Err(error) => {
let _ = env.throw_new("net/liquidev/d3r/D3rException", error.to_string());
T::default()
}
}
}
#[no_mangle]
pub extern "system" fn Java_net_liquidev_d3r_D3r_initialize(_env: JNIEnv, _: JClass) {
env_logger::builder()
.filter(Some("dawd3_d3r"), LevelFilter::Trace)
.format_timestamp(None)
.init();
info!("d3r initialized successfully")
}
#[no_mangle]
pub extern "system" fn Java_net_liquidev_d3r_D3r_openDefaultHost(env: JNIEnv, _: JClass) {
try_with_global_state(env, |state| {
if state.host.is_some() {
Err("Audio host already open")
} else {
let host = cpal::default_host();
info!("using host: {:?}", host.id());
state.host = Some(host);
Ok(())
}
})
}
#[no_mangle]
pub extern "system" fn Java_net_liquidev_d3r_D3r_openDefaultOutputDevice(
env: JNIEnv,
_: JClass,
) -> u32 {
try_with_global_state(env, |state| {
let Some(host) = &state.host else { return Err("Host is not open"); };
let Some(device) = host.default_output_device() else { return Err("No default output device found"); };
if let Ok(name) = device.name() {
info!("default output device opened successfully: {name}");
} else {
warn!("default output device opened successfully, but could not obtain its name");
}
Ok(state.devices.add(device))
})
}
fn generate_audio(
output: &mut [f32],
config: &StreamConfig,
env: JNIEnv,
generator: JObject,
method: JMethodID,
) -> Result<(), String> {
let buffer = env
.call_method_unchecked(
generator,
method,
ReturnType::Array,
&[
jvalue {
i: output.len() as i32,
},
jvalue {
i: config.channels as i32,
},
],
)
.map_err(|e| format!("error while calling into the audio generator: {e}"))?;
let buffer = buffer.l().expect("buffer must be an object");
let len = env
.get_array_length(buffer.into_raw())
.expect("buffer must be a float[]");
if (len as usize) < output.len() {
return Err(format!(
"audio buffer length is too short (expected {}, but generator returned {len})",
output.len()
));
}
env.get_float_array_region(buffer.into_raw(), 0, output)
.expect("buffer must be a float[]");
Ok(())
}
#[no_mangle]
pub extern "system" fn Java_net_liquidev_d3r_D3r_openOutputStream(
env: JNIEnv,
_: JClass,
output_device_id: u32,
sample_rate: u32,
channel_count: u16,
buffer_size: u32,
generator: JObject,
) -> u32 {
try_with_global_state(env, |state| {
let Some(device) = state.devices.get(output_device_id) else { return Err("Invalid output device ID".to_string()); };
let config = StreamConfig {
channels: channel_count,
sample_rate: SampleRate(sample_rate),
buffer_size: if buffer_size == 0 {
BufferSize::Default
} else {
BufferSize::Fixed(buffer_size)
},
};
let class = env.get_object_class(generator).map_err(|e| e.to_string())?;
let generate_method = env
.get_method_id(class, "getOutputBuffer", "(II)[F")
.map_err(|e| e.to_string())?;
let generator_ref = env.new_global_ref(generator).map_err(|e| e.to_string())?;
let jvm = env.get_java_vm().map_err(|e| e.to_string())?;
let mut initialized = false;
let stream = device
.build_output_stream(
&config.clone(),
move |data: &mut [f32], _| {
if !initialized {
if let Err(error) = jvm.attach_current_thread_permanently() {
error!("cannot attach JVM to audio thread: {error}");
// TODO: propagate the error?
return;
}
initialized = true;
}
let env = jvm
.get_env()
.expect("thread should be attached at this point");
let generator = generator_ref.as_obj();
if let Err(error) =
generate_audio(data, &config, env, generator, generate_method)
{
error!("{error}");
}
},
|error| {
error!("{error}"); // lol
},
)
.map_err(|e| e.to_string())?;
Ok(state.streams.add(stream))
})
}
#[no_mangle]
pub extern "system" fn Java_net_liquidev_d3r_D3r_closeOutputStream(
env: JNIEnv,
_: JClass,
output_stream_id: u32,
) {
try_with_global_state(env, |state| {
let Some(stream) = state.devices.remove(output_stream_id) else { return Err("Invalid output stream ID"); };
drop(stream);
Ok(())
});
}
#[no_mangle]
pub extern "system" fn Java_net_liquidev_d3r_D3r_startPlayback(
env: JNIEnv,
_: JClass,
output_stream_id: u32,
) {
try_with_global_state(env, |state| {
let Some(stream) = state.streams.get(output_stream_id) else { return Err("Invalid output stream ID".to_string()); };
stream.play().map_err(|e| e.to_string())
});
}

62
d3r/src/registry.rs Normal file
View file

@ -0,0 +1,62 @@
//! Registry that attaches names to objects.
use std::mem::MaybeUninit;
use bitvec::vec::BitVec;
pub struct Registry<T> {
next_free: u32,
free_list: Vec<u32>,
valid: BitVec,
store: Vec<MaybeUninit<T>>,
}
impl<T> Registry<T> {
pub fn new() -> Self {
Self {
next_free: 0,
free_list: vec![],
valid: BitVec::new(),
store: vec![]
}
}
pub fn add(&mut self, item: T) -> u32 {
if let Some(id) = self.free_list.pop() {
self.valid.set(id as usize, true);
self.store[id as usize].write(item);
id
} else {
let free = self.next_free;
self.next_free += 1;
self.valid.push(true);
self.store.push(MaybeUninit::new(item));
free
}
}
pub fn remove(&mut self, index: u32) -> Option<T> {
if self.valid[index as usize] {
self.valid.set(index as usize, false);
let item = std::mem::replace(&mut self.store[index as usize], MaybeUninit::uninit());
Some(unsafe { item.assume_init() })
} else {
None
}
}
pub fn get(&self, index: u32) -> Option<&T> {
if self.valid[index as usize] {
Some(unsafe { self.store[index as usize].assume_init_ref() })
} else {
None
}
}
pub fn get_mut(&mut self, index: u32) -> Option<&mut T> {
if self.valid[index as usize] {
Some(unsafe { self.store[index as usize].assume_init_mut() })
} else {
None
}
}
}

25
gradle.properties Normal file
View file

@ -0,0 +1,25 @@
##########################################################################
# Standard Properties
kotlin.code.style = official
org.gradle.jvmargs = -Xmx1G
org.gradle.warning.mode = all
##########################################################################
# Standard Fabric Dependencies
# Check these on https://fabricmc.net/develop/
minecraft_version = 1.19.2
yarn_mappings = 1.19.2+build.28
loader_version = 0.14.10
# Fabric API
fabric_version = 0.66.0+1.19.2
loom_version = 1.0-SNAPSHOT
java_version = 17
##########################################################################
# Mod Properties
mod_version = 0.1.0
maven_group = net.liquidev.dawd3
archives_base_name = dawd3
##########################################################################
# Kotlin Dependencies
systemProp.kotlin_version = 1.7.20
fabric_language_kotlin_version = 1.8.5+kotlin.1.7.20
##########################################################################

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

Binary file not shown.

View file

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

234
gradlew vendored Executable 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

Binary file not shown.

Binary file not shown.

BIN
proj/icon.ase Normal file

Binary file not shown.

BIN
proj/item/dawd3.ase Normal file

Binary file not shown.

BIN
proj/item/patch_cable.ase Normal file

Binary file not shown.

BIN
proj/tilde.ase Normal file

Binary file not shown.

BIN
proj/tilde.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

13
settings.gradle.kts Normal file
View file

@ -0,0 +1,13 @@
pluginManagement {
repositories {
maven("https://maven.fabricmc.net") { name = "Fabric" }
mavenCentral()
gradlePluginPortal()
}
plugins {
id("fabric-loom").version(settings.extra["loom_version"] as String)
kotlin("jvm").version(System.getProperty("kotlin_version"))
}
}
include("d3r")

View file

@ -0,0 +1,7 @@
package net.liquidev.d3r;
public interface AudioOutputStream {
float[] getOutputBuffer(int sampleCount, int channels);
void error(String message);
}

View file

@ -0,0 +1,88 @@
package net.liquidev.d3r;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
public class D3r {
private static final Logger LOGGER = LoggerFactory.getLogger("dawd³/d3r");
private static Path tempDir = null;
public static void load() throws D3rException, IOException {
LOGGER.info("unpacking native library");
var dynlibName = System.mapLibraryName("dawd3_d3r");
var dynlibClassPath = "/d3r/" + dynlibName;
LOGGER.debug("class path: " + dynlibClassPath);
try (var resourceStream = D3r.class.getResourceAsStream(dynlibClassPath)) {
if (resourceStream == null) {
throw new D3rException("dawd3 cannot find an appropriate version of the d3r audio library for your system");
}
var bytes = resourceStream.readAllBytes();
tempDir = Files.createTempDirectory("d3r_native_libs");
var libFile = tempDir.resolve(dynlibName);
if (Files.deleteIfExists(libFile)) {
LOGGER.debug("deleted old unpacked library file");
}
try (var outputStream = Files.newOutputStream(libFile)) {
outputStream.write(bytes);
outputStream.flush();
}
LOGGER.info("loading library");
System.load(libFile.toString());
}
LOGGER.info("initializing");
initialize();
LOGGER.info("loaded successfully");
}
public static void unload() {
if (tempDir != null) {
LOGGER.info("removing native library directory");
try (var walker = Files.walk(tempDir)) {
walker
.sorted(Comparator.reverseOrder())
.forEach(p -> {
try {
Files.delete(p);
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
} else {
LOGGER.warn("unload() called twice or without calling load() first");
}
}
private static native void initialize();
// Host
public static native void openDefaultHost();
// Output device
public static native int openDefaultOutputDevice();
public static native void closeOutputDevice(int outputDeviceId);
// Output stream
public static native int openOutputStream(int outputDeviceId, int sampleRate, short channelCount, int bufferSize, AudioOutputStream generator);
public static native void closeOutputStream(int outputStreamId);
public static native void startPlayback(int outputStreamId);
}

View file

@ -0,0 +1,7 @@
package net.liquidev.d3r;
public class D3rException extends Exception {
D3rException(String what) {
super(what);
}
}

View file

@ -0,0 +1,23 @@
package net.liquidev.dawd3
import net.minecraft.util.Identifier
abstract class D3Registry<T> {
abstract fun doRegister(identifier: Identifier, item: T)
var registered = arrayListOf<Registered<T>>()
fun add(id: String, item: T): Registered<T> {
val entry = Registered(Identifier(Mod.id, id), item)
registered.add(entry)
return entry
}
fun registerAll() {
registered.forEach { reg ->
doRegister(reg.identifier, reg.item)
}
}
data class Registered<T>(val identifier: Identifier, val item: T)
}

View file

@ -0,0 +1,36 @@
package net.liquidev.dawd3
import net.fabricmc.api.ClientModInitializer
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents
import net.liquidev.d3r.D3r
import net.liquidev.dawd3.block.Blocks
import net.liquidev.dawd3.item.Items
import net.liquidev.dawd3.sound.Sound
import org.slf4j.LoggerFactory
@Suppress("UNUSED")
object Mod : ModInitializer, ClientModInitializer {
const val id = "dawd3"
private val logger = LoggerFactory.getLogger("dawd³")
override fun onInitialize() {
logger.info("hello, sound traveler! welcome to the dawd³ experience")
Blocks.blockRegistry.registerAll()
Items.registry.registerAll()
}
override fun onInitializeClient() {
logger.info("booting up sound engine")
D3r.load()
Sound.forceInitializationNow()
ClientLifecycleEvents.CLIENT_STOPPING.register {
logger.info("shutting down sound engine")
Sound.deinitialize()
D3r.unload()
}
}
}

View file

@ -0,0 +1,38 @@
package net.liquidev.dawd3.block
import net.fabricmc.fabric.api.item.v1.FabricItemSettings
import net.fabricmc.fabric.api.`object`.builder.v1.block.FabricBlockSettings
import net.fabricmc.fabric.api.`object`.builder.v1.block.entity.FabricBlockEntityTypeBuilder
import net.liquidev.dawd3.D3Registry
import net.liquidev.dawd3.Mod
import net.liquidev.dawd3.item.Items
import net.minecraft.block.Block
import net.minecraft.block.Material
import net.minecraft.item.BlockItem
import net.minecraft.util.Identifier
import net.minecraft.util.registry.Registry
object Blocks {
var blockRegistry = object : D3Registry<Block>() {
override fun doRegister(identifier: Identifier, item: Block) {
Registry.register(Registry.BLOCK, identifier, item)
}
}
val speaker = add("speaker", SpeakerBlock(moduleBlockSettings()))
val speakerEntity = Registry.register(
Registry.BLOCK_ENTITY_TYPE,
Identifier(Mod.id, "speaker"),
FabricBlockEntityTypeBuilder.create(::SpeakerBlockEntity, speaker.item).build(),
)
private fun moduleBlockSettings() = FabricBlockSettings
.of(Material.METAL)
.hardness(5.0f)
.resistance(6.0f)
private fun add(name: String, block: Block): D3Registry.Registered<Block> {
Items.addItem(name, BlockItem(block, FabricItemSettings().group(Items.creativeTab)))
return blockRegistry.add(name, block)
}
}

View file

@ -0,0 +1,46 @@
package net.liquidev.dawd3.block
import net.minecraft.block.*
import net.minecraft.block.entity.BlockEntity
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.item.ItemPlacementContext
import net.minecraft.item.ItemStack
import net.minecraft.state.StateManager
import net.minecraft.state.property.Properties
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
class SpeakerBlock(settings: Settings) : BlockWithEntity(settings), BlockEntityProvider {
override fun appendProperties(builder: StateManager.Builder<Block, BlockState>) {
builder.add(Properties.HORIZONTAL_FACING)
}
override fun getPlacementState(ctx: ItemPlacementContext): BlockState {
return defaultState.with(Properties.HORIZONTAL_FACING, ctx.playerFacing.opposite)
}
override fun createBlockEntity(pos: BlockPos, state: BlockState): BlockEntity {
return SpeakerBlockEntity(pos, state)
}
override fun getRenderType(state: BlockState): BlockRenderType {
return BlockRenderType.MODEL
}
override fun onPlaced(
world: World,
pos: BlockPos,
state: BlockState,
placer: LivingEntity?,
itemStack: ItemStack,
) {
println("Speaker placed")
}
override fun onBreak(world: World, pos: BlockPos, state: BlockState, player: PlayerEntity) {
println("Speaker broken, deinitializing block entity")
val blockEntity = world.getBlockEntity(pos) as SpeakerBlockEntity
blockEntity.deinit()
}
}

View file

@ -0,0 +1,20 @@
package net.liquidev.dawd3.block
import net.minecraft.block.BlockState
import net.minecraft.block.entity.BlockEntity
import net.minecraft.util.math.BlockPos
class SpeakerBlockEntity(pos: BlockPos, state: BlockState) : BlockEntity(Blocks.speakerEntity, pos, state) {
init {
println("Speaker block entity created")
}
fun deinit() {
println("Speaker block entity deinitialized")
}
private fun finalize() {
deinit()
}
}

View file

@ -0,0 +1,52 @@
package net.liquidev.dawd3.item
import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder
import net.fabricmc.fabric.api.item.v1.FabricItemSettings
import net.liquidev.dawd3.D3Registry
import net.liquidev.dawd3.Mod
import net.minecraft.item.Item
import net.minecraft.item.ItemGroup
import net.minecraft.util.Identifier
import net.minecraft.util.registry.Registry
object Items {
var registry = object : D3Registry<RegisteredItem>() {
override fun doRegister(identifier: Identifier, item: RegisteredItem) {
Registry.register(Registry.ITEM, identifier, item.item)
}
}
// Creative tab
val creativeTab: ItemGroup = FabricItemGroupBuilder.create(Identifier(Mod.id, "main"))
.icon { dawd3.item.item.defaultStack }
.appendItems { list ->
registry.registered.forEach { reg ->
val item = reg.item
if (item.showInCreativeTab) {
list.add(reg.item.item.defaultStack)
}
}
}
.build()
// Icon for creative tab
val dawd3 = registry.add("dawd3", RegisteredItem(Item(FabricItemSettings())).hiddenFromCreativeTab())
// Tools
val patchCable = addItem("patch_cable", PatchCable(FabricItemSettings().group(ItemGroup.REDSTONE)))
fun addItem(name: String, item: Item) {
registry.add(name, RegisteredItem(item))
}
data class RegisteredItem(
val item: Item,
var showInCreativeTab: Boolean = true,
) {
fun hiddenFromCreativeTab(): RegisteredItem {
this.showInCreativeTab = false
return this
}
}
}

View file

@ -0,0 +1,16 @@
package net.liquidev.dawd3.item
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.sound.SoundEvents
import net.minecraft.util.Hand
import net.minecraft.util.TypedActionResult
import net.minecraft.world.World
class PatchCable(settings: Settings) : Item(settings) {
override fun use(world: World, user: PlayerEntity, hand: Hand): TypedActionResult<ItemStack> {
user.playSound(SoundEvents.BLOCK_METAL_PLACE, 1.0f, 1.0f)
return TypedActionResult.success(user.getStackInHand(hand))
}
}

View file

@ -0,0 +1,12 @@
package net.liquidev.dawd3.mixin
import net.minecraft.client.sound.SoundManager
import net.minecraft.client.sound.SoundSystem
import org.spongepowered.asm.mixin.Mixin
import org.spongepowered.asm.mixin.gen.Accessor
@Mixin(SoundManager::class)
interface SoundManagerAccessor {
@Accessor
fun getSoundSystem(): SoundSystem
}

View file

@ -0,0 +1,12 @@
package net.liquidev.dawd3.mixin
import net.minecraft.client.sound.Channel
import net.minecraft.client.sound.SoundSystem
import org.spongepowered.asm.mixin.Mixin
import org.spongepowered.asm.mixin.gen.Accessor
@Mixin(SoundSystem::class)
interface SoundSystemAccessor {
@Accessor
fun getChannel(): Channel
}

View file

@ -0,0 +1,27 @@
package net.liquidev.dawd3.sound
import net.liquidev.d3r.AudioOutputStream
abstract class AudioGenerator : AudioOutputStream {
private var outputBuffer: FloatArray? = null
private fun allocateOutputBuffer(sampleCount: Int): FloatArray {
val inOutputBuffer = outputBuffer
if (inOutputBuffer == null || inOutputBuffer.size < sampleCount) {
outputBuffer = FloatArray(sampleCount)
}
return outputBuffer!!
}
abstract fun generate(output: FloatArray, sampleCount: Int, channels: Int)
override fun getOutputBuffer(sampleCount: Int, channels: Int): FloatArray {
val outputBuffer = allocateOutputBuffer(sampleCount)
generate(outputBuffer, sampleCount, channels)
return outputBuffer
}
override fun error(message: String) {
println("Error reported by audio stream: $message")
}
}

View file

@ -0,0 +1,21 @@
package net.liquidev.dawd3.sound
import kotlin.math.sin
class SineOscGenerator(frequency: Float, private val amplitude: Float) : AudioGenerator() {
private val phaseStep = (1.0f / Sound.sampleRate.toFloat()) * frequency
private var phase = 0.0f
private fun synthesize(): Float {
phase += phaseStep
phase %= 1.0f
return sin(phase * 2.0f * kotlin.math.PI.toFloat()) * amplitude
}
override fun generate(output: FloatArray, sampleCount: Int, channels: Int) {
for (i in 0 until sampleCount) {
val sample = synthesize()
output[i] = sample
}
}
}

View file

@ -0,0 +1,32 @@
package net.liquidev.dawd3.sound
import net.liquidev.d3r.D3r
/** Common sound utilities. */
object Sound {
const val sampleRate = 48000
private const val bufferSize = 256
val outputDeviceId: Int
val outputStreamId: Int
init {
D3r.openDefaultHost()
outputDeviceId = D3r.openDefaultOutputDevice()
outputStreamId = D3r.openOutputStream(
outputDeviceId,
sampleRate,
1,
bufferSize,
SineOscGenerator(frequency = 440.0f, amplitude = 0.5f)
)
D3r.startPlayback(outputStreamId)
}
fun forceInitializationNow() {}
fun deinitialize() {
D3r.closeOutputStream(outputStreamId)
D3r.closeOutputDevice(outputDeviceId)
}
}

View file

@ -0,0 +1,8 @@
{
"variants": {
"facing=north": { "model": "dawd3:block/speaker" },
"facing=east": { "model": "dawd3:block/speaker", "y": 90 },
"facing=south": { "model": "dawd3:block/speaker", "y": 180 },
"facing=west": { "model": "dawd3:block/speaker", "y": 270 }
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 307 B

View file

@ -0,0 +1,3 @@
{
"item.dawd3.patch_cable": "Patch Cable"
}

View file

@ -0,0 +1,21 @@
{
"parent": "block/block",
"textures": {
"side": "dawd3:block/module_side",
"particle": "#side"
},
"elements": [
{
"from": [0, 0, 0],
"to": [16, 16, 16],
"faces": {
"down": { "texture": "#side", "cullface": "down" },
"up": { "texture": "#side", "cullface": "up" },
"north": { "texture": "#front", "cullface": "north" },
"east": { "texture": "#side", "cullface": "east" },
"south": { "texture": "#side", "cullface": "south" },
"west": { "texture": "#side", "cullface": "west" }
}
}
]
}

View file

@ -0,0 +1,6 @@
{
"parent": "dawd3:block/module_with_front",
"textures": {
"front": "dawd3:block/speaker_front"
}
}

View file

@ -0,0 +1,6 @@
{
"parent": "item/generated",
"textures": {
"layer0": "dawd3:item/dawd3"
}
}

View file

@ -0,0 +1,6 @@
{
"parent": "item/generated",
"textures": {
"layer0": "dawd3:item/patch_cable"
}
}

View file

@ -0,0 +1,3 @@
{
"parent": "dawd3:block/speaker"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 230 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 246 B

View file

@ -0,0 +1,12 @@
{
"required": true,
"package": "net.liquidev.dawd3.mixin",
"compatibilityLevel": "JAVA_${java}",
"injectors": {
"defaultRequire": 1
},
"mixins": [
"SoundManagerAccessor",
"SoundSystemAccessor"
]
}

View file

@ -0,0 +1,42 @@
{
"schemaVersion": 1,
"id": "dawd3",
"version": "${version}",
"name": "dawd³",
"description": "music making experiments",
"authors": [
"liquidev"
],
"contact": {
"homepage": "https://liquidev.net/",
"issues": "https://liquidev.net/",
"sources": "https://liquidev.net/"
},
"license": "MIT",
"icon": "assets/dawd3/icon.png",
"environment": "*",
"entrypoints": {
"main": [
{
"adapter": "kotlin",
"value": "net.liquidev.dawd3.Mod"
}
],
"client": [
{
"adapter": "kotlin",
"value": "net.liquidev.dawd3.Mod"
}
]
},
"mixins": [
"dawd3.mixins.json"
],
"depends": {
"fabricloader": ">=${fabricloader}",
"fabric-api": ">=${fabric_api}",
"fabric-language-kotlin": ">=${fabric_language_kotlin}",
"minecraft": ">=${minecraft}",
"java": ">=${java}"
}
}