diff --git a/.gitignore b/.gitignore index 3c37caf..d87b4ea 100644 --- a/.gitignore +++ b/.gitignore @@ -112,7 +112,8 @@ gradle-app.setting **/build/ # Common working directory -run/ +run-client/ +run-server/ # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) !gradle-wrapper.jar diff --git a/.woodpecker.yml b/.woodpecker.yml new file mode 100644 index 0000000..123ea6e --- /dev/null +++ b/.woodpecker.yml @@ -0,0 +1,51 @@ +pipeline: + restore-cache: + image: bash + commands: + - mkdir -p /tmp/woodpecker/Elixium/Lymel + - ls -a /tmp/woodpecker/Elixium/Lymel + - ls -a + - cp -r /tmp/woodpecker/Elixium/Lymel/* $(pwd)/ + - ls -a + volumes: + - /tmp/woodpecker/Elixium/Lymel:/tmp/woodpecker/Elixium/Lymel + when: + event: push + build: + image: gradle:jdk17 + commands: + - ls -a + - chmox +x gradlew + - ./gradlew build --stacktrace + - ls -a + when: + event: push + gitea_release: + image: python:3.9 + secrets: + - api_key + commands: + - export PRERELEASE=true + - chmod +x git_release.py + - pip install giteapy + - python git_release.py --token "$API_KEY" --message "${DRONE_COMMIT_MESSAGE}" --prerelease $PRERELEASE --tag "${DRONE_TAG}" + when: + event: tag + + rebuild-cache-with-filesystem: + image: bash + commands: + - ls -a + - mkdir -p /tmp/woodpecker/Elixium/Lymel/build + - ls -a /tmp/woodpecker/Elixium/Lymel + - cp -f -R $(pwd)/build/classes /tmp/woodpecker/Elixium/Lymel/build/classes + - cp -f -R $(pwd)/build/generated /tmp/woodpecker/Elixium/Lymel/build/generated + - cp -f -R $(pwd)/build/resources /tmp/woodpecker/Elixium/Lymel/build/resources + - cp -f -R $(pwd)/build/tmp /tmp/woodpecker/Elixium/Lymel/build/tmp + - cp -f -R $(pwd)/.gradle /tmp/woodpecker/Elixium/Lymel + - ls -a + - ls -a /tmp/woodpecker/Elixium/Lymel + volumes: + - /tmp/woodpecker/Elixium/Lymel:/tmp/woodpecker/Elixium/Lymel + when: + event: push \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..86f153b --- /dev/null +++ b/LICENSE @@ -0,0 +1,2 @@ +Copyright (c) 2023 unurled +All rights reserved. diff --git a/build.gradle b/build.gradle index 44616a6..2d76296 100644 --- a/build.gradle +++ b/build.gradle @@ -3,26 +3,39 @@ plugins { id 'maven-publish' } +sourceCompatibility = JavaVersion.VERSION_17 +targetCompatibility = JavaVersion.VERSION_17 + +archivesBaseName = project.archives_base_name version = project.mod_version group = project.maven_group repositories { - // Add repositories to retrieve artifacts from in here. - // You should only use this when depending on other mods because - // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. - // See https://docs.gradle.org/current/userguide/declaring_repositories.html - // for more information about repositories. + maven { url 'https://dl.cloudsmith.io/public/geckolib3/geckolib/maven/' } + maven { url "https://maven.terraformersmc.com/releases"} + maven { + name = 'Ladysnake Mods' + url = 'https://ladysnake.jfrog.io/artifactory/mods' + } } dependencies { - // To change the versions see the gradle.properties file minecraft "com.mojang:minecraft:${project.minecraft_version}" mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" - // Fabric API. This is technically optional, but you probably want it anyway. modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" - } + modImplementation 'software.bernie.geckolib:geckolib-fabric-1.19.3:4.0.3' + implementation 'org.mongodb:mongodb-driver-reactivestreams:4.9.0' + modApi "com.terraformersmc:modmenu:${project.modmenu_version}" + + modImplementation "dev.onyxstudios.cardinal-components-api:cardinal-components-base:${project.cardinal_component_version}" + // Adds a dependency on a specific module + modImplementation "dev.onyxstudios.cardinal-components-api:cardinal-components-entity:${project.cardinal_component_version}" + // Includes Cardinal Components API as a Jar-in-Jar dependency (optional) + include "dev.onyxstudios.cardinal-components-api:cardinal-components-base:${project.cardinal_component_version}" + include "dev.onyxstudios.cardinal-components-api:cardinal-components-entity:${project.cardinal_component_version}" +} processResources { inputs.property "version", project.version @@ -33,24 +46,23 @@ processResources { } } -def targetJavaVersion = 17 tasks.withType(JavaCompile).configureEach { // ensure that the encoding is set to UTF-8, no matter what the system default is // this fixes some edge cases with special characters not displaying correctly // see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html // If Javadoc is generated, this must be specified in that task too. it.options.encoding = "UTF-8" - if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { - it.options.release = targetJavaVersion + if (Integer.parseInt(targetCompatibility as String) >= 10 || JavaVersion.current().isJava10Compatible()) { + it.options.release = Integer.parseInt(targetCompatibility as String) } } java { - def javaVersion = JavaVersion.toVersion(targetJavaVersion) + def javaVersion = JavaVersion.toVersion(targetCompatibility) if (JavaVersion.current() < javaVersion) { - toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) + toolchain.languageVersion = JavaLanguageVersion.of(targetCompatibility as String) } - archivesBaseName = project.archives_base_name + // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task // if it is present. // If you remove this line, sources will not be generated. diff --git a/gradle.properties b/gradle.properties index a450e11..1c5fc2e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ # Done to increase the memory available to gradle. -org.gradle.jvmargs=-Xmx1G +org.gradle.jvmargs=-Xmx2G # Fabric Properties # check these on https://modmuss50.me/fabric.html @@ -15,3 +15,7 @@ org.gradle.jvmargs=-Xmx1G # Dependencies # check this on https://modmuss50.me/fabric.html fabric_version=0.76.0+1.19.4 + +# owo lib version https://maven.wispforest.io/io/wispforest/owo-lib/ +modmenu_version = 6.1.0-rc.4 +cardinal_component_version = 5.1.0 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..ccebba7 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9b0dc1a..bdc9a83 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1 +1,6 @@ -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..79a61d4 --- /dev/null +++ b/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# 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*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/generated/LymelConfig.java b/src/main/generated/LymelConfig.java new file mode 100644 index 0000000..532832a --- /dev/null +++ b/src/main/generated/LymelConfig.java @@ -0,0 +1,48 @@ +package me.unurled.lymel.config; + +import blue.endless.jankson.Jankson; +import io.wispforest.owo.config.ConfigWrapper; +import io.wispforest.owo.config.Option; +import io.wispforest.owo.util.Observable; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +public class LymelConfig extends ConfigWrapper { + + private final Option useDB = this.optionForKey(new Option.Key("useDB")); + + private LymelConfig() { + super(me.unurled.lymel.config.ConfigModel.class); + } + + private LymelConfig(Consumer janksonBuilder) { + super(me.unurled.lymel.config.ConfigModel.class, janksonBuilder); + } + + public static LymelConfig createAndLoad() { + var wrapper = new LymelConfig(); + wrapper.load(); + return wrapper; + } + + public static LymelConfig createAndLoad(Consumer janksonBuilder) { + var wrapper = new LymelConfig(janksonBuilder); + wrapper.load(); + return wrapper; + } + + public boolean useDB() { + return useDB.value(); + } + + public void useDB(boolean value) { + useDB.set(value); + } + + + + +} + diff --git a/src/main/java/me/unurled/lymel/Lymel.java b/src/main/java/me/unurled/lymel/Lymel.java index 5f0ab12..6a052a4 100644 --- a/src/main/java/me/unurled/lymel/Lymel.java +++ b/src/main/java/me/unurled/lymel/Lymel.java @@ -1,2 +1,62 @@ -package PACKAGE_NAME;public class Lymel { +package me.unurled.lymel; + +import me.unurled.lymel.config.Config; +import me.unurled.lymel.managers.ModEvent; +import me.unurled.lymel.managers.ModItems; +import me.unurled.lymel.server.LymelServer; +import me.unurled.lymel.util.ConfigDataUtil; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.ModInitializer; +import net.fabricmc.loader.api.FabricLoader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.bernie.geckolib.GeckoLib; + +import java.nio.file.Path; + +public class Lymel implements ModInitializer { + + public static final String MODID = "lymel"; + public static Lymel INSTANCE; + + public static final Logger LOGGER = LoggerFactory.getLogger(MODID); + + private Config config = new Config(); + + private LymelServer server; + + ModEvent modEvent; + ModItems modItems; + + @Override + public void onInitialize() { + INSTANCE = this; + GeckoLib.initialize(); + loadConfig(); + register(); + if (FabricLoader.getInstance().getEnvironmentType() == EnvType.SERVER) { + server = new LymelServer(); + server.register(config); + } + LOGGER.info("Hallo from Lymel !"); + } + + private void loadConfig() { + Path configPath = FabricLoader.getInstance().getConfigDir().resolve("Lymel/lymel.json"); + config = ConfigDataUtil.loadConfigData(Config.class, configPath); + } + + private void saveConfig() { + Path configPath = FabricLoader.getInstance().getConfigDir().resolve("Lymel/lymel.json"); + ConfigDataUtil.saveConfigData(Config.class, configPath.toFile(), config); + } + + private void register() { + modEvent = new ModEvent(); + modItems = new ModItems(); + } + + public LymelServer getServer() { + return server; + } } diff --git a/src/main/java/me/unurled/lymel/client/LymelClient.java b/src/main/java/me/unurled/lymel/client/LymelClient.java index c92a9ae..8a69496 100644 --- a/src/main/java/me/unurled/lymel/client/LymelClient.java +++ b/src/main/java/me/unurled/lymel/client/LymelClient.java @@ -1,2 +1,10 @@ -public class LymelClient { +package me.unurled.lymel.client; + +import net.fabricmc.api.ClientModInitializer; + +@net.fabricmc.api.Environment(net.fabricmc.api.EnvType.CLIENT) +public class LymelClient implements ClientModInitializer { + @Override + public void onInitializeClient() { + } } diff --git a/src/main/java/me/unurled/lymel/components/entity/PlayerComponents.java b/src/main/java/me/unurled/lymel/components/entity/PlayerComponents.java new file mode 100644 index 0000000..c8089d3 --- /dev/null +++ b/src/main/java/me/unurled/lymel/components/entity/PlayerComponents.java @@ -0,0 +1,33 @@ +package me.unurled.lymel.components.entity; + +import dev.onyxstudios.cca.api.v3.component.ComponentKey; +import dev.onyxstudios.cca.api.v3.component.ComponentRegistryV3; +import dev.onyxstudios.cca.api.v3.entity.EntityComponentFactoryRegistry; +import dev.onyxstudios.cca.api.v3.entity.EntityComponentInitializer; +import dev.onyxstudios.cca.api.v3.entity.RespawnCopyStrategy; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.util.Identifier; + +public class PlayerComponents implements EntityComponentInitializer { + + public static final ComponentKey STATISTICS = + ComponentRegistryV3.INSTANCE.getOrCreate(new Identifier("lymel:stats"), StatComponent.class); + @Override + public void registerEntityComponentFactories(EntityComponentFactoryRegistry registry) { + registry.registerForPlayers(STATISTICS, StatisicsComponent::new, RespawnCopyStrategy.ALWAYS_COPY); + } + + public static void speed(PlayerEntity e) { + float speed = STATISTICS.get(e).getSpeed(); + e.getAbilities().setWalkSpeed(speed); + e.getAbilities().setFlySpeed(speed); + } + + public static void setEverything(PlayerEntity e, float speed) { + STATISTICS.get(e).setSpeed(speed); + } + + public static void setDefault(PlayerEntity player) { + STATISTICS.get(player).setSpeed(1.0f); + } +} diff --git a/src/main/java/me/unurled/lymel/components/entity/StatComponent.java b/src/main/java/me/unurled/lymel/components/entity/StatComponent.java new file mode 100644 index 0000000..471ccdc --- /dev/null +++ b/src/main/java/me/unurled/lymel/components/entity/StatComponent.java @@ -0,0 +1,14 @@ +package me.unurled.lymel.components.entity; + +import dev.onyxstudios.cca.api.v3.component.ComponentV3; +import net.minecraft.nbt.NbtCompound; + +public interface StatComponent extends ComponentV3 { + float getSpeed(); + + Object get(String key); + + void setSpeed(float speed); + + void set(String key, Object value); +} \ No newline at end of file diff --git a/src/main/java/me/unurled/lymel/components/entity/StatisicsComponent.java b/src/main/java/me/unurled/lymel/components/entity/StatisicsComponent.java new file mode 100644 index 0000000..08c012d --- /dev/null +++ b/src/main/java/me/unurled/lymel/components/entity/StatisicsComponent.java @@ -0,0 +1,62 @@ +package me.unurled.lymel.components.entity; + +import dev.onyxstudios.cca.api.v3.component.sync.AutoSyncedComponent; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.nbt.NbtCompound; + +public class StatisicsComponent implements StatComponent, AutoSyncedComponent { + + private float speed = 1.0f; + private final PlayerEntity provider; + + + public StatisicsComponent(PlayerEntity provider) { + this.provider = provider; + } + + @Override + public float getSpeed() { + return this.speed; + } + + /** + * @param key + * @return + */ + @Override + public Object get(String key) { + return switch (key) { + case "speed" -> getSpeed(); + default -> null; + }; + } + + @Override + public void setSpeed(float speed) { + this.speed = speed; + PlayerComponents.STATISTICS.sync(this.provider); + } + + /** + * @param key + * @param value + */ + @Override + public void set(String key, Object value) { + switch (key) { + case "speed" -> setSpeed((float) value); + }; + } + + @Override + public void readFromNbt(NbtCompound tag) { + this.speed = tag.getFloat("speed"); + } + + @Override + public void writeToNbt(NbtCompound tag) { + tag.putFloat("speed", this.speed); + } +} + diff --git a/src/main/java/me/unurled/lymel/components/events/player/EquipementChangeCallback.java b/src/main/java/me/unurled/lymel/components/events/player/EquipementChangeCallback.java new file mode 100644 index 0000000..fb49a10 --- /dev/null +++ b/src/main/java/me/unurled/lymel/components/events/player/EquipementChangeCallback.java @@ -0,0 +1,28 @@ +package me.unurled.lymel.components.events.player; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.entity.EquipmentSlot; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ActionResult; + +/** + * Callback when player change his armor. + * Upon return : + * - SUCCESS cancels further processing and continues with normal armor change behavior + * - PASS falls back to further processing and defaults to SUCCESS if no other listeners are available + * - FAIL cancels further processing and does not change the armor. + */ +public interface EquipementChangeCallback { + + Event EVENT = EventFactory.createArrayBacked(EquipementChangeCallback.class, + (listeners) -> (player, slot, stack) -> { + for (EquipementChangeCallback listener : listeners) { + listener.changeEquipment(player, slot, stack); + } + return ActionResult.SUCCESS; + }); + + ActionResult changeEquipment(PlayerEntity player, EquipmentSlot slot, ItemStack stack); +} diff --git a/src/main/java/me/unurled/lymel/components/events/player/EquipmentChangeHandler.java b/src/main/java/me/unurled/lymel/components/events/player/EquipmentChangeHandler.java new file mode 100644 index 0000000..4a7e126 --- /dev/null +++ b/src/main/java/me/unurled/lymel/components/events/player/EquipmentChangeHandler.java @@ -0,0 +1,27 @@ +package me.unurled.lymel.components.events.player; + +import me.unurled.lymel.util.EquipmentUtil; +import net.minecraft.entity.EquipmentSlot; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ActionResult; + +public class EquipmentChangeHandler implements EquipementChangeCallback{ + + public static void init() { + EquipementChangeCallback.EVENT.register(new EquipmentChangeHandler()); + } + + @Override + public ActionResult changeEquipment(PlayerEntity player, EquipmentSlot slot, ItemStack stack) { + EquipmentUtil.updateStatuses(player, stack); + if (slot == EquipmentSlot.MAINHAND) { +// player.onEquipStack(slot, player.getInventory().main.set(player.getInventory().selectedSlot, stack), stack); + } else if (slot == EquipmentSlot.OFFHAND) { +// player.onEquipStack(slot, player.getInventory().offHand.set(0, stack), stack); + } else if (slot.getType() == EquipmentSlot.Type.ARMOR) { +// player.onEquipStack(slot, player.getInventory().armor.set(slot.getEntitySlotId(), stack), stack); + } + return ActionResult.PASS; + } +} diff --git a/src/main/java/me/unurled/lymel/components/events/player/JoinServerCallback.java b/src/main/java/me/unurled/lymel/components/events/player/JoinServerCallback.java new file mode 100644 index 0000000..6c32cd1 --- /dev/null +++ b/src/main/java/me/unurled/lymel/components/events/player/JoinServerCallback.java @@ -0,0 +1,28 @@ +package me.unurled.lymel.components.events.player; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.network.ClientConnection; +import net.minecraft.server.PlayerManager; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.util.ActionResult; + +/** + * Callback when a Player joins the server. + * Upon return : + * - + */ +public interface JoinServerCallback { + + Event EVENT = EventFactory.createArrayBacked(JoinServerCallback.class, + (listeners) -> (manager, connection, player) -> { + for (JoinServerCallback listener : listeners) { + listener.join(manager, connection, player); + } + return ActionResult.SUCCESS; + }); + + ActionResult join(PlayerManager manager, ClientConnection connection, ServerPlayerEntity player); + +} diff --git a/src/main/java/me/unurled/lymel/components/events/player/JoinServerHandler.java b/src/main/java/me/unurled/lymel/components/events/player/JoinServerHandler.java new file mode 100644 index 0000000..dcf5bc5 --- /dev/null +++ b/src/main/java/me/unurled/lymel/components/events/player/JoinServerHandler.java @@ -0,0 +1,17 @@ +package me.unurled.lymel.components.events.player; + +import net.minecraft.network.ClientConnection; +import net.minecraft.server.PlayerManager; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.util.ActionResult; + +public class JoinServerHandler implements JoinServerCallback { + public static void init() { + JoinServerCallback.EVENT.register(new JoinServerHandler()); + } + + @Override + public ActionResult join(PlayerManager manager, ClientConnection connection, ServerPlayerEntity player) { + return ActionResult.PASS; + } +} diff --git a/src/main/java/me/unurled/lymel/components/events/player/LeaveServerCallback.java b/src/main/java/me/unurled/lymel/components/events/player/LeaveServerCallback.java new file mode 100644 index 0000000..5132387 --- /dev/null +++ b/src/main/java/me/unurled/lymel/components/events/player/LeaveServerCallback.java @@ -0,0 +1,19 @@ +package me.unurled.lymel.components.events.player; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.server.PlayerManager; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.util.ActionResult; + +public interface LeaveServerCallback { + Event EVENT = EventFactory.createArrayBacked(LeaveServerCallback.class, + (listeners) -> (manager, player) -> { + for (LeaveServerCallback listener : listeners) { + listener.leave(manager, player); + } + return ActionResult.SUCCESS; + }); + + ActionResult leave(PlayerManager manager, ServerPlayerEntity player); +} diff --git a/src/main/java/me/unurled/lymel/components/events/player/LeaveServerHandler.java b/src/main/java/me/unurled/lymel/components/events/player/LeaveServerHandler.java new file mode 100644 index 0000000..c67e8ed --- /dev/null +++ b/src/main/java/me/unurled/lymel/components/events/player/LeaveServerHandler.java @@ -0,0 +1,23 @@ +package me.unurled.lymel.components.events.player; + +import me.unurled.lymel.server.PlayerConfiguration; +import net.minecraft.server.PlayerManager; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.util.ActionResult; + +public class LeaveServerHandler implements LeaveServerCallback { + + public static void init() { + LeaveServerCallback.EVENT.register(new LeaveServerHandler()); + } + + /** + * @param player + * @return + */ + @Override + public ActionResult leave(PlayerManager manager, ServerPlayerEntity player) { + PlayerConfiguration.save(player); + return ActionResult.SUCCESS; + } +} diff --git a/src/main/java/me/unurled/lymel/components/items/weapon/CombatKnife.java b/src/main/java/me/unurled/lymel/components/items/weapon/CombatKnife.java new file mode 100644 index 0000000..d86df0e --- /dev/null +++ b/src/main/java/me/unurled/lymel/components/items/weapon/CombatKnife.java @@ -0,0 +1,9 @@ +package me.unurled.lymel.components.items.weapon; + +import net.minecraft.item.Item; + +public class CombatKnife extends Item { + public CombatKnife(Settings settings) { + super(settings); + } +} diff --git a/src/main/java/me/unurled/lymel/config/Config.java b/src/main/java/me/unurled/lymel/config/Config.java new file mode 100644 index 0000000..8cef94c --- /dev/null +++ b/src/main/java/me/unurled/lymel/config/Config.java @@ -0,0 +1,32 @@ +package me.unurled.lymel.config; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import me.unurled.lymel.Lymel; + +public class Config { + + @SerializedName("useDB") + @Expose + public boolean useDB = false; + + @SerializedName("DBuri") + @Expose + public String dbUri = "mongodb://localhost:27017"; + + public boolean isUseDB() { + return useDB; + } + + public void setUseDB(boolean useDB) { + this.useDB = useDB; + } + + public String getDbUri() { + return dbUri; + } + + public void setDbUri(String dbUri) { + this.dbUri = dbUri; + } +} diff --git a/src/main/java/me/unurled/lymel/config/QuestConfig.java b/src/main/java/me/unurled/lymel/config/QuestConfig.java new file mode 100644 index 0000000..d29264f --- /dev/null +++ b/src/main/java/me/unurled/lymel/config/QuestConfig.java @@ -0,0 +1,4 @@ +package me.unurled.lymel.config; + +public class QuestConfig { +} diff --git a/src/main/java/me/unurled/lymel/managers/ModEvent.java b/src/main/java/me/unurled/lymel/managers/ModEvent.java new file mode 100644 index 0000000..0196139 --- /dev/null +++ b/src/main/java/me/unurled/lymel/managers/ModEvent.java @@ -0,0 +1,18 @@ +package me.unurled.lymel.managers; + +import me.unurled.lymel.components.events.player.EquipmentChangeHandler; +import me.unurled.lymel.components.events.player.JoinServerHandler; +import me.unurled.lymel.components.events.player.LeaveServerHandler; + +public class ModEvent { + + public ModEvent() { + register(); + } + + public void register() { + EquipmentChangeHandler.init(); + JoinServerHandler.init(); + LeaveServerHandler.init(); + } +} diff --git a/src/main/java/me/unurled/lymel/managers/ModItems.java b/src/main/java/me/unurled/lymel/managers/ModItems.java new file mode 100644 index 0000000..9a663ee --- /dev/null +++ b/src/main/java/me/unurled/lymel/managers/ModItems.java @@ -0,0 +1,31 @@ +package me.unurled.lymel.managers; + +import me.unurled.lymel.Lymel; +import me.unurled.lymel.components.items.weapon.CombatKnife; +import net.fabricmc.fabric.api.item.v1.FabricItemSettings; +import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup; +import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; +import net.minecraft.item.Item; +import net.minecraft.item.ItemGroup; +import net.minecraft.item.ItemStack; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.util.Identifier; + +public class ModItems { + private static final Item LOGO_ITEM = Registry.register(Registries.ITEM, new Identifier(Lymel.MODID, "logo"), + new Item(new FabricItemSettings())); + + private static final ItemGroup ITEM_GROUP = FabricItemGroup.builder(new Identifier(Lymel.MODID, "lymel")) + .icon(() -> new ItemStack(LOGO_ITEM)) + .build(); + + private static final CombatKnife COMBAT_KNIFE = Registry.register(Registries.ITEM, new Identifier(Lymel.MODID, "combat_knife"), + new CombatKnife(new FabricItemSettings().maxCount(1))); + + public ModItems() { + ItemGroupEvents.modifyEntriesEvent(ITEM_GROUP).register(content -> { + content.add(COMBAT_KNIFE); + }); + } +} diff --git a/src/main/java/me/unurled/lymel/mixin/server/Player/PlayerChangeEquipmentMixin.java b/src/main/java/me/unurled/lymel/mixin/server/Player/PlayerChangeEquipmentMixin.java new file mode 100644 index 0000000..142a57e --- /dev/null +++ b/src/main/java/me/unurled/lymel/mixin/server/Player/PlayerChangeEquipmentMixin.java @@ -0,0 +1,18 @@ +package me.unurled.lymel.mixin.server.Player; + +import me.unurled.lymel.components.events.player.EquipementChangeCallback; +import net.minecraft.entity.EquipmentSlot; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.item.ItemStack; +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(PlayerEntity.class) +public class PlayerChangeEquipmentMixin { + @Inject(method = "equipStack", at = @At(value = "HEAD"), cancellable = true) + private void onEquipmentChange(EquipmentSlot slot, ItemStack stack, CallbackInfo ci) { + EquipementChangeCallback.EVENT.invoker().changeEquipment((PlayerEntity) (Object) this, slot, stack); + } +} diff --git a/src/main/java/me/unurled/lymel/mixin/server/Player/PlayerManagerMixin.java b/src/main/java/me/unurled/lymel/mixin/server/Player/PlayerManagerMixin.java new file mode 100644 index 0000000..f330bc9 --- /dev/null +++ b/src/main/java/me/unurled/lymel/mixin/server/Player/PlayerManagerMixin.java @@ -0,0 +1,24 @@ +package me.unurled.lymel.mixin.server.Player; + +import me.unurled.lymel.components.events.player.JoinServerCallback; +import me.unurled.lymel.components.events.player.LeaveServerCallback; +import net.minecraft.network.ClientConnection; +import net.minecraft.server.PlayerManager; +import net.minecraft.server.network.ServerPlayerEntity; +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(PlayerManager.class) +public class PlayerManagerMixin { + @Inject(method = "onPlayerConnect", at = @At(value = "TAIL"), cancellable = true) + public void onJoin(ClientConnection connection, ServerPlayerEntity player, CallbackInfo ci) { + JoinServerCallback.EVENT.invoker().join((PlayerManager) (Object) this, connection, player); + } + + @Inject(method = "remove", at = @At(value = "HEAD")) + public void onLeave(ServerPlayerEntity player, CallbackInfo ci) { + LeaveServerCallback.EVENT.invoker().leave((PlayerManager) (Object) this, player); + } +} diff --git a/src/main/java/me/unurled/lymel/server/LymelServer.java b/src/main/java/me/unurled/lymel/server/LymelServer.java new file mode 100644 index 0000000..273467b --- /dev/null +++ b/src/main/java/me/unurled/lymel/server/LymelServer.java @@ -0,0 +1,16 @@ +package me.unurled.lymel.server; + +import me.unurled.lymel.config.Config; + +public class LymelServer { + + private MongoDB mongoDB; + + public void register(Config config) { + mongoDB = new MongoDB(config); + } + + public MongoDB getMongoDB() { + return mongoDB; + } +} diff --git a/src/main/java/me/unurled/lymel/server/MongoDB.java b/src/main/java/me/unurled/lymel/server/MongoDB.java new file mode 100644 index 0000000..7fda6f3 --- /dev/null +++ b/src/main/java/me/unurled/lymel/server/MongoDB.java @@ -0,0 +1,83 @@ +package me.unurled.lymel.server; + +import com.mongodb.reactivestreams.client.MongoClient; +import com.mongodb.reactivestreams.client.MongoClients; +import com.mongodb.reactivestreams.client.MongoCollection; +import com.mongodb.reactivestreams.client.MongoDatabase; +import me.unurled.lymel.config.Config; +import me.unurled.lymel.util.SubscriberHelpers; +import org.bson.Document; + +import java.util.UUID; + +import static com.mongodb.client.model.Filters.eq; + +public class MongoDB { + + + private MongoClient mongoClient; + private MongoDatabase database; + + /** + * Documents in data is in the following style : + * { + * "_id": ObjectId('13513631848'), + * "uuid": "player's uuid", + * "name": "player's name", + * "inventory": "very long string of base64 encoded items" (see {@link me.unurled.lymel.util.EquipmentUtil}), + * "stats": { + * "speed" : 100, + * ... + * } + * } + */ + private MongoCollection data; + + public MongoDB(Config config) { + connect(config.getDbUri()); + } + + void connect(String uri) { + mongoClient = MongoClients.create(uri); + database = mongoClient.getDatabase("Lymel"); + data = database.getCollection("data"); + } + + Document getPlayerInfos(String name) { + SubscriberHelpers.OperationSubscriber op = new SubscriberHelpers.OperationSubscriber(); + data.find(eq("name", name)).first().subscribe(op); + op.await(); + return op.first(); + } + + Document getPlayerInfos(UUID uuid) { + SubscriberHelpers.OperationSubscriber op = new SubscriberHelpers.OperationSubscriber(); + data.find(eq("uuid", uuid)).first().subscribe(op); + op.await(); + return op.first(); + } + + MongoClient getMongoClient() { + return mongoClient; + } + + MongoDatabase getDatabase() { + return database; + } + + MongoCollection getData() { + return data; + } + + void setMongoClient(MongoClient mongoClient) { + this.mongoClient = mongoClient; + } + + void setDatabase(MongoDatabase database) { + this.database = database; + } + + void setData(MongoCollection data) { + this.data = data; + } +} diff --git a/src/main/java/me/unurled/lymel/server/PlayerConfiguration.java b/src/main/java/me/unurled/lymel/server/PlayerConfiguration.java new file mode 100644 index 0000000..b07f935 --- /dev/null +++ b/src/main/java/me/unurled/lymel/server/PlayerConfiguration.java @@ -0,0 +1,77 @@ +package me.unurled.lymel.server; + +import com.mongodb.client.model.InsertOneOptions; +import com.mongodb.client.model.UpdateOneModel; +import com.mongodb.client.result.InsertOneResult; +import me.unurled.lymel.Lymel; +import me.unurled.lymel.components.entity.PlayerComponents; +import me.unurled.lymel.util.SubscriberHelpers; +import net.minecraft.entity.player.PlayerInventory; +import net.minecraft.server.network.ServerPlayerEntity; +import org.bson.Document; + +import static com.mongodb.client.model.Filters.eq; +import static me.unurled.lymel.util.EquipmentUtil.decodeInventory; +import static me.unurled.lymel.util.EquipmentUtil.encodeInventory; + +public class PlayerConfiguration { + + public static void save(ServerPlayerEntity player) { + // get inv and stats from player + PlayerInventory inv = player.getInventory(); + float speed = PlayerComponents.STATISTICS.get(player).getSpeed(); + Document stats = new Document(); + stats.append("speed", speed); + //save to mongodb + + Document doc = new Document(); + doc.append("uuid", player.getUuid()) + .append("name", player.getEntityName()) + .append("inventory", encodeInventory(inv)) + .append("stats", stats); + + MongoDB mongo = Lymel.INSTANCE.getServer().getMongoDB(); + + SubscriberHelpers.OperationSubscriber op = new SubscriberHelpers.OperationSubscriber(); + mongo.getData().find(eq("uuid", player.getUuid())).subscribe(op); + op.await(); + Document oldDoc = op.first(); + if (oldDoc != null) { + mongo.getData().updateOne(eq("uuid", player.getUuid()), doc); + return; + } + var subscriber = new SubscriberHelpers.OperationSubscriber(); + mongo.getData().insertOne(doc).subscribe(subscriber); + subscriber.await(); + } + + public static void load(ServerPlayerEntity player) { + // get inv and stats from monogdb + MongoDB mongo = Lymel.INSTANCE.getServer().getMongoDB(); + Document doc = mongo.getPlayerInfos(player.getUuid()); + if (doc == null) { + // create document, insert and continue + doc = new Document(); + } + String inventory = doc.getString("inventory"); + Document list = doc.get("stats", Document.class); + + // set inv + decodeInventory(player, inventory); + + // set stats + if (list != null) { + for (Object s : list.values().toArray()) { + // add stat to player... + if (s instanceof String) { + PlayerComponents.STATISTICS.get(player).set((String) s, doc.get(s)); + } + } + } else { + // set stats to default... + PlayerComponents.setDefault(player); + + // TODO: first time coming, make a tuto ? + } + } +} diff --git a/src/main/java/me/unurled/lymel/util/ConfigDataUtil.java b/src/main/java/me/unurled/lymel/util/ConfigDataUtil.java new file mode 100644 index 0000000..caff037 --- /dev/null +++ b/src/main/java/me/unurled/lymel/util/ConfigDataUtil.java @@ -0,0 +1,52 @@ +package me.unurled.lymel.util; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonIOException; +import com.google.gson.JsonSyntaxException; +import me.unurled.lymel.Lymel; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class ConfigDataUtil { + private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + public static T loadConfigData(Class configClass, Path configPath) { + T configData = null; + try { + Files.createDirectories(configPath.getParent()); + } catch (IOException e) { + Lymel.LOGGER.error("Error when creating new folder for Lymel Config" + e); + } + File configFile = configPath.toFile(); + try (FileReader reader = new FileReader(configFile)) { + configData = gson.fromJson(reader, configClass); + } catch (IOException e) { + Lymel.LOGGER.warn("Could not read Lymel Config."); + } catch (JsonIOException | JsonSyntaxException e) { + Lymel.LOGGER.error("Error Parsing Lymel Config."); + } + if (configData == null) { + try { + configData = configClass.getDeclaredConstructor().newInstance(); + saveConfigData(configClass, configFile, configData); + } catch (Exception e) { + Lymel.LOGGER.error("Generating Lymel Config."); + } + } + return configData; + } + + public static void saveConfigData(Class configClass, File configFile, T configData) { + try (FileWriter writer = new FileWriter(configFile)) { + gson.toJson(configData, configClass, writer); + } catch (IOException e) { + Lymel.LOGGER.error("Could not write config file."); + } + } +} diff --git a/src/main/java/me/unurled/lymel/util/EquipmentUtil.java b/src/main/java/me/unurled/lymel/util/EquipmentUtil.java new file mode 100644 index 0000000..0a02d09 --- /dev/null +++ b/src/main/java/me/unurled/lymel/util/EquipmentUtil.java @@ -0,0 +1,86 @@ +package me.unurled.lymel.util; + +import com.google.gson.Gson; +import com.google.gson.JsonParser; +import com.mojang.serialization.JsonOps; +import me.unurled.lymel.Lymel; +import net.minecraft.block.Material; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.entity.player.PlayerInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.Registries; +import net.minecraft.registry.entry.RegistryEntry; +import org.bson.Document; +import org.bson.conversions.Bson; + +import java.util.Arrays; +import java.util.Base64; + +public class EquipmentUtil { + public static void updateStatuses(PlayerEntity player, ItemStack stack) { + if (stack.hasNbt()) { + String s = serelizeItemStack(stack); + Lymel.LOGGER.info("nbt looooooooooooog " + s); + } + } + + static String serelizeItemStack(ItemStack stack) { + var json = ItemStack.CODEC.encode(stack, JsonOps.INSTANCE, JsonOps.INSTANCE.empty()); + String string = ""; + Gson GSON = new Gson(); + if (json.result().isPresent()) { + string = GSON.toJson(json.result().get()); + } + return string; + } + + static ItemStack deserilizeItemStack(String string) { + var jsonDecoded = JsonParser.parseString(string); + var stackDecoded = ItemStack.CODEC.decode(JsonOps.INSTANCE, jsonDecoded); + if (stackDecoded.result().isPresent()) { + return stackDecoded.result().get().getFirst(); + } + return null; + } + + static String encodeItem(ItemStack item) { + String string = serelizeItemStack(item); + return Base64.getEncoder().encodeToString(string.getBytes()); + } + + static ItemStack decodeString(String string) { + var s = Arrays.toString(Base64.getDecoder().decode(string.getBytes())); + return deserilizeItemStack(s); + } + + public static String encodeInventory(PlayerInventory inv) { + StringBuilder string = new StringBuilder(); + for (int i = 0 ; i < inv.size() ; i++) { + if (inv.getStack(i) != ItemStack.EMPTY) { + string + .append(i) + .append(":") + .append(encodeItem(inv.getStack(i))) + .append("$"); + } + } + return string.toString(); + } + + public static PlayerInventory decodeInventory(PlayerEntity player, String strings) { + PlayerInventory playerInventory = player.getInventory(); + if (strings.contains("\\$")) { + String[] items = strings.split("\\$"); + for (String item : items) { + String[] hehe = item.split(":"); + int i = Integer.parseInt(hehe[0]); + ItemStack stack = decodeString(hehe[1]); + if (stack != null) { + playerInventory.insertStack(i, stack); + } + } + } + return playerInventory; + } +} diff --git a/src/main/java/me/unurled/lymel/util/StatUtil.java b/src/main/java/me/unurled/lymel/util/StatUtil.java new file mode 100644 index 0000000..1500006 --- /dev/null +++ b/src/main/java/me/unurled/lymel/util/StatUtil.java @@ -0,0 +1,12 @@ +package me.unurled.lymel.util; + +import me.unurled.lymel.components.entity.PlayerComponents; +import net.minecraft.entity.player.PlayerEntity; + +public class StatUtil { + public static void updatePlayer(PlayerEntity p) { + float speed = PlayerComponents.STATISTICS.get(p).getSpeed(); + p.getAbilities().setWalkSpeed(speed); + p.getAbilities().setFlySpeed(speed); + } +} diff --git a/src/main/java/me/unurled/lymel/util/SubscriberHelpers.java b/src/main/java/me/unurled/lymel/util/SubscriberHelpers.java new file mode 100644 index 0000000..e557633 --- /dev/null +++ b/src/main/java/me/unurled/lymel/util/SubscriberHelpers.java @@ -0,0 +1,249 @@ +package me.unurled.lymel.util; + +import com.mongodb.MongoInterruptedException; +import com.mongodb.MongoTimeoutException; +import org.bson.Document; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +/** + * Subscriber helper implementations for the Quick Tour. + */ +public final class SubscriberHelpers { + + /** + * A Subscriber that stores the publishers results and provides a latch so can block on completion. + * + * @param The publishers result type + */ + public abstract static class ObservableSubscriber implements Subscriber { + private final List received; + private final List errors; + private final CountDownLatch latch; + private volatile Subscription subscription; + private volatile boolean completed; + + /** + * Construct an instance + */ + public ObservableSubscriber() { + this.received = new ArrayList<>(); + this.errors = new ArrayList<>(); + this.latch = new CountDownLatch(1); + } + + @Override + public void onSubscribe(final Subscription s) { + subscription = s; + } + + @Override + public void onNext(final T t) { + received.add(t); + } + + @Override + public void onError(final Throwable t) { + if (t instanceof RuntimeException) { + errors.add((RuntimeException) t); + } else { + errors.add(new RuntimeException("Unexpected exception", t)); + } + onComplete(); + } + + @Override + public void onComplete() { + completed = true; + latch.countDown(); + } + + /** + * Gets the subscription + * + * @return the subscription + */ + public Subscription getSubscription() { + return subscription; + } + + /** + * Get received elements + * + * @return the list of received elements + */ + public List getReceived() { + return received; + } + + /** + * Get error from subscription + * + * @return the error, which may be null + */ + public RuntimeException getError() { + if (errors.size() > 0) { + return errors.get(0); + } + return null; + } + + /** + * Get received elements. + * + * @return the list of receive elements + */ + public List get() { + return await().getReceived(); + } + + /** + * Get received elements. + * + * @param timeout how long to wait + * @param unit the time unit + * @return the list of receive elements + */ + public List get(final long timeout, final TimeUnit unit) { + return await(timeout, unit).getReceived(); + } + + + /** + * Get the first received element. + * + * @return the first received element + */ + public T first() { + List received = await().getReceived(); + return received.size() > 0 ? received.get(0) : null; + } + + /** + * Await completion or error + * + * @return this + */ + public ObservableSubscriber await() { + return await(60, TimeUnit.SECONDS); + } + + /** + * Await completion or error + * + * @param timeout how long to wait + * @param unit the time unit + * @return this + */ + public ObservableSubscriber await(final long timeout, final TimeUnit unit) { + subscription.request(Integer.MAX_VALUE); + try { + if (!latch.await(timeout, unit)) { + throw new MongoTimeoutException("Publisher onComplete timed out"); + } + } catch (InterruptedException e) { + throw new MongoInterruptedException("Interrupted waiting for observeration", e); + } + if (!errors.isEmpty()) { + throw errors.get(0); + } + return this; + } + } + + /** + * A Subscriber that immediately requests Integer.MAX_VALUE onSubscribe + * + * @param The publishers result type + */ + public static class OperationSubscriber extends ObservableSubscriber { + + @Override + public void onSubscribe(final Subscription s) { + super.onSubscribe(s); + s.request(Integer.MAX_VALUE); + } + } + + /** + * A Subscriber that prints a message including the received items on completion + * + * @param The publishers result type + */ + public static class PrintSubscriber extends OperationSubscriber { + private final String message; + + /** + * A Subscriber that outputs a message onComplete. + * + * @param message the message to output onComplete + */ + public PrintSubscriber(final String message) { + this.message = message; + } + + @Override + public void onComplete() { + System.out.printf((message) + "%n", getReceived()); + super.onComplete(); + } + } + + /** + * A Subscriber that prints the json version of each document + */ + public static class PrintDocumentSubscriber extends ConsumerSubscriber { + /** + * Construct a new instance + */ + public PrintDocumentSubscriber() { + super(t -> System.out.println(t.toJson())); + } + } + + /** + * A Subscriber that prints the toString version of each element + * @param the type of the element + */ + public static class PrintToStringSubscriber extends ConsumerSubscriber { + /** + * Construct a new instance + */ + public PrintToStringSubscriber() { + super(System.out::println); + } + } + + /** + * A Subscriber that processes a consumer for each element + * @param the type of the element + */ + public static class ConsumerSubscriber extends OperationSubscriber { + private final Consumer consumer; + + /** + * Construct a new instance + * @param consumer the consumer + */ + public ConsumerSubscriber(final Consumer consumer) { + this.consumer = consumer; + } + + + @Override + public void onNext(final T document) { + super.onNext(document); + consumer.accept(document); + } + } + + private SubscriberHelpers() { + } +} + diff --git a/src/main/resources/assets/lymel/lang/en_us.json b/src/main/resources/assets/lymel/lang/en_us.json new file mode 100644 index 0000000..46d275a --- /dev/null +++ b/src/main/resources/assets/lymel/lang/en_us.json @@ -0,0 +1,4 @@ +{ + "itemGroup.lymel.lymel": "Lymel", + "item.lymel.combat_knife": "Combat Knife" +} diff --git a/src/main/resources/assets/lymel/logo.png b/src/main/resources/assets/lymel/logo.png new file mode 100644 index 0000000..d156f88 Binary files /dev/null and b/src/main/resources/assets/lymel/logo.png differ diff --git a/src/main/resources/assets/lymel/models/item/combat_knife.json b/src/main/resources/assets/lymel/models/item/combat_knife.json new file mode 100644 index 0000000..e8f6cc0 --- /dev/null +++ b/src/main/resources/assets/lymel/models/item/combat_knife.json @@ -0,0 +1,6 @@ +{ + "parent": "item/handheld", + "textures": { + "layer0": "lymel:item/combatknife" + } +} diff --git a/src/main/resources/assets/lymel/models/item/logo.json b/src/main/resources/assets/lymel/models/item/logo.json new file mode 100644 index 0000000..ba75f12 --- /dev/null +++ b/src/main/resources/assets/lymel/models/item/logo.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "lymel:item/logo" + } +} \ No newline at end of file diff --git a/src/main/resources/assets/lymel/textures/item/combatknife.png b/src/main/resources/assets/lymel/textures/item/combatknife.png new file mode 100644 index 0000000..343e773 Binary files /dev/null and b/src/main/resources/assets/lymel/textures/item/combatknife.png differ diff --git a/src/main/resources/assets/lymel/textures/item/logo.png b/src/main/resources/assets/lymel/textures/item/logo.png new file mode 100644 index 0000000..f9278e5 Binary files /dev/null and b/src/main/resources/assets/lymel/textures/item/logo.png differ diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..322d0a1 --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,41 @@ +{ + "schemaVersion": 1, + "id": "lymel", + "version": "${version}", + "name": "Lymel", + "description": "A minecraft mod that is for the Elixium Server", + "authors": [ + "unurled" + ], + "contact": { + "website": "https://git.unurled.me/Elixium", + "repo": "https://git.unurled.me/Elixium/Lymel" + }, + "license": "All-Rights-Reserved", + "icon": "assets/lymel/logo.png", + "environment": "*", + "entrypoints": { + "client": [ + "me.unurled.lymel.client.LymelClient" + ], + "main": [ + "me.unurled.lymel.Lymel" + ], + "cardinal-components": [ + "me.unurled.lymel.components.entity.PlayerComponents" + ] + }, + "mixins": [ + "lymel.mixins.json" + ], + "custom": { + "cardinal-components": [ + "lymel:stats" + ] + }, + "depends": { + "fabricloader": ">=0.14.17", + "fabric": "*", + "minecraft": "1.19.4" + } +} diff --git a/src/main/resources/lymel.mixins.json b/src/main/resources/lymel.mixins.json new file mode 100644 index 0000000..e5fba7d --- /dev/null +++ b/src/main/resources/lymel.mixins.json @@ -0,0 +1,15 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "me.unurled.lymel.mixin", + "compatibilityLevel": "JAVA_17", + "server": [ + "server.Player.PlayerChangeEquipmentMixin", + "server.Player.PlayerManagerMixin" + ], + "client": [ + ], + "injectors": { + "defaultRequire": 1 + } +}