Initial sanctuary sources

This commit is contained in:
cnstiout
2026-07-04 20:27:08 +02:00
commit c796a20321
1582 changed files with 253264 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
plugins {
id "net.fabricmc.fabric-loom" version "${loom_version}"
id "maven-publish"
}
version = project.mod_version
group = project.maven_group
base {
archivesName = project.archives_base_name
}
repositories {
}
loom {
splitEnvironmentSourceSets()
mods {
"events" {
sourceSet sourceSets.main
sourceSet sourceSets.client
}
}
}
dependencies {
minecraft "com.mojang:minecraft:${project.minecraft_version}"
implementation "net.fabricmc:fabric-loader:${project.loader_version}"
implementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_api_version}"
}
processResources {
def version = project.version
inputs.property "version", version
filesMatching("fabric.mod.json") {
expand "version": version
}
}
tasks.withType(JavaCompile).configureEach {
it.options.release = 25
}
java {
withSourcesJar()
sourceCompatibility = JavaVersion.VERSION_25
targetCompatibility = JavaVersion.VERSION_25
}
jar {
def projectName = project.name
inputs.property "projectName", projectName
from("../../license.txt") {
rename { "${it}_${projectName}" }
}
}
publishing {
publications {
create("mavenJava", MavenPublication) {
artifactId = project.archives_base_name
from components.java
}
}
repositories {
}
}
+15
View File
@@ -0,0 +1,15 @@
# Done to increase the memory available to Gradle.
org.gradle.jvmargs=-Xmx1G
org.gradle.parallel=true
org.gradle.configuration-cache=false
# Fabric properties
minecraft_version=26.1.2
loader_version=0.19.2
loom_version=1.16-SNAPSHOT
fabric_api_version=0.148.0+26.1.2
# Mod properties
mod_version=1.0.0
maven_group=fr.koka99cab
archives_base_name=events
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+253
View File
@@ -0,0 +1,253 @@
#!/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/2d6327017519d23b96af35865dc997fcb544fb40/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
if [ -z "$JAVA_HOME" ] && [ -x "$APP_HOME/.jdk/current/bin/java" ] ; then
JAVA_HOME=$APP_HOME/.jdk/current
export JAVA_HOME
fi
# 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" "$@"
+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
+12
View File
@@ -0,0 +1,12 @@
pluginManagement {
repositories {
maven {
name = "Fabric"
url = "https://maven.fabricmc.net/"
}
mavenCentral()
gradlePluginPortal()
}
}
rootProject.name = "events"
@@ -0,0 +1,26 @@
package fr.koka99cab.events;
import fr.koka99cab.events.command.EventsCommands;
import fr.koka99cab.events.engine.EventsEngine;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class EventsMod implements ModInitializer {
public static final String MOD_ID = "events";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
private static final EventsEngine ENGINE = new EventsEngine();
@Override
public void onInitialize() {
ServerLifecycleEvents.SERVER_STARTED.register(ENGINE::start);
ServerLifecycleEvents.SERVER_STOPPING.register(server -> ENGINE.stop());
ServerTickEvents.END_SERVER_TICK.register(ENGINE::tick);
EventsCommands.register(ENGINE);
LOGGER.info("Events charge: moteur d'automations serveur pret.");
}
}
@@ -0,0 +1,102 @@
package fr.koka99cab.events.command;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.arguments.StringArgumentType;
import fr.koka99cab.events.config.EventDefinition;
import fr.koka99cab.events.engine.EventsEngine;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.server.permissions.Permissions;
import java.io.IOException;
import java.util.List;
public final class EventsCommands {
private EventsCommands() {
}
public static void register(EventsEngine engine) {
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> dispatcher.register(
Commands.literal("events")
.requires(source -> source.permissions().hasPermission(Permissions.COMMANDS_GAMEMASTER))
.executes(context -> showStatus(context.getSource(), engine))
.then(Commands.literal("status")
.executes(context -> showStatus(context.getSource(), engine)))
.then(Commands.literal("list")
.executes(context -> listEvents(context.getSource(), engine)))
.then(Commands.literal("reload")
.executes(context -> reload(context.getSource(), engine)))
.then(Commands.literal("run")
.then(Commands.argument("id", StringArgumentType.word())
.suggests((context, builder) -> SharedSuggestionProvider.suggest(engine.eventIds(), builder))
.executes(context -> runEvent(context.getSource(), engine, StringArgumentType.getString(context, "id")))))
.then(Commands.literal("enable")
.then(Commands.argument("id", StringArgumentType.word())
.suggests((context, builder) -> SharedSuggestionProvider.suggest(engine.eventIds(), builder))
.executes(context -> setEnabled(context.getSource(), engine, StringArgumentType.getString(context, "id"), true))))
.then(Commands.literal("disable")
.then(Commands.argument("id", StringArgumentType.word())
.suggests((context, builder) -> SharedSuggestionProvider.suggest(engine.eventIds(), builder))
.executes(context -> setEnabled(context.getSource(), engine, StringArgumentType.getString(context, "id"), false))))
));
}
private static int showStatus(CommandSourceStack source, EventsEngine engine) {
List<EventDefinition> events = engine.events();
long enabled = events.stream().filter(event -> event.enabled).count();
source.sendSuccess(() -> Component.literal("Events: " + enabled + "/" + events.size() + " events actifs."), false);
source.sendSuccess(() -> Component.literal("Config: " + engine.configPathLabel()), false);
return Command.SINGLE_SUCCESS;
}
private static int listEvents(CommandSourceStack source, EventsEngine engine) {
List<EventDefinition> events = engine.events();
if (events.isEmpty()) {
source.sendSuccess(() -> Component.literal("Events: aucun event configure."), false);
return Command.SINGLE_SUCCESS;
}
source.sendSuccess(() -> Component.literal("Events configures:"), false);
for (EventDefinition event : events) {
String status = event.enabled ? "on" : "off";
String trigger = event.normalizedTrigger().normalizedType();
source.sendSuccess(() -> Component.literal("- " + event.normalizedId() + " [" + status + ", " + trigger + "]"), false);
}
return Command.SINGLE_SUCCESS;
}
private static int reload(CommandSourceStack source, EventsEngine engine) {
engine.reload(source.getServer());
source.sendSuccess(() -> Component.literal("Events: config rechargee."), true);
return Command.SINGLE_SUCCESS;
}
private static int runEvent(CommandSourceStack source, EventsEngine engine, String id) {
if (!engine.runNow(source.getServer(), id, "commande")) {
source.sendFailure(Component.literal("Events: event introuvable: " + id));
return 0;
}
source.sendSuccess(() -> Component.literal("Events: event lance: " + id), true);
return Command.SINGLE_SUCCESS;
}
private static int setEnabled(CommandSourceStack source, EventsEngine engine, String id, boolean enabled) {
try {
if (!engine.setEnabled(id, enabled)) {
source.sendFailure(Component.literal("Events: event introuvable: " + id));
return 0;
}
} catch (IOException exception) {
source.sendFailure(Component.literal("Events: impossible de sauvegarder la config: " + exception.getMessage()));
return 0;
}
String status = enabled ? "active" : "desactive";
source.sendSuccess(() -> Component.literal("Events: " + id + " " + status + "."), true);
return Command.SINGLE_SUCCESS;
}
}
@@ -0,0 +1,72 @@
package fr.koka99cab.events.config;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
public final class EventAction {
public String type = "broadcast";
public String message = "";
public List<String> messages = new ArrayList<>();
public String title = "";
public String subtitle = "";
public String sound = "";
public String command = "";
public List<String> commands = new ArrayList<>();
public float volume = 1.0F;
public float pitch = 1.0F;
public int fadeInTicks = 10;
public int stayTicks = 60;
public int fadeOutTicks = 20;
public String normalizedType() {
return Objects.requireNonNullElse(this.type, "broadcast")
.strip()
.toLowerCase(Locale.ROOT);
}
public List<String> normalizedMessages() {
if (this.messages == null) {
return List.of();
}
return this.messages.stream()
.filter(Objects::nonNull)
.map(String::strip)
.filter(message -> !message.isEmpty())
.toList();
}
public List<String> normalizedCommands() {
if (this.commands == null) {
return List.of();
}
return this.commands.stream()
.filter(Objects::nonNull)
.map(String::strip)
.filter(command -> !command.isEmpty())
.toList();
}
public String normalizedMessage() {
return Objects.requireNonNullElse(this.message, "").strip();
}
public String normalizedTitle() {
return Objects.requireNonNullElse(this.title, "").strip();
}
public String normalizedSubtitle() {
return Objects.requireNonNullElse(this.subtitle, "").strip();
}
public String normalizedSound() {
return Objects.requireNonNullElse(this.sound, "").strip();
}
public String normalizedCommand() {
return Objects.requireNonNullElse(this.command, "").strip();
}
}
@@ -0,0 +1,23 @@
package fr.koka99cab.events.config;
public final class EventCondition {
public int minPlayers = 0;
public int maxPlayers = -1;
public double chance = 1.0D;
public int normalizedMinPlayers() {
return Math.max(0, this.minPlayers);
}
public int normalizedMaxPlayers() {
return this.maxPlayers < 0 ? -1 : this.maxPlayers;
}
public double normalizedChance() {
if (Double.isNaN(this.chance)) {
return 1.0D;
}
return Math.clamp(this.chance, 0.0D, 1.0D);
}
}
@@ -0,0 +1,35 @@
package fr.koka99cab.events.config;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public final class EventDefinition {
public String id = "";
public boolean enabled = true;
public EventTrigger trigger = new EventTrigger();
public EventCondition conditions = new EventCondition();
public List<EventAction> actions = new ArrayList<>();
public String normalizedId() {
return Objects.requireNonNullElse(this.id, "").strip();
}
public EventTrigger normalizedTrigger() {
return this.trigger == null ? new EventTrigger() : this.trigger;
}
public EventCondition normalizedConditions() {
return this.conditions == null ? new EventCondition() : this.conditions;
}
public List<EventAction> normalizedActions() {
if (this.actions == null) {
return List.of();
}
return this.actions.stream()
.filter(Objects::nonNull)
.toList();
}
}
@@ -0,0 +1,58 @@
package fr.koka99cab.events.config;
import java.util.Locale;
import java.util.Objects;
public final class EventTrigger {
public String type = "minecraft_time";
public String time = "";
public String timezone = "system";
public long tick = -1L;
public int intervalTicks = 0;
public int intervalSeconds = 0;
public boolean runOnStart = false;
public String normalizedType() {
return Objects.requireNonNullElse(this.type, "minecraft_time")
.strip()
.toLowerCase(Locale.ROOT);
}
public String normalizedTime() {
return Objects.requireNonNullElse(this.time, "").strip();
}
public String normalizedTimezone() {
return Objects.requireNonNullElse(this.timezone, "system").strip();
}
public long normalizedTick() {
if (this.tick >= 0L) {
return Math.floorMod(this.tick, 24000L);
}
return switch (normalizedTime().toLowerCase(Locale.ROOT)) {
case "noon", "midi", "midday" -> 6000L;
case "midnight", "minuit" -> 18000L;
case "sunrise", "lever", "morning" -> 0L;
case "sunset", "coucher", "evening" -> 12000L;
default -> parseTick(normalizedTime());
};
}
public int normalizedIntervalTicks() {
if (this.intervalTicks > 0) {
return this.intervalTicks;
}
return Math.max(0, this.intervalSeconds) * 20;
}
private static long parseTick(String raw) {
try {
return Math.floorMod(Long.parseLong(raw), 24000L);
} catch (NumberFormatException exception) {
return -1L;
}
}
}
@@ -0,0 +1,166 @@
package fr.koka99cab.events.config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public final class EventsConfig {
private static final Gson GSON = new GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.create();
public List<EventDefinition> events = new ArrayList<>();
public static EventsConfig load(Path path, Logger logger) {
EventsConfig defaults = defaults();
try {
Files.createDirectories(path.getParent());
if (Files.notExists(path)) {
save(path, defaults);
logger.info("Events: config creee dans {}", path);
return defaults;
}
try (Reader reader = Files.newBufferedReader(path)) {
EventsConfig loaded = GSON.fromJson(reader, EventsConfig.class);
if (loaded == null) {
save(path, defaults);
return defaults;
}
return sanitize(loaded);
}
} catch (IOException | JsonParseException exception) {
logger.error("Events: impossible de charger {}, valeurs par defaut utilisees", path, exception);
return defaults;
}
}
public static void save(Path path, EventsConfig config) throws IOException {
Files.createDirectories(path.getParent());
try (Writer writer = Files.newBufferedWriter(path)) {
GSON.toJson(config, writer);
}
}
public List<EventDefinition> normalizedEvents() {
if (this.events == null) {
return List.of();
}
return this.events.stream()
.filter(Objects::nonNull)
.filter(event -> !event.normalizedId().isEmpty())
.toList();
}
public Optional<EventDefinition> find(String id) {
String normalizedId = Objects.requireNonNullElse(id, "").strip();
if (normalizedId.isEmpty()) {
return Optional.empty();
}
return normalizedEvents().stream()
.filter(event -> event.normalizedId().equals(normalizedId))
.findFirst();
}
public static EventsConfig defaults() {
EventsConfig config = new EventsConfig();
config.events.add(backupEvent());
config.events.add(middayEvent());
config.events.add(midnightEvent());
return config;
}
private static EventsConfig sanitize(EventsConfig config) {
EventsConfig sanitized = new EventsConfig();
sanitized.events = new ArrayList<>(config.normalizedEvents());
return sanitized;
}
private static EventDefinition backupEvent() {
EventDefinition event = new EventDefinition();
event.id = "backup_21h";
event.trigger.type = "real_time";
event.trigger.time = "21:00";
event.trigger.timezone = "system";
EventAction announce = new EventAction();
announce.type = "broadcast";
announce.message = "[Events] Backup serveur de 21h: on range les coffres et on sauvegarde le monde.";
EventAction actionbar = new EventAction();
actionbar.type = "actionbar";
actionbar.message = "Backup serveur en cours...";
EventAction command = new EventAction();
command.type = "command";
command.command = "save-all";
event.actions.add(announce);
event.actions.add(actionbar);
event.actions.add(command);
return event;
}
private static EventDefinition middayEvent() {
EventDefinition event = new EventDefinition();
event.id = "midi_sort_du_lit";
event.trigger.type = "minecraft_time";
event.trigger.tick = 6000L;
EventAction message = new EventAction();
message.type = "random_message";
message.messages.add("Il est midi, on sort du lit !");
message.messages.add("Midi pile: les couvertures rendent les armes.");
message.messages.add("Le soleil est au-dessus de vos tetes, c'est l'heure du sandwich.");
EventAction sound = new EventAction();
sound.type = "sound";
sound.sound = "minecraft:block.bell.use";
sound.volume = 0.8F;
sound.pitch = 1.15F;
event.actions.add(message);
event.actions.add(sound);
return event;
}
private static EventDefinition midnightEvent() {
EventDefinition event = new EventDefinition();
event.id = "minuit_au_lit";
event.trigger.type = "minecraft_time";
event.trigger.tick = 18000L;
EventAction title = new EventAction();
title.type = "title";
title.title = "Il est minuit";
title.subtitle = "On saute dans le lit !";
title.fadeInTicks = 10;
title.stayTicks = 70;
title.fadeOutTicks = 20;
EventAction message = new EventAction();
message.type = "broadcast";
message.message = "Il est minuit, on saute dans le lit !";
event.actions.add(title);
event.actions.add(message);
return event;
}
}
@@ -0,0 +1,432 @@
package fr.koka99cab.events.engine;
import fr.koka99cab.events.EventsMod;
import fr.koka99cab.events.config.EventAction;
import fr.koka99cab.events.config.EventCondition;
import fr.koka99cab.events.config.EventDefinition;
import fr.koka99cab.events.config.EventTrigger;
import fr.koka99cab.events.config.EventsConfig;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundSetActionBarTextPacket;
import net.minecraft.network.protocol.game.ClientboundSetSubtitleTextPacket;
import net.minecraft.network.protocol.game.ClientboundSetTitleTextPacket;
import net.minecraft.network.protocol.game.ClientboundSetTitlesAnimationPacket;
import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.clock.WorldClock;
import net.minecraft.world.clock.WorldClocks;
import java.io.IOException;
import java.nio.file.Path;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
public final class EventsEngine {
private static final long MINECRAFT_DAY_TICKS = 24000L;
private final Map<String, LocalDate> realTimeRuns = new HashMap<>();
private final Map<String, Long> minecraftTimeRuns = new HashMap<>();
private final Map<String, Integer> intervalRuns = new HashMap<>();
private EventsConfig config = EventsConfig.defaults();
private Path configPath = FabricLoader.getInstance().getConfigDir().resolve("events/events.json");
private long previousMinecraftTick = -1L;
private long minecraftCycle = 0L;
public void start(MinecraftServer server) {
this.configPath = FabricLoader.getInstance().getConfigDir().resolve("events/events.json");
reload(server);
runStartupEvents(server);
EventsMod.LOGGER.info("Events: {} events charges depuis {}", events().size(), this.configPath);
}
public void stop() {
this.previousMinecraftTick = -1L;
this.minecraftCycle = 0L;
this.realTimeRuns.clear();
this.minecraftTimeRuns.clear();
this.intervalRuns.clear();
}
public void reload(MinecraftServer server) {
this.config = EventsConfig.load(this.configPath, EventsMod.LOGGER);
this.previousMinecraftTick = readMinecraftDayTick(server).orElse(-1L);
this.realTimeRuns.clear();
this.minecraftTimeRuns.clear();
this.intervalRuns.clear();
}
public void tick(MinecraftServer server) {
List<EventDefinition> events = events();
if (events.isEmpty()) {
return;
}
long currentMinecraftTick = readMinecraftDayTick(server).orElse(-1L);
boolean hasMinecraftTick = currentMinecraftTick >= 0L;
long previousTick = this.previousMinecraftTick;
if (hasMinecraftTick && previousTick >= 0L && previousTick > currentMinecraftTick) {
this.minecraftCycle++;
}
for (EventDefinition event : events) {
if (!event.enabled) {
continue;
}
EventTrigger trigger = event.normalizedTrigger();
switch (trigger.normalizedType()) {
case "real_time" -> tickRealTimeEvent(server, event, trigger);
case "minecraft_time" -> {
if (hasMinecraftTick && previousTick >= 0L) {
tickMinecraftTimeEvent(server, event, trigger, previousTick, currentMinecraftTick);
}
}
case "interval" -> tickIntervalEvent(server, event, trigger);
default -> {
}
}
}
if (hasMinecraftTick) {
this.previousMinecraftTick = currentMinecraftTick;
}
}
public List<EventDefinition> events() {
return List.copyOf(this.config.normalizedEvents());
}
public List<String> eventIds() {
return events().stream()
.map(EventDefinition::normalizedId)
.toList();
}
public String configPathLabel() {
return this.configPath.toString();
}
public boolean runNow(MinecraftServer server, String id, String reason) {
Optional<EventDefinition> event = this.config.find(id);
if (event.isEmpty()) {
return false;
}
runEvent(server, event.get(), reason, true);
return true;
}
public boolean setEnabled(String id, boolean enabled) throws IOException {
Optional<EventDefinition> event = this.config.find(id);
if (event.isEmpty()) {
return false;
}
event.get().enabled = enabled;
EventsConfig.save(this.configPath, this.config);
return true;
}
private void runStartupEvents(MinecraftServer server) {
for (EventDefinition event : events()) {
if (event.enabled && event.normalizedTrigger().runOnStart) {
runEvent(server, event, "startup", false);
}
}
}
private void tickRealTimeEvent(MinecraftServer server, EventDefinition event, EventTrigger trigger) {
LocalTime target;
try {
target = LocalTime.parse(trigger.normalizedTime());
} catch (DateTimeParseException exception) {
EventsMod.LOGGER.warn("Events: heure real_time invalide pour {}: {}", event.normalizedId(), trigger.normalizedTime());
return;
}
ZoneId zone = zoneFor(trigger.normalizedTimezone());
ZonedDateTime now = ZonedDateTime.now(zone);
if (now.getHour() != target.getHour() || now.getMinute() != target.getMinute()) {
return;
}
LocalDate today = now.toLocalDate();
if (Objects.equals(this.realTimeRuns.get(event.normalizedId()), today)) {
return;
}
this.realTimeRuns.put(event.normalizedId(), today);
runEvent(server, event, "real_time", false);
}
private void tickMinecraftTimeEvent(MinecraftServer server, EventDefinition event, EventTrigger trigger, long previousTick, long currentTick) {
long targetTick = trigger.normalizedTick();
if (targetTick < 0L) {
EventsMod.LOGGER.warn("Events: tick minecraft_time invalide pour {}", event.normalizedId());
return;
}
if (!crossedMinecraftTick(previousTick, currentTick, targetTick)) {
return;
}
long runCycle = currentTick < previousTick && targetTick > previousTick
? this.minecraftCycle - 1L
: this.minecraftCycle;
String runKey = event.normalizedId();
if (Objects.equals(this.minecraftTimeRuns.get(runKey), runCycle)) {
return;
}
this.minecraftTimeRuns.put(runKey, runCycle);
runEvent(server, event, "minecraft_time", false);
}
private void tickIntervalEvent(MinecraftServer server, EventDefinition event, EventTrigger trigger) {
int intervalTicks = trigger.normalizedIntervalTicks();
if (intervalTicks <= 0) {
EventsMod.LOGGER.warn("Events: interval invalide pour {}", event.normalizedId());
return;
}
int now = server.getTickCount();
Integer lastRun = this.intervalRuns.get(event.normalizedId());
if (lastRun == null) {
this.intervalRuns.put(event.normalizedId(), now);
return;
}
if (now - lastRun < intervalTicks) {
return;
}
this.intervalRuns.put(event.normalizedId(), now);
runEvent(server, event, "interval", false);
}
private void runEvent(MinecraftServer server, EventDefinition event, String reason, boolean force) {
if (!force && !conditionsPass(server, event.normalizedConditions())) {
EventsMod.LOGGER.info("Events: {} ignore, conditions non remplies.", event.normalizedId());
return;
}
Map<String, String> placeholders = placeholders(server, event, reason);
for (EventAction action : event.normalizedActions()) {
runAction(server, event, action, placeholders);
}
EventsMod.LOGGER.info("Events: {} execute ({})", event.normalizedId(), reason);
}
private boolean conditionsPass(MinecraftServer server, EventCondition conditions) {
int playerCount = server.getPlayerCount();
if (playerCount < conditions.normalizedMinPlayers()) {
return false;
}
int maxPlayers = conditions.normalizedMaxPlayers();
if (maxPlayers >= 0 && playerCount > maxPlayers) {
return false;
}
double chance = conditions.normalizedChance();
return chance >= 1.0D || ThreadLocalRandom.current().nextDouble() <= chance;
}
private void runAction(MinecraftServer server, EventDefinition event, EventAction action, Map<String, String> placeholders) {
switch (action.normalizedType()) {
case "broadcast", "message" -> broadcast(server, applyPlaceholders(action.normalizedMessage(), placeholders));
case "random_message" -> randomMessage(server, action, placeholders);
case "actionbar" -> actionbar(server, applyPlaceholders(action.normalizedMessage(), placeholders));
case "title" -> title(server, action, placeholders);
case "sound" -> sound(server, event, action);
case "command" -> commands(server, action, placeholders);
default -> EventsMod.LOGGER.warn("Events: action inconnue dans {}: {}", event.normalizedId(), action.normalizedType());
}
}
private void broadcast(MinecraftServer server, String message) {
if (message.isEmpty()) {
return;
}
server.getPlayerList().broadcastSystemMessage(Component.literal(message), false);
}
private void randomMessage(MinecraftServer server, EventAction action, Map<String, String> placeholders) {
List<String> messages = action.normalizedMessages();
if (messages.isEmpty()) {
broadcast(server, applyPlaceholders(action.normalizedMessage(), placeholders));
return;
}
String message = messages.get(ThreadLocalRandom.current().nextInt(messages.size()));
broadcast(server, applyPlaceholders(message, placeholders));
}
private void actionbar(MinecraftServer server, String message) {
if (message.isEmpty()) {
return;
}
ClientboundSetActionBarTextPacket packet = new ClientboundSetActionBarTextPacket(Component.literal(message));
for (ServerPlayer player : server.getPlayerList().getPlayers()) {
player.connection.send(packet);
}
}
private void title(MinecraftServer server, EventAction action, Map<String, String> placeholders) {
String title = applyPlaceholders(action.normalizedTitle(), placeholders);
String subtitle = applyPlaceholders(action.normalizedSubtitle(), placeholders);
if (title.isEmpty() && subtitle.isEmpty()) {
return;
}
ClientboundSetTitlesAnimationPacket animationPacket = new ClientboundSetTitlesAnimationPacket(
Math.max(0, action.fadeInTicks),
Math.max(1, action.stayTicks),
Math.max(0, action.fadeOutTicks)
);
ClientboundSetTitleTextPacket titlePacket = new ClientboundSetTitleTextPacket(Component.literal(title));
ClientboundSetSubtitleTextPacket subtitlePacket = new ClientboundSetSubtitleTextPacket(Component.literal(subtitle));
for (ServerPlayer player : server.getPlayerList().getPlayers()) {
player.connection.send(animationPacket);
if (!subtitle.isEmpty()) {
player.connection.send(subtitlePacket);
}
if (!title.isEmpty()) {
player.connection.send(titlePacket);
}
}
}
private void sound(MinecraftServer server, EventDefinition event, EventAction action) {
String rawSound = action.normalizedSound();
if (rawSound.isEmpty()) {
return;
}
Identifier id = Identifier.tryParse(rawSound);
if (id == null) {
EventsMod.LOGGER.warn("Events: son invalide dans {}: {}", event.normalizedId(), rawSound);
return;
}
Optional<SoundEvent> sound = BuiltInRegistries.SOUND_EVENT.getOptional(id);
if (sound.isEmpty()) {
EventsMod.LOGGER.warn("Events: son inconnu dans {}: {}", event.normalizedId(), rawSound);
return;
}
for (ServerPlayer player : server.getPlayerList().getPlayers()) {
player.level().playSound(
null,
player.getX(),
player.getY(),
player.getZ(),
sound.get(),
SoundSource.MASTER,
Math.max(0.0F, action.volume),
Math.max(0.01F, action.pitch)
);
}
}
private void commands(MinecraftServer server, EventAction action, Map<String, String> placeholders) {
List<String> commands = new ArrayList<>(action.normalizedCommands());
String singleCommand = action.normalizedCommand();
if (!singleCommand.isEmpty()) {
commands.add(singleCommand);
}
for (String command : commands) {
String applied = applyPlaceholders(command, placeholders);
if (!applied.isEmpty()) {
server.getCommands().performPrefixedCommand(server.createCommandSourceStack().withSuppressedOutput(), applied);
}
}
}
private Map<String, String> placeholders(MinecraftServer server, EventDefinition event, String reason) {
Map<String, String> values = new HashMap<>();
List<ServerPlayer> players = server.getPlayerList().getPlayers();
ZonedDateTime now = ZonedDateTime.now();
values.put("event", event.normalizedId());
values.put("reason", reason);
values.put("online", Integer.toString(server.getPlayerCount()));
values.put("max_players", Integer.toString(server.getPlayerList().getMaxPlayers()));
values.put("server_tick", Integer.toString(server.getTickCount()));
values.put("minecraft_time", Long.toString(readMinecraftDayTick(server).orElse(0L)));
values.put("date", now.toLocalDate().toString());
values.put("time", now.toLocalTime().withNano(0).toString());
values.put("random_player", players.isEmpty() ? "personne" : players.get(ThreadLocalRandom.current().nextInt(players.size())).getName().getString());
return values;
}
private String applyPlaceholders(String input, Map<String, String> placeholders) {
String output = Objects.requireNonNullElse(input, "");
for (Map.Entry<String, String> entry : placeholders.entrySet()) {
output = output.replace("{" + entry.getKey() + "}", entry.getValue());
}
return output;
}
private Optional<Long> readMinecraftDayTick(MinecraftServer server) {
try {
Holder<WorldClock> overworldClock = server.registryAccess()
.lookupOrThrow(Registries.WORLD_CLOCK)
.getOrThrow(WorldClocks.OVERWORLD);
return Optional.of(Math.floorMod(server.clockManager().getTotalTicks(overworldClock), MINECRAFT_DAY_TICKS));
} catch (RuntimeException exception) {
EventsMod.LOGGER.warn("Events: impossible de lire l'heure Minecraft.", exception);
return Optional.empty();
}
}
private static ZoneId zoneFor(String rawZone) {
String zone = Objects.requireNonNullElse(rawZone, "system").strip();
if (zone.isEmpty() || zone.equalsIgnoreCase("system")) {
return ZoneId.systemDefault();
}
try {
return ZoneId.of(zone);
} catch (DateTimeException exception) {
EventsMod.LOGGER.warn("Events: timezone invalide '{}', timezone systeme utilisee.", rawZone);
return ZoneId.systemDefault();
}
}
private static boolean crossedMinecraftTick(long previousTick, long currentTick, long targetTick) {
if (previousTick == currentTick) {
return false;
}
if (previousTick < currentTick) {
return previousTick < targetTick && targetTick <= currentTick;
}
return targetTick > previousTick || targetTick <= currentTick;
}
}
@@ -0,0 +1,3 @@
{
"events.mod": "Events"
}
@@ -0,0 +1,3 @@
{
"events.mod": "Events"
}
@@ -0,0 +1,23 @@
{
"schemaVersion": 1,
"id": "events",
"version": "${version}",
"name": "Events",
"description": "A small multiplayer server automation engine for timed messages, commands, titles, actionbars, and sounds.",
"authors": [
"KOKA99CAB"
],
"license": "LGPL-3.0-or-later",
"environment": "*",
"entrypoints": {
"main": [
"fr.koka99cab.events.EventsMod"
]
},
"depends": {
"fabricloader": ">=0.19.2",
"minecraft": "~26.1.2",
"java": ">=25",
"fabric-api": "*"
}
}