Initial commit
build / build (push) Successful in 3m28s

This commit is contained in:
ciomek committed 2026-08-15 15:59:56 +02:00
commit 6c112140a9
61 files changed
+2355

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
tab_width = 4
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.gradle.kts]
indent_style = tab
[*.java]
indent_style = tab
[*.json]
indent_style = space
indent_size = 2
[fabric.mod.json]
indent_style = tab
tab_width = 2
[*.properties]
indent_style = space
indent_size = 2
+5
View File
@@ -0,0 +1,5 @@
* text=auto eol=lf
gradlew text eol=lf
*.bat text eol=crlf
*.cmd text eol=crlf
gradle-wrapper.jar -text -diff -merge -filter
+38
View File
@@ -0,0 +1,38 @@
name: build
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: checkout repository
uses: actions/checkout@v6
- name: cache gradle
uses: actions/cache@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
- name: setup jdk
uses: actions/setup-java@v5
with:
java-version: 21
distribution: temurin
- name: make gradle wrapper executable
run: chmod +x ./gradlew
- name: build
run: ./gradlew build --no-daemon -x test
- name: upload artifacts
uses: actions/upload-artifact@v3
with:
name: artifacts
path: build/libs/
+8
View File
@@ -0,0 +1,8 @@
.gradle/
.idea/
.vscode/
bin/
build/
out/
run/
run-server/
+121
View File
@@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
+39
View File
@@ -0,0 +1,39 @@
# Example Mod
Template for making Babric mods for BTA!
**Note: *DO NOT fork this repository unless you want to contribute!***
## Prerequisites
- JDK for Java 21 ([Eclipse Temurin](https://adoptium.net/temurin/releases/) recommended)
- [Intellij IDEA](https://www.jetbrains.com/idea/download/) (Scroll down for the free community edition, if using linux **DO NOT** use the flatpak distribution)
- Minecraft Development plugin (Optional, but highly recommended)
## Setup instructions
1. Click the `Use this template` button on this repo's page above (Will only appear if logged in). Choose `Create a new repository`, you will be redirected to a new page. Enter your repo's name and description, and hit `Create repository`.
To get your project, open IntelliJ IDEA and click `Clone Repository` (`Get from VCS` on older versions). Select `Repository URL` and enter your repo's url
2. After the project has finished importing, close it and open it again.
If that does not work, open the right sidebar with `Gradle` on it, open `Tasks` > `fabric` and run `ideaSyncTask`.
3. Create a new run configuration by going in `Run > Edit Configurations`.
Then click on the plus icon and select Gradle. In the `Tasks and Arguments` field enter `build`.
Running it will build your finished jar files and put them in `build/libs/`.
4. Lastly, open `File` > `Settings` and head to `Build, Execution, Development` > `Build Tools` > `Gradle`.
Make sure `Build and run using` and `Run tests using` is set to `Gradle`.
5. Done! Now, all that's left is to change every mention of `loon` and `ciomek` to your own mod id and mod group, respectively. Happy modding!
## Tips
1. If you haven't already you should join the BTA modding discord! https://discord.gg/FTUNJhswBT
2. You can set your username when launching the client run configuration by setting `--username <username>` in your program arguments.
3. When launching the server run configuration you may want to remove the `nogui` program argument in order to see the regular server GUI.
4. In Intellij you can double press shift or press ctrl+N to search class files, change the search from the default `Project Files` to `All Places` you can easily explore the classes for your dependencies and even BTA itself.
5. In Intellij if ctrl+left-click on a field or method you can quickly get information on when and where that field or method is assign or used.
6. Ensure IntelliJ is updated to the latest version. This is important because this template uses the latest Gradle version and if your IntelliJ installation is outdated, it may not support the latest version.
7. In the `loon.mixins.json` you'll see `"compatibilityLevel": "JAVA_${java}",` along with an error message from the `Minecraft Development` plugin stating `Cannot resolve compatibility level 'JAVA_${java}'`. You can safely ignore this. The Gradle build system has been set up to grab the Java version from your `gradle.properties` and replace `${java}` with it. So the compiled binary will properly have it as `JAVA_8`.
+166
View File
@@ -0,0 +1,166 @@
plugins {
alias(libs.plugins.loom)
java
}
val lwjglNatives = resolveLwjglNatives()
val modVersion = "${providers.gradleProperty("mod_version").get()}+${libs.versions.bta.get()}"
val modGroup: Provider<String> = providers.gradleProperty("mod_group")
val modName: Provider<String> = providers.gradleProperty("mod_name")
val javaVersion: Provider<Int> = libs.versions.java.map { it.toInt() }
base.archivesName = modName
group = modGroup.get()
version = modVersion
loom {
val btaChannel = libs.versions.btaChannel.get()
val btaVersion = (if (btaChannel == "nightly") "" else "v") + libs.versions.bta.get()
customMinecraftMetadata.set("https://downloads.betterthanadventure.net/bta-client/${btaChannel}/$btaVersion/manifest.json")
}
repositories {
mavenCentral()
maven("https://maven.fabricmc.net/") { name = "Fabric" }
maven("https://maven.thesignalumproject.net/infrastructure") { name = "SignalumMavenInfrastructure" }
maven("https://maven.thesignalumproject.net/releases") { name = "SignalumMavenReleases" }
maven("https://maven.thesignalumproject.net/nightly") { name = "SignalumMavenNightly" }
ivy("https://piston-data.mojang.com") {
patternLayout { artifact("v1/[organisation]/[revision]/[module].jar") }
metadataSources { artifact() }
}
}
dependencies {
minecraft("::${libs.versions.bta.get()}")
// Required at compilation & runtime
// included in builds as a runtime dependency
implementation(libs.loader)
implementation(libs.halplibe) // If you do not need halplibe you can delete this line
// Only required at compilation
// provides documentation, can be removed if that isn't needed
compileOnly(libs.bundles.btaLwjgl)
compileOnly(libs.joml)
compileOnly(libs.joml.primitives)
compileOnly(libs.slf4jApi)
// Only required for development/launch at runtime, won't be part of any builds
localRuntime(libs.modMenu) // Optional, can be removed
runtimeClasspath(libs.clientJar)
val lwjglVer = libs.versions.lwjgl.get()
localRuntime(platform("org.lwjgl:lwjgl-bom:${lwjglVer}"))
localRuntime("org.lwjgl:lwjgl::$lwjglNatives")
localRuntime("org.lwjgl:lwjgl-glfw::$lwjglNatives")
localRuntime("org.lwjgl:lwjgl-openal::$lwjglNatives")
localRuntime("org.lwjgl:lwjgl-opengl::$lwjglNatives")
localRuntime("org.lwjgl:lwjgl-stb::$lwjglNatives")
// MQTT
implementation("org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5")
// JSON
implementation("com.fasterxml.jackson.core:jackson-databind:2.20.0")
}
java {
toolchain {
languageVersion = javaVersion.map { JavaLanguageVersion.of(it) }
vendor = JvmVendorSpec.ADOPTIUM
}
sourceCompatibility = JavaVersion.toVersion(javaVersion.get())
targetCompatibility = JavaVersion.toVersion(javaVersion.get())
withSourcesJar()
}
val licenseFile = run {
val rootLicense = layout.projectDirectory.file("LICENSE")
val parentLicense = layout.projectDirectory.file("../LICENSE")
when {
rootLicense.asFile.exists() -> {
logger.lifecycle("Using LICENSE from project root: {}", rootLicense.asFile)
rootLicense
}
parentLicense.asFile.exists() -> {
logger.lifecycle("Using LICENSE from parent directory: {}", parentLicense.asFile)
parentLicense
}
else -> {
logger.warn("No LICENSE file found in project or parent directory.")
null
}
}
}
tasks {
withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
sourceCompatibility = javaVersion.get().toString()
targetCompatibility = javaVersion.get().toString()
if (javaVersion.get() > 8) options.release = javaVersion
}
named<UpdateDaemonJvm>("updateDaemonJvm") {
languageVersion = libs.versions.gradleJava.map { JavaLanguageVersion.of(it.toInt()) }
vendor = JvmVendorSpec.ADOPTIUM
}
withType<JavaExec>().configureEach { defaultCharacterEncoding = "UTF-8" }
withType<Javadoc>().configureEach { options.encoding = "UTF-8" }
withType<Test>().configureEach { defaultCharacterEncoding = "UTF-8" }
withType<Jar>().configureEach {
licenseFile?.let {
from(it) {
rename { original -> "${original}_${archiveBaseName.get()}" }
}
}
}
processResources {
val resourceMap = mapOf(
"version" to modVersion,
"fabricloader" to libs.versions.loader.get(),
"halplibe" to libs.versions.halplibe.get(),
"java" to libs.versions.java.get(),
"modmenu" to libs.versions.modMenu.get()
)
// This is needed for gradle to recognize changes
// made to expanded files
inputs.properties(resourceMap)
duplicatesStrategy = DuplicatesStrategy.INCLUDE
with(copySpec {
from("src/main/resources/") {
include("fabric.mod.json")
include("*.mixins.json")
expand(resourceMap)
}
})
}
}
// Removes all outdated manifest.json dependencies
configurations.configureEach {
exclude(group = "org.lwjgl.lwjgl")
exclude(group = "net.java.jutils")
exclude(group = "net.java.jinput")
exclude(group = "net.sf.jopt-simple")
exclude(group = "net.minecraft", module = "launchwrapper")
}
fun resolveLwjglNatives(): String { // Sourced from https://www.lwjgl.org/
return Pair(
System.getProperty("os.name")!!,
System.getProperty("os.arch")!!
).let { (name, arch) ->
when {
arrayOf("Linux", "SunOS", "Unit").any { name.startsWith(it) } ->
if (arrayOf("arm", "aarch64").any { arch.startsWith(it) })
"natives-linux${if (arch.contains("64") || arch.startsWith("armv8")) "-arm64" else "-arm32"}"
else
"natives-linux"
arrayOf("Mac OS X", "Darwin").any { name.startsWith(it) } ->
"natives-macos${if (arch.startsWith("aarch64")) "-arm64" else ""}"
arrayOf("Windows").any { name.startsWith(it) } ->
if (arch.contains("64"))
"natives-windows${if (arch.startsWith("aarch64")) "-arm64" else ""}"
else
"natives-windows-x86"
else ->
throw Error("Unrecognized or unsupported platform. Please set \"lwjglNatives\" manually")
}
}
}
+18
View File
@@ -0,0 +1,18 @@
##########################################################################
# Standard Properties
org.gradle.jvmargs = -Xmx2G
org.gradle.warning.mode = all
# This currently has to be set to false because the "Minecraft Client" and "Minecraft Server" configurations generated
# by IntelliJ aren't currently compatible with the configuration cache. If you use the runClient and runServer Gradle
# tasks instead, then this can (and should) be set to true.
org.gradle.configuration-cache = false
##########################################################################
# Mod Properties
mod_version = 1.0.0
mod_group = ciomek
mod_name = loon
##########################################################################
# Plugin Dependency
# Check this on https://plugins.gradle.org/plugin/org.gradle.toolchains.foojay-resolver-convention/
foojay_resolver_version = 1.0.0
##########################################################################
+13
View File
@@ -0,0 +1,13 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/df211d3c3eefdc408b462041881bc575/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/b41931cf1e70bc8e08d7dd19c343ef00/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/df211d3c3eefdc408b462041881bc575/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/b41931cf1e70bc8e08d7dd19c343ef00/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/46949723aaa20c7b64d7ecfed7207034/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/d6690dfd71c4c91e08577437b5b2beb0/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/df211d3c3eefdc408b462041881bc575/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/b41931cf1e70bc8e08d7dd19c343ef00/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/3cd7045fca9a72cd9bc7d14a385e594c/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/552c7bffe0370c66410a51c55985b511/redirect
toolchainVendor=ADOPTIUM
toolchainVersion=21
+57
View File
@@ -0,0 +1,57 @@
[versions]
##########################################################################
# Plugins
# Check this on https://github.com/FabricMC/fabric-loom/releases/latest/
loom = "1.15-SNAPSHOT"
##########################################################################
# Java Configuration
# The Java version the JDK will be for compiling and running code.
java = "17"
# The Java version the JDK will be for running Gradle.
gradleJava = "21"
##########################################################################EEE
# Mod Dependencies
# Check this on https://downloads.betterthanadventure.net/bta-client/
bta = "8.0.1"
# Options are release, prerelease, nightly, and misc.
btaChannel = "release"
# Check this on https://maven.thesignalumproject.net/#/infrastructure/net/fabricmc/fabric-loader/
loader = "0.18.4-bta.11"
# Check this on https://github.com/Turnip-Labs/ModMenu/releases/latest/
modMenu = "5.0.2"
# Check this on https://github.com/Turnip-Labs/bta-halplibe/releases/latest/
halplibe = "6.1.3+8.0"
# Check this on https://github.com/Better-than-Adventure/legacy-lwjgl3/releases/latest/
legacyLwjgl = "1.0.6"
##########################################################################
# Dependencies
# Check this on https://central.sonatype.com/artifact/org.slf4j/slf4j-api/
slf4jApi = "2.0.17"
# This should match the version used by the current BTA release.
lwjgl = "3.3.3"
joml = "1.10.8" # Note: BTA uses 1.10.7, patch 8 removes the kotlin stdlib dependency
jomlPrimitivess = "1.10.0"
##########################################################################
[libraries]
loader = { group = "net.fabricmc", name = "fabric-loader", version.ref = "loader" }
halplibe = { group = "turniplabs", name = "halplibe", version.ref = "halplibe" }
modMenu = { group = "turniplabs", name = "modmenu-bta", version.ref = "modMenu" }
legacyLwjgl = { group = "com.github.Better-than-Adventure", name = "legacy-lwjgl3", version.ref = "legacyLwjgl" }
slf4jApi = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4jApi" }
# https://piston-data.mojang.com/v1/objects/43db9b498cb67058d2e12d394e6507722e71bb45/client.jar
clientJar = { group = "objects", name = "client", version = "43db9b498cb67058d2e12d394e6507722e71bb45" }
joml = { group = "org.joml", name = "joml", version.ref = "joml" }
joml-primitives = { group = "org.joml", name = "joml-primitives", version.ref = "jomlPrimitivess" }
lwjgl = { group = "org.lwjgl", name = "lwjgl", version.ref = "lwjgl"}
lwjgl-glfw = { group = "org.lwjgl", name = "lwjgl-glfw", version.ref = "lwjgl"}
lwjgl-openal = { group = "org.lwjgl", name = "lwjgl-openal", version.ref = "lwjgl"}
lwjgl-opengl = { group = "org.lwjgl", name = "lwjgl-opengl", version.ref = "lwjgl"}
lwjgl-stb = { group = "org.lwjgl", name = "lwjgl-stb", version.ref = "lwjgl"}
[bundles]
btaLwjgl = [ "lwjgl", "lwjgl-glfw", "lwjgl-openal", "lwjgl-opengl", "lwjgl-stb", "legacyLwjgl" ]
[plugins]
loom = { id = "net.fabricmc.fabric-loom", version.ref = "loom" }
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
# Check this on https://gradle.org/releases/
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+93
View File
@@ -0,0 +1,93 @@
@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
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+59
View File
@@ -0,0 +1,59 @@
val modName: Provider<String> = providers.gradleProperty("mod_name")
rootProject.name = modName.get()
pluginManagement {
fun isRepoHealthy(url: String): Boolean {
var connection: javax.net.ssl.HttpsURLConnection? = null
return try {
connection = java.net.URI(url).toURL().openConnection() as javax.net.ssl.HttpsURLConnection
connection.requestMethod = "HEAD"
connection.connectTimeout = 2000
connection.readTimeout = 2000
connection.instanceFollowRedirects = true
connection.connect()
val code = connection.responseCode
code in 200..399
} catch (_: Exception) {
false
} finally {
connection?.disconnect()
}
}
fun repoUrlWithFallbacks(candidates: List<String>): String {
if (candidates.isEmpty()) {
val badLink = "https://mock.httpstatus.io/500"
logger.error("No repositories have been provided. Defaulting to: {}", badLink)
return badLink
}
val chosenRepository = candidates.firstOrNull { isRepoHealthy(it) } ?: run {
if (candidates.size == 1) {
logger.error("\"{}\" could not be resolved.", candidates.first())
} else {
logger.error("All {} repositories could not be resolved. Defaulting to: {}", candidates.size, candidates.first())
}
return candidates.first()
}
logger.lifecycle("Using \"{}\" as the Fabric repository.", chosenRepository)
return chosenRepository
}
repositories {
maven(
repoUrlWithFallbacks(
listOf(
"https://maven.fabricmc.net",
"https://maven2.fabricmc.net",
"https://maven3.fabricmc.net"
)
)
) { name = "Fabric" }
maven("https://maven.thesignalumproject.net/infrastructure") { name = "SignalumMavenInfrastructure" }
mavenCentral()
gradlePluginPortal()
}
val foojayResolverVersion = providers.gradleProperty("foojay_resolver_version")
plugins {
id("org.gradle.toolchains.foojay-resolver-convention").version(foojayResolverVersion.get())
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention")
}
+39
View File
@@ -0,0 +1,39 @@
package ciomek.loon;
import ciomek.loon.commands.ChangePasswordCommand;
import ciomek.loon.commands.RegisterCommand;
import ciomek.loon.mqtt.MQTTClient;
import net.fabricmc.api.ModInitializer;
import net.minecraft.core.net.command.CommandManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import turniplabs.halplibe.HalpLibe;
import turniplabs.halplibe.event.defs.CommonEvents;
import turniplabs.halplibe.util.dependency.Key;
public class Loon implements ModInitializer {
public static final String MOD_ID = HalpLibe.registerMod("loon", true);
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
public static final String EnvVarPrefix = "LOON__";
@Override
public void onInitialize() {
CommonEvents.BEFORE_GAME_START.listen(Key.of(MOD_ID), this::beforeGameStart);
CommonEvents.AFTER_GAME_START.listen(Key.of(MOD_ID), this::afterGameStart);
LOGGER.info("Loon initialized.");
CommandManager.registerCommand(new RegisterCommand());
CommandManager.registerCommand(new ChangePasswordCommand());
MQTTClient.getInstance();
}
public void beforeGameStart() {
}
public void afterGameStart() {
}
}
+18
View File
@@ -0,0 +1,18 @@
package ciomek.loon;
import org.spongepowered.asm.mixin.Unique;
public class TPSTracker {
@Unique
private static volatile double tps = 0;
public static double getTPS()
{
return tps;
}
public static void setTPS(double tps)
{
TPSTracker.tps = tps;
}
}
@@ -0,0 +1,72 @@
package ciomek.loon.commands;
import ciomek.loon.mqtt.MQTTClient;
import ciomek.loon.mqtt.payload.ChangePasswordPayload;
import ciomek.loon.mqtt.payload.RegisterResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.ArgumentTypeString;
import com.mojang.brigadier.builder.ArgumentBuilderLiteral;
import com.mojang.brigadier.builder.ArgumentBuilderRequired;
import net.minecraft.core.entity.player.Player;
import net.minecraft.core.net.command.CommandManager;
import net.minecraft.core.net.command.CommandSource;
import static com.mojang.brigadier.builder.ArgumentBuilderLiteral.literal;
public class ChangePasswordCommand implements CommandManager.CommandRegistry {
@SuppressWarnings("unchecked")
@Override
public void register(CommandDispatcher<CommandSource> commandDispatcher) {
commandDispatcher
.register(
(ArgumentBuilderLiteral<CommandSource>) (Object) literal("change-password")
.then(
ArgumentBuilderRequired.argument("password", ArgumentTypeString.string())
.executes(context -> {
CommandSource source = (CommandSource) context.getSource();
Player player = source.getSender();
if (player == null) {
source.sendMessage("This command can only be run by a player!");
return 0;
}
String password = ArgumentTypeString.getString(context, "password");
ChangePasswordPayload payload = new ChangePasswordPayload(player.uuid.toString(), password);
MQTTClient.getInstance().publish(payload.topics().get(0), payload.toJson());
source.sendMessage("Sent request to the server! Waiting for the response. ");
MQTTClient.getInstance().subscribe("loon/register/+/response", (topic, message) -> {
String[] parts = topic.split("/");
String playerUuid = parts[2];
ObjectMapper objectMapper = new ObjectMapper();
RegisterResponse response = objectMapper.readValue(
message.getPayload(),
RegisterResponse.class
);
if (response == null)
return;
if (response.success())
source.sendMessage("Successfully changed your password!");
else
{
source.sendMessage("Failed to change your password!");
source.sendMessage("Here's what went wrong:");
source.sendMessage(response.error());
}
});
return 1;
})
)
);
}
}
@@ -0,0 +1,76 @@
package ciomek.loon.commands;
import ciomek.loon.mqtt.MQTTClient;
import ciomek.loon.mqtt.payload.RegisterPayload;
import ciomek.loon.mqtt.payload.RegisterResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.ArgumentTypeString;
import com.mojang.brigadier.builder.ArgumentBuilderLiteral;
import com.mojang.brigadier.builder.ArgumentBuilderRequired;
import net.minecraft.core.entity.player.Player;
import net.minecraft.core.net.command.CommandManager;
import net.minecraft.core.net.command.CommandSource;
import static com.mojang.brigadier.builder.ArgumentBuilderLiteral.literal;
public class RegisterCommand implements CommandManager.CommandRegistry {
@SuppressWarnings("unchecked")
@Override
public void register(CommandDispatcher<CommandSource> commandDispatcher) {
commandDispatcher
.register(
(ArgumentBuilderLiteral<CommandSource>) (Object) literal("register")
.then(
ArgumentBuilderRequired.argument("internalUsername", ArgumentTypeString.string())
.then(
ArgumentBuilderRequired.argument("password", ArgumentTypeString.string())
.executes(context -> {
CommandSource source = (CommandSource) context.getSource();
Player player = source.getSender();
if (player == null) {
source.sendMessage("This command can only be run by a player!");
return 0;
}
String internalUsername = ArgumentTypeString.getString(context, "internalUsername");
String password = ArgumentTypeString.getString(context, "password");
RegisterPayload payload = new RegisterPayload(player.uuid.toString(), password, internalUsername);
MQTTClient.getInstance().publish(payload.topics().get(0), payload.toJson());
source.sendMessage("Sent request to the server! Waiting for the response. ");
MQTTClient.getInstance().subscribe("loon/register/+/response", (topic, message) -> {
String[] parts = topic.split("/");
String playerUuid = parts[2];
ObjectMapper objectMapper = new ObjectMapper();
RegisterResponse response = objectMapper.readValue(
message.getPayload(),
RegisterResponse.class
);
if (response == null)
return;
if (response.success())
source.sendMessage("Successfully registered the user!");
else
{
source.sendMessage("Failed to register the user!");
source.sendMessage("Here's what went wrong:");
source.sendMessage(response.error());
}
});
return 1;
})
)
)
);
}
}
@@ -0,0 +1,63 @@
package ciomek.loon.mixin;
import ciomek.loon.mqtt.payload.data.ItemStackData;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import ciomek.loon.mqtt.payload.player.inventory.PlayerInventoryPayload;
import net.minecraft.core.entity.player.Player;
import net.minecraft.core.item.ItemStack;
import net.minecraft.core.player.inventory.container.ContainerInventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Arrays;
@Mixin(value = ContainerInventory.class, remap = false)
public class ContainerInventoryMQTTMixin {
@Shadow
public Player player;
@Shadow
public ItemStack[] mainInventory;
@Shadow
public @Nullable ItemStack @NotNull [] armorInventory;
@Unique
private void sendFullInventory() {
if (player == null) {
return;
}
new PlayerInventoryPayload(
new PlayerIdentity(player.uuid, player.username),
Arrays.stream(mainInventory).map(ItemStackData::from).toList(),
Arrays.stream(armorInventory).map(ItemStackData::from).toList()
).send();
}
@Inject(method = {
"setItem",
"insertItem",
"sort",
"dropAllItems",
"transferAllContents",
"load"
}, at = @At("RETURN"))
private void onInventoryChanged(CallbackInfo ci) {
sendFullInventory();
}
@Inject(method = {
"removeItem",
"consumeInventoryItem"
}, at = @At("RETURN"))
private void onInventoryChangedReturn(CallbackInfoReturnable<?> cir) {
sendFullInventory();
}
}
@@ -0,0 +1,43 @@
package ciomek.loon.mixin;
import ciomek.loon.mqtt.MQTTClient;
import ciomek.loon.mqtt.payload.data.ItemStackData;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import ciomek.loon.mqtt.payload.player.inventory.PlayerPickUpItemPayload;
import net.minecraft.core.entity.EntityItem;
import net.minecraft.core.entity.player.Player;
import net.minecraft.core.item.ItemStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(value = EntityItem.class, remap = false)
public class EntityItemMQTTMixin {
@Shadow
public ItemStack item;
@Unique
private int originalStackSize;
@Inject(method = "playerTouch", at = @At("HEAD"))
public void onPlayerTouchHead(Player player, CallbackInfo ci) {
originalStackSize = item != null ? item.stackSize : 0;
}
@Inject(method = "playerTouch", at = @At("TAIL"))
public void onPlayerTouch(Player player, CallbackInfo ci) {
if (item == null || item.stackSize >= originalStackSize) {
return;
}
PlayerPickUpItemPayload payload = new PlayerPickUpItemPayload(
new PlayerIdentity(player.uuid, player.username),
ItemStackData.from(item, originalStackSize - item.stackSize)
);
payload.send();
}
}
@@ -0,0 +1,62 @@
package ciomek.loon.mixin;
import ciomek.loon.mqtt.MQTTClient;
import ciomek.loon.mqtt.payload.CommandPayload;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import ciomek.loon.mqtt.payload.player.list.PlayerKickedPayload;
import ciomek.loon.mqtt.payload.player.PlayerTeleportedPayload;
import net.minecraft.server.entity.player.PlayerServer;
import net.minecraft.server.net.handler.PacketHandlerServer;
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;
@Mixin(value = PacketHandlerServer.class, remap = false)
public class PacketHandlerServerMQTTMixin {
@Shadow
private PlayerServer playerEntity;
@Inject(method = "handleSlashCommand", at = @At("TAIL"))
private void onSlashCommand(String command, CallbackInfo ci) {
CommandPayload payload = new CommandPayload(command, playerEntity.username);
payload.send();
}
@Inject(method = "kickPlayer", at = @At("HEAD"))
private void onKickPlayer(String reason, CallbackInfo ci) {
PlayerKickedPayload payload = new PlayerKickedPayload(
new PlayerIdentity(playerEntity.uuid, playerEntity.username),
reason
);
payload.send();
}
@Inject(method = "teleport(DDD)V", at = @At("HEAD"))
private void onTeleport(double x, double y, double z, CallbackInfo ci) {
publishTeleport(x, y, z, playerEntity.dimension);
}
@Inject(method = "teleportAndRotate", at = @At("HEAD"))
private void onTeleportAndRotate(double x, double y, double z, float yaw, float pitch, CallbackInfo ci) {
publishTeleport(x, y, z, playerEntity.dimension);
}
private void publishTeleport(double toX, double toY, double toZ, int dimension) {
PlayerTeleportedPayload payload = new PlayerTeleportedPayload(
new PlayerIdentity(playerEntity.uuid, playerEntity.username),
playerEntity.x,
playerEntity.y,
playerEntity.z,
toX,
toY,
toZ,
dimension
);
payload.send();
}
}
@@ -0,0 +1,29 @@
package ciomek.loon.mixin;
import ciomek.loon.mqtt.MQTTClient;
import ciomek.loon.mqtt.payload.player.list.PlayerJoinedPayload;
import ciomek.loon.mqtt.payload.player.list.PlayerLeftPayload;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import net.minecraft.server.entity.player.PlayerServer;
import net.minecraft.server.net.PlayerList;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(value = PlayerList.class, remap = false)
public class PlayerListMQTTMixin {
@Inject(method = "playerLoggedIn", at = @At(value = "TAIL"))
public void onPayerLoggedIn(PlayerServer player, CallbackInfo ci) {
PlayerJoinedPayload payload = new PlayerJoinedPayload(new PlayerIdentity(player.uuid, player.username));
payload.send();
}
@Inject(method = "playerLoggedOut", at = @At(value = "TAIL"))
public void onPayerLoggedOut(PlayerServer entityplayermp, CallbackInfo ci) {
PlayerLeftPayload payload = new PlayerLeftPayload(new PlayerIdentity(entityplayermp.uuid, entityplayermp.username));
payload.send();
}
}
@@ -0,0 +1,91 @@
package ciomek.loon.mixin;
import ciomek.loon.mqtt.payload.data.ItemStackData;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import ciomek.loon.mqtt.payload.player.PlayerDiedPayload;
import ciomek.loon.mqtt.payload.player.PlayerHurtPayload;
import ciomek.loon.mqtt.payload.player.inventory.PlayerDropItemPayload;
import ciomek.loon.mqtt.payload.player.inventory.PlayerInventoryPayload;
import net.minecraft.core.entity.Entity;
import net.minecraft.core.entity.player.Player;
import net.minecraft.core.item.ItemStack;
import net.minecraft.core.util.helper.DamageType;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Arrays;
@Mixin(value = Player.class, remap = false)
public class PlayerMQTTMixin {
@Unique
DamageType lastDamageType = null;
@Inject(method = "hurt", at = @At(value = "HEAD"))
public void onHurtStart(Entity attacker, int damage, DamageType type, CallbackInfoReturnable<Boolean> cir) {
lastDamageType = type;
}
@Inject(method = "hurt", at = @At(value = "TAIL"))
public void onHurt(Entity attacker, int damage, DamageType type, CallbackInfoReturnable<Boolean> cir) {
Player player = (Player) (Object) this;
PlayerHurtPayload payload = new PlayerHurtPayload(new PlayerIdentity(player.uuid, player.username), damageTypeName(type));
payload.send();
}
@Inject(method = "onDeath", at = @At(value = "TAIL"))
public void onDeath(Entity entityKilledBy, CallbackInfo ci) {
Player player = (Player) (Object) this;
String killerName;
if (entityKilledBy instanceof Player killer) {
killerName = killer.username;
} else if (entityKilledBy != null) {
killerName = Entity.getNameFromEntity(entityKilledBy, true);
} else {
killerName = null;
}
String damageType = lastDamageType == null ? null : damageTypeName(lastDamageType);
PlayerDiedPayload payload = new PlayerDiedPayload(new PlayerIdentity(player.uuid, player.username), killerName, damageType);
payload.send();
}
@Inject(method = "dropItem", at = @At("TAIL"))
public void onDropItem(ItemStack stack, boolean randomDirection, CallbackInfo ci) {
if (stack == null) {
return;
}
Player player = (Player) (Object) this;
PlayerDropItemPayload payload = new PlayerDropItemPayload(
new PlayerIdentity(player.uuid, player.username),
ItemStackData.from(stack)
);
payload.send();
}
@Inject(method = "setItemInArmorSlot", at = @At("TAIL"))
private void onArmorChanged(CallbackInfo ci) {
Player player = (Player) (Object) this;
new PlayerInventoryPayload(
new PlayerIdentity(player.uuid, player.username),
Arrays.stream(player.inventory.mainInventory).map(ItemStackData::from).toList(),
Arrays.stream(player.inventory.armorInventory).map(ItemStackData::from).toList()
).send();
}
@Unique
private static String damageTypeName(DamageType type) {
String key = type.getLanguageKey();
return key.substring(key.lastIndexOf('.') + 1);
}
}
@@ -0,0 +1,97 @@
package ciomek.loon.mixin;
import ciomek.loon.TPSTracker;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import ciomek.loon.mqtt.payload.data.PositionData;
import ciomek.loon.mqtt.payload.player.PlayerPositionPayload;
import ciomek.loon.mqtt.request.IRequest;
import ciomek.loon.mqtt.request.RequestManager;
import net.minecraft.core.world.Dimension;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.entity.player.PlayerServer;
import net.minecraft.server.world.WorldServer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Mixin(value = WorldServer.class, remap = false)
public class WorldServerMixin {
@Unique
private static final int POSITION_CHECK_INTERVAL_TICKS = 20;
@Shadow
public MinecraftServer mcServer;
@Unique
private static final ExecutorService EXECUTOR = Executors.newCachedThreadPool();
@Unique
private static long lastTickNanos;
@Unique
private static long gapSumNanos;
@Unique
private static int gapTicks;
@Unique
private static int positionCheckTicks;
@Unique
private static final Map<UUID, PositionData> lastSentPositions = new HashMap<>();
@Inject(method = "tick", at = @At("TAIL"))
private void onTick(CallbackInfo ci) {
WorldServer self = (WorldServer) (Object) this;
if (self.dimension == Dimension.OVERWORLD) {
long now = System.nanoTime();
if (lastTickNanos != 0) {
gapSumNanos += now - lastTickNanos;
gapTicks++;
if (gapSumNanos >= 1_000_000_000L) {
TPSTracker.setTPS(Math.min(20.0, gapTicks / (gapSumNanos / 1e9)));
gapSumNanos = 0;
gapTicks = 0;
}
}
lastTickNanos = now;
if (++positionCheckTicks >= POSITION_CHECK_INTERVAL_TICKS) {
positionCheckTicks = 0;
broadcastMovedPlayerPositions();
}
}
IRequest request;
while ((request = RequestManager.pollRequest()) != null) {
IRequest current = request;
EXECUTOR.submit(() -> current.handle(mcServer));
}
}
@Unique
private void broadcastMovedPlayerPositions() {
for (PlayerServer player : mcServer.playerList.playerEntities) {
PositionData position = new PositionData(player.x, player.y, player.z);
if (!position.equals(lastSentPositions.put(player.uuid, position))) {
PlayerPositionPayload payload = new PlayerPositionPayload(
new PlayerIdentity(player.uuid, player.username),
position,
player.dimension
);
payload.send();
}
}
}
}
@@ -0,0 +1,161 @@
package ciomek.loon.mqtt;
import ciomek.loon.Loon;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import ciomek.loon.mqtt.request.*;
import org.eclipse.paho.client.mqttv3.*;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MQTTClient {
private static MQTTClient instance;
private MqttClient client;
private MQTTSettings settings;
public static synchronized MQTTClient getInstance() {
if(instance != null)
return instance;
MQTTClient mqttClient = MQTTClient.init();
instance = mqttClient;
return instance;
}
public void subscribe(String topicFilter, IMqttMessageListener messageListener) {
try {
client.subscribe(topicFilter, messageListener);
} catch (MqttException e) {
throw new RuntimeException(e);
}
}
public void publish(String topic, String message, int qos) {
MqttMessage mqttMessage = new MqttMessage(message.getBytes());
mqttMessage.setQos(qos);
try {
client.publish(topic, mqttMessage);
} catch (MqttException e) {
throw new RuntimeException(e);
}
}
public void publish(String topic, String message) {
publish(topic, message, 1);
}
public void publish(String topic, Payload payload) {
publish(topic, payload.toJson());
}
static MQTTClient init() {
MQTTClient client = new MQTTClient();
client.establish();
return client;
}
public void establish() {
settings = MQTTSettings.getFromEnvVars();
String broker = settings.broker();
String clientId = settings.clientId();
String username = settings.username();
String password = settings.password();
try {
client = new MqttClient(broker, clientId);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(username);
options.setPassword(password.toCharArray());
options.setMaxInflight(10000);
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
}
@Override
public void messageArrived(String topic, MqttMessage message) {
if (topic.matches("loon/player/[^/]+/inventory/full/request")) {
Pattern pattern = Pattern.compile("loon/player/([^/]+)/inventory/full/request");
Matcher matcher = pattern.matcher(topic);
if (matcher.matches()) {
UUID playerId = UUID.fromString(matcher.group(1));
InventoryRequest inventoryRequest = new InventoryRequest(playerId);
RequestManager.addRequest(inventoryRequest);
}
}
if (topic.matches("loon/player/[^/]+/online/request")) {
Pattern pattern = Pattern.compile("loon/player/([^/]+)/online/request");
Matcher matcher = pattern.matcher(topic);
if (matcher.matches()) {
UUID playerId = UUID.fromString(matcher.group(1));
PlayerOnlineRequest playerOnlineRequest = new PlayerOnlineRequest(playerId);
RequestManager.addRequest(playerOnlineRequest);
}
}
if (topic.matches("loon/player/[^/]+/position/request")) {
Pattern pattern = Pattern.compile("loon/player/([^/]+)/position/request");
Matcher matcher = pattern.matcher(topic);
if (matcher.matches()) {
UUID playerId = UUID.fromString(matcher.group(1));
PlayerPositionRequest request = new PlayerPositionRequest(playerId);
RequestManager.addRequest(request);
}
}
Pattern pattern = Pattern.compile("loon/world/chunks/(-?\\d+):(-?\\d+)/(-?\\d+):(-?\\d+)/request");
Matcher matcher = pattern.matcher(topic);
if (matcher.matches())
{
int xStart = Integer.parseInt(matcher.group(1));
int xEnd = Integer.parseInt(matcher.group(2));
int zStart = Integer.parseInt(matcher.group(3));
int zEnd = Integer.parseInt(matcher.group(4));
ChunkMapRequest request = new ChunkMapRequest(xStart, xEnd, zStart, zEnd);
RequestManager.addRequest(request);
}
if (topic.equals("loon/server/info/request")) {
RequestManager.addRequest(new ServerInfoRequest());
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
client.connect(options);
client.subscribe("loon/player/+/inventory/full/request");
client.subscribe("loon/player/+/online/request");
client.subscribe("loon/player/+/position/request");
client.subscribe("loon/world/chunks/+/+/request");
client.subscribe("loon/server/info/request");
} catch (MqttException e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,30 @@
package ciomek.loon.mqtt;
import ciomek.loon.Loon;
public record MQTTSettings (
String broker,
String username,
String password,
String clientId
)
{
public static MQTTSettings getFromEnvVars()
{
return new MQTTSettings(getEnvVar("broker"), getEnvVar("username"), getEnvVar("password"), getEnvVar("clientid"));
}
static String getEnvVar(String name)
{
String fullName = Loon.EnvVarPrefix + name.toUpperCase();
String value = System.getenv(fullName);
if (value == null || value.isBlank())
throw new IllegalArgumentException(
"Missing environment variable: " + fullName + ". "
);
return value;
}
}
@@ -0,0 +1,13 @@
package ciomek.loon.mqtt.payload;
import java.util.List;
public record ChangePasswordPayload (
String uuid,
String password
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/register/change_password");
}
}
@@ -0,0 +1,13 @@
package ciomek.loon.mqtt.payload;
import java.util.List;
public record CommandPayload(
String command,
String source
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/commands", "loon/all");
}
}
@@ -0,0 +1,34 @@
package ciomek.loon.mqtt.payload;
import ciomek.loon.mqtt.MQTTClient;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public interface Payload {
ObjectMapper MAPPER = new ObjectMapper();
List<String> topics();
default String toJson() {
try {
MAPPER.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
return MAPPER.writeValueAsString(this);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
default void send()
{
topics().forEach(topic -> {
MQTTClient.getInstance().publish(
topic,
this
);
});
}
}
@@ -0,0 +1,14 @@
package ciomek.loon.mqtt.payload;
import java.util.List;
public record RegisterPayload (
String uuid,
String password,
String internalUsername
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/register/request");
}
}
@@ -0,0 +1,6 @@
package ciomek.loon.mqtt.payload;
public record RegisterResponse(
boolean success,
String error
) {}
@@ -0,0 +1,22 @@
package ciomek.loon.mqtt.payload;
import java.util.List;
public record ServerInfoPayload(
double tps,
String version,
String motd,
boolean onlineMode,
int sleepPercentage,
int currentPlayerCount,
int maxPlayerCount,
int difficulty,
boolean pvpOn,
int viewDistance
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/server/info");
}
}
@@ -0,0 +1,8 @@
package ciomek.loon.mqtt.payload.data;
public record BlockData(
String blockName,
int blockId,
int color
) {
}
@@ -0,0 +1,12 @@
package ciomek.loon.mqtt.payload.data;
import java.util.List;
public record ChunkData (
List<List<BlockData>> map,
String biome,
int x,
int z,
boolean loaded
) {
}
@@ -0,0 +1,25 @@
package ciomek.loon.mqtt.payload.data;
import net.minecraft.core.item.ItemStack;
public record ItemStackData(
String itemName,
int itemID,
int itemCount
) {
public static ItemStackData from(ItemStack stack) {
if (stack == null) {
return null;
}
return from(stack, stack.stackSize);
}
public static ItemStackData from(ItemStack stack, int itemCount) {
if (stack == null) {
return null;
}
return new ItemStackData(stack.getDisplayName(), stack.itemID, itemCount);
}
}
@@ -0,0 +1,9 @@
package ciomek.loon.mqtt.payload.data;
import java.util.UUID;
public record PlayerIdentity
(
UUID uuid,
String username
) { }
@@ -0,0 +1,7 @@
package ciomek.loon.mqtt.payload.data;
public record PositionData (
double x,
double y,
double z
) {}
@@ -0,0 +1,17 @@
package ciomek.loon.mqtt.payload.player;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import java.util.List;
public record PlayerDiedPayload(
PlayerIdentity player,
String killer,
String damageType
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/player/" + player.uuid() + "/died");
}
}
@@ -0,0 +1,16 @@
package ciomek.loon.mqtt.payload.player;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import java.util.List;
public record PlayerHurtPayload (
PlayerIdentity player,
String damageType
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/player/" + player.uuid() + "/hurt");
}
}
@@ -0,0 +1,16 @@
package ciomek.loon.mqtt.payload.player;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import java.util.List;
public record PlayerOnlinePayload(
PlayerIdentity player,
boolean online
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/player/" + player.uuid() + "/online", "loon/player/" + player.uuid() + "/online/response");
}
}
@@ -0,0 +1,18 @@
package ciomek.loon.mqtt.payload.player;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import ciomek.loon.mqtt.payload.data.PositionData;
import java.util.List;
public record PlayerPositionPayload(
PlayerIdentity player,
PositionData position,
Integer dimension
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/player/" + player.uuid() + "/position", "loon/player/" + player.uuid() + "/position/response");
}
}
@@ -0,0 +1,22 @@
package ciomek.loon.mqtt.payload.player;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import java.util.List;
public record PlayerTeleportedPayload(
PlayerIdentity player,
double fromX,
double fromY,
double fromZ,
double toX,
double toY,
double toZ,
int dimension
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/player/" + player.uuid() + "/teleported");
}
}
@@ -0,0 +1,17 @@
package ciomek.loon.mqtt.payload.player.inventory;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.ItemStackData;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import java.util.List;
public record PlayerDropItemPayload(
PlayerIdentity player,
ItemStackData itemStack
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/player/" + player.uuid() + "/inventory/dropped");
}
}
@@ -0,0 +1,18 @@
package ciomek.loon.mqtt.payload.player.inventory;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.ItemStackData;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import java.util.List;
public record PlayerInventoryPayload(
PlayerIdentity player,
List<ItemStackData> grid,
List<ItemStackData> armor
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/player/" + player.uuid() + "/inventory/full/response");
}
}
@@ -0,0 +1,17 @@
package ciomek.loon.mqtt.payload.player.inventory;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.ItemStackData;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import java.util.List;
public record PlayerPickUpItemPayload (
PlayerIdentity player,
ItemStackData itemStack
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/player/" + player.uuid() + "/inventory/picked_up");
}
}
@@ -0,0 +1,15 @@
package ciomek.loon.mqtt.payload.player.list;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import java.util.List;
public record PlayerJoinedPayload(
PlayerIdentity player
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/playerlist/joined", "loon/player/" + player.uuid() + "/joined");
}
}
@@ -0,0 +1,16 @@
package ciomek.loon.mqtt.payload.player.list;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import java.util.List;
public record PlayerKickedPayload(
PlayerIdentity player,
String reason
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/playerlist/kicked", "loon/player/" + player.uuid() + "/kicked");
}
}
@@ -0,0 +1,15 @@
package ciomek.loon.mqtt.payload.player.list;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import java.util.List;
public record PlayerLeftPayload(
PlayerIdentity player
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/playerlist/left", "loon/player/" + player.uuid() + "/left");
}
}
@@ -0,0 +1,17 @@
package ciomek.loon.mqtt.payload.world.chunks;
import ciomek.loon.mqtt.payload.Payload;
import ciomek.loon.mqtt.payload.data.ChunkData;
import ciomek.loon.mqtt.payload.data.ItemStackData;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import java.util.List;
public record ChunkMapPayload(
ChunkData chunk
) implements Payload {
@Override
public List<String> topics() {
return List.of("loon/world/chunk/" + chunk.x() + "/" + chunk.z(), "loon/world/chunk/" + chunk.x() + "/" + chunk.z() + "/response");
}
}
@@ -0,0 +1,89 @@
package ciomek.loon.mqtt.request;
import ciomek.loon.mqtt.payload.data.BlockData;
import ciomek.loon.mqtt.payload.data.ChunkData;
import ciomek.loon.mqtt.payload.world.chunks.ChunkMapPayload;
import net.minecraft.core.block.Block;
import net.minecraft.core.block.material.MaterialColor;
import net.minecraft.core.world.World;
import net.minecraft.core.world.biome.Biome;
import net.minecraft.core.world.chunk.Chunk;
import net.minecraft.core.world.chunk.ChunkLoader;
import net.minecraft.core.world.chunk.provider.ChunkProvider;
import net.minecraft.core.world.pos.ChunkPos;
import net.minecraft.core.world.pos.ChunkTilePos;
import net.minecraft.server.MinecraftServer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public record ChunkMapRequest(int xStart, int xEnd, int zStart, int zEnd) implements IRequest {
@Override
public void handle(MinecraftServer server) {
World world = server.getDimensionWorld(0);
ChunkProvider provider = world.getChunkProvider();
ChunkLoader loader = world.getLevelStorage().getChunkLoader(world.dimension);
for (int x = xStart; x <= xEnd; x++) {
for (int z = zStart; z <= zEnd; z++) {
Chunk currentChunk = resolveChunk(world, provider, loader, x, z);
if (currentChunk == null) {
ChunkData chunkData = new ChunkData(null, "", x, z, false);
new ChunkMapPayload(chunkData).send();
continue;
}
String biomeName = getBiomeName(currentChunk);
List<List<BlockData>> chunkMap = new ArrayList<>();
for (int chunkX = 0; chunkX < 16; chunkX++) {
chunkMap.add(new ArrayList<>());
for (int chunkZ = 0; chunkZ < 16; chunkZ++) {
int highestBlockY = Math.max(0, currentChunk.getHeightValue(chunkX, chunkZ) - 1);
Block block = currentChunk.getBlock(new ChunkTilePos(chunkX, highestBlockY, chunkZ));
int meta = currentChunk.getBlockMetadata(chunkX, highestBlockY, chunkZ);
int rgb = MaterialColor.getColorFromIndex(
MaterialColor.getColorIndexFromBlock(block, meta)
);
BlockData blockData = new BlockData(block.getKey(), block.id(), rgb);
chunkMap.get(chunkX).add(blockData);
}
}
ChunkData chunkData = new ChunkData(chunkMap, biomeName, x, z, true);
new ChunkMapPayload(chunkData).send();
}
}
}
String getBiomeName(Chunk chunk)
{
int surfaceY = Math.max(0, chunk.getHeightValue(8, 8) - 1);
Biome biome = chunk.getBlockBiome(new ChunkTilePos(8, surfaceY, 8));
return biome != null ? biome.getRegistryKey() : "?";
}
Chunk resolveChunk(World world, ChunkProvider provider, ChunkLoader loader, int x, int z)
{
ChunkPos chunkPos = new ChunkPos(x, z);
if (provider.isChunkLoaded(chunkPos))
return world.getChunk(chunkPos);
if (loader == null || !loader.chunkExists(world, x, z))
return null;
try {
return loader.loadChunk(world, x, z);
} catch (IOException e) {
return null;
}
}
}
@@ -0,0 +1,9 @@
package ciomek.loon.mqtt.request;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.entity.player.PlayerServer;
public interface IRequest
{
void handle(MinecraftServer server);
}
@@ -0,0 +1,37 @@
package ciomek.loon.mqtt.request;
import ciomek.loon.mqtt.MQTTClient;
import ciomek.loon.mqtt.payload.data.ItemStackData;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import ciomek.loon.mqtt.payload.player.inventory.PlayerInventoryPayload;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.entity.player.PlayerServer;
import java.util.Arrays;
import java.util.UUID;
public record InventoryRequest(UUID playerUuid) implements IRequest {
@Override
public void handle(MinecraftServer server) {
PlayerServer player = server.playerList.playerEntities.stream()
.filter(playerServer -> playerServer.uuid.equals(playerUuid))
.findFirst()
.orElse(null);
if (player == null) {
return;
}
PlayerInventoryPayload payload = new PlayerInventoryPayload(
new PlayerIdentity(player.uuid, player.username),
Arrays.stream(player.inventory.mainInventory)
.map(ItemStackData::from)
.toList(),
Arrays.stream(player.inventory.armorInventory)
.map(ItemStackData::from)
.toList()
);
payload.send();
}
}
@@ -0,0 +1,38 @@
package ciomek.loon.mqtt.request;
import ciomek.loon.mqtt.payload.data.ItemStackData;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import ciomek.loon.mqtt.payload.player.PlayerOnlinePayload;
import ciomek.loon.mqtt.payload.player.inventory.PlayerInventoryPayload;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.entity.player.PlayerServer;
import java.util.Arrays;
import java.util.UUID;
public record PlayerOnlineRequest(UUID playerUuid) implements IRequest {
@Override
public void handle(MinecraftServer server) {
boolean online = server.playerList.playerEntities.stream()
.anyMatch(p -> p.uuid.equals(playerUuid));
PlayerServer player = server.playerList.playerEntities.stream()
.filter(p -> p.uuid.equals(playerUuid))
.findFirst()
.orElse(null);
PlayerIdentity identity;
if(player == null) {
identity = new PlayerIdentity(playerUuid, "");
}
else {
identity = new PlayerIdentity(player.uuid, player.username);
}
PlayerOnlinePayload payload = new PlayerOnlinePayload(
identity,
online);
payload.send();
}
}
@@ -0,0 +1,39 @@
package ciomek.loon.mqtt.request;
import ciomek.loon.mqtt.payload.data.PlayerIdentity;
import ciomek.loon.mqtt.payload.data.PositionData;
import ciomek.loon.mqtt.payload.player.PlayerOnlinePayload;
import ciomek.loon.mqtt.payload.player.PlayerPositionPayload;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.entity.player.PlayerServer;
import java.util.UUID;
public record PlayerPositionRequest(UUID playerUuid) implements IRequest {
@Override
public void handle(MinecraftServer server) {
PlayerServer player = server.playerList.playerEntities.stream()
.filter(p -> p.uuid.equals(playerUuid))
.findFirst()
.orElse(null);
if (player == null) {
PlayerPositionPayload payload = new PlayerPositionPayload(
new PlayerIdentity(playerUuid, null),
null,
null
);
payload.send();
}
else {
PositionData playerPosition = new PositionData(player.x, player.y, player.z);
PlayerPositionPayload payload = new PlayerPositionPayload(
new PlayerIdentity(player.uuid, player.username),
playerPosition,
player.dimension
);
payload.send();
}
}
}
@@ -0,0 +1,17 @@
package ciomek.loon.mqtt.request;
import java.util.concurrent.ConcurrentLinkedQueue;
public class RequestManager {
static ConcurrentLinkedQueue<IRequest> queue = new ConcurrentLinkedQueue<>();
public static void addRequest(IRequest request)
{
queue.add(request);
}
public static IRequest pollRequest()
{
return queue.poll();
}
}
@@ -0,0 +1,25 @@
package ciomek.loon.mqtt.request;
import ciomek.loon.TPSTracker;
import ciomek.loon.mixin.WorldServerMixin;
import ciomek.loon.mqtt.payload.ServerInfoPayload;
import net.minecraft.server.MinecraftServer;
public record ServerInfoRequest() implements IRequest {
@Override
public void handle(MinecraftServer server) {
ServerInfoPayload payload = new ServerInfoPayload(
TPSTracker.getTPS(),
server.getMinecraftVersion(),
server.motd,
server.onlineMode,
server.sleepPercentage,
server.playerList.playerEntities.size(),
server.maxPlayers,
server.difficulty,
server.pvpOn,
server.viewDistance);
payload.send();
}
}
Whitespace-only changes.
+33
View File
@@ -0,0 +1,33 @@
{
"schemaVersion": 1,
"id": "loon",
"version": "${version}",
"name": "Example Mod",
"description": "This mod aims to help new BTA modders.",
"authors": [
"Turnip Labs"
],
"contact": {
"homepage": "",
"sources": ""
},
"icon": "icon.png",
"license": "CC0-1.0",
"environment": "*",
"entrypoints": {
"main": [
"ciomek.loon.Loon"
]
},
"mixins": [
"loon.mixins.json"
],
"depends": {
"fabricloader": ">=${fabricloader}",
"minecraft": "*",
"java": ">=${java}"
},
"suggests": {
"modmenu": ">=${modmenu}"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

+18
View File
@@ -0,0 +1,18 @@
{
"required": true,
"package": "ciomek.loon.mixin",
"compatibilityLevel": "JAVA_${java}",
"injectors": {
"defaultRequire": 1
},
"mixins": [
"ContainerInventoryMQTTMixin",
"EntityItemMQTTMixin",
"PacketHandlerServerMQTTMixin",
"PlayerListMQTTMixin",
"PlayerMQTTMixin",
"WorldServerMixin"
],
"client": []
}