Mod GastinelMindPNJ : Mind en PNJ, /msg mind en chuchotement, entrée TAB

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cette révision appartient à :
Theo GastineletClaude Opus 5.5 a révisé 2026-10-08 11:28:00 +02:00
révision c6f61950a3
19 fichiers modifiés
+898

Aucun fichier ne correspond à votre recherche

+22
Voir le fichier
@@ -0,0 +1,22 @@
package com.gastinelmind;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.common.Mod;
import net.neoforged.neoforge.common.NeoForge;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Mod(GastinelMind.MOD_ID)
public class GastinelMind {
public static final String MOD_ID = "gastinelmind";
public static final Logger LOGGER = LoggerFactory.getLogger(GastinelMind.class);
public GastinelMind(IEventBus modEventBus, ModContainer modContainer) {
NeoForge.EVENT_BUS.register(MindChat.class);
NeoForge.EVENT_BUS.register(MindNpc.class);
NeoForge.EVENT_BUS.register(MindTabList.class);
LOGGER.info("[GastinelMind] Mind PNJ chargé.");
}
}
+33
Voir le fichier
@@ -0,0 +1,33 @@
package com.gastinelmind;
import com.gastinelmind.core.MindRequest;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.CommandEvent;
import java.util.Optional;
/**
* Intercepte /msg, /tell, /w mind <texte> : la commande vanilla est annulée, le joueur voit son
* chuchotement, et une ligne marquée part dans le journal serveur pour le pont Python.
*/
public final class MindChat {
@SubscribeEvent(priority = EventPriority.HIGHEST)
public static void onCommand(CommandEvent event) {
ServerPlayer player = event.getParseResults().getContext().getSource().getPlayer();
if (player == null) return; // console, blocs de commande : comportement vanilla
Optional<String> text = MindRequest.parse(event.getParseResults().getReader().getString());
if (text.isEmpty()) return;
event.setCanceled(true);
player.sendSystemMessage(Component.literal("Vous chuchotez à Mind : " + text.get())
.withStyle(ChatFormatting.GRAY, ChatFormatting.ITALIC));
String name = MindRequest.clean(player.getGameProfile().getName());
GastinelMind.LOGGER.info("[GastinelMind] DEMANDE {} {} :: {}", name, player.getUUID(), text.get());
}
}
+44
Voir le fichier
@@ -0,0 +1,44 @@
package com.gastinelmind;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.saveddata.SavedData;
import java.util.UUID;
/** Retient l'UUID du PNJ Mind actuel (data/gastinelmind.dat) : tout autre PNJ marqué est retiré. */
public final class MindData extends SavedData {
private static final String NAME = "gastinelmind";
public static final SavedData.Factory<MindData> FACTORY =
new SavedData.Factory<>(MindData::new, MindData::load, null);
private UUID current;
public static MindData get(MinecraftServer server) {
return server.overworld().getDataStorage().computeIfAbsent(FACTORY, NAME);
}
public UUID current() {
return current;
}
public void setCurrent(UUID uuid) {
current = uuid;
setDirty();
}
static MindData load(CompoundTag tag, HolderLookup.Provider provider) {
MindData data = new MindData();
if (tag.hasUUID("current")) data.current = tag.getUUID("current");
return data;
}
@Override
public CompoundTag save(CompoundTag tag, HolderLookup.Provider provider) {
if (current != null) tag.putUUID("current", current);
return tag;
}
}
+158
Voir le fichier
@@ -0,0 +1,158 @@
package com.gastinelmind;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.tags.DamageTypeTags;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.monster.Evoker;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.Vec3;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.entity.living.LivingIncomingDamageEvent;
import net.neoforged.neoforge.event.entity.living.MobDespawnEvent;
import net.neoforged.neoforge.event.tick.EntityTickEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/** PNJ décoratif : un évocateur « Mind » immobile, invulnérable, qui regarde le joueur le plus proche. */
public final class MindNpc {
public static final String TAG = "gastinel_mind";
private static final String ANCHOR = "gastinel_mind_ancre";
private static final double LOOK_RANGE = 10.0;
// --- Commandes ---
@SubscribeEvent
public static void onRegister(RegisterCommandsEvent event) {
event.getDispatcher().register(Commands.literal("mind")
.requires(s -> s.hasPermission(2))
.then(Commands.literal("spawn").executes(MindNpc::spawn))
.then(Commands.literal("remove").executes(MindNpc::remove)));
}
private static int spawn(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException {
ServerPlayer p = ctx.getSource().getPlayerOrException();
ServerLevel level = p.serverLevel();
int removed = removeAll(p.server);
Evoker mind = EntityType.EVOKER.create(level);
if (mind == null) {
ctx.getSource().sendFailure(Component.literal("Impossible de créer le PNJ."));
return 0;
}
mind.moveTo(p.getX(), p.getY(), p.getZ(), p.getYRot(), 0.0F);
mind.setYHeadRot(p.getYRot());
mind.setYBodyRot(p.getYRot());
mind.setCustomName(Component.literal("Mind"));
mind.setCustomNameVisible(true);
mind.setNoAi(true); // pas d'IA : ni déplacement ni sorts
mind.setInvulnerable(true);
mind.setSilent(true);
mind.setPersistenceRequired();
mind.addTag(TAG);
CompoundTag anchor = new CompoundTag();
anchor.putDouble("x", p.getX());
anchor.putDouble("y", p.getY());
anchor.putDouble("z", p.getZ());
mind.getPersistentData().put(ANCHOR, anchor);
level.addFreshEntity(mind);
MindData.get(p.server).setCurrent(mind.getUUID());
String msg = removed > 0 ? "PNJ Mind déplacé ici." : "PNJ Mind créé ici.";
ctx.getSource().sendSuccess(() -> Component.literal(msg), true);
return 1;
}
private static int remove(CommandContext<CommandSourceStack> ctx) {
MinecraftServer server = ctx.getSource().getServer();
int removed = removeAll(server);
// Un ancien PNJ dans un chunk non chargé sera retiré à son chargement (voir onTick).
MindData.get(server).setCurrent(null);
ctx.getSource().sendSuccess(() -> Component.literal(
removed > 0 ? "PNJ Mind retiré." : "Aucun PNJ Mind chargé."), true);
return 1;
}
/** Retire tous les PNJ Mind chargés, toutes dimensions. */
private static int removeAll(MinecraftServer server) {
List<Entity> found = new ArrayList<>();
for (ServerLevel level : server.getAllLevels()) {
for (Entity e : level.getAllEntities()) {
if (isMind(e)) found.add(e);
}
}
found.forEach(Entity::discard);
return found.size();
}
private static boolean isMind(Entity e) {
return e instanceof Evoker && e.getTags().contains(TAG);
}
// --- Comportement ---
@SubscribeEvent
public static void onTick(EntityTickEvent.Pre event) {
Entity e = event.getEntity();
if (!(e instanceof Evoker mind) || mind.level().isClientSide() || !isMind(mind)) return;
if (mind.tickCount % 5 != 0) return;
MinecraftServer server = mind.getServer();
if (server == null) return;
UUID current = MindData.get(server).current();
if (!mind.getUUID().equals(current)) { // doublon ou PNJ retiré : un seul Mind à la fois
mind.discard();
return;
}
// Reste à sa place (ne peut pas être poussé)
CompoundTag anchor = mind.getPersistentData().getCompound(ANCHOR);
if (anchor.contains("x")) {
Vec3 home = new Vec3(anchor.getDouble("x"), anchor.getDouble("y"), anchor.getDouble("z"));
if (mind.position().distanceToSqr(home) > 0.01) {
mind.teleportTo(home.x, home.y, home.z);
}
mind.setDeltaMovement(Vec3.ZERO);
}
// Tourne la tête vers le joueur le plus proche
Player target = mind.level().getNearestPlayer(mind, LOOK_RANGE);
if (target == null) return;
double dx = target.getX() - mind.getX();
double dz = target.getZ() - mind.getZ();
double dy = target.getEyeY() - mind.getEyeY();
float yaw = (float) (Mth.atan2(dz, dx) * Mth.RAD_TO_DEG) - 90.0F;
float pitch = (float) -(Mth.atan2(dy, Math.sqrt(dx * dx + dz * dz)) * Mth.RAD_TO_DEG);
mind.setYRot(yaw);
mind.setYHeadRot(yaw);
mind.setYBodyRot(yaw);
mind.setXRot(pitch);
}
/** Le serveur est en paisible : sans ça, l'évocateur (monstre) serait retiré aussitôt. */
@SubscribeEvent
public static void onDespawn(MobDespawnEvent event) {
if (isMind(event.getEntity())) event.setResult(MobDespawnEvent.Result.DENY);
}
/** Invulnérable même face aux joueurs en créatif ; seul /kill (dégâts qui ignorent l'invulnérabilité) passe. */
@SubscribeEvent
public static void onDamage(LivingIncomingDamageEvent event) {
if (isMind(event.getEntity()) && !event.getSource().is(DamageTypeTags.BYPASSES_INVULNERABILITY)) {
event.setCanceled(true);
}
}
}
+75
Voir le fichier
@@ -0,0 +1,75 @@
package com.gastinelmind;
import com.gastinelmind.core.MindProfile;
import com.mojang.authlib.properties.PropertyMap;
import io.netty.buffer.Unpooled;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Action;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.GameType;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.OnDatapackSyncEvent;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
import java.util.EnumSet;
/**
* Fausse entrée « Mind » dans la liste TAB de chaque client (aucun vrai joueur côté serveur) :
* le client la propose donc dans l'autocomplétion de /msg. Skin par défaut.
*/
public final class MindTabList {
private static final EnumSet<Action> ACTIONS =
EnumSet.of(Action.ADD_PLAYER, Action.UPDATE_GAME_MODE, Action.UPDATE_LISTED, Action.UPDATE_LATENCY);
@SubscribeEvent
public static void onLogin(PlayerEvent.PlayerLoggedInEvent event) {
if (event.getEntity() instanceof ServerPlayer p) send(p);
}
/** /reload : renvoyer l'entrée à tous les joueurs connectés. */
@SubscribeEvent
public static void onReload(OnDatapackSyncEvent event) {
if (event.getPlayer() == null) event.getPlayerList().getPlayers().forEach(MindTabList::send);
}
/** Vérification au démarrage : le paquet se construit bien (une erreur ici ne bloque pas le serveur). */
@SubscribeEvent
public static void onStarted(ServerStartedEvent event) {
try {
var e = packet(event.getServer().registryAccess()).entries().get(0);
GastinelMind.LOGGER.info("[GastinelMind] Entrée TAB prête : {} {} listée={}", e.profile().getName(), e.profileId(), e.listed());
} catch (Exception ex) {
GastinelMind.LOGGER.error("[GastinelMind] Entrée TAB impossible à construire", ex);
}
}
private static void send(ServerPlayer p) {
p.connection.send(packet(p.server.registryAccess()));
}
/**
* Le paquet n'a de constructeur public que pour un vrai ServerPlayer : on écrit les octets
* au format du protocole (même ordre que ClientboundPlayerInfoUpdatePacket.write) puis on le relit.
*/
static ClientboundPlayerInfoUpdatePacket packet(RegistryAccess access) {
RegistryFriendlyByteBuf buf = new RegistryFriendlyByteBuf(Unpooled.buffer(), access);
try {
buf.writeEnumSet(ACTIONS, Action.class);
buf.writeVarInt(1); // une entrée
buf.writeUUID(MindProfile.ID);
buf.writeUtf(MindProfile.NAME, 16); // ADD_PLAYER : nom + propriétés (aucune = skin par défaut)
ByteBufCodecs.GAME_PROFILE_PROPERTIES.encode(buf, new PropertyMap());
buf.writeVarInt(GameType.SURVIVAL.getId()); // UPDATE_GAME_MODE
buf.writeBoolean(true); // UPDATE_LISTED
buf.writeVarInt(0); // UPDATE_LATENCY
return ClientboundPlayerInfoUpdatePacket.STREAM_CODEC.decode(buf);
} finally {
buf.release();
}
}
}
+13
Voir le fichier
@@ -0,0 +1,13 @@
package com.gastinelmind.core;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
/** Identité fixe de la fausse entrée « Mind » dans la liste des joueurs (TAB). */
public final class MindProfile {
public static final String NAME = "Mind";
public static final UUID ID = UUID.nameUUIDFromBytes("gastinel:mind".getBytes(StandardCharsets.UTF_8));
private MindProfile() { }
}
+40
Voir le fichier
@@ -0,0 +1,40 @@
package com.gastinelmind.core;
import java.util.Locale;
import java.util.Optional;
/** Logique pure : reconnaît « /msg|/tell|/w mind <texte> » et nettoie le texte. */
public final class MindRequest {
public static final String TARGET = "mind";
private MindRequest() { }
/**
* Renvoie le texte nettoyé si la commande est un message privé à Mind, sinon vide.
* Accepte avec ou sans « / » et le préfixe « minecraft: ».
*/
public static Optional<String> parse(String input) {
if (input == null) return Optional.empty();
String s = input.strip();
if (s.startsWith("/")) s = s.substring(1);
String[] parts = s.split("\\s+", 3);
if (parts.length < 3) return Optional.empty();
String cmd = parts[0].toLowerCase(Locale.ROOT);
if (cmd.startsWith("minecraft:")) cmd = cmd.substring("minecraft:".length());
if (!cmd.equals("msg") && !cmd.equals("tell") && !cmd.equals("w")) return Optional.empty();
if (!parts[1].equalsIgnoreCase(TARGET)) return Optional.empty();
String text = clean(parts[2]);
return text.isEmpty() ? Optional.empty() : Optional.of(text);
}
/** Une seule ligne : retours à la ligne et caractères de contrôle -> espace, codes § retirés, espaces réduits. */
public static String clean(String text) {
if (text == null) return "";
String t = text.replaceAll("§.?", "");
t = t.replaceAll("[\\p{Cntrl}\\u0085\\u2028\\u2029]", " ");
return t.replaceAll("\\s+", " ").strip();
}
}
+26
Voir le fichier
@@ -0,0 +1,26 @@
modLoader="javafml"
loaderVersion="[1,)"
license="MIT"
[[mods]]
modId="gastinelmind"
version="1.0.0"
displayName="GastinelMind PNJ"
authors="Théo Gastinel"
description='''Mind devient un PNJ : /msg mind <texte> est transmis à l'IA locale, /mind spawn|remove pour le PNJ évocateur. Mod côté serveur uniquement.'''
# Les clients n'ont pas besoin du mod.
displayTest="IGNORE_ALL_VERSION"
[[dependencies.gastinelmind]]
modId="neoforge"
type="required"
versionRange="[21.1,)"
ordering="NONE"
side="SERVER"
[[dependencies.gastinelmind]]
modId="minecraft"
type="required"
versionRange="[1.21.1,1.21.2)"
ordering="NONE"
side="SERVER"
+18
Voir le fichier
@@ -0,0 +1,18 @@
package com.gastinelmind.core;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class MindProfileTest {
@Test
void uuidStableEtNomValide() {
// Même UUID à chaque démarrage : pas de doublon côté client
assertEquals(MindProfile.ID, java.util.UUID.nameUUIDFromBytes("gastinel:mind".getBytes()));
assertEquals(3, MindProfile.ID.version());
assertTrue(MindProfile.NAME.length() <= 16);
// Le nom suggéré par l'autocomplétion est bien reconnu par l'interception
assertEquals(java.util.Optional.of("salut"), MindRequest.parse("msg " + MindProfile.NAME + " salut"));
}
}
+49
Voir le fichier
@@ -0,0 +1,49 @@
package com.gastinelmind.core;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
class MindRequestTest {
@Test
void reconnaitLesTroisCommandes() {
assertEquals(Optional.of("salut"), MindRequest.parse("msg mind salut"));
assertEquals(Optional.of("salut"), MindRequest.parse("tell mind salut"));
assertEquals(Optional.of("salut"), MindRequest.parse("w mind salut"));
}
@Test
void slashPrefixeEtCasse() {
assertEquals(Optional.of("comment faire du pain ?"), MindRequest.parse("/MSG MiNd comment faire du pain ?"));
assertEquals(Optional.of("ok"), MindRequest.parse("minecraft:tell MIND ok"));
assertEquals(Optional.of("ok"), MindRequest.parse(" /w mind ok "));
}
@Test
void ignoreLesAutresCas() {
assertTrue(MindRequest.parse("msg Steve salut").isEmpty());
assertTrue(MindRequest.parse("msg mindy salut").isEmpty());
assertTrue(MindRequest.parse("msg mind").isEmpty());
assertTrue(MindRequest.parse("msg mind ").isEmpty());
assertTrue(MindRequest.parse("say mind salut").isEmpty());
assertTrue(MindRequest.parse("message mind salut").isEmpty());
assertTrue(MindRequest.parse("").isEmpty());
assertTrue(MindRequest.parse(null).isEmpty());
}
@Test
void nettoyage() {
assertEquals("a b c", MindRequest.clean("a\nb\r\nc"));
assertEquals("rouge", MindRequest.clean("§crouge"));
assertEquals("x y", MindRequest.clean("x\t\u0000 y
"));
assertEquals("", MindRequest.clean(null));
}
@Test
void texteGardeSesCaracteres() {
assertEquals(Optional.of("l'\"épée\" :: {}"), MindRequest.parse("msg mind l'\"épée\" :: {}"));
}
}