commit b07c6b56f2ee336d27b2ebc8717b7e70dbe48581 Author: gastinelt <264859180+gastinelt@users.noreply.github.com> Date: Wed Oct 14 00:06:39 2026 +0200 GastinelGarde 0.1.0 : phase 0 et 1 (coeur pur, adaptateurs NeoForge, 62 tests) Coeur pur : points d'infraction avec decroissance, paliers, exemptions, killaura (angle, cibles multiples), cadence et regularite, timer, enregistreur de traces JSONL, tolerance riptide reprise de GastinelClaims. Adaptateurs : configuration rechargeable, commandes /garde, mixins de lecture des paquets de mouvement. Tout demarre en observe. Jamais de bannissement automatique. Co-Authored-By: Claude Sonnet 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cb3b3a9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +build/ +build-out/ +.gradle/ +run/ +*.jar +!gradle/wrapper/gradle-wrapper.jar diff --git a/build-sur-cornafserver.sh b/build-sur-cornafserver.sh new file mode 100644 index 0000000..9067be8 --- /dev/null +++ b/build-sur-cornafserver.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Compile GastinelGarde dans un conteneur JDK 21 jetable (rien n'est installé sur l'hôte). +# Usage (sur cornafserver) : sh build-sur-cornafserver.sh -> build/libs/*.jar +set -e +cd "$(dirname "$0")" +mkdir -p "$HOME/.cache/gastinelclaims-gradle" +nice -n 10 docker run --rm --memory 4g --cpus 4 \ + -u "$(id -u):$(id -g)" \ + -e GRADLE_USER_HOME=/gradle-home \ + -v "$HOME/.cache/gastinelclaims-gradle:/gradle-home" \ + -v "$(pwd):/src" -w /src \ + eclipse-temurin:21-jdk \ + sh ./gradlew --no-daemon clean test build +ls -l build/libs diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..7eebc57 --- /dev/null +++ b/build.gradle @@ -0,0 +1,50 @@ +plugins { + id 'java' + id 'net.neoforged.moddev' version '2.0.142' +} + +version = project.mod_version +group = project.mod_group_id +base { archivesName = "${project.mod_id}-neoforge-1.21.1" } + +java { toolchain { languageVersion = JavaLanguageVersion.of(21) } } + +repositories { + mavenCentral() + maven { name = 'NeoForged'; url = 'https://maven.neoforged.net/releases' } +} + +neoForge { + version = project.neoforge_version + runs { + server { + server() + } + } + mods { + "${project.mod_id}" { + sourceSet sourceSets.main + } + } + unitTest { + enable() + testedMod = mods."${project.mod_id}" + } +} + +dependencies { + // Tests de la logique pure (package core, sans Minecraft) + testImplementation platform('org.junit:junit-bom:5.11.4') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +test { + useJUnitPlatform() + testLogging { events 'passed', 'failed'; exceptionFormat 'full' } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.release = 21 +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..36f5839 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,9 @@ +org.gradle.jvmargs=-Xmx2G +org.gradle.parallel=true + +mod_version=0.1.0 +mod_group_id=com.gastinelgarde +mod_id=gastinelgarde + +minecraft_version=1.21.1 +neoforge_version=21.1.234 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b1b8ef5 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 new file mode 100644 index 0000000..5dd3c01 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..b9bb139 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..24c62d5 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@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, and ensure extensions are enabled +setlocal EnableExtensions + +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 + +"%COMSPEC%" /c exit 1 + +: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 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..791415d --- /dev/null +++ b/settings.gradle @@ -0,0 +1,8 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + maven { name = 'NeoForged'; url = 'https://maven.neoforged.net/releases' } + } +} +rootProject.name = 'gastinelgarde-neoforge-1.21.1' diff --git a/src/main/java/com/gastinelgarde/Garde.java b/src/main/java/com/gastinelgarde/Garde.java new file mode 100644 index 0000000..6f37525 --- /dev/null +++ b/src/main/java/com/gastinelgarde/Garde.java @@ -0,0 +1,331 @@ +package com.gastinelgarde; + +import com.gastinelgarde.core.EtatJoueur; +import com.gastinelgarde.core.GardeConfig; +import com.gastinelgarde.core.Moteur; +import com.gastinelgarde.core.Sanction; +import com.gastinelgarde.core.Suivi; +import com.gastinelgarde.core.TraceFichier; +import com.gastinelgarde.core.TraceLigne; +import com.gastinelgarde.core.Verdict; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.Instant; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.UseAnim; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.EnchantmentHelper; +import net.neoforged.fml.loading.FMLPaths; + +/** + * État d'exécution du mod (une seule instance par serveur) et pont entre Minecraft et le moteur pur. + * Toute la logique de décision est dans {@code com.gastinelgarde.core} ; ici on ne fait que lire l'état du + * serveur, appeler le moteur et appliquer le résultat. + */ +public final class Garde { + + /** Marques propres à un joueur, côté adaptateur (ticks du serveur). */ + private static final class Marques { + int teleportTick = Integer.MIN_VALUE; + int reculTick = Integer.MIN_VALUE; + int dernierVerdictTick = Integer.MIN_VALUE; + int dernierTraceTick = Integer.MIN_VALUE; + int dernierRiptideTick = Integer.MIN_VALUE; + long exemptJusquaMs = 0; + double dernierX, dernierY, dernierZ; + boolean aDernierePosition; + } + + private static final GardeConfig CONFIG = new GardeConfig(); + private static final Moteur MOTEUR = new Moteur(CONFIG); + private static final Map MARQUES = new HashMap<>(); + private static final Set ALERTES_COUPEES = new HashSet<>(); + + private static TraceFichier traces; + private static Path journal; + private static boolean tracesEnCours; + private static int gelTick = Integer.MIN_VALUE; + private static double tpsEstime = 20.0; + + private Garde() { } + + public static GardeConfig config() { + return CONFIG; + } + + public static Moteur moteur() { + return MOTEUR; + } + + // --- Cycle de vie --- + + public static void surConfigChargee() { + GastinelGarde.LOGGER.info("[GastinelGarde] Configuration appliquée."); + } + + public static synchronized void demarrer() { + GardeSpec.appliquer(CONFIG); + Path jeu = FMLPaths.GAMEDIR.get(); + journal = jeu.resolve("logs").resolve("gastinelgarde.log"); + try { + Files.createDirectories(journal.getParent()); + traces = new TraceFichier(jeu.resolve("gastinelgarde-traces"), GardeSpec.tracesJours(), GardeSpec.tracesTailleOctets()); + tracesEnCours = GardeSpec.tracesActives(); + } catch (IOException e) { + GastinelGarde.LOGGER.error("[GastinelGarde] Impossible d'ouvrir le dossier de traces", e); + traces = null; + tracesEnCours = false; + } + } + + public static synchronized void arreter() { + if (traces != null) { + try { + traces.close(); + } catch (IOException ignored) { + // fermeture du serveur : rien à faire de plus + } + traces = null; + } + MARQUES.clear(); + } + + public static synchronized void flushTraces() { + if (traces == null) return; + try { + traces.flush(); + } catch (IOException e) { + GastinelGarde.LOGGER.warn("[GastinelGarde] flush des traces : {}", e.toString()); + } + } + + public static boolean tracesEnCours() { + return tracesEnCours && traces != null; + } + + public static void definirTraces(boolean actif) { + tracesEnCours = actif && traces != null; + } + + public static void joueurParti(UUID id) { + MOTEUR.retirer(id); + MARQUES.remove(id); + ALERTES_COUPEES.remove(id); + } + + // --- Faits collectés --- + + public static void noterTeleport(ServerPlayer p) { + marques(p.getUUID()).teleportTick = p.server.getTickCount(); + } + + public static void noterRecul(ServerPlayer p) { + marques(p.getUUID()).reculTick = p.server.getTickCount(); + } + + public static void noterTickServeur(MinecraftServer server, long dureeNs) { + double ms = dureeNs / 1_000_000.0; + if (ms > 250.0) gelTick = server.getTickCount(); + double moyenne = server.getAverageTickTimeNanos() / 1_000_000.0; + tpsEstime = moyenne <= 50.0 ? 20.0 : 1000.0 / moyenne; + } + + public static void exempter(UUID id, long dureeMs) { + marques(id).exemptJusquaMs = System.currentTimeMillis() + dureeMs; + } + + public static boolean estExempteManuellement(UUID id) { + Marques m = MARQUES.get(id); + return m != null && m.exemptJusquaMs > System.currentTimeMillis(); + } + + public static boolean alertesActivesPour(UUID id) { + return !ALERTES_COUPEES.contains(id); + } + + public static void definirAlertes(UUID id, boolean actif) { + if (actif) ALERTES_COUPEES.remove(id); + else ALERTES_COUPEES.add(id); + } + + private static Marques marques(UUID id) { + return MARQUES.computeIfAbsent(id, k -> new Marques()); + } + + // --- État d'un joueur pour le moteur --- + + public static EtatJoueur etat(ServerPlayer p, boolean chercherContraption) { + int tick = p.server.getTickCount(); + Marques m = marques(p.getUUID()); + + boolean riptide = p.isAutoSpinAttack() || tridentImpulsion(p.getMainHandItem(), p) || tridentImpulsion(p.getOffhandItem(), p); + if (riptide) m.dernierRiptideTick = tick; + boolean riptideRecent = m.dernierRiptideTick != Integer.MIN_VALUE + && tick - m.dernierRiptideTick <= com.gastinelgarde.core.RiptideTolerance.GRACE_TICKS; + + boolean mange = false; + if (p.isUsingItem()) { + UseAnim anim = p.getUseItem().getUseAnimation(); + mange = anim == UseAnim.EAT || anim == UseAnim.DRINK; + } + + return EtatJoueur.builder() + .creatif(p.isCreative()) + .spectateur(p.isSpectator()) + .peutVoler(p.getAbilities().mayfly) + .riptide(riptideRecent) + .elytres(p.isFallFlying()) + .levitation(p.hasEffect(MobEffects.LEVITATION)) + .chuteLente(p.hasEffect(MobEffects.SLOW_FALLING)) + .enVehicule(p.isPassenger()) + .pocheContraption(chercherContraption && pocheContraption(p)) + .utiliseObjet(mange) + .ticksDepuisTeleport(depuis(tick, m.teleportTick)) + .ticksDepuisRecul(depuis(tick, m.reculTick)) + .ticksDepuisGel(depuis(tick, gelTick)) + .tps(tpsEstime) + .pingMs(p.connection.latency()) + .build(); + } + + private static int depuis(int tick, int marque) { + if (marque == Integer.MIN_VALUE) return EtatJoueur.JAMAIS; + return Math.max(0, tick - marque); + } + + private static boolean tridentImpulsion(ItemStack stack, ServerPlayer joueur) { + return stack.is(Items.TRIDENT) && EnchantmentHelper.getTridentSpinAttackStrength(stack, joueur) > 0.0F; + } + + /** Une entité de contraption (Create, Aeronautics…) est-elle toute proche ? Détection par nom de classe. */ + private static boolean pocheContraption(Player p) { + int dist = GardeSpec.distanceContraption(); + if (dist <= 0) return false; + String[] prefixes = GardeSpec.prefixesContraption().split(","); + List proches = p.level().getEntities(p, p.getBoundingBox().inflate(dist), e -> { + String nom = e.getClass().getName(); + for (String pre : prefixes) { + String t = pre.trim(); + if (!t.isEmpty() && nom.startsWith(t)) return true; + } + return false; + }); + return !proches.isEmpty(); + } + + // --- Réaction aux verdicts --- + + /** + * Journalise, prévient les ops et renvoie la pire sanction applicable. Ne modifie pas le joueur : l'appelant + * décide de l'action (annuler le coup, retour arrière, expulsion). + */ + public static Sanction traiter(ServerPlayer p, List verdicts) { + if (verdicts.isEmpty()) return Sanction.AUCUNE; + marques(p.getUUID()).dernierVerdictTick = p.server.getTickCount(); + for (Verdict v : verdicts) { + String ligne = String.format("%s %s mode=%s vl=%.1f (+%.1f) palier=%s applique=%s %s exemptions=%s", + p.getGameProfile().getName(), v.controle().id(), v.mode(), v.vl(), v.points(), + v.palier(), v.applicable(), v.details(), v.exemptions()); + ecrireJournal(ligne); + if (v.notifier()) alerterOps(p, v); + } + return Verdict.pire(verdicts); + } + + private static void alerterOps(ServerPlayer cible, Verdict v) { + Component msg = Component.literal(String.format("[Garde] %s : %s VL=%.1f (%s, %s)", + cible.getGameProfile().getName(), v.controle().id(), v.vl(), v.mode(), v.applicable())) + .withStyle(ChatFormatting.GOLD); + for (ServerPlayer op : cible.server.getPlayerList().getPlayers()) { + if (op.hasPermissions(2) && alertesActivesPour(op.getUUID())) op.sendSystemMessage(msg); + } + } + + private static synchronized void ecrireJournal(String ligne) { + GastinelGarde.LOGGER.warn("[GastinelGarde] {}", ligne); + if (journal == null) return; + try { + Files.writeString(journal, Instant.now() + " " + ligne + System.lineSeparator(), StandardCharsets.UTF_8, + StandardOpenOption.CREATE, StandardOpenOption.APPEND); + } catch (IOException e) { + GastinelGarde.LOGGER.warn("[GastinelGarde] journal : {}", e.toString()); + } + } + + // --- Traces --- + + public static synchronized void tracer(TraceLigne l) { + if (!tracesEnCours()) return; + try { + traces.ecrire(System.currentTimeMillis(), l.json()); + } catch (IOException e) { + GastinelGarde.LOGGER.warn("[GastinelGarde] trace : {}", e.toString()); + tracesEnCours = false; + } + } + + // --- Paquet de mouvement (appelé par le mixin) --- + + /** Début du traitement d'un paquet de mouvement : contrôle du débit. */ + public static void avantMouvement(ServerPlayer p) { + if (estExempteManuellement(p.getUUID())) return; + EtatJoueur etat = etat(p, false); + List v = MOTEUR.paquetMouvement(p.getUUID(), System.currentTimeMillis(), etat); + Sanction s = traiter(p, v); + if (s.ordinal() >= Sanction.SETBACK.ordinal()) appliquerSanctionMouvement(p, s, v); + } + + /** Fin du traitement d'un paquet accepté : mémorise la position valide et trace. */ + public static void apresMouvement(ServerPlayer p) { + int tick = p.server.getTickCount(); + Marques m = marques(p.getUUID()); + if (m.dernierVerdictTick != tick) { + MOTEUR.suivi(p.getUUID()).memoriserPosition(p.getX(), p.getY(), p.getZ(), p.getYRot(), p.getXRot(), + p.level().dimension().location().toString()); + } + if (tracesEnCours() && m.dernierTraceTick != tick) { + m.dernierTraceTick = tick; + double vx = m.aDernierePosition ? p.getX() - m.dernierX : 0; + double vy = m.aDernierePosition ? p.getY() - m.dernierY : 0; + double vz = m.aDernierePosition ? p.getZ() - m.dernierZ : 0; + m.dernierX = p.getX(); + m.dernierY = p.getY(); + m.dernierZ = p.getZ(); + m.aDernierePosition = true; + boolean solServeur = !p.level().noCollision(p, p.getBoundingBox().move(0.0, -0.05, 0.0)); + tracer(new TraceLigne(tick, p.getGameProfile().getName(), "move", p.getX(), p.getY(), p.getZ(), + vx, vy, vz, p.onGround(), solServeur, TraceLigne.masque(etat(p, false)), -1, Double.NaN, null)); + } + } + + public static void appliquerSanctionMouvement(ServerPlayer p, Sanction s, List verdicts) { + String raison = verdicts.isEmpty() ? "anti-triche" : verdicts.get(0).controle().id(); + if (s == Sanction.EXPULSION) { + ecrireJournal(p.getGameProfile().getName() + " EXPULSE (" + raison + ")"); + p.connection.disconnect(Component.literal("Expulsé par l'anti-triche (" + raison + ").")); + } else if (s == Sanction.SETBACK) { + Suivi sv = MOTEUR.suivi(p.getUUID()); + String dim = p.level().dimension().location().toString(); + if (sv.aPositionValide() && sv.dimension().equals(dim)) { + p.connection.teleport(sv.x(), sv.y(), sv.z(), sv.yaw(), sv.pitch()); + ecrireJournal(p.getGameProfile().getName() + " SETBACK (" + raison + ")"); + } + } + } +} diff --git a/src/main/java/com/gastinelgarde/GardeCommands.java b/src/main/java/com/gastinelgarde/GardeCommands.java new file mode 100644 index 0000000..ca4d29f --- /dev/null +++ b/src/main/java/com/gastinelgarde/GardeCommands.java @@ -0,0 +1,133 @@ +package com.gastinelgarde; + +import com.gastinelgarde.core.Controle; +import com.gastinelgarde.core.GardeConfig; +import com.gastinelgarde.core.Mode; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.arguments.IntegerArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.minecraft.ChatFormatting; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.EntityArgument; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.event.RegisterCommandsEvent; + +/** + * /garde status [joueur] | alertes on|off | mode off|observe|enforce | exempter + * | traces on|off | reload (réservé aux ops, niveau 2) + */ +public final class GardeCommands { + + private GardeCommands() { } + + @SubscribeEvent + public static void onRegister(RegisterCommandsEvent event) { + CommandDispatcher d = event.getDispatcher(); + + LiteralArgumentBuilder racine = Commands.literal("garde") + .requires(src -> src.hasPermission(2)) + .executes(GardeCommands::status); + + racine.then(Commands.literal("status") + .executes(GardeCommands::status) + .then(Commands.argument("joueur", EntityArgument.player()).executes(GardeCommands::statusJoueur))); + + racine.then(Commands.literal("alertes") + .then(Commands.literal("on").executes(ctx -> alertes(ctx, true))) + .then(Commands.literal("off").executes(ctx -> alertes(ctx, false)))); + + racine.then(Commands.literal("traces") + .then(Commands.literal("on").executes(ctx -> traces(ctx, true))) + .then(Commands.literal("off").executes(ctx -> traces(ctx, false)))); + + LiteralArgumentBuilder mode = Commands.literal("mode"); + for (Controle c : Controle.values()) { + LiteralArgumentBuilder noeud = Commands.literal(c.id()); + for (Mode m : Mode.values()) { + noeud.then(Commands.literal(m.name().toLowerCase()).executes(ctx -> definirMode(ctx, c, m))); + } + mode.then(noeud); + } + racine.then(mode); + + racine.then(Commands.literal("exempter") + .then(Commands.argument("joueur", EntityArgument.player()) + .then(Commands.argument("minutes", IntegerArgumentType.integer(1, 1440)) + .executes(GardeCommands::exempter)))); + + racine.then(Commands.literal("reload").executes(GardeCommands::recharger)); + + d.register(racine); + } + + // --- Commandes --- + + private static int status(CommandContext ctx) { + GardeConfig c = Garde.config(); + StringBuilder sb = new StringBuilder("GastinelGarde :"); + for (Controle k : Controle.values()) sb.append("\n ").append(k.id()).append(" = ").append(c.mode(k)); + sb.append("\n sanction max = ").append(c.sanctionMax) + .append(" | traces = ").append(Garde.tracesEnCours() ? "on" : "off") + .append(" | joueurs suivis = ").append(Garde.moteur().joueursSuivis()); + ok(ctx, sb.toString()); + return 1; + } + + private static int statusJoueur(CommandContext ctx) throws CommandSyntaxException { + ServerPlayer p = EntityArgument.getPlayer(ctx, "joueur"); + long now = p.server.getTickCount() * 50L; + var suivi = Garde.moteur().suivi(p.getUUID()); + StringBuilder sb = new StringBuilder("Garde, " + p.getGameProfile().getName() + " :"); + for (Controle k : Controle.values()) { + sb.append("\n ").append(k.id()).append(" VL=") + .append(String.format(java.util.Locale.ROOT, "%.1f", suivi.vl.valeur(k, now))); + } + if (Garde.estExempteManuellement(p.getUUID())) sb.append("\n (exempté manuellement)"); + ok(ctx, sb.toString()); + return 1; + } + + private static int alertes(CommandContext ctx, boolean actif) throws CommandSyntaxException { + ServerPlayer p = ctx.getSource().getPlayerOrException(); + Garde.definirAlertes(p.getUUID(), actif); + ok(ctx, "Alertes de l'anti-triche : " + (actif ? "activées" : "coupées") + " pour toi."); + return 1; + } + + private static int traces(CommandContext ctx, boolean actif) { + Garde.definirTraces(actif); + ok(ctx, "Enregistreur de traces : " + (Garde.tracesEnCours() ? "actif" : "coupé") + " (jusqu'au prochain redémarrage ; " + + "réglage permanent dans la configuration)."); + return 1; + } + + private static int definirMode(CommandContext ctx, Controle c, Mode m) { + Garde.config().mode(c, m); + GardeSpec.definirMode(c, m); + ok(ctx, "Contrôle " + c.id() + " : " + m + (m == Mode.ENFORCE ? " (les sanctions s'appliquent)" : "")); + return 1; + } + + private static int exempter(CommandContext ctx) throws CommandSyntaxException { + ServerPlayer p = EntityArgument.getPlayer(ctx, "joueur"); + int minutes = IntegerArgumentType.getInteger(ctx, "minutes"); + Garde.exempter(p.getUUID(), minutes * 60_000L); + ok(ctx, p.getGameProfile().getName() + " est exempté de l'anti-triche pendant " + minutes + " min."); + return 1; + } + + private static int recharger(CommandContext ctx) { + GardeSpec.appliquer(Garde.config()); + ok(ctx, "Configuration de l'anti-triche rechargée."); + return 1; + } + + private static void ok(CommandContext ctx, String texte) { + ctx.getSource().sendSuccess(() -> Component.literal(texte).withStyle(ChatFormatting.GREEN), false); + } +} diff --git a/src/main/java/com/gastinelgarde/GardeEvents.java b/src/main/java/com/gastinelgarde/GardeEvents.java new file mode 100644 index 0000000..46ee511 --- /dev/null +++ b/src/main/java/com/gastinelgarde/GardeEvents.java @@ -0,0 +1,106 @@ +package com.gastinelgarde; + +import com.gastinelgarde.core.EtatJoueur; +import com.gastinelgarde.core.KillauraAngle; +import com.gastinelgarde.core.Sanction; +import com.gastinelgarde.core.TraceLigne; +import com.gastinelgarde.core.Verdict; +import java.util.List; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.common.util.FakePlayer; +import net.neoforged.neoforge.event.entity.living.LivingDamageEvent; +import net.neoforged.neoforge.event.entity.player.AttackEntityEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.event.server.ServerStartingEvent; +import net.neoforged.neoforge.event.server.ServerStoppedEvent; +import net.neoforged.neoforge.event.tick.ServerTickEvent; + +/** Collecte des faits côté serveur (D3) : coups, déconnexions, téléportations, reculs, durée des ticks. */ +public final class GardeEvents { + + private static long debutTickNs; + + private GardeEvents() { } + + @SubscribeEvent + public static void onServerStarting(ServerStartingEvent event) { + Garde.demarrer(); + } + + @SubscribeEvent + public static void onServerStopped(ServerStoppedEvent event) { + Garde.arreter(); + } + + @SubscribeEvent + public static void onTickPre(ServerTickEvent.Pre event) { + debutTickNs = System.nanoTime(); + } + + @SubscribeEvent + public static void onTickPost(ServerTickEvent.Post event) { + long duree = System.nanoTime() - debutTickNs; + Garde.noterTickServeur(event.getServer(), duree); + if (event.getServer().getTickCount() % 20 == 0) Garde.flushTraces(); + } + + @SubscribeEvent + public static void onAttaque(AttackEntityEvent event) { + if (!(event.getEntity() instanceof ServerPlayer p) || p instanceof FakePlayer) return; + if (Garde.estExempteManuellement(p.getUUID())) return; + + Entity cible = event.getTarget(); + int tick = p.server.getTickCount(); + EtatJoueur etat = Garde.etat(p, true); + + AABB bb = cible.getBoundingBox(); + Vec3 oeil = p.getEyePosition(); + Vec3 regard = p.getLookAngle(); + double excedent = KillauraAngle.excedentDegres(oeil.x, oeil.y, oeil.z, regard.x, regard.y, regard.z, + bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); + boolean visible = p.hasLineOfSight(cible); + + List verdicts = Garde.moteur().attaque(p.getUUID(), tick * 50L, etat, excedent, cible.getId(), visible); + + if (Garde.tracesEnCours()) { + Garde.tracer(new TraceLigne(tick, p.getGameProfile().getName(), "atk", p.getX(), p.getY(), p.getZ(), + 0, 0, 0, p.onGround(), p.onGround(), TraceLigne.masque(etat), cible.getId(), excedent, + visible ? null : "non-visible")); + } + + Sanction s = Garde.traiter(p, verdicts); + if (s.ordinal() >= Sanction.SETBACK.ordinal()) { + event.setCanceled(true); // le « retour en arrière » d'un coup : il est simplement annulé + if (s == Sanction.EXPULSION) Garde.appliquerSanctionMouvement(p, s, verdicts); + } + } + + @SubscribeEvent + public static void onDegats(LivingDamageEvent.Post event) { + if (event.getEntity() instanceof ServerPlayer p) Garde.noterRecul(p); + } + + @SubscribeEvent + public static void onConnexion(PlayerEvent.PlayerLoggedInEvent event) { + if (event.getEntity() instanceof ServerPlayer p) Garde.noterTeleport(p); + } + + @SubscribeEvent + public static void onDeconnexion(PlayerEvent.PlayerLoggedOutEvent event) { + Garde.joueurParti(event.getEntity().getUUID()); + } + + @SubscribeEvent + public static void onChangementDimension(PlayerEvent.PlayerChangedDimensionEvent event) { + if (event.getEntity() instanceof ServerPlayer p) Garde.noterTeleport(p); + } + + @SubscribeEvent + public static void onReapparition(PlayerEvent.PlayerRespawnEvent event) { + if (event.getEntity() instanceof ServerPlayer p) Garde.noterTeleport(p); + } +} diff --git a/src/main/java/com/gastinelgarde/GardeSpec.java b/src/main/java/com/gastinelgarde/GardeSpec.java new file mode 100644 index 0000000..eb34ed2 --- /dev/null +++ b/src/main/java/com/gastinelgarde/GardeSpec.java @@ -0,0 +1,177 @@ +package com.gastinelgarde; + +import com.gastinelgarde.core.Controle; +import com.gastinelgarde.core.GardeConfig; +import com.gastinelgarde.core.Mode; +import com.gastinelgarde.core.Sanction; +import java.util.EnumMap; +import java.util.Map; +import net.neoforged.fml.event.config.ModConfigEvent; +import net.neoforged.neoforge.common.ModConfigSpec; + +/** Fichier de configuration (NeoForge) et recopie vers la configuration du moteur. */ +public final class GardeSpec { + + public static final ModConfigSpec SPEC; + + private static final Map> MODES = new EnumMap<>(Controle.class); + + private static final ModConfigSpec.DoubleValue VL_DECROISSANCE; + private static final ModConfigSpec.DoubleValue SEUIL_ALERTE; + private static final ModConfigSpec.DoubleValue SEUIL_SETBACK; + private static final ModConfigSpec.DoubleValue SEUIL_EXPULSION; + private static final ModConfigSpec.EnumValue SANCTION_MAX; + + private static final ModConfigSpec.DoubleValue ANGLE_MAX; + private static final ModConfigSpec.IntValue CIBLES_MAX; + private static final ModConfigSpec.IntValue FENETRE_CIBLES_MS; + private static final ModConfigSpec.IntValue CPS_MAX; + private static final ModConfigSpec.DoubleValue ECART_TYPE_MIN; + private static final ModConfigSpec.DoubleValue INTERVALLE_MOYEN_MAX; + private static final ModConfigSpec.IntValue PAQUETS_PAR_SECONDE; + private static final ModConfigSpec.IntValue TIMER_SECONDES; + + private static final ModConfigSpec.IntValue GRACE_TELEPORT; + private static final ModConfigSpec.IntValue GRACE_RECUL; + private static final ModConfigSpec.IntValue GRACE_GEL; + private static final ModConfigSpec.DoubleValue TPS_LAG; + private static final ModConfigSpec.IntValue PING_LAG; + private static final ModConfigSpec.DoubleValue FACTEUR_LAG; + + private static final ModConfigSpec.ConfigValue PREFIXES_CONTRAPTION; + private static final ModConfigSpec.IntValue DISTANCE_CONTRAPTION; + + private static final ModConfigSpec.BooleanValue TRACES_ACTIVES; + private static final ModConfigSpec.IntValue TRACES_JOURS; + private static final ModConfigSpec.IntValue TRACES_TAILLE_MO; + + static { + ModConfigSpec.Builder b = new ModConfigSpec.Builder(); + + b.comment("Mode de chaque contrôle : OFF (coupé), OBSERVE (journal et message aux ops, aucune sanction),", + "ENFORCE (sanctions appliquées). Tout démarre en OBSERVE ; ne passer en ENFORCE qu'après", + "plusieurs jours sans fausse alerte sur des joueurs honnêtes.").push("modes"); + for (Controle c : Controle.values()) { + MODES.put(c, b.defineEnum(c.id(), Mode.OBSERVE)); + } + b.pop(); + + b.push("sanctions"); + VL_DECROISSANCE = b.comment("Points d'infraction perdus par seconde (par contrôle). S'applique aux joueurs qui se connectent après le rechargement.") + .defineInRange("decroissanceParSeconde", 0.5, 0.0, 100.0); + SEUIL_ALERTE = b.defineInRange("seuilAlerte", 5.0, 0.1, 1000.0); + SEUIL_SETBACK = b.defineInRange("seuilSetback", 10.0, 0.1, 1000.0); + SEUIL_EXPULSION = b.defineInRange("seuilExpulsion", 20.0, 0.1, 1000.0); + SANCTION_MAX = b.comment("Sanction la plus forte autorisée : JOURNAL, ALERTE, SETBACK ou EXPULSION. Il n'y a jamais de bannissement automatique.") + .defineEnum("sanctionMax", Sanction.EXPULSION); + b.pop(); + + b.push("combat"); + ANGLE_MAX = b.comment("Excédent d'angle maximal entre le regard et la silhouette de la cible (degrés).") + .defineInRange("angleMaxDegres", 60.0, 5.0, 180.0); + CIBLES_MAX = b.defineInRange("ciblesMax", 3, 1, 20); + FENETRE_CIBLES_MS = b.defineInRange("fenetreCiblesMs", 1000, 100, 10000); + CPS_MAX = b.comment("Coups par seconde, soutenus 2 s, au-delà desquels on lève une infraction.") + .defineInRange("cpsMax", 20, 5, 100); + ECART_TYPE_MIN = b.defineInRange("ecartTypeMinMs", 12.0, 0.0, 100.0); + INTERVALLE_MOYEN_MAX = b.defineInRange("intervalleMoyenMaxMs", 150.0, 20.0, 1000.0); + b.pop(); + + b.push("timer"); + PAQUETS_PAR_SECONDE = b.defineInRange("paquetsParSecondeMax", 22, 20, 200); + TIMER_SECONDES = b.defineInRange("secondesSoutenues", 3, 1, 30); + b.pop(); + + b.push("exemptions"); + GRACE_TELEPORT = b.defineInRange("graceTeleportTicks", 40, 0, 600); + GRACE_RECUL = b.defineInRange("graceReculTicks", 20, 0, 600); + GRACE_GEL = b.defineInRange("graceGelTicks", 100, 0, 1200); + TPS_LAG = b.defineInRange("tpsLag", 18.0, 1.0, 20.0); + PING_LAG = b.defineInRange("pingLagMs", 250, 50, 5000); + FACTEUR_LAG = b.comment("Multiplicateur des seuils quand le serveur ou le réseau tire.") + .defineInRange("facteurLag", 1.5, 1.0, 5.0); + PREFIXES_CONTRAPTION = b.comment("Préfixes de classes (séparés par des virgules) des entités de contraptions Create / Aeronautics.", + "Un joueur près d'une telle entité est exempté. À valider sur le serveur réel (voir README).") + .define("prefixesContraption", "com.simibubi.create.content.contraptions,dev.simulated_team,dev.ryanhcode"); + DISTANCE_CONTRAPTION = b.defineInRange("distanceContraptionBlocs", 3, 0, 16); + b.pop(); + + b.comment("Enregistreur de traces JSONL (une ligne par mouvement et par coup). Données personnelles : positions des joueurs.") + .push("traces"); + TRACES_ACTIVES = b.comment("Enregistrement continu pour tous les joueurs (décision T7 de Théo, 13/10/2026).") + .define("actives", true); + TRACES_JOURS = b.defineInRange("joursConservation", 7, 1, 90); + TRACES_TAILLE_MO = b.defineInRange("tailleMaxMo", 1024, 16, 102400); + b.pop(); + + SPEC = b.build(); + } + + private GardeSpec() { } + + public static void onConfig(ModConfigEvent event) { + if (event.getConfig().getSpec() == SPEC) { + appliquer(Garde.config()); + Garde.surConfigChargee(); + } + } + + /** Recopie les valeurs du fichier dans la configuration du moteur (si le fichier est chargé). */ + public static void appliquer(GardeConfig c) { + if (!SPEC.isLoaded()) return; + for (Map.Entry> e : MODES.entrySet()) { + c.mode(e.getKey(), e.getValue().get()); + } + c.vlDecroissanceParSeconde = VL_DECROISSANCE.get(); + c.seuilAlerte = SEUIL_ALERTE.get(); + c.seuilSetback = Math.max(SEUIL_SETBACK.get(), c.seuilAlerte); + c.seuilExpulsion = Math.max(SEUIL_EXPULSION.get(), c.seuilSetback); + c.sanctionMax = SANCTION_MAX.get(); + c.angleMaxDegres = ANGLE_MAX.get(); + c.ciblesMax = CIBLES_MAX.get(); + c.fenetreCiblesMs = FENETRE_CIBLES_MS.get(); + c.cpsMax = CPS_MAX.get(); + c.ecartTypeMinMs = ECART_TYPE_MIN.get(); + c.intervalleMoyenMaxMs = INTERVALLE_MOYEN_MAX.get(); + c.paquetsParSecondeMax = PAQUETS_PAR_SECONDE.get(); + c.timerSecondesSoutenues = TIMER_SECONDES.get(); + c.graceTeleportTicks = GRACE_TELEPORT.get(); + c.graceReculTicks = GRACE_RECUL.get(); + c.graceGelTicks = GRACE_GEL.get(); + c.tpsLag = TPS_LAG.get(); + c.pingLagMs = PING_LAG.get(); + c.facteurLag = FACTEUR_LAG.get(); + } + + // --- Réglages propres à l'adaptateur --- + + public static String prefixesContraption() { + return SPEC.isLoaded() ? PREFIXES_CONTRAPTION.get() : PREFIXES_CONTRAPTION.getDefault(); + } + + public static int distanceContraption() { + return SPEC.isLoaded() ? DISTANCE_CONTRAPTION.get() : DISTANCE_CONTRAPTION.getDefault(); + } + + public static boolean tracesActives() { + return SPEC.isLoaded() ? TRACES_ACTIVES.get() : TRACES_ACTIVES.getDefault(); + } + + public static int tracesJours() { + return SPEC.isLoaded() ? TRACES_JOURS.get() : TRACES_JOURS.getDefault(); + } + + public static long tracesTailleOctets() { + int mo = SPEC.isLoaded() ? TRACES_TAILLE_MO.get() : TRACES_TAILLE_MO.getDefault(); + return mo * 1024L * 1024L; + } + + /** Modifie un mode dans le fichier de configuration (conservé au prochain démarrage). */ + public static void definirMode(Controle c, Mode m) { + ModConfigSpec.EnumValue v = MODES.get(c); + if (v != null && SPEC.isLoaded()) { + v.set(m); + SPEC.save(); + } + } +} diff --git a/src/main/java/com/gastinelgarde/GastinelGarde.java b/src/main/java/com/gastinelgarde/GastinelGarde.java new file mode 100644 index 0000000..53b62a0 --- /dev/null +++ b/src/main/java/com/gastinelgarde/GastinelGarde.java @@ -0,0 +1,29 @@ +package com.gastinelgarde; + +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.config.ModConfig; +import net.neoforged.fml.event.config.ModConfigEvent; +import net.neoforged.neoforge.common.NeoForge; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Mod(GastinelGarde.MOD_ID) +public class GastinelGarde { + + public static final String MOD_ID = "gastinelgarde"; + public static final Logger LOGGER = LoggerFactory.getLogger(GastinelGarde.class); + + public GastinelGarde(IEventBus modEventBus, ModContainer modContainer) { + // Config rechargeable : config/gastinelgarde-server.toml (décision D8), plus /garde reload. + modContainer.registerConfig(ModConfig.Type.COMMON, GardeSpec.SPEC, "gastinelgarde-server.toml"); + modEventBus.addListener(ModConfigEvent.Loading.class, GardeSpec::onConfig); + modEventBus.addListener(ModConfigEvent.Reloading.class, GardeSpec::onConfig); + + NeoForge.EVENT_BUS.register(GardeEvents.class); + NeoForge.EVENT_BUS.register(GardeCommands.class); + + LOGGER.info("[GastinelGarde] Anti-triche chargé (tous les contrôles démarrent en observe)."); + } +} diff --git a/src/main/java/com/gastinelgarde/core/AttaqueImpossible.java b/src/main/java/com/gastinelgarde/core/AttaqueImpossible.java new file mode 100644 index 0000000..1b3bc80 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/AttaqueImpossible.java @@ -0,0 +1,16 @@ +package com.gastinelgarde.core; + +/** + * Contrôle 4 : frapper en mangeant ou en buvant, ou sans voir la cible. Vanilla refuse déjà les coups à plus de + * 3 blocs sans ligne de vue : ce contrôle ne couvre que les cas à courte portée. + */ +public final class AttaqueImpossible { + + private AttaqueImpossible() { } + + public static double points(boolean mangeOuBoit, boolean cibleNonVisible) { + if (mangeOuBoit) return 2.0; + if (cibleNonVisible) return 1.0; + return 0; + } +} diff --git a/src/main/java/com/gastinelgarde/core/Cadence.java b/src/main/java/com/gastinelgarde/core/Cadence.java new file mode 100644 index 0000000..a588bb0 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/Cadence.java @@ -0,0 +1,53 @@ +package com.gastinelgarde.core; + +/** + * Contrôles 3 : cadence des coups (plus de {@code cpsMax} par seconde pendant deux secondes) et régularité + * suspecte des intervalles (écart type très bas à cadence rapide). Les temps sont ceux du serveur en ms + * (tick × 50) : un client honnête est donc quantifié au tick, d'où un seuil d'écart type volontairement bas. + */ +public final class Cadence { + + public record Resultat(double cadence, double regularite) { + public static final Resultat RIEN = new Resultat(0, 0); + } + + private final Fenetre fenetre = new Fenetre(128); + + public Resultat enregistrer(long nowMs, GardeConfig cfg, double facteur) { + fenetre.ajouter(nowMs, 0); + + double points = 0; + int cps = (int) Math.floor(cfg.cpsMax * facteur); + int dernierSecond = fenetre.compter(nowMs - 999, nowMs + 1); + int precedent = fenetre.compter(nowMs - 1999, nowMs - 999); + if (dernierSecond > cps && precedent > cps) { + points = 1.0 + Math.min(3.0, (dernierSecond - cps) / 5.0); + } + + double regularite = 0; + int echantillons = cfg.echantillonsRegularite; + int n = fenetre.taille(); + if (echantillons >= 3 && n >= echantillons + 1) { + double somme = 0; + double[] intervalles = new double[echantillons]; + for (int k = 0; k < echantillons; k++) { + long a = fenetre.temps(n - echantillons - 1 + k); + long b = fenetre.temps(n - echantillons + k); + intervalles[k] = b - a; + somme += intervalles[k]; + } + double moyenne = somme / echantillons; + double variance = 0; + for (double v : intervalles) variance += (v - moyenne) * (v - moyenne); + double ecartType = Math.sqrt(variance / echantillons); + if (moyenne < cfg.intervalleMoyenMaxMs && ecartType < cfg.ecartTypeMinMs) { + regularite = ecartType < 3.0 ? 2.0 : 1.0; + } + } + return new Resultat(points, regularite); + } + + public void vider() { + fenetre.vider(); + } +} diff --git a/src/main/java/com/gastinelgarde/core/CiblesMultiples.java b/src/main/java/com/gastinelgarde/core/CiblesMultiples.java new file mode 100644 index 0000000..bf1c7b3 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/CiblesMultiples.java @@ -0,0 +1,36 @@ +package com.gastinelgarde.core; + +/** Contrôle 2 : trop d'entités différentes touchées en peu de temps. */ +public final class CiblesMultiples { + + private final Fenetre fenetre = new Fenetre(32); + + /** + * @param facteur tolérance (1.0 normal) + * @return points d'infraction (0 si rien d'anormal) + */ + public double enregistrer(long nowMs, int idCible, GardeConfig cfg, double facteur) { + fenetre.ajouter(nowMs, idCible); + long depuis = nowMs - cfg.fenetreCiblesMs; + int distinctes = 0; + int n = fenetre.taille(); + for (int i = 0; i < n; i++) { + if (fenetre.temps(i) < depuis) continue; + int id = fenetre.valeur(i); + boolean dejaVue = false; + for (int j = 0; j < i; j++) { + if (fenetre.temps(j) >= depuis && fenetre.valeur(j) == id) { + dejaVue = true; + break; + } + } + if (!dejaVue) distinctes++; + } + int max = (int) Math.floor(cfg.ciblesMax * facteur); + return distinctes > max ? distinctes - max : 0; + } + + public void vider() { + fenetre.vider(); + } +} diff --git a/src/main/java/com/gastinelgarde/core/Controle.java b/src/main/java/com/gastinelgarde/core/Controle.java new file mode 100644 index 0000000..1d0728c --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/Controle.java @@ -0,0 +1,29 @@ +package com.gastinelgarde.core; + +/** Les contrôles de la phase 1 (combat et cadence). Les phases 2 et 3 s'ajouteront ici. */ +public enum Controle { + KILLAURA_ANGLE("killaura-angle"), + KILLAURA_CIBLES("killaura-cibles"), + CADENCE("cadence"), + REGULARITE("regularite"), + ATTAQUE_IMPOSSIBLE("attaque-impossible"), + TIMER("timer"); + + private final String id; + + Controle(String id) { + this.id = id; + } + + public String id() { + return id; + } + + public static Controle parse(String texte) { + if (texte == null) return null; + for (Controle c : values()) { + if (c.id.equalsIgnoreCase(texte.trim())) return c; + } + return null; + } +} diff --git a/src/main/java/com/gastinelgarde/core/EtatJoueur.java b/src/main/java/com/gastinelgarde/core/EtatJoueur.java new file mode 100644 index 0000000..c00779c --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/EtatJoueur.java @@ -0,0 +1,64 @@ +package com.gastinelgarde.core; + +/** + * Ce que le serveur sait d'un joueur à l'instant d'un contrôle. Tout vient du serveur (jamais d'un état déclaré + * par le client). Les distances en ticks valent {@link #JAMAIS} quand l'événement ne s'est pas produit. + */ +public record EtatJoueur( + boolean creatif, + boolean spectateur, + boolean peutVoler, + boolean riptide, + boolean elytres, + boolean levitation, + boolean chuteLente, + boolean enVehicule, + boolean pocheContraption, + boolean utiliseObjet, + int ticksDepuisTeleport, + int ticksDepuisRecul, + int ticksDepuisGel, + double tps, + int pingMs) { + + public static final int JAMAIS = Integer.MAX_VALUE; + + /** Joueur ordinaire, serveur en forme, rien de particulier. */ + public static EtatJoueur normal() { + return new Builder().build(); + } + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private boolean creatif, spectateur, peutVoler, riptide, elytres, levitation, chuteLente; + private boolean enVehicule, pocheContraption, utiliseObjet; + private int ticksDepuisTeleport = JAMAIS, ticksDepuisRecul = JAMAIS, ticksDepuisGel = JAMAIS; + private double tps = 20.0; + private int pingMs = 30; + + public Builder creatif(boolean v) { creatif = v; return this; } + public Builder spectateur(boolean v) { spectateur = v; return this; } + public Builder peutVoler(boolean v) { peutVoler = v; return this; } + public Builder riptide(boolean v) { riptide = v; return this; } + public Builder elytres(boolean v) { elytres = v; return this; } + public Builder levitation(boolean v) { levitation = v; return this; } + public Builder chuteLente(boolean v) { chuteLente = v; return this; } + public Builder enVehicule(boolean v) { enVehicule = v; return this; } + public Builder pocheContraption(boolean v) { pocheContraption = v; return this; } + public Builder utiliseObjet(boolean v) { utiliseObjet = v; return this; } + public Builder ticksDepuisTeleport(int v) { ticksDepuisTeleport = v; return this; } + public Builder ticksDepuisRecul(int v) { ticksDepuisRecul = v; return this; } + public Builder ticksDepuisGel(int v) { ticksDepuisGel = v; return this; } + public Builder tps(double v) { tps = v; return this; } + public Builder pingMs(int v) { pingMs = v; return this; } + + public EtatJoueur build() { + return new EtatJoueur(creatif, spectateur, peutVoler, riptide, elytres, levitation, chuteLente, + enVehicule, pocheContraption, utiliseObjet, ticksDepuisTeleport, ticksDepuisRecul, + ticksDepuisGel, tps, pingMs); + } + } +} diff --git a/src/main/java/com/gastinelgarde/core/Exemptions.java b/src/main/java/com/gastinelgarde/core/Exemptions.java new file mode 100644 index 0000000..99b9f13 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/Exemptions.java @@ -0,0 +1,55 @@ +package com.gastinelgarde.core; + +import java.util.ArrayList; +import java.util.List; + +/** + * Une seule fonction, testée, qui décide si un joueur est exempté d'une famille de contrôles (décision D7). + * Les fausses alertes viennent toujours des cas oubliés : tout cas particulier passe par ici. + */ +public final class Exemptions { + + public enum Famille { COMBAT, MOUVEMENT, TIMER } + + /** + * @param exempt le contrôle ne doit pas s'appliquer + * @param facteur multiplicateur de tolérance des seuils (1.0 normal, plus quand le serveur ou le réseau tire) + * @param raisons pourquoi (pour le journal) + */ + public record Resultat(boolean exempt, double facteur, List raisons) { } + + private Exemptions() { } + + public static Resultat evaluer(EtatJoueur e, GardeConfig cfg, Famille famille) { + List raisons = new ArrayList<>(2); + + if (e.creatif()) raisons.add("creatif"); + if (e.spectateur()) raisons.add("spectateur"); + + switch (famille) { + case COMBAT -> { + if (e.enVehicule()) raisons.add("vehicule"); + if (e.pocheContraption()) raisons.add("contraption"); + } + case MOUVEMENT -> { + if (e.peutVoler()) raisons.add("peut-voler"); + if (e.riptide()) raisons.add("riptide"); + if (e.elytres()) raisons.add("elytres"); + if (e.levitation()) raisons.add("levitation"); + if (e.chuteLente()) raisons.add("chute-lente"); + if (e.enVehicule()) raisons.add("vehicule"); + if (e.pocheContraption()) raisons.add("contraption"); + if (e.ticksDepuisTeleport() <= cfg.graceTeleportTicks) raisons.add("teleportation"); + if (e.ticksDepuisRecul() <= cfg.graceReculTicks) raisons.add("recul"); + } + case TIMER -> { + if (e.ticksDepuisTeleport() <= cfg.graceTeleportTicks) raisons.add("teleportation"); + if (e.ticksDepuisGel() <= cfg.graceGelTicks) raisons.add("gel-serveur"); + } + } + + boolean lag = e.tps() < cfg.tpsLag || e.pingMs() > cfg.pingLagMs; + double facteur = lag ? cfg.facteurLag : 1.0; + return new Resultat(!raisons.isEmpty(), facteur, raisons); + } +} diff --git a/src/main/java/com/gastinelgarde/core/Fenetre.java b/src/main/java/com/gastinelgarde/core/Fenetre.java new file mode 100644 index 0000000..8c5185f --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/Fenetre.java @@ -0,0 +1,59 @@ +package com.gastinelgarde.core; + +/** + * Tampon circulaire de taille fixe de couples (horodatage en ms, valeur entière). Aucune allocation après la + * construction (décision D4) : coût constant par joueur. + */ +public final class Fenetre { + + private final long[] temps; + private final int[] valeurs; + private int debut; + private int taille; + + public Fenetre(int capacite) { + if (capacite <= 0) throw new IllegalArgumentException("capacite > 0"); + this.temps = new long[capacite]; + this.valeurs = new int[capacite]; + } + + public void ajouter(long tempsMs, int valeur) { + int idx; + if (taille < temps.length) { + idx = (debut + taille) % temps.length; + taille++; + } else { + idx = debut; + debut = (debut + 1) % temps.length; + } + temps[idx] = tempsMs; + valeurs[idx] = valeur; + } + + public int taille() { + return taille; + } + + public long temps(int i) { + return temps[(debut + i) % temps.length]; + } + + public int valeur(int i) { + return valeurs[(debut + i) % valeurs.length]; + } + + /** Nombre d'entrées dont l'horodatage est dans [de, jusqua[. */ + public int compter(long deMs, long jusquaMs) { + int n = 0; + for (int i = 0; i < taille; i++) { + long t = temps(i); + if (t >= deMs && t < jusquaMs) n++; + } + return n; + } + + public void vider() { + debut = 0; + taille = 0; + } +} diff --git a/src/main/java/com/gastinelgarde/core/GardeConfig.java b/src/main/java/com/gastinelgarde/core/GardeConfig.java new file mode 100644 index 0000000..d73cbf8 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/GardeConfig.java @@ -0,0 +1,61 @@ +package com.gastinelgarde.core; + +import java.util.EnumMap; +import java.util.Map; + +/** + * Réglages du moteur (logique pure). L'adaptateur NeoForge recopie ici les valeurs du fichier de configuration + * à chaque chargement ou rechargement (/garde reload). Les valeurs par défaut sont celles du plan. + */ +public final class GardeConfig { + + // --- Points d'infraction (VL) et paliers --- + /** Points perdus par seconde et par contrôle. */ + public double vlDecroissanceParSeconde = 0.5; + public double seuilAlerte = 5.0; + public double seuilSetback = 10.0; + public double seuilExpulsion = 20.0; + /** Sanction la plus forte autorisée (T4 : setback puis expulsion, jamais de bannissement). */ + public Sanction sanctionMax = Sanction.EXPULSION; + + // --- Killaura --- + /** Angle maximal entre le regard et la silhouette de la cible, en degrés. */ + public double angleMaxDegres = 60.0; + public int ciblesMax = 3; + public long fenetreCiblesMs = 1000; + + // --- Cadence --- + /** Coups par seconde au-delà desquels, soutenus sur deux secondes, on lève une infraction. */ + public int cpsMax = 20; + /** Écart type des intervalles (ms) sous lequel la régularité est suspecte. */ + public double ecartTypeMinMs = 12.0; + public int echantillonsRegularite = 10; + /** Régularité suspecte seulement si l'intervalle moyen est inférieur (ms) : une arme à cadence fixe est normale. */ + public double intervalleMoyenMaxMs = 150.0; + + // --- Timer (paquets de mouvement) --- + public int paquetsParSecondeMax = 22; + public int timerSecondesSoutenues = 3; + + // --- Exemptions --- + public int graceTeleportTicks = 40; + public int graceReculTicks = 20; + public int graceGelTicks = 100; + public double tpsLag = 18.0; + public int pingLagMs = 250; + public double facteurLag = 1.5; + + private final Map modes = new EnumMap<>(Controle.class); + + public GardeConfig() { + for (Controle c : Controle.values()) modes.put(c, Mode.OBSERVE); + } + + public Mode mode(Controle c) { + return modes.getOrDefault(c, Mode.OBSERVE); + } + + public void mode(Controle c, Mode m) { + modes.put(c, m); + } +} diff --git a/src/main/java/com/gastinelgarde/core/KillauraAngle.java b/src/main/java/com/gastinelgarde/core/KillauraAngle.java new file mode 100644 index 0000000..1b74ff5 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/KillauraAngle.java @@ -0,0 +1,46 @@ +package com.gastinelgarde.core; + +/** + * Contrôle 1 : angle entre le regard de l'attaquant et la silhouette de la cible (géométrie pure). + * Un joueur honnête frappe ce qu'il regarde : l'excédent est proche de 0. Une killaura frappe aussi derrière. + */ +public final class KillauraAngle { + + private KillauraAngle() { } + + /** + * Excédent angulaire, en degrés : angle entre le regard et le centre de la boîte, moins le demi-angle sous + * lequel on voit la boîte (rayon de la boîte englobante, tolérant). 0 si le regard touche la silhouette. + * + * @param look vecteur de regard (pas forcément unitaire) + */ + public static double excedentDegres(double eyeX, double eyeY, double eyeZ, + double lookX, double lookY, double lookZ, + double minX, double minY, double minZ, + double maxX, double maxY, double maxZ) { + double lookLen = Math.sqrt(lookX * lookX + lookY * lookY + lookZ * lookZ); + if (lookLen < 1e-9) return 0; + + // Œil dans la boîte : pas d'angle significatif. + if (eyeX >= minX && eyeX <= maxX && eyeY >= minY && eyeY <= maxY && eyeZ >= minZ && eyeZ <= maxZ) return 0; + + double cx = (minX + maxX) / 2, cy = (minY + maxY) / 2, cz = (minZ + maxZ) / 2; + double vx = cx - eyeX, vy = cy - eyeY, vz = cz - eyeZ; + double d = Math.sqrt(vx * vx + vy * vy + vz * vz); + double rayon = 0.5 * Math.sqrt((maxX - minX) * (maxX - minX) + (maxY - minY) * (maxY - minY) + + (maxZ - minZ) * (maxZ - minZ)); + if (d <= rayon || d < 1e-9) return 0; // collé à la cible + + double cos = (lookX * vx + lookY * vy + lookZ * vz) / (lookLen * d); + cos = Math.max(-1.0, Math.min(1.0, cos)); + double angle = Math.toDegrees(Math.acos(cos)); + double demi = Math.toDegrees(Math.asin(Math.min(1.0, rayon / d))); + return Math.max(0, angle - demi); + } + + /** Points d'infraction pour un excédent donné : 0 sous le seuil, puis de 1 à 4. */ + public static double points(double excedentDegres, double seuilDegres) { + if (excedentDegres <= seuilDegres) return 0; + return 1.0 + Math.min(3.0, (excedentDegres - seuilDegres) / 30.0); + } +} diff --git a/src/main/java/com/gastinelgarde/core/Mode.java b/src/main/java/com/gastinelgarde/core/Mode.java new file mode 100644 index 0000000..9295299 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/Mode.java @@ -0,0 +1,14 @@ +package com.gastinelgarde.core; + +/** État d'un contrôle : coupé, journal seulement, ou sanctions appliquées. Tout démarre en OBSERVE. */ +public enum Mode { + OFF, OBSERVE, ENFORCE; + + public static Mode parse(String texte, Mode defaut) { + if (texte == null) return defaut; + for (Mode m : values()) { + if (m.name().equalsIgnoreCase(texte.trim())) return m; + } + return defaut; + } +} diff --git a/src/main/java/com/gastinelgarde/core/Moteur.java b/src/main/java/com/gastinelgarde/core/Moteur.java new file mode 100644 index 0000000..af4d0d8 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/Moteur.java @@ -0,0 +1,119 @@ +package com.gastinelgarde.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; + +/** + * Cœur du système : reçoit des faits (attaque, paquet de mouvement) avec l'état du joueur, applique les + * exemptions, évalue les contrôles, tient les points d'infraction et renvoie des verdicts. Aucune dépendance à + * Minecraft : tout est rejouable dans les tests. + * + * Le moteur n'est pas thread-safe : il est appelé depuis le thread du serveur. + */ +public final class Moteur { + + /** Délai minimal entre deux messages aux ops pour un même joueur et un même contrôle. */ + public static final long DELAI_ALERTE_MS = 5000; + + private final GardeConfig cfg; + private final Map suivis = new HashMap<>(); + + public Moteur(GardeConfig cfg) { + this.cfg = cfg; + } + + public GardeConfig config() { + return cfg; + } + + public Suivi suivi(UUID joueur) { + return suivis.computeIfAbsent(joueur, k -> new Suivi(cfg.vlDecroissanceParSeconde)); + } + + public void retirer(UUID joueur) { + suivis.remove(joueur); + } + + public int joueursSuivis() { + return suivis.size(); + } + + // --- Combat ----------------------------------------------------------------------------------------- + + /** + * Un coup vient d'être porté. + * + * @param nowMs temps du serveur en ms (tick × 50), identique pour deux coups du même tick + * @param excedentDegres sortie de {@link KillauraAngle#excedentDegres}, -1 si non calculé + * @param idCible identifiant stable de l'entité frappée + * @param cibleVisible résultat du lancer de rayon serveur (vrai si rien ne bloque) + */ + public List attaque(UUID joueur, long nowMs, EtatJoueur etat, double excedentDegres, + int idCible, boolean cibleVisible) { + Exemptions.Resultat ex = Exemptions.evaluer(etat, cfg, Exemptions.Famille.COMBAT); + if (ex.exempt()) return List.of(); + + Suivi s = suivi(joueur); + List verdicts = new ArrayList<>(2); + double f = ex.facteur(); + + if (cfg.mode(Controle.KILLAURA_ANGLE) != Mode.OFF && excedentDegres >= 0) { + double pts = KillauraAngle.points(excedentDegres, cfg.angleMaxDegres * f); + ajouter(verdicts, s, Controle.KILLAURA_ANGLE, pts, nowMs, ex, + String.format(Locale.ROOT, "excedent=%.1f deg (seuil %.0f)", excedentDegres, cfg.angleMaxDegres * f)); + } + if (cfg.mode(Controle.KILLAURA_CIBLES) != Mode.OFF) { + double pts = s.cibles.enregistrer(nowMs, idCible, cfg, f); + ajouter(verdicts, s, Controle.KILLAURA_CIBLES, pts, nowMs, ex, "cibles multiples en " + cfg.fenetreCiblesMs + " ms"); + } + boolean cadenceActive = cfg.mode(Controle.CADENCE) != Mode.OFF; + boolean regulariteActive = cfg.mode(Controle.REGULARITE) != Mode.OFF; + if (cadenceActive || regulariteActive) { + Cadence.Resultat r = s.cadence.enregistrer(nowMs, cfg, f); + if (cadenceActive) ajouter(verdicts, s, Controle.CADENCE, r.cadence(), nowMs, ex, "coups par seconde trop eleves"); + if (regulariteActive) ajouter(verdicts, s, Controle.REGULARITE, r.regularite(), nowMs, ex, "intervalles trop reguliers"); + } + if (cfg.mode(Controle.ATTAQUE_IMPOSSIBLE) != Mode.OFF) { + double pts = AttaqueImpossible.points(etat.utiliseObjet(), !cibleVisible); + ajouter(verdicts, s, Controle.ATTAQUE_IMPOSSIBLE, pts, nowMs, ex, + etat.utiliseObjet() ? "coup en utilisant un objet" : "cible non visible"); + } + return verdicts; + } + + // --- Mouvement -------------------------------------------------------------------------------------- + + /** Un paquet de mouvement vient d'arriver (temps réel en ms, pour mesurer le débit). */ + public List paquetMouvement(UUID joueur, long nowMs, EtatJoueur etat) { + if (cfg.mode(Controle.TIMER) == Mode.OFF) return List.of(); + Exemptions.Resultat ex = Exemptions.evaluer(etat, cfg, Exemptions.Famille.TIMER); + if (ex.exempt()) { + // On ne compte pas les paquets d'une période exemptée : une rafale de rattrapage ne doit pas peser. + suivi(joueur).timer.vider(); + return List.of(); + } + Suivi s = suivi(joueur); + double pts = s.timer.enregistrer(nowMs, cfg, ex.facteur()); + List verdicts = new ArrayList<>(1); + ajouter(verdicts, s, Controle.TIMER, pts, nowMs, ex, "paquets de mouvement trop frequents"); + return verdicts; + } + + // --- Interne ---------------------------------------------------------------------------------------- + + private void ajouter(List sortie, Suivi s, Controle c, double points, long nowMs, + Exemptions.Resultat ex, String details) { + if (points <= 0) return; + Mode mode = cfg.mode(c); + double vl = s.vl.ajouter(c, points, nowMs); + Sanction palier = Paliers.palier(vl, cfg); + Sanction applicable = Paliers.applicable(palier, mode); + boolean notifier = applicable.ordinal() >= Sanction.ALERTE.ordinal() + && s.autoriserAlerte(c, nowMs, DELAI_ALERTE_MS); + sortie.add(new Verdict(c, mode, points, vl, palier, applicable, notifier, details, ex.raisons())); + } +} diff --git a/src/main/java/com/gastinelgarde/core/Paliers.java b/src/main/java/com/gastinelgarde/core/Paliers.java new file mode 100644 index 0000000..c84a2bb --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/Paliers.java @@ -0,0 +1,30 @@ +package com.gastinelgarde.core; + +/** Traduit un nombre de points d'infraction en sanction, en tenant compte du mode du contrôle. */ +public final class Paliers { + + private Paliers() { } + + /** Sanction que mériterait ce nombre de points, plafonnée par {@code sanctionMax}. */ + public static Sanction palier(double vl, GardeConfig cfg) { + Sanction s; + if (vl <= 0) s = Sanction.AUCUNE; + else if (vl < cfg.seuilAlerte) s = Sanction.JOURNAL; + else if (vl < cfg.seuilSetback) s = Sanction.ALERTE; + else if (vl < cfg.seuilExpulsion) s = Sanction.SETBACK; + else s = Sanction.EXPULSION; + return Sanction.min(s, cfg.sanctionMax); + } + + /** + * Sanction réellement applicable : OFF ne fait rien, OBSERVE ne dépasse jamais l'alerte (journal et message + * aux ops, aucun effet sur le joueur), ENFORCE applique le palier. + */ + public static Sanction applicable(Sanction palier, Mode mode) { + return switch (mode) { + case OFF -> Sanction.AUCUNE; + case OBSERVE -> Sanction.min(palier, Sanction.ALERTE); + case ENFORCE -> palier; + }; + } +} diff --git a/src/main/java/com/gastinelgarde/core/RiptideTolerance.java b/src/main/java/com/gastinelgarde/core/RiptideTolerance.java new file mode 100644 index 0000000..7e8d707 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/RiptideTolerance.java @@ -0,0 +1,26 @@ +package com.gastinelgarde.core; + +/** + * Seuil du contrôle vanilla « moved too quickly » pendant un riptide (logique pure, sans Minecraft). + * Repris de GastinelClaims 1.1.6 (décision T6 : le mouvement relève de l'anti-triche). + * + * Vanilla refuse un déplacement si (distance² - vitesse attendue²) dépasse 100 × paquets. Un enchaînement de + * riptides dépasse 30 à 66 blocs par paquet (mesuré le 13/10/2026), d'où les retours en arrière. On relève le + * seuil uniquement pendant le riptide et juste après (l'élan continue), jamais en marche normale. + */ +public final class RiptideTolerance { + + /** 100 blocs par paquet, au carré (60 ne suffisait pas : sauts de 63 et 66 blocs relevés le 13/10). */ + public static final float SEUIL_RIPTIDE = 100f * 100f; + /** L'élan dure encore un peu après la fin de la vrille (2 s). */ + public static final int GRACE_TICKS = 40; + + private RiptideTolerance() { } + + public static float seuil(float seuilVanilla, boolean enVrille, int ticksDepuisVrille) { + if (enVrille || (ticksDepuisVrille >= 0 && ticksDepuisVrille <= GRACE_TICKS)) { + return Math.max(seuilVanilla, SEUIL_RIPTIDE); + } + return seuilVanilla; + } +} diff --git a/src/main/java/com/gastinelgarde/core/Sanction.java b/src/main/java/com/gastinelgarde/core/Sanction.java new file mode 100644 index 0000000..b0580bd --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/Sanction.java @@ -0,0 +1,21 @@ +package com.gastinelgarde.core; + +/** + * Paliers de réaction, du plus doux au plus fort. Il n'y a volontairement aucun bannissement automatique + * (décision D5 / T4 : le bannissement reste une décision humaine). + */ +public enum Sanction { + AUCUNE, JOURNAL, ALERTE, SETBACK, EXPULSION; + + public static Sanction min(Sanction a, Sanction b) { + return a.ordinal() <= b.ordinal() ? a : b; + } + + public static Sanction parse(String texte, Sanction defaut) { + if (texte == null) return defaut; + for (Sanction s : values()) { + if (s.name().equalsIgnoreCase(texte.trim())) return s; + } + return defaut; + } +} diff --git a/src/main/java/com/gastinelgarde/core/Suivi.java b/src/main/java/com/gastinelgarde/core/Suivi.java new file mode 100644 index 0000000..c28e358 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/Suivi.java @@ -0,0 +1,51 @@ +package com.gastinelgarde.core; + +import java.util.EnumMap; +import java.util.Map; + +/** Tout ce que le moteur garde d'un joueur. Libéré à la déconnexion. Coût mémoire constant. */ +public final class Suivi { + + public final VlCompteur vl; + public final CiblesMultiples cibles = new CiblesMultiples(); + public final Cadence cadence = new Cadence(); + public final TimerPaquets timer = new TimerPaquets(); + + // Dernière position jugée valide (retour en arrière). + private boolean positionValide; + private double x, y, z; + private float yaw, pitch; + private String dimension = ""; + + private final Map derniereAlerte = new EnumMap<>(Controle.class); + + public Suivi(double decroissanceParSeconde) { + this.vl = new VlCompteur(decroissanceParSeconde); + } + + public void memoriserPosition(double x, double y, double z, float yaw, float pitch, String dimension) { + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + this.dimension = dimension == null ? "" : dimension; + this.positionValide = true; + } + + public boolean aPositionValide() { return positionValide; } + public double x() { return x; } + public double y() { return y; } + public double z() { return z; } + public float yaw() { return yaw; } + public float pitch() { return pitch; } + public String dimension() { return dimension; } + + /** Vrai si une alerte peut partir maintenant pour ce contrôle (au plus une toutes les {@code delaiMs}). */ + boolean autoriserAlerte(Controle c, long nowMs, long delaiMs) { + Long derniere = derniereAlerte.get(c); + if (derniere != null && nowMs - derniere < delaiMs) return false; + derniereAlerte.put(c, nowMs); + return true; + } +} diff --git a/src/main/java/com/gastinelgarde/core/TimerPaquets.java b/src/main/java/com/gastinelgarde/core/TimerPaquets.java new file mode 100644 index 0000000..fb8165e --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/TimerPaquets.java @@ -0,0 +1,28 @@ +package com.gastinelgarde.core; + +/** + * Contrôle 5 : trop de paquets de mouvement par seconde, soutenu plusieurs secondes (le jeu en envoie 20). + * Les horodatages sont en ms réelles : c'est le débit d'arrivée qu'on mesure. + */ +public final class TimerPaquets { + + private final Fenetre fenetre = new Fenetre(512); + + public double enregistrer(long nowMs, GardeConfig cfg, double facteur) { + fenetre.ajouter(nowMs, 0); + int max = (int) Math.floor(cfg.paquetsParSecondeMax * facteur); + int secondes = Math.max(1, cfg.timerSecondesSoutenues); + int premier = 0; + for (int k = 0; k < secondes; k++) { + long jusqua = nowMs - k * 1000L + 1; + int n = fenetre.compter(jusqua - 1000, jusqua); + if (k == 0) premier = n; + if (n <= max) return 0; + } + return 1.0 + Math.min(3.0, (premier - max) / 10.0); + } + + public void vider() { + fenetre.vider(); + } +} diff --git a/src/main/java/com/gastinelgarde/core/TraceFichier.java b/src/main/java/com/gastinelgarde/core/TraceFichier.java new file mode 100644 index 0000000..fa5a1b0 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/TraceFichier.java @@ -0,0 +1,119 @@ +package com.gastinelgarde.core; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Stream; + +/** + * Écriture des traces JSONL : un fichier par jour (UTC), rotation automatique, durée de conservation et taille + * totale plafonnées (T7 : enregistrement continu pour tous, donc il faut des garde-fous : positions de joueurs, + * donc données personnelles, et volumétrie). + * + * Non thread-safe côté appelant : toutes les méthodes sont synchronisées. + */ +public final class TraceFichier implements AutoCloseable { + + private static final String PREFIXE = "trace-"; + private static final String SUFFIXE = ".jsonl"; + + private final Path dossier; + private final int joursConservation; + private final long tailleMaxOctets; + + private LocalDate jourCourant; + private BufferedWriter ecrivain; + private long octetsEcritsFichier; + + public TraceFichier(Path dossier, int joursConservation, long tailleMaxOctets) throws IOException { + this.dossier = dossier; + this.joursConservation = Math.max(1, joursConservation); + this.tailleMaxOctets = Math.max(1024, tailleMaxOctets); + Files.createDirectories(dossier); + } + + public synchronized void ecrire(long epochMs, String ligne) throws IOException { + LocalDate jour = Instant.ofEpochMilli(epochMs).atZone(ZoneOffset.UTC).toLocalDate(); + if (ecrivain == null || !jour.equals(jourCourant)) { + ouvrir(jour); + purger(jour); + } + ecrivain.write(ligne); + ecrivain.write('\n'); + octetsEcritsFichier += ligne.getBytes(StandardCharsets.UTF_8).length + 1; + } + + public synchronized void flush() throws IOException { + if (ecrivain != null) ecrivain.flush(); + } + + @Override + public synchronized void close() throws IOException { + if (ecrivain != null) { + ecrivain.close(); + ecrivain = null; + } + } + + /** Nom du fichier d'un jour donné (pour les tests et pour /garde). */ + public Path fichierDuJour(LocalDate jour) { + return dossier.resolve(PREFIXE + jour + SUFFIXE); + } + + private void ouvrir(LocalDate jour) throws IOException { + if (ecrivain != null) ecrivain.close(); + Path f = fichierDuJour(jour); + ecrivain = Files.newBufferedWriter(f, StandardCharsets.UTF_8, + StandardOpenOption.CREATE, StandardOpenOption.APPEND); + octetsEcritsFichier = Files.exists(f) ? Files.size(f) : 0; + jourCourant = jour; + } + + /** Supprime les fichiers trop vieux, puis les plus anciens tant que la taille totale dépasse le plafond. */ + private void purger(LocalDate aujourdhui) throws IOException { + List fichiers = new ArrayList<>(); + try (Stream s = Files.list(dossier)) { + s.filter(p -> { + String n = p.getFileName().toString(); + return n.startsWith(PREFIXE) && n.endsWith(SUFFIXE); + }).forEach(fichiers::add); + } + fichiers.sort(Comparator.comparing(p -> p.getFileName().toString())); + + LocalDate limite = aujourdhui.minusDays(joursConservation); + List restants = new ArrayList<>(); + for (Path p : fichiers) { + LocalDate d = dateDe(p); + if (d != null && d.isBefore(limite) && !d.equals(jourCourant)) Files.deleteIfExists(p); + else restants.add(p); + } + + long total = 0; + for (Path p : restants) total += Files.size(p); + for (Path p : restants) { + if (total <= tailleMaxOctets) break; + if (dateDe(p) != null && dateDe(p).equals(jourCourant)) continue; + long t = Files.size(p); + Files.deleteIfExists(p); + total -= t; + } + } + + private static LocalDate dateDe(Path p) { + String n = p.getFileName().toString(); + try { + return LocalDate.parse(n.substring(PREFIXE.length(), n.length() - SUFFIXE.length())); + } catch (RuntimeException e) { + return null; + } + } +} diff --git a/src/main/java/com/gastinelgarde/core/TraceLigne.java b/src/main/java/com/gastinelgarde/core/TraceLigne.java new file mode 100644 index 0000000..6755dd8 --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/TraceLigne.java @@ -0,0 +1,80 @@ +package com.gastinelgarde.core; + +import java.util.Locale; + +/** + * Une ligne de trace JSONL (décision D11 : des seuils mesurés, pas devinés). Format compact, une ligne par + * événement. Les traces servent à rejouer des sessions dans les tests JUnit. + * + * Clés : t tick, j pseudo, ev événement (move, atk, tp, ...), x y z position, vx vy vz vitesse, sc au sol vu par le + * client, ss au sol vu par le serveur, f masque d'exemptions (voir {@link #masque}), c identifiant de la cible, + * a angle excédentaire, n nombre de paquets du dernier tick, m message libre. + */ +public record TraceLigne(long tick, String joueur, String evenement, + double x, double y, double z, double vx, double vy, double vz, + boolean auSolClient, boolean auSolServeur, int masque, + int idCible, double angle, String message) { + + public static final int F_CREATIF = 1, F_SPECTATEUR = 2, F_PEUT_VOLER = 4, F_RIPTIDE = 8, F_ELYTRES = 16, + F_LEVITATION = 32, F_CHUTE_LENTE = 64, F_VEHICULE = 128, F_CONTRAPTION = 256, F_UTILISE_OBJET = 512; + + public static int masque(EtatJoueur e) { + int m = 0; + if (e.creatif()) m |= F_CREATIF; + if (e.spectateur()) m |= F_SPECTATEUR; + if (e.peutVoler()) m |= F_PEUT_VOLER; + if (e.riptide()) m |= F_RIPTIDE; + if (e.elytres()) m |= F_ELYTRES; + if (e.levitation()) m |= F_LEVITATION; + if (e.chuteLente()) m |= F_CHUTE_LENTE; + if (e.enVehicule()) m |= F_VEHICULE; + if (e.pocheContraption()) m |= F_CONTRAPTION; + if (e.utiliseObjet()) m |= F_UTILISE_OBJET; + return m; + } + + public String json() { + StringBuilder sb = new StringBuilder(160); + sb.append("{\"t\":").append(tick) + .append(",\"j\":").append(texte(joueur)) + .append(",\"ev\":").append(texte(evenement)) + .append(",\"x\":").append(nombre(x)) + .append(",\"y\":").append(nombre(y)) + .append(",\"z\":").append(nombre(z)) + .append(",\"vx\":").append(nombre(vx)) + .append(",\"vy\":").append(nombre(vy)) + .append(",\"vz\":").append(nombre(vz)) + .append(",\"sc\":").append(auSolClient ? 1 : 0) + .append(",\"ss\":").append(auSolServeur ? 1 : 0) + .append(",\"f\":").append(masque); + if (idCible >= 0) sb.append(",\"c\":").append(idCible); + if (!Double.isNaN(angle)) sb.append(",\"a\":").append(nombre(angle)); + if (message != null && !message.isEmpty()) sb.append(",\"m\":").append(texte(message)); + return sb.append('}').toString(); + } + + private static String nombre(double v) { + if (Double.isNaN(v) || Double.isInfinite(v)) return "0"; + return String.format(Locale.ROOT, "%.3f", v); + } + + private static String texte(String s) { + if (s == null) return "\"\""; + StringBuilder sb = new StringBuilder(s.length() + 2).append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + switch (c) { + case '"' -> sb.append("\\\""); + case '\\' -> sb.append("\\\\"); + case '\n' -> sb.append("\\n"); + case '\r' -> sb.append("\\r"); + case '\t' -> sb.append("\\t"); + default -> { + if (c < 0x20) sb.append(String.format("\\u%04x", (int) c)); + else sb.append(c); + } + } + } + return sb.append('"').toString(); + } +} diff --git a/src/main/java/com/gastinelgarde/core/Verdict.java b/src/main/java/com/gastinelgarde/core/Verdict.java new file mode 100644 index 0000000..c57119d --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/Verdict.java @@ -0,0 +1,26 @@ +package com.gastinelgarde.core; + +import java.util.List; + +/** + * Résultat d'un contrôle qui a levé une infraction. + * + * @param points points ajoutés par cet événement + * @param vl total du contrôle après ajout (avec décroissance) + * @param palier sanction que mériterait ce total + * @param applicable sanction réellement appliquée compte tenu du mode (OBSERVE ne dépasse jamais l'alerte) + * @param notifier vrai si les ops doivent être prévenus (limité dans le temps pour ne pas spammer) + * @param exemptions exemptions actives au moment du contrôle (information pour le journal) + */ +public record Verdict(Controle controle, Mode mode, double points, double vl, Sanction palier, + Sanction applicable, boolean notifier, String details, List exemptions) { + + /** La plus forte sanction applicable d'une liste de verdicts (AUCUNE si vide). */ + public static Sanction pire(List verdicts) { + Sanction pire = Sanction.AUCUNE; + for (Verdict v : verdicts) { + if (v.applicable().ordinal() > pire.ordinal()) pire = v.applicable(); + } + return pire; + } +} diff --git a/src/main/java/com/gastinelgarde/core/VlCompteur.java b/src/main/java/com/gastinelgarde/core/VlCompteur.java new file mode 100644 index 0000000..6c80b6d --- /dev/null +++ b/src/main/java/com/gastinelgarde/core/VlCompteur.java @@ -0,0 +1,50 @@ +package com.gastinelgarde.core; + +import java.util.EnumMap; +import java.util.Map; + +/** Points d'infraction d'un joueur, par contrôle, avec décroissance linéaire dans le temps. */ +public final class VlCompteur { + + private static final class Etat { + double valeur; + long dernierMs; + } + + private final Map etats = new EnumMap<>(Controle.class); + private final double decroissanceParSeconde; + + public VlCompteur(double decroissanceParSeconde) { + this.decroissanceParSeconde = Math.max(0, decroissanceParSeconde); + } + + /** Ajoute des points et renvoie la nouvelle valeur du contrôle. Un nombre négatif ou nul est ignoré. */ + public double ajouter(Controle c, double points, long nowMs) { + Etat e = etats.computeIfAbsent(c, k -> new Etat()); + e.valeur = decayed(e, nowMs); + e.dernierMs = nowMs; + if (points > 0) e.valeur += points; + return e.valeur; + } + + public double valeur(Controle c, long nowMs) { + Etat e = etats.get(c); + return e == null ? 0 : decayed(e, nowMs); + } + + public double total(long nowMs) { + double t = 0; + for (Etat e : etats.values()) t += decayed(e, nowMs); + return t; + } + + public void remettreAZero() { + etats.clear(); + } + + private double decayed(Etat e, long nowMs) { + if (nowMs <= e.dernierMs) return e.valeur; + double perdu = (nowMs - e.dernierMs) / 1000.0 * decroissanceParSeconde; + return Math.max(0, e.valeur - perdu); + } +} diff --git a/src/main/java/com/gastinelgarde/mixin/MovePacketMixin.java b/src/main/java/com/gastinelgarde/mixin/MovePacketMixin.java new file mode 100644 index 0000000..8b19742 --- /dev/null +++ b/src/main/java/com/gastinelgarde/mixin/MovePacketMixin.java @@ -0,0 +1,39 @@ +package com.gastinelgarde.mixin; + +import com.gastinelgarde.Garde; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** + * Observe les paquets de mouvement et les téléportations. Aucune modification du comportement vanilla : on + * lit seulement (début : débit des paquets ; fin : position acceptée ; teleport : marque de grâce). + */ +@Mixin(ServerGamePacketListenerImpl.class) +public abstract class MovePacketMixin { + + @Shadow public ServerPlayer player; + + @Inject(method = "handleMovePlayer", at = @At("HEAD")) + private void gastinelgarde$avantMouvement(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket packet, + CallbackInfo ci) { + if (player != null) Garde.avantMouvement(player); + } + + @Inject(method = "handleMovePlayer", at = @At("TAIL")) + private void gastinelgarde$apresMouvement(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket packet, + CallbackInfo ci) { + if (player != null) Garde.apresMouvement(player); + } + + // Toute téléportation (commande, mod, perle, setback) passe par cette méthode : on marque le joueur. + @Inject(method = "teleport(DDDFFLjava/util/Set;)V", at = @At("HEAD")) + private void gastinelgarde$marqueTeleport(double x, double y, double z, float yaw, float pitch, + java.util.Set relatifs, CallbackInfo ci) { + if (player != null) Garde.noterTeleport(player); + } +} diff --git a/src/main/java/com/gastinelgarde/mixin/RiptideMoveMixin.java b/src/main/java/com/gastinelgarde/mixin/RiptideMoveMixin.java new file mode 100644 index 0000000..79a6bb3 --- /dev/null +++ b/src/main/java/com/gastinelgarde/mixin/RiptideMoveMixin.java @@ -0,0 +1,81 @@ +package com.gastinelgarde.mixin; + +import com.gastinelgarde.GastinelGarde; +import com.gastinelgarde.core.RiptideTolerance; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.enchantment.EnchantmentHelper; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Constant; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyConstant; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** + * Plus de retour en arrière en enchaînant les riptides (repris de GastinelClaims 1.1.6, décision T6) : seuil + * « moved too quickly » relevé quand le joueur tient un trident Impulsion (ou est en vrille), et 2 s après. + * + * On ne se fie pas seulement à isAutoSpinAttack() : le serveur ne lance la vrille que s'il juge le joueur sous la + * pluie ou dans l'eau (biome, altitude), alors que le client la lance quand même (constaté le 13/10/2026). + * + * ATTENTION au déploiement : GastinelClaims 1.1.6 contient le même mixin. Retirer celui de GastinelClaims + * (1.1.7) avant ou en même temps que de déployer GastinelGarde, sinon le seuil est relevé deux fois (sans + * danger : les deux prennent le maximum, mais le journal de debug est doublé). + */ +@Mixin(ServerGamePacketListenerImpl.class) +public abstract class RiptideMoveMixin { + + @Shadow public ServerPlayer player; + + @Unique private int gastinelgarde$dernierTickRiptide = Integer.MIN_VALUE; + + // 100.0f n'apparaît qu'une fois dans handleMovePlayer (vérifié par javap sur NeoForge 21.1.234) : + // c'est le seuil hors élytres du contrôle « moved too quickly ». + @ModifyConstant(method = "handleMovePlayer", constant = @Constant(floatValue = 100.0F)) + private float gastinelgarde$seuilRiptide(float seuil) { + return gastinelgarde$seuil(seuil); + } + + // 300.0f : même contrôle quand le joueur vole en élytres (riptide + élytres), unique lui aussi dans la méthode. + @ModifyConstant(method = "handleMovePlayer", constant = @Constant(floatValue = 300.0F)) + private float gastinelgarde$seuilRiptideElytres(float seuil) { + return gastinelgarde$seuil(seuil); + } + + @Unique + private float gastinelgarde$seuil(float seuil) { + boolean riptide = player.isAutoSpinAttack() + || gastinelgarde$tridentImpulsion(player.getMainHandItem(), player) + || gastinelgarde$tridentImpulsion(player.getOffhandItem(), player); + if (riptide) gastinelgarde$dernierTickRiptide = player.tickCount; + int depuis = gastinelgarde$dernierTickRiptide == Integer.MIN_VALUE ? -1 : player.tickCount - gastinelgarde$dernierTickRiptide; + float resultat = RiptideTolerance.seuil(seuil, riptide, depuis); + if (resultat != seuil) { + GastinelGarde.LOGGER.debug("[GastinelGarde] riptide : seuil relevé pour {} (vrille={}, depuis={} ticks)", + player.getGameProfile().getName(), player.isAutoSpinAttack(), depuis); + } + return resultat; + } + + /** + * Contrôle anti-vol (allow-flight=false) : après une vrille, le joueur plane encore sur son élan et serait + * expulsé (« Flying is not enabled »). On lui laisse 10 s au lieu de 4 s, seulement juste après un riptide. + */ + @Inject(method = "getMaximumFlyingTicks", at = @At("RETURN"), cancellable = true) + private void gastinelgarde$volApresRiptide(Entity entity, CallbackInfoReturnable cir) { + if (entity != player || gastinelgarde$dernierTickRiptide == Integer.MIN_VALUE) return; + int depuis = player.tickCount - gastinelgarde$dernierTickRiptide; + if (depuis >= 0 && depuis <= RiptideTolerance.GRACE_TICKS) cir.setReturnValue(Math.max(cir.getReturnValue(), 200)); + } + + @Unique + private static boolean gastinelgarde$tridentImpulsion(ItemStack stack, ServerPlayer joueur) { + return stack.is(Items.TRIDENT) && EnchantmentHelper.getTridentSpinAttackStrength(stack, joueur) > 0.0F; + } +} diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..c04e0e1 --- /dev/null +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,29 @@ +modLoader="javafml" +loaderVersion="[1,)" +license="MIT" + +[[mods]] +modId="gastinelgarde" +version="0.1.0" +displayName="GastinelGarde" +authors="Théo Gastinel" +description='''Anti-triche maison : contrôles de combat et de cadence (phase 1), points d'infraction avec décroissance, setback puis expulsion, jamais de bannissement automatique. Mod côté serveur uniquement.''' +# Les clients n'ont pas besoin du mod : ne pas exiger sa présence côté client. +displayTest="IGNORE_ALL_VERSION" + +[[dependencies.gastinelgarde]] + modId="neoforge" + type="required" + versionRange="[21.1,)" + ordering="NONE" + side="SERVER" + +[[dependencies.gastinelgarde]] + modId="minecraft" + type="required" + versionRange="[1.21.1,1.21.2)" + ordering="NONE" + side="SERVER" + +[[mixins]] +config="gastinelgarde.mixins.json" diff --git a/src/main/resources/gastinelgarde.mixins.json b/src/main/resources/gastinelgarde.mixins.json new file mode 100644 index 0000000..5e51266 --- /dev/null +++ b/src/main/resources/gastinelgarde.mixins.json @@ -0,0 +1,8 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "com.gastinelgarde.mixin", + "compatibilityLevel": "JAVA_21", + "mixins": ["MovePacketMixin", "RiptideMoveMixin"], + "injectors": {"defaultRequire": 1} +} diff --git a/src/test/java/com/gastinelgarde/MixinsAppliquesTest.java b/src/test/java/com/gastinelgarde/MixinsAppliquesTest.java new file mode 100644 index 0000000..4ad287b --- /dev/null +++ b/src/test/java/com/gastinelgarde/MixinsAppliquesTest.java @@ -0,0 +1,22 @@ +package com.gastinelgarde; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; + +/** + * Charge la classe visée par les mixins avec le transformateur actif : si une injection ne trouve pas sa cible + * (nom de méthode, descripteur, constante absente), Mixin lève une erreur ici plutôt qu'au démarrage du serveur + * (injecteurs en defaultRequire = 1). + */ +class MixinsAppliquesTest { + + @Test + void lesMixinsDeLaCouchePaquetsSAppliquent() throws Exception { + Class c = Class.forName("net.minecraft.server.network.ServerGamePacketListenerImpl", false, + getClass().getClassLoader()); + assertNotNull(c); + // Force le chargement complet (liaison) de la classe transformée. + c.getDeclaredMethods(); + } +} diff --git a/src/test/java/com/gastinelgarde/core/ControlesTest.java b/src/test/java/com/gastinelgarde/core/ControlesTest.java new file mode 100644 index 0000000..421bab2 --- /dev/null +++ b/src/test/java/com/gastinelgarde/core/ControlesTest.java @@ -0,0 +1,226 @@ +package com.gastinelgarde.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class ControlesTest { + + private final GardeConfig cfg = new GardeConfig(); + + // --- Fenetre --- + + @Test + void fenetreCirculaire() { + Fenetre f = new Fenetre(3); + for (int i = 1; i <= 4; i++) f.ajouter(i * 100L, i); + assertEquals(3, f.taille()); + assertEquals(200, f.temps(0)); + assertEquals(4, f.valeur(2)); + assertEquals(2, f.compter(200, 400)); + f.vider(); + assertEquals(0, f.taille()); + } + + // --- Angle --- + + private static double excedent(double lx, double lz) { + // Œil en (0,0,0), cible de 0,6 × 1,8 à 4 blocs sur +x. + return KillauraAngle.excedentDegres(0, 0, 0, lx, 0, lz, 4.0, -0.9, -0.3, 4.6, 0.9, 0.3); + } + + @Test + void angleRegardDroitSurLaCible() { + assertEquals(0.0, excedent(1, 0), 1e-6); + } + + @Test + void angleLegerementDecaleResteDansLaSilhouette() { + double a = Math.toRadians(10); + assertEquals(0.0, excedent(Math.cos(a), Math.sin(a)), 1e-6); + } + + @Test + void angleDansLeDosEstGrand() { + assertTrue(excedent(-1, 0) > 150); + assertTrue(KillauraAngle.points(excedent(-1, 0), cfg.angleMaxDegres) >= 4.0 - 1e-9); + } + + @Test + void angleOeilDansLaBoiteOuRegardNul() { + assertEquals(0.0, KillauraAngle.excedentDegres(4.3, 0, 0, -1, 0, 0, 4.0, -0.9, -0.3, 4.6, 0.9, 0.3), 1e-9); + assertEquals(0.0, KillauraAngle.excedentDegres(0, 0, 0, 0, 0, 0, 4.0, -0.9, -0.3, 4.6, 0.9, 0.3), 1e-9); + } + + @Test + void pointsAngle() { + assertEquals(0.0, KillauraAngle.points(0, 60), 1e-9); + assertEquals(0.0, KillauraAngle.points(60, 60), 1e-9); + assertEquals(2.0, KillauraAngle.points(90, 60), 1e-9); + assertEquals(4.0, KillauraAngle.points(300, 60), 1e-9); + } + + // --- Cibles multiples --- + + @Test + void troisCiblesDifferentesSontNormales() { + CiblesMultiples c = new CiblesMultiples(); + assertEquals(0, c.enregistrer(0, 1, cfg, 1.0), 1e-9); + assertEquals(0, c.enregistrer(100, 2, cfg, 1.0), 1e-9); + assertEquals(0, c.enregistrer(200, 3, cfg, 1.0), 1e-9); + } + + @Test + void quatriemeCibleEnUneSeconde() { + CiblesMultiples c = new CiblesMultiples(); + c.enregistrer(0, 1, cfg, 1.0); + c.enregistrer(100, 2, cfg, 1.0); + c.enregistrer(200, 3, cfg, 1.0); + assertEquals(1.0, c.enregistrer(300, 4, cfg, 1.0), 1e-9); + } + + @Test + void memeCibleAutantDeFoisQueVoulu() { + CiblesMultiples c = new CiblesMultiples(); + for (int i = 0; i < 30; i++) assertEquals(0, c.enregistrer(i * 20L, 7, cfg, 1.0), 1e-9); + } + + @Test + void ciblesEtaleesDansLeTemps() { + CiblesMultiples c = new CiblesMultiples(); + for (int i = 0; i < 10; i++) assertEquals(0, c.enregistrer(i * 1500L, i, cfg, 1.0), 1e-9); + } + + @Test + void laToleranceDuLagRelevaLeSeuil() { + CiblesMultiples c = new CiblesMultiples(); + for (int i = 0; i < 4; i++) assertEquals(0, c.enregistrer(i * 100L, i, cfg, 1.5), 1e-9); + assertEquals(1.0, c.enregistrer(400, 4, cfg, 1.5), 1e-9); + } + + // --- Cadence --- + + @Test + void cadenceNormaleSansInfraction() { + Cadence c = new Cadence(); + for (int i = 0; i < 30; i++) { + Cadence.Resultat r = c.enregistrer(i * 600L, cfg, 1.0); + assertEquals(0, r.cadence(), 1e-9); + assertEquals(0, r.regularite(), 1e-9); + } + } + + @Test + void cadenceFolleSoutenue() { + Cadence c = new Cadence(); + double dernier = 0; + double premier = -1; + for (long t = 0; t <= 2000; t += 40) { + double p = c.enregistrer(t, cfg, 1.0).cadence(); + if (premier < 0) premier = p; + dernier = p; + } + assertEquals(0, premier, 1e-9); + assertEquals(2.0, dernier, 1e-9); + } + + @Test + void rafaleCourteNEstPasUneInfractionDeCadence() { + Cadence c = new Cadence(); + double max = 0; + for (long t = 0; t < 700; t += 40) max = Math.max(max, c.enregistrer(t, cfg, 1.0).cadence()); + assertEquals(0, max, 1e-9); + } + + @Test + void regulariteParfaiteARythmeRapide() { + Cadence c = new Cadence(); + double derniere = 0; + for (int i = 0; i < 15; i++) derniere = c.enregistrer(i * 100L, cfg, 1.0).regularite(); + assertEquals(2.0, derniere, 1e-9); + } + + @Test + void regulariteAvecUnPeuDeBruit() { + Cadence c = new Cadence(); + double derniere = 0; + long t = 0; + for (int i = 0; i < 15; i++) { + t += (i % 2 == 0) ? 95 : 105; + derniere = c.enregistrer(t, cfg, 1.0).regularite(); + } + assertEquals(1.0, derniere, 1e-9); + } + + @Test + void intervallesVariablesNeSontPasSuspects() { + Cadence c = new Cadence(); + double derniere = 0; + long t = 0; + for (int i = 0; i < 15; i++) { + t += (i % 2 == 0) ? 80 : 160; + derniere = c.enregistrer(t, cfg, 1.0).regularite(); + } + assertEquals(0, derniere, 1e-9); + } + + @Test + void armeALentCadenceFixeNEstPasSuspecte() { + Cadence c = new Cadence(); + double max = 0; + for (int i = 0; i < 30; i++) max = Math.max(max, c.enregistrer(i * 600L, cfg, 1.0).regularite()); + assertEquals(0, max, 1e-9); + } + + // --- Timer --- + + @Test + void vingtPaquetsParSecondeSontNormaux() { + TimerPaquets t = new TimerPaquets(); + for (long ms = 0; ms < 6000; ms += 50) assertEquals(0, t.enregistrer(ms, cfg, 1.0), 1e-9); + } + + @Test + void timerAttendTroisSecondes() { + TimerPaquets t = new TimerPaquets(); + double a2000 = -1; + double a3000 = -1; + for (long ms = 0; ms <= 3000; ms += 25) { + double p = t.enregistrer(ms, cfg, 1.0); + if (ms == 2000) a2000 = p; + if (ms == 3000) a3000 = p; + } + assertEquals(0, a2000, 1e-9); + assertTrue(a3000 > 0); + } + + @Test + void picCourtNEstPasUnTimer() { + TimerPaquets t = new TimerPaquets(); + double max = 0; + for (long ms = 0; ms < 1000; ms += 25) max = Math.max(max, t.enregistrer(ms, cfg, 1.0)); + for (long ms = 1000; ms < 4000; ms += 50) max = Math.max(max, t.enregistrer(ms, cfg, 1.0)); + assertEquals(0, max, 1e-9); + } + + // --- Attaque impossible --- + + @Test + void attaqueImpossible() { + assertEquals(2.0, AttaqueImpossible.points(true, false), 1e-9); + assertEquals(1.0, AttaqueImpossible.points(false, true), 1e-9); + assertEquals(0.0, AttaqueImpossible.points(false, false), 1e-9); + } + + // --- Riptide --- + + @Test + void riptideRelevantLeSeuilSeulementPendantEtApres() { + assertEquals(100f, RiptideTolerance.seuil(100f, false, -1)); + assertEquals(RiptideTolerance.SEUIL_RIPTIDE, RiptideTolerance.seuil(100f, true, -1)); + assertEquals(RiptideTolerance.SEUIL_RIPTIDE, RiptideTolerance.seuil(100f, false, 40)); + assertEquals(100f, RiptideTolerance.seuil(100f, false, 41)); + assertEquals(RiptideTolerance.SEUIL_RIPTIDE, RiptideTolerance.seuil(300f, true, -1)); + } +} diff --git a/src/test/java/com/gastinelgarde/core/ExemptionsTest.java b/src/test/java/com/gastinelgarde/core/ExemptionsTest.java new file mode 100644 index 0000000..3c40153 --- /dev/null +++ b/src/test/java/com/gastinelgarde/core/ExemptionsTest.java @@ -0,0 +1,83 @@ +package com.gastinelgarde.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.gastinelgarde.core.Exemptions.Famille; +import org.junit.jupiter.api.Test; + +class ExemptionsTest { + + private final GardeConfig cfg = new GardeConfig(); + + @Test + void joueurOrdinaireNonExempte() { + for (Famille f : Famille.values()) { + Exemptions.Resultat r = Exemptions.evaluer(EtatJoueur.normal(), cfg, f); + assertFalse(r.exempt(), f.name()); + assertEquals(1.0, r.facteur(), 1e-9); + } + } + + @Test + void creatifEtSpectateurExemptesPartout() { + for (Famille f : Famille.values()) { + assertTrue(Exemptions.evaluer(EtatJoueur.builder().creatif(true).build(), cfg, f).exempt()); + assertTrue(Exemptions.evaluer(EtatJoueur.builder().spectateur(true).build(), cfg, f).exempt()); + } + } + + @Test + void riptideExempteLeMouvementPasLeCombat() { + EtatJoueur e = EtatJoueur.builder().riptide(true).build(); + assertTrue(Exemptions.evaluer(e, cfg, Famille.MOUVEMENT).exempt()); + assertFalse(Exemptions.evaluer(e, cfg, Famille.COMBAT).exempt()); + assertFalse(Exemptions.evaluer(e, cfg, Famille.TIMER).exempt()); + } + + @Test + void contraptionExempteCombatEtMouvement() { + EtatJoueur e = EtatJoueur.builder().pocheContraption(true).build(); + assertTrue(Exemptions.evaluer(e, cfg, Famille.COMBAT).exempt()); + assertTrue(Exemptions.evaluer(e, cfg, Famille.MOUVEMENT).exempt()); + assertFalse(Exemptions.evaluer(e, cfg, Famille.TIMER).exempt()); + } + + @Test + void teleportationGraceLimitee() { + assertTrue(Exemptions.evaluer(EtatJoueur.builder().ticksDepuisTeleport(10).build(), cfg, Famille.TIMER).exempt()); + assertTrue(Exemptions.evaluer(EtatJoueur.builder().ticksDepuisTeleport(40).build(), cfg, Famille.MOUVEMENT).exempt()); + assertFalse(Exemptions.evaluer(EtatJoueur.builder().ticksDepuisTeleport(41).build(), cfg, Famille.MOUVEMENT).exempt()); + assertFalse(Exemptions.evaluer(EtatJoueur.builder().build(), cfg, Famille.MOUVEMENT).exempt()); + } + + @Test + void reculExempteLeMouvementSeulement() { + EtatJoueur e = EtatJoueur.builder().ticksDepuisRecul(5).build(); + assertTrue(Exemptions.evaluer(e, cfg, Famille.MOUVEMENT).exempt()); + assertFalse(Exemptions.evaluer(e, cfg, Famille.COMBAT).exempt()); + } + + @Test + void gelDuServeurExempteLeTimer() { + EtatJoueur e = EtatJoueur.builder().ticksDepuisGel(60).build(); + assertTrue(Exemptions.evaluer(e, cfg, Famille.TIMER).exempt()); + assertFalse(Exemptions.evaluer(EtatJoueur.builder().ticksDepuisGel(101).build(), cfg, Famille.TIMER).exempt()); + } + + @Test + void lagAugmenteLaTolerance() { + assertEquals(1.5, Exemptions.evaluer(EtatJoueur.builder().tps(15).build(), cfg, Famille.COMBAT).facteur(), 1e-9); + assertEquals(1.5, Exemptions.evaluer(EtatJoueur.builder().pingMs(300).build(), cfg, Famille.COMBAT).facteur(), 1e-9); + assertEquals(1.0, Exemptions.evaluer(EtatJoueur.builder().tps(19.5).pingMs(250).build(), cfg, Famille.COMBAT).facteur(), 1e-9); + } + + @Test + void raisonsListees() { + EtatJoueur e = EtatJoueur.builder().riptide(true).elytres(true).build(); + var r = Exemptions.evaluer(e, cfg, Famille.MOUVEMENT); + assertTrue(r.raisons().contains("riptide")); + assertTrue(r.raisons().contains("elytres")); + } +} diff --git a/src/test/java/com/gastinelgarde/core/MoteurTest.java b/src/test/java/com/gastinelgarde/core/MoteurTest.java new file mode 100644 index 0000000..f1b8586 --- /dev/null +++ b/src/test/java/com/gastinelgarde/core/MoteurTest.java @@ -0,0 +1,152 @@ +package com.gastinelgarde.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class MoteurTest { + + private final GardeConfig cfg = new GardeConfig(); + private final Moteur moteur = new Moteur(cfg); + private final UUID joueur = UUID.randomUUID(); + + @Test + void combattantHonnete() { + for (int i = 0; i < 20; i++) { + List v = moteur.attaque(joueur, i * 600L, EtatJoueur.normal(), 3.0, 42, true); + assertTrue(v.isEmpty(), "coup " + i); + } + } + + @Test + void killauraEnObserveNeDepasseJamaisLAlerte() { + Sanction pire = Sanction.AUCUNE; + double vlFinal = 0; + for (int i = 0; i < 15; i++) { + List v = moteur.attaque(joueur, i * 600L, EtatJoueur.normal(), 150, 42, true); + assertFalse(v.isEmpty()); + for (Verdict x : v) { + assertEquals(Controle.KILLAURA_ANGLE, x.controle()); + assertEquals(Mode.OBSERVE, x.mode()); + vlFinal = x.vl(); + } + Sanction s = Verdict.pire(v); + if (s.ordinal() > pire.ordinal()) pire = s; + } + assertEquals(Sanction.ALERTE, pire); + assertTrue(vlFinal >= cfg.seuilExpulsion, "le palier mérité était bien l'expulsion : vl=" + vlFinal); + } + + @Test + void killauraEnEnforceFinitParExpulser() { + cfg.mode(Controle.KILLAURA_ANGLE, Mode.ENFORCE); + Sanction pire = Sanction.AUCUNE; + for (int i = 0; i < 15; i++) { + Sanction s = Verdict.pire(moteur.attaque(joueur, i * 600L, EtatJoueur.normal(), 150, 42, true)); + if (s.ordinal() > pire.ordinal()) pire = s; + } + assertEquals(Sanction.EXPULSION, pire); + } + + @Test + void sanctionMaxSetbackEmpecheLExpulsion() { + cfg.mode(Controle.KILLAURA_ANGLE, Mode.ENFORCE); + cfg.sanctionMax = Sanction.SETBACK; + Sanction pire = Sanction.AUCUNE; + for (int i = 0; i < 15; i++) { + Sanction s = Verdict.pire(moteur.attaque(joueur, i * 600L, EtatJoueur.normal(), 150, 42, true)); + if (s.ordinal() > pire.ordinal()) pire = s; + } + assertEquals(Sanction.SETBACK, pire); + } + + @Test + void creatifEtContraptionExemptes() { + assertTrue(moteur.attaque(joueur, 0, EtatJoueur.builder().creatif(true).build(), 170, 1, true).isEmpty()); + assertTrue(moteur.attaque(joueur, 0, EtatJoueur.builder().pocheContraption(true).build(), 170, 1, true).isEmpty()); + } + + @Test + void modeOffNeFaitRien() { + for (Controle c : Controle.values()) cfg.mode(c, Mode.OFF); + assertTrue(moteur.attaque(joueur, 0, EtatJoueur.normal(), 170, 1, false).isEmpty()); + assertTrue(moteur.paquetMouvement(joueur, 0, EtatJoueur.normal()).isEmpty()); + } + + @Test + void alertesLimiteesDansLeTemps() { + int notifications = 0; + for (int i = 0; i < 10; i++) { // 10 coups en 1 seconde + for (Verdict v : moteur.attaque(joueur, i * 100L, EtatJoueur.normal(), 150, 42, true)) { + if (v.notifier()) notifications++; + } + } + assertEquals(1, notifications); + } + + @Test + void ciblesMultiplesEtAttaqueImpossibleRemontent() { + EtatJoueur mange = EtatJoueur.builder().utiliseObjet(true).build(); + List v = moteur.attaque(joueur, 0, mange, 0, 1, true); + assertEquals(1, v.size()); + assertEquals(Controle.ATTAQUE_IMPOSSIBLE, v.get(0).controle()); + + UUID autre = UUID.randomUUID(); + boolean cibles = false; + for (int i = 0; i < 6; i++) { + for (Verdict x : moteur.attaque(autre, i * 100L, EtatJoueur.normal(), 0, 100 + i, true)) { + if (x.controle() == Controle.KILLAURA_CIBLES) cibles = true; + } + } + assertTrue(cibles); + } + + @Test + void timerLeveUneInfractionApresTroisSecondes() { + boolean infraction = false; + for (long ms = 0; ms <= 3200; ms += 25) { + if (!moteur.paquetMouvement(joueur, ms, EtatJoueur.normal()).isEmpty()) infraction = true; + } + assertTrue(infraction); + } + + @Test + void timerExempteApresTeleportation() { + EtatJoueur tp = EtatJoueur.builder().ticksDepuisTeleport(5).build(); + for (long ms = 0; ms <= 3200; ms += 25) { + assertTrue(moteur.paquetMouvement(joueur, ms, tp).isEmpty()); + } + } + + @Test + void rafaleDeRattrapageApresGelNEstPasCompteeEnsuite() { + // 3 s à 40 paquets/s pendant un gel (exempté), puis retour à la normale : aucune infraction. + EtatJoueur gel = EtatJoueur.builder().ticksDepuisGel(10).build(); + for (long ms = 0; ms < 3000; ms += 25) moteur.paquetMouvement(joueur, ms, gel); + for (long ms = 3000; ms < 6000; ms += 50) { + assertTrue(moteur.paquetMouvement(joueur, ms, EtatJoueur.normal()).isEmpty()); + } + } + + @Test + void libereLaMemoireDeLaDeconnexion() { + moteur.attaque(joueur, 0, EtatJoueur.normal(), 0, 1, true); + assertEquals(1, moteur.joueursSuivis()); + moteur.retirer(joueur); + assertEquals(0, moteur.joueursSuivis()); + } + + @Test + void positionValideMemorisee() { + Suivi s = moteur.suivi(joueur); + assertFalse(s.aPositionValide()); + s.memoriserPosition(1, 2, 3, 90f, 10f, "minecraft:overworld"); + assertTrue(s.aPositionValide()); + assertEquals(2.0, s.y(), 1e-9); + assertEquals("minecraft:overworld", s.dimension()); + } +} diff --git a/src/test/java/com/gastinelgarde/core/TraceTest.java b/src/test/java/com/gastinelgarde/core/TraceTest.java new file mode 100644 index 0000000..6cdd7c2 --- /dev/null +++ b/src/test/java/com/gastinelgarde/core/TraceTest.java @@ -0,0 +1,93 @@ +package com.gastinelgarde.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.LocalDate; +import java.time.ZoneOffset; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class TraceTest { + + private static long epoch(int jour) { + return LocalDate.of(2026, 10, jour).atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli() + 1000; + } + + @Test + void formatJsonCompact() { + TraceLigne l = new TraceLigne(12, "Theo", "move", 1.5, 64, -2.25, 0.1, 0, 0, true, true, 0, -1, Double.NaN, null); + assertEquals("{\"t\":12,\"j\":\"Theo\",\"ev\":\"move\",\"x\":1.500,\"y\":64.000,\"z\":-2.250," + + "\"vx\":0.100,\"vy\":0.000,\"vz\":0.000,\"sc\":1,\"ss\":1,\"f\":0}", l.json()); + } + + @Test + void champsFacultatifsEtEchappement() { + TraceLigne l = new TraceLigne(1, "ga\"by", "atk", 0, 0, 0, 0, 0, 0, false, false, 9, 77, 12.5, "a\nb"); + String j = l.json(); + assertTrue(j.contains("\"j\":\"ga\\\"by\"")); + assertTrue(j.contains("\"c\":77")); + assertTrue(j.contains("\"a\":12.500")); + assertTrue(j.contains("\"m\":\"a\\nb\"")); + assertFalse(j.contains("\n")); + } + + @Test + void masqueDExemptions() { + EtatJoueur e = EtatJoueur.builder().creatif(true).riptide(true).build(); + assertEquals(TraceLigne.F_CREATIF | TraceLigne.F_RIPTIDE, TraceLigne.masque(e)); + } + + @Test + void ecritureEtRotationQuotidienne(@TempDir Path dir) throws IOException { + try (TraceFichier t = new TraceFichier(dir, 7, 1_000_000)) { + t.ecrire(epoch(10), "{\"a\":1}"); + t.ecrire(epoch(10) + 5, "{\"a\":2}"); + t.ecrire(epoch(11), "{\"a\":3}"); + } + List j10 = Files.readAllLines(dir.resolve("trace-2026-10-10.jsonl")); + List j11 = Files.readAllLines(dir.resolve("trace-2026-10-11.jsonl")); + assertEquals(2, j10.size()); + assertEquals(1, j11.size()); + } + + @Test + void conservationLimitee(@TempDir Path dir) throws IOException { + try (TraceFichier t = new TraceFichier(dir, 2, 1_000_000)) { + t.ecrire(epoch(1), "x"); + t.ecrire(epoch(2), "x"); + t.ecrire(epoch(5), "x"); // limite = 3 oct : les fichiers du 1 et du 2 sont trop vieux + } + assertFalse(Files.exists(dir.resolve("trace-2026-10-01.jsonl"))); + assertFalse(Files.exists(dir.resolve("trace-2026-10-02.jsonl"))); + assertTrue(Files.exists(dir.resolve("trace-2026-10-05.jsonl"))); + } + + @Test + void taillePlafonneeSupprimeLesPlusAnciens(@TempDir Path dir) throws IOException { + String grosse = "y".repeat(1000); + try (TraceFichier t = new TraceFichier(dir, 30, 2500)) { + t.ecrire(epoch(1), grosse); + t.ecrire(epoch(2), grosse); + t.ecrire(epoch(3), grosse); + t.ecrire(epoch(4), grosse); + } + assertFalse(Files.exists(dir.resolve("trace-2026-10-01.jsonl"))); + assertTrue(Files.exists(dir.resolve("trace-2026-10-03.jsonl"))); + assertTrue(Files.exists(dir.resolve("trace-2026-10-04.jsonl"))); + } + + @Test + void ignoreLesFichiersEtrangers(@TempDir Path dir) throws IOException { + Files.writeString(dir.resolve("notes.txt"), "a garder"); + try (TraceFichier t = new TraceFichier(dir, 1, 10_000)) { + t.ecrire(epoch(20), "x"); + } + assertTrue(Files.exists(dir.resolve("notes.txt"))); + } +} diff --git a/src/test/java/com/gastinelgarde/core/VlEtPaliersTest.java b/src/test/java/com/gastinelgarde/core/VlEtPaliersTest.java new file mode 100644 index 0000000..5ef87f7 --- /dev/null +++ b/src/test/java/com/gastinelgarde/core/VlEtPaliersTest.java @@ -0,0 +1,83 @@ +package com.gastinelgarde.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class VlEtPaliersTest { + + @Test + void decroissanceLineaire() { + VlCompteur vl = new VlCompteur(0.5); + assertEquals(4.0, vl.ajouter(Controle.CADENCE, 4, 0), 1e-9); + assertEquals(2.0, vl.valeur(Controle.CADENCE, 4000), 1e-9); + assertEquals(0.0, vl.valeur(Controle.CADENCE, 10000), 1e-9); + } + + @Test + void ajoutApresDecroissance() { + VlCompteur vl = new VlCompteur(0.5); + vl.ajouter(Controle.CADENCE, 4, 0); + assertEquals(5.0, vl.ajouter(Controle.CADENCE, 2, 2000), 1e-9); // 4 - 1 + 2 + } + + @Test + void controlesIndependantsEtTotal() { + VlCompteur vl = new VlCompteur(0); + vl.ajouter(Controle.CADENCE, 2, 0); + vl.ajouter(Controle.TIMER, 3, 0); + assertEquals(2.0, vl.valeur(Controle.CADENCE, 0), 1e-9); + assertEquals(5.0, vl.total(0), 1e-9); + vl.remettreAZero(); + assertEquals(0.0, vl.total(0), 1e-9); + } + + @Test + void pointsNegatifsOuNulsIgnores() { + VlCompteur vl = new VlCompteur(0); + assertEquals(0.0, vl.ajouter(Controle.TIMER, -5, 0), 1e-9); + assertEquals(0.0, vl.ajouter(Controle.TIMER, 0, 0), 1e-9); + } + + @Test + void tempsQuiRecule() { + VlCompteur vl = new VlCompteur(1); + vl.ajouter(Controle.TIMER, 5, 10_000); + assertEquals(5.0, vl.valeur(Controle.TIMER, 5_000), 1e-9); + } + + @Test + void paliersParDefaut() { + GardeConfig c = new GardeConfig(); + assertEquals(Sanction.AUCUNE, Paliers.palier(0, c)); + assertEquals(Sanction.JOURNAL, Paliers.palier(1, c)); + assertEquals(Sanction.JOURNAL, Paliers.palier(4.99, c)); + assertEquals(Sanction.ALERTE, Paliers.palier(5, c)); + assertEquals(Sanction.SETBACK, Paliers.palier(10, c)); + assertEquals(Sanction.EXPULSION, Paliers.palier(20, c)); + } + + @Test + void sanctionMaxPlafonne() { + GardeConfig c = new GardeConfig(); + c.sanctionMax = Sanction.SETBACK; + assertEquals(Sanction.SETBACK, Paliers.palier(100, c)); + } + + @Test + void modeObserveNeDepassePasLAlerte() { + assertEquals(Sanction.ALERTE, Paliers.applicable(Sanction.EXPULSION, Mode.OBSERVE)); + assertEquals(Sanction.JOURNAL, Paliers.applicable(Sanction.JOURNAL, Mode.OBSERVE)); + assertEquals(Sanction.AUCUNE, Paliers.applicable(Sanction.EXPULSION, Mode.OFF)); + assertEquals(Sanction.EXPULSION, Paliers.applicable(Sanction.EXPULSION, Mode.ENFORCE)); + } + + @Test + void analyseTolerante() { + assertEquals(Mode.ENFORCE, Mode.parse(" enforce ", Mode.OFF)); + assertEquals(Mode.OFF, Mode.parse("n'importe quoi", Mode.OFF)); + assertEquals(Controle.TIMER, Controle.parse("TIMER")); + assertEquals(null, Controle.parse("inconnu")); + assertEquals(Sanction.SETBACK, Sanction.parse("setback", Sanction.AUCUNE)); + } +}