10 Commits

Author SHA1 Message Date
skippyall 948741f663 Overlays 2026-05-31 15:06:34 +02:00
skippyall d3c84ac000 More Errors 2026-05-30 14:34:43 +02:00
skippyall 7ed686d8d9 Error & Nullability Spam 2026-05-26 13:45:14 +02:00
skippyall f8eb1578b2 Back to the Future
Fun is still suspended though
2026-05-09 17:04:27 +02:00
skippyall 48a38b87c5 Rename .java to .kt 2026-05-09 17:04:27 +02:00
skippyall bd87a15cf2 You have no choice 2026-05-02 23:33:45 +02:00
skippyall f3c934c619 Gehen Sie zu Kotlin. Gehen Sie nicht über Los und ziehen Sie nicht 200 RM ein.
Migrate some classes to Kotlin, let's see if I will regret
2026-05-02 10:48:13 +02:00
skippyall 71016f9e70 Rename .java to .kt 2026-05-02 10:48:13 +02:00
skippyall 08f9763b83 Go Back! 2026-04-30 23:56:21 +02:00
skippyall e117139a63 Port to 26.1 2026-04-29 17:20:13 +02:00
177 changed files with 2232 additions and 1695 deletions
+1
View File
@@ -1,6 +1,7 @@
# User-specific stuff # User-specific stuff
.idea/ .idea/
urlaub/ urlaub/
.kotlin/
*.iml *.iml
*.ipr *.ipr
-138
View File
@@ -1,138 +0,0 @@
plugins {
id 'net.fabricmc.fabric-loom-remap' version '1.16-SNAPSHOT'
id 'maven-publish'
}
version = project.mod_version
group = project.maven_group
base {
archivesName = project.archives_base_name
}
loom {
accessWidenerPath = file("src/main/resources/minions.accesswidener")
splitEnvironmentSourceSets()
mods {
minions {
sourceSet sourceSets.main
sourceSet sourceSets.client
}
}
runs.forEach {
it.vmArg("-XX:+AllowEnhancedClassRedefinition")
}
}
repositories {
// Add repositories to retrieve artifacts from in here.
// You should only use this when depending on other mods because
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
// for more information about repositories.
maven { url 'https://maven.nucleoid.xyz' }
exclusiveContent {
forRepository {
maven {
name = "Modrinth"
url = "https://api.modrinth.com/maven"
}
}
filter {
includeGroup "maven.modrinth"
}
}
}
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings loom.officialMojangMappings()
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
modImplementation "eu.pb4:polymer-core:${project.polymer_version}"
modImplementation "eu.pb4:polymer-virtual-entity:${project.polymer_version}"
modImplementation "eu.pb4:polymer-resource-pack:${project.polymer_version}"
modLocalRuntime "eu.pb4:polymer-autohost:${project.polymer_version}"
modImplementation include("eu.pb4:sgui:${project.sgui_version}")
modImplementation include("xyz.nucleoid:server-translations-api:${project.server_translations_version}")
implementation include("com.electronwill.night-config:toml:${project.night_config_version}")
modCompileOnly "maven.modrinth:universal-graves:${project.universal_graves_version}"
}
processResources {
inputs.property "version", project.version
inputs.property "minecraft_version", project.minecraft_version
inputs.property "loader_version", project.loader_version
filteringCharset "UTF-8"
filesMatching("fabric.mod.json") {
expand "version": project.version,
"minecraft_version": project.minecraft_version,
"loader_version": project.loader_version
}
}
def targetJavaVersion = 21
tasks.withType(JavaCompile).configureEach {
// ensure that the encoding is set to UTF-8, no matter what the system default is
// this fixes some edge cases with special characters not displaying correctly
// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html
// If Javadoc is generated, this must be specified in that task too.
it.options.encoding = "UTF-8"
if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) {
it.options.release.set(targetJavaVersion)
}
}
java {
def javaVersion = JavaVersion.toVersion(targetJavaVersion)
if (JavaVersion.current() < javaVersion) {
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
}
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this line, sources will not be generated.
withSourcesJar()
}
jar {
from("LICENSE") {
rename { "${it}_${project.archives_base_name}"}
}
from("src/main/resoures/assets/minions/lang") {
include("*")
into("data/minions/lang/")
}
}
// configure the maven publication
publishing {
publications {
maven (MavenPublication) {
from components.java
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
// Add repositories to publish to here.
// Notice: This block does NOT have the same function as the block in the top level.
// The repositories here will be used for publishing your artifact, not for
// retrieving dependencies.
maven {
name = "foxgalaxy"
url = "https://maven.foxgalaxy.de/private"
credentials(PasswordCredentials)
}
}
}
+128
View File
@@ -0,0 +1,128 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
id("net.fabricmc.fabric-loom")
`maven-publish`
id("org.jetbrains.kotlin.jvm") version "2.3.21"
}
version = providers.gradleProperty("mod_version").get()
group = providers.gradleProperty("maven_group").get()
repositories {
// Add repositories to retrieve artifacts from in here.
// You should only use this when depending on other mods because
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
// for more information about repositories.
maven("https://maven.nucleoid.xyz")
exclusiveContent {
forRepository {
maven ("https://api.modrinth.com/maven")
}
filter {
includeGroup("maven.modrinth")
}
}
}
loom {
splitEnvironmentSourceSets()
mods {
register("minions") {
sourceSet(sourceSets.main.get())
sourceSet(sourceSets.getByName("client"))
}
}
for (settings in runs) {
settings.vmArg("-XX:+AllowEnhancedClassRedefinition")
}
accessWidenerPath = file("src/main/resources/minions.classtweaker")
}
dependencies {
// To change the versions see the gradle.properties file
minecraft("com.mojang:minecraft:${providers.gradleProperty("minecraft_version").get()}")
implementation("net.fabricmc:fabric-loader:${providers.gradleProperty("loader_version").get()}")
// Fabric API. This is technically optional, but you probably want it anyway.
implementation("net.fabricmc.fabric-api:fabric-api:${providers.gradleProperty("fabric_api_version").get()}")
implementation("net.fabricmc:fabric-language-kotlin:${providers.gradleProperty("fabric_kotlin_version").get()}")
val polymer_version = providers.gradleProperty("polymer_version").get()
implementation("eu.pb4:polymer-core:${polymer_version}")
implementation("eu.pb4:polymer-virtual-entity:${polymer_version}")
implementation("eu.pb4:polymer-resource-pack:${polymer_version}")
localRuntime("eu.pb4:polymer-autohost:${polymer_version}")
implementation("eu.pb4:sgui:${providers.gradleProperty("sgui_version").get()}")
implementation("xyz.nucleoid:server-translations-api:${providers.gradleProperty("server_translations_version").get()}")
implementation("com.electronwill.night-config:toml:${providers.gradleProperty("night_config_version").get()}")
compileOnly("maven.modrinth:universal-graves:${providers.gradleProperty("universal_graves_version").get()}")
}
tasks.processResources {
val version = version
inputs.property("version", version)
filesMatching("fabric.mod.json") {
expand("version" to version)
}
}
tasks.withType<JavaCompile>().configureEach {
options.release = 25
}
kotlin {
compilerOptions {
jvmTarget = JvmTarget.JVM_25
}
}
java {
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this line, sources will not be generated.
withSourcesJar()
sourceCompatibility = JavaVersion.VERSION_25
targetCompatibility = JavaVersion.VERSION_25
}
tasks.jar {
val projectName = project.name
inputs.property("projectName", projectName)
from("LICENSE") {
rename { "${it}_$projectName" }
}
}
// configure the maven publication
publishing {
publications {
register<MavenPublication>("mavenJava") {
from(components["java"])
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
// Add repositories to publish to here.
// Notice: This block does NOT have the same function as the block in the top level.
// The repositories here will be used for publishing your artifact, not for
// retrieving dependencies.
maven("https://maven.foxgalaxy.de/private") {
name = "foxgalaxy"
credentials(PasswordCredentials::class.java)
}
}
}
+9 -8
View File
@@ -3,9 +3,9 @@ org.gradle.jvmargs=-Xmx1G
# Fabric Properties # Fabric Properties
# check these on https://modmuss50.me/fabric.html # check these on https://modmuss50.me/fabric.html
minecraft_version=1.21.7 loom_version=1.16-SNAPSHOT
loader_version=0.16.14 minecraft_version=26.1.2
yarn_mappings=1.21.7+build.2 loader_version=0.19.2
# Mod Properties # Mod Properties
mod_version = 1.0.0-TEST-1 mod_version = 1.0.0-TEST-1
@@ -14,12 +14,13 @@ org.gradle.jvmargs=-Xmx1G
# Dependencies # Dependencies
# check this on https://modmuss50.me/fabric.html # check this on https://modmuss50.me/fabric.html
fabric_version=0.128.1+1.21.7 fabric_api_version=0.147.0+26.1.2
fabric_kotlin_version=1.13.11+kotlin.2.3.21
polymer_version=0.13.3+1.21.6 polymer_version=0.16.3+26.1.2
sgui_version=1.10.0+1.21.6 sgui_version=2.0.0+26.1
server_translations_version=2.5.1+1.21.5 server_translations_version=3.0.3+26.1
night_config_version=3.8.3 night_config_version=3.8.3
universal_graves_version=3.8.0+1.21.6 universal_graves_version=3.11.0+26.1.2
-9
View File
@@ -1,9 +0,0 @@
pluginManagement {
repositories {
maven {
name = 'Fabric'
url = 'https://maven.fabricmc.net/'
}
gradlePluginPortal()
}
}
+17
View File
@@ -0,0 +1,17 @@
pluginManagement {
repositories {
maven {
name = "Fabric"
url = uri("https://maven.fabricmc.net/")
}
mavenCentral()
gradlePluginPortal()
}
plugins {
id("net.fabricmc.fabric-loom") version providers.gradleProperty("loom_version")
}
}
// Should match your modid
rootProject.name = "minions"
@@ -2,16 +2,11 @@ package io.github.skippyall.minions.client;
import eu.pb4.polymer.networking.api.client.PolymerClientNetworking; import eu.pb4.polymer.networking.api.client.PolymerClientNetworking;
import io.github.skippyall.minions.polymer.VersionSync; import io.github.skippyall.minions.polymer.VersionSync;
import io.github.skippyall.minions.registration.MinionBlocks;
import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.rendering.v1.BlockRenderLayerMap;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
public class MinionsClient implements ClientModInitializer { public class MinionsClient implements ClientModInitializer {
@Override @Override
public void onInitializeClient() { public void onInitializeClient() {
BlockRenderLayerMap.putBlock(MinionBlocks.MINION_TRIGGER_BLOCK, ChunkSectionLayer.TRANSLUCENT);
PolymerClientNetworking.registerCommonHandler(VersionSync.VersionSyncPayload.class, (client, handler, payload) -> {}); PolymerClientNetworking.registerCommonHandler(VersionSync.VersionSyncPayload.class, (client, handler, payload) -> {});
} }
} }
@@ -1,6 +1,7 @@
package io.github.skippyall.minions; package io.github.skippyall.minions;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import org.jspecify.annotations.Nullable;
import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
@@ -15,6 +16,7 @@ public class MinionMixinConfigPlugin implements IMixinConfigPlugin {
} }
@Override @Override
@Nullable
public String getRefMapperConfig() { public String getRefMapperConfig() {
return null; return null;
} }
@@ -34,6 +36,7 @@ public class MinionMixinConfigPlugin implements IMixinConfigPlugin {
public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) {} public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) {}
@Override @Override
@Nullable
public List<String> getMixins() { public List<String> getMixins() {
return null; return null;
} }
@@ -1,16 +1,16 @@
package io.github.skippyall.minions; package io.github.skippyall.minions;
import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils;
import io.github.skippyall.minions.command.MinionsCommand; import io.github.skippyall.minions.command.MinionsCommand;
import io.github.skippyall.minions.docs.DocsManager; import io.github.skippyall.minions.docs.DocsManager;
import io.github.skippyall.minions.minion.MinionPersistentState; import io.github.skippyall.minions.minion.MinionPersistentState;
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer; import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.polymer.VersionSync; import io.github.skippyall.minions.polymer.PolymerRegistration;
import io.github.skippyall.minions.registration.MinionRegistration; import io.github.skippyall.minions.registration.MinionRegistration;
import net.fabricmc.api.ModInitializer; import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.resource.ResourceManagerHelper; import net.fabricmc.fabric.api.resource.v1.ResourceLoader;
import net.minecraft.resources.Identifier;
import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.PackType;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -26,8 +26,6 @@ public class Minions implements ModInitializer {
MinionRegistration.register(); MinionRegistration.register();
VersionSync.register();
ServerLifecycleEvents.SERVER_STARTED.register(server -> { ServerLifecycleEvents.SERVER_STARTED.register(server -> {
MinionPersistentState.get(server).getMinionData().forEach((uuid, data) -> { MinionPersistentState.get(server).getMinionData().forEach((uuid, data) -> {
if(data.isSpawned()) { if(data.isSpawned()) {
@@ -38,8 +36,8 @@ public class Minions implements ModInitializer {
CommandRegistrationCallback.EVENT.register(MinionsCommand::register); CommandRegistrationCallback.EVENT.register(MinionsCommand::register);
PolymerResourcePackUtils.addModAssets(Minions.MOD_ID); PolymerRegistration.register();
ResourceManagerHelper.get(PackType.SERVER_DATA).registerReloadListener(new DocsManager()); ResourceLoader.get(PackType.SERVER_DATA).registerReloadListener(Identifier.fromNamespaceAndPath(Minions.MOD_ID, "docs"), new DocsManager());
} }
} }
@@ -11,13 +11,14 @@ import com.electronwill.nightconfig.core.serde.annotations.SerdeComment;
import com.electronwill.nightconfig.toml.TomlFormat; import com.electronwill.nightconfig.toml.TomlFormat;
import com.electronwill.nightconfig.toml.TomlParser; import com.electronwill.nightconfig.toml.TomlParser;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import org.jspecify.annotations.Nullable;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
public class MinionsConfig { public class MinionsConfig {
private static MinionsConfig INSTANCE; private static @Nullable MinionsConfig INSTANCE;
public Minion minion = new Minion(); public Minion minion = new Minion();
@@ -16,7 +16,7 @@ public class AnalogInputBlock extends Block {
@Override @Override
protected InteractionResult useWithoutItem(BlockState state, Level world, BlockPos pos, Player player, BlockHitResult hit) { protected InteractionResult useWithoutItem(BlockState state, Level world, BlockPos pos, Player player, BlockHitResult hit) {
if(!world.isClientSide) { if(!world.isClientSide()) {
player.getInventory().placeItemBackInInventory(ClipboardItem.createBlockPosReference(world, pos), true); player.getInventory().placeItemBackInInventory(ClipboardItem.createBlockPosReference(world, pos), true);
} }
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.block.input;
import org.jspecify.annotations.NullMarked;
@@ -7,7 +7,9 @@ import io.github.skippyall.minions.registration.MinionBlocks;
import io.github.skippyall.minions.registration.MinionComponentTypes; import io.github.skippyall.minions.registration.MinionComponentTypes;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource; import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionHand;
@@ -30,10 +32,10 @@ public abstract class InstructionBoundBlock extends Block implements EntityBlock
@Override @Override
protected InteractionResult useItemOn(ItemStack stack, BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { protected InteractionResult useItemOn(ItemStack stack, BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
if(stack.get(MinionComponentTypes.REFERENCE) instanceof InstructionClipboard instruction) { if(stack.get(MinionComponentTypes.REFERENCE) instanceof InstructionClipboard instruction && player instanceof ServerPlayer serverPlayer) {
world.getBlockEntity(pos, getBlockEntityType()).ifPresent(be -> { world.getBlockEntity(pos, getBlockEntityType()).ifPresent(be -> {
be.setInstruction(instruction.selectedMinion(), instruction.selectedInstruction()); be.setInstruction(instruction.selectedMinion(), instruction.selectedInstruction());
player.playNotifySound(SoundEvents.NOTE_BLOCK_CHIME.value(), SoundSource.BLOCKS, 1, 1); serverPlayer.connection.send(new ClientboundSoundPacket(SoundEvents.NOTE_BLOCK_CHIME, SoundSource.BLOCKS, pos.getX(), pos.getY(), pos.getZ(), 1, 1, 0));
stack.shrink(1); stack.shrink(1);
}); });
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
@@ -49,8 +51,8 @@ public abstract class InstructionBoundBlock extends Block implements EntityBlock
} }
world.getBlockEntity(pos, getBlockEntityType()).ifPresent(be -> { world.getBlockEntity(pos, getBlockEntityType()).ifPresent(be -> {
String name = MinionPersistentState.get(world.getServer()).getMinionData(be.getMinionUuid()).name(); String name = MinionPersistentState.get(world.getServer()).getMinionData(be.getMinionUuid()).getName();
player.displayClientMessage(Component.translatable("minions.reference.instruction.tooltip", name, be.getInstructionName()), true); player.sendSystemMessage(Component.translatable("minions.reference.instruction.tooltip", be.getInstructionName(), name));
}); });
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
@@ -4,16 +4,18 @@ import io.github.skippyall.minions.listener.BlockEntityMinionListener;
import io.github.skippyall.minions.minion.MinionRuntime; import io.github.skippyall.minions.minion.MinionRuntime;
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer; import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction; import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
import java.util.Optional;
import java.util.UUID;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import org.jspecify.annotations.Nullable;
import java.util.Optional;
import java.util.UUID;
public abstract class InstructionBoundBlockEntity<L extends BlockEntityMinionListener<?>> extends BlockEntity { public abstract class InstructionBoundBlockEntity<L extends BlockEntityMinionListener<?>> extends BlockEntity {
protected UUID minionUuid; protected @Nullable UUID minionUuid;
protected String instructionName = ""; protected String instructionName = "";
public InstructionBoundBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) { public InstructionBoundBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
@@ -27,9 +29,11 @@ public abstract class InstructionBoundBlockEntity<L extends BlockEntityMinionLis
public void removeListener() { public void removeListener() {
if(level instanceof ServerLevel serverWorld) { if(level instanceof ServerLevel serverWorld) {
L listener = getListener(); L listener = getListener();
if(listener != null) {
listener.remove(serverWorld.getServer()); listener.remove(serverWorld.getServer());
} }
} }
}
public void addListener() { public void addListener() {
if(level instanceof ServerLevel serverWorld) { if(level instanceof ServerLevel serverWorld) {
@@ -53,7 +57,7 @@ public abstract class InstructionBoundBlockEntity<L extends BlockEntityMinionLis
return Optional.empty(); return Optional.empty();
} }
public UUID getMinionUuid() { public @Nullable UUID getMinionUuid() {
return minionUuid; return minionUuid;
} }
@@ -69,7 +73,7 @@ public abstract class InstructionBoundBlockEntity<L extends BlockEntityMinionLis
return getMinion().flatMap(this::getInstruction); return getMinion().flatMap(this::getInstruction);
} }
public L getListener() { public @Nullable L getListener() {
return BlockEntityMinionListener.getListener(level, worldPosition, minionUuid, getListenerClass()); return BlockEntityMinionListener.getListener(level, worldPosition, minionUuid, getListenerClass());
} }
} }
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.block.instruction_bound;
import org.jspecify.annotations.NullMarked;
@@ -1,32 +1,14 @@
package io.github.skippyall.minions.block.miniontrigger; package io.github.skippyall.minions.block.miniontrigger;
import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapCodec;
import eu.pb4.polymer.core.api.block.PolymerBlock;
import eu.pb4.polymer.core.api.utils.PolymerClientDecoded;
import eu.pb4.polymer.core.api.utils.PolymerKeepModel;
import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils;
import eu.pb4.polymer.virtualentity.api.BlockWithElementHolder;
import eu.pb4.polymer.virtualentity.api.ElementHolder;
import eu.pb4.polymer.virtualentity.api.elements.ItemDisplayElement;
import io.github.skippyall.minions.Minions;
import io.github.skippyall.minions.block.instruction_bound.InstructionBoundBlock; import io.github.skippyall.minions.block.instruction_bound.InstructionBoundBlock;
import io.github.skippyall.minions.polymer.VersionSync;
import io.github.skippyall.minions.registration.MinionBlocks; import io.github.skippyall.minions.registration.MinionBlocks;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.component.DataComponents;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.DiodeBlock;
import net.minecraft.world.level.block.SupportType; import net.minecraft.world.level.block.SupportType;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.entity.BlockEntityType;
@@ -36,10 +18,10 @@ import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.redstone.Orientation; import net.minecraft.world.level.redstone.Orientation;
import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable; import org.jspecify.annotations.NullMarked;
import xyz.nucleoid.packettweaker.PacketContext; import org.jspecify.annotations.Nullable;
public class MinionTriggerBlock extends InstructionBoundBlock implements PolymerBlock, PolymerKeepModel, PolymerClientDecoded, BlockWithElementHolder { public class MinionTriggerBlock extends InstructionBoundBlock {
public static final MapCodec<MinionTriggerBlock> CODEC = simpleCodec(MinionTriggerBlock::new); public static final MapCodec<MinionTriggerBlock> CODEC = simpleCodec(MinionTriggerBlock::new);
public static final BooleanProperty POWERED = BooleanProperty.create("powered"); public static final BooleanProperty POWERED = BooleanProperty.create("powered");
@@ -71,6 +53,7 @@ public class MinionTriggerBlock extends InstructionBoundBlock implements Polymer
} }
@Override @Override
@NullMarked
protected void neighborChanged(BlockState state, Level world, BlockPos pos, Block sourceBlock, @Nullable Orientation wireOrientation, boolean notify) { protected void neighborChanged(BlockState state, Level world, BlockPos pos, Block sourceBlock, @Nullable Orientation wireOrientation, boolean notify) {
if(!canSurvive(state, world, pos)) { if(!canSurvive(state, world, pos)) {
dropResources(state, world, pos); dropResources(state, world, pos);
@@ -91,7 +74,7 @@ public class MinionTriggerBlock extends InstructionBoundBlock implements Polymer
} }
@Override @Override
protected int getAnalogOutputSignal(BlockState state, Level world, BlockPos pos) { protected int getAnalogOutputSignal(BlockState state, Level world, BlockPos pos, Direction direction) {
return world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).map(MinionTriggerBlockEntity::getComparatorOutput).orElse(0); return world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).map(MinionTriggerBlockEntity::getComparatorOutput).orElse(0);
} }
@@ -104,35 +87,4 @@ public class MinionTriggerBlock extends InstructionBoundBlock implements Polymer
protected BlockEntityType<MinionTriggerBlockEntity> getBlockEntityType() { protected BlockEntityType<MinionTriggerBlockEntity> getBlockEntityType() {
return MinionBlocks.MINION_TRIGGER_BE_TYPE; return MinionBlocks.MINION_TRIGGER_BE_TYPE;
} }
@Override
public BlockState getPolymerBlockState(BlockState state, PacketContext context) {
return VersionSync.isOnClient(context) ? state : net.minecraft.world.level.block.Blocks.COMPARATOR.defaultBlockState().setValue(DiodeBlock.POWERED, state.getValue(POWERED));
}
@Override
public boolean handleMiningOnServer(ItemStack tool, BlockState state, BlockPos pos, ServerPlayer player) {
return false;
}
@Override
public @Nullable ElementHolder createElementHolder(ServerLevel world, BlockPos pos, BlockState initialBlockState) {
ElementHolder holder = new ElementHolder() {
@Override
public boolean startWatching(ServerGamePacketListenerImpl player) {
if(PolymerResourcePackUtils.hasMainPack(player) && !VersionSync.isOnClient(player)) {
return super.startWatching(player);
} else {
return false;
}
}
};
ItemStack stack = new ItemStack(Items.BARRIER);
stack.set(DataComponents.ITEM_MODEL, ResourceLocation.fromNamespaceAndPath(Minions.MOD_ID, "minion_trigger_no_plate_" + (initialBlockState.getValue(MinionTriggerBlock.POWERED) ? "active" : "inactive")));
ItemDisplayElement element = new ItemDisplayElement(stack);
element.setItemDisplayContext(ItemDisplayContext.NONE);
holder.addElement(element);
return holder;
}
} }
@@ -1,25 +0,0 @@
package io.github.skippyall.minions.block.miniontrigger;
import eu.pb4.polymer.core.api.item.PolymerBlockItem;
import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.Block;
import org.jetbrains.annotations.Nullable;
import xyz.nucleoid.packettweaker.PacketContext;
public class MinionTriggerBlockItem extends PolymerBlockItem {
public MinionTriggerBlockItem(Block block, Properties settings, Item polymerItem) {
super(block, settings, polymerItem, true);
}
@Override
public @Nullable ResourceLocation getPolymerItemModel(ItemStack stack, PacketContext context) {
if(PolymerResourcePackUtils.hasMainPack(context)) {
return super.getPolymerItemModel(stack, context);
} else {
return null;
}
}
}
@@ -11,10 +11,11 @@ import io.github.skippyall.minions.program.instruction.ConfiguredInstructionList
import io.github.skippyall.minions.registration.MinionBlocks; import io.github.skippyall.minions.registration.MinionBlocks;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.UUIDUtil; import net.minecraft.core.UUIDUtil;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@@ -82,8 +83,8 @@ public class MinionTriggerMinionListener extends BlockEntityMinionInstructionLis
} }
@Override @Override
public Optional<ResourceLocation> getCodecId() { public Optional<Identifier> getCodecId() {
return Optional.of(ResourceLocation.fromNamespaceAndPath(Minions.MOD_ID, "minion_trigger")); return Optional.of(Identifier.fromNamespaceAndPath(Minions.MOD_ID, "minion_trigger"));
} }
public void updateComparatorsIfLoaded(MinecraftServer server) { public void updateComparatorsIfLoaded(MinecraftServer server) {
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.block.miniontrigger;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.block;
import org.jspecify.annotations.NullMarked;
@@ -2,7 +2,6 @@ package io.github.skippyall.minions.clipboard;
import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder; import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.function.Consumer;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponentGetter; import net.minecraft.core.component.DataComponentGetter;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
@@ -11,6 +10,8 @@ import net.minecraft.world.item.Item;
import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import java.util.function.Consumer;
public record BlockPosClipboard(ResourceKey<Level> world, BlockPos pos) implements Clipboard { public record BlockPosClipboard(ResourceKey<Level> world, BlockPos pos) implements Clipboard {
public static final MapCodec<BlockPosClipboard> CODEC = RecordCodecBuilder.mapCodec(instance -> public static final MapCodec<BlockPosClipboard> CODEC = RecordCodecBuilder.mapCodec(instance ->
instance.group( instance.group(
@@ -3,9 +3,10 @@ package io.github.skippyall.minions.clipboard;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapCodec;
import io.github.skippyall.minions.registration.MinionRegistries; import io.github.skippyall.minions.registration.MinionRegistries;
import java.util.function.Function;
import net.minecraft.world.item.component.TooltipProvider; import net.minecraft.world.item.component.TooltipProvider;
import java.util.function.Function;
public interface Clipboard extends TooltipProvider { public interface Clipboard extends TooltipProvider {
Codec<Clipboard> CODEC = MinionRegistries.CLIPBOARD_TYPES.byNameCodec().dispatch(Clipboard::getCodec, Function.identity()); Codec<Clipboard> CODEC = MinionRegistries.CLIPBOARD_TYPES.byNameCodec().dispatch(Clipboard::getCodec, Function.identity());
@@ -1,45 +1,17 @@
package io.github.skippyall.minions.clipboard; package io.github.skippyall.minions.clipboard;
import eu.pb4.polymer.core.api.item.PolymerItem;
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer; import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.registration.MinionComponentTypes; import io.github.skippyall.minions.registration.MinionComponentTypes;
import io.github.skippyall.minions.registration.MinionItems; import io.github.skippyall.minions.registration.MinionItems;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponents;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import org.jetbrains.annotations.Nullable;
import xyz.nucleoid.packettweaker.PacketContext;
public class ClipboardItem extends Item implements PolymerItem { public class ClipboardItem {
public ClipboardItem(Properties settings) {
super(settings);
}
@Override
public Item getPolymerItem(ItemStack itemStack, PacketContext context) {
return /*VersionSync.isOnClient(context) ? this : */Items.PAPER;
}
@Override
public @Nullable ResourceLocation getPolymerItemModel(ItemStack stack, PacketContext context) {
return null;
}
@Override
public ItemStack getPolymerItemStack(ItemStack itemStack, TooltipFlag tooltipType, PacketContext context) {
ItemStack stack = PolymerItem.super.getPolymerItemStack(itemStack, tooltipType, context);
stack.set(DataComponents.ENCHANTMENT_GLINT_OVERRIDE, true);
return stack;
}
public static ItemStack createInstructionReference(MinionFakePlayer minion, String instructionName) { public static ItemStack createInstructionReference(MinionFakePlayer minion, String instructionName) {
ItemStack stack = new ItemStack(MinionItems.REFERENCE_ITEM); ItemStack stack = new ItemStack(MinionItems.REFERENCE_ITEM);
stack.set(MinionComponentTypes.REFERENCE, new InstructionClipboard(minion.getUUID(), instructionName, minion.getGameProfile().getName())); stack.set(MinionComponentTypes.REFERENCE, new InstructionClipboard(minion.getUUID(), instructionName, minion.getGameProfile().name()));
return stack; return stack;
} }
@@ -3,14 +3,15 @@ package io.github.skippyall.minions.clipboard;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder; import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.UUID;
import java.util.function.Consumer;
import net.minecraft.core.UUIDUtil; import net.minecraft.core.UUIDUtil;
import net.minecraft.core.component.DataComponentGetter; import net.minecraft.core.component.DataComponentGetter;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.TooltipFlag;
import java.util.UUID;
import java.util.function.Consumer;
public record InstructionClipboard(UUID selectedMinion, String selectedInstruction, String visualMinionName) implements Clipboard { public record InstructionClipboard(UUID selectedMinion, String selectedInstruction, String visualMinionName) implements Clipboard {
public static final MapCodec<InstructionClipboard> CODEC = RecordCodecBuilder.mapCodec(instance -> public static final MapCodec<InstructionClipboard> CODEC = RecordCodecBuilder.mapCodec(instance ->
instance.group( instance.group(
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.clipboard;
import org.jspecify.annotations.NullMarked;
@@ -6,10 +6,11 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder; import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import io.github.skippyall.minions.docs.DocsManager; import io.github.skippyall.minions.docs.DocsManager;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.ResourceLocationArgument; import net.minecraft.commands.arguments.IdentifierArgument;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.Identifier;
import java.util.concurrent.CompletableFuture;
import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal; import static net.minecraft.commands.Commands.literal;
@@ -17,7 +18,7 @@ import static net.minecraft.commands.Commands.literal;
public class DocsSubcommand { public class DocsSubcommand {
public static final LiteralArgumentBuilder<CommandSourceStack> DOCS = literal("docs") public static final LiteralArgumentBuilder<CommandSourceStack> DOCS = literal("docs")
.then( .then(
argument("docName", ResourceLocationArgument.id()) argument("docName", IdentifierArgument.id())
.suggests(DocsSubcommand::getSuggestions) .suggests(DocsSubcommand::getSuggestions)
.executes(DocsSubcommand::execute) .executes(DocsSubcommand::execute)
); );
@@ -28,7 +29,7 @@ public class DocsSubcommand {
} }
public static int execute(CommandContext<CommandSourceStack> context) throws CommandSyntaxException { public static int execute(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
ResourceLocation id = ResourceLocationArgument.getId(context, "docName"); Identifier id = IdentifierArgument.getId(context, "docName");
DocsManager.showDocsEntry(context.getSource().getPlayerOrException(), id); DocsManager.showDocsEntry(context.getSource().getPlayerOrException(), id);
return 1; return 1;
} }
@@ -4,10 +4,11 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import io.github.skippyall.minions.minion.MinionData; import io.github.skippyall.minions.minion.MinionData;
import io.github.skippyall.minions.minion.MinionPersistentState; import io.github.skippyall.minions.minion.MinionPersistentState;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import java.util.Collection;
import static net.minecraft.commands.Commands.literal; import static net.minecraft.commands.Commands.literal;
public class ListSubcommand { public class ListSubcommand {
@@ -17,7 +18,7 @@ public class ListSubcommand {
public static int list(CommandContext<CommandSourceStack> context) { public static int list(CommandContext<CommandSourceStack> context) {
Collection<MinionData> minions = MinionPersistentState.get(context.getSource().getServer()).getMinionData().values(); Collection<MinionData> minions = MinionPersistentState.get(context.getSource().getServer()).getMinionData().values();
for (MinionData minion : minions) { for (MinionData minion : minions) {
context.getSource().sendSuccess(() -> Component.literal(minion.name() + "(" + minion.uuid() + "):" + minion.isSpawned()), false); context.getSource().sendSuccess(() -> Component.literal(minion.getName() + "(" + minion.getUuid() + "):" + minion.isSpawned()), false);
} }
return 0; return 0;
} }
@@ -41,7 +41,7 @@ public class MinionArgument {
@Override @Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<CommandSourceStack> context, SuggestionsBuilder builder) throws CommandSyntaxException { public CompletableFuture<Suggestions> getSuggestions(CommandContext<CommandSourceStack> context, SuggestionsBuilder builder) throws CommandSyntaxException {
for (MinionData data : MinionPersistentState.get(context.getSource().getServer()).getMinionDataList()) { for (MinionData data : MinionPersistentState.get(context.getSource().getServer()).getMinionDataList()) {
builder.suggest(data.name()); builder.suggest(data.getName());
} }
return builder.buildFuture(); return builder.buildFuture();
@@ -9,13 +9,15 @@ import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.coordinates.Coordinates; import net.minecraft.commands.arguments.coordinates.Coordinates;
import net.minecraft.commands.arguments.coordinates.Vec3Argument; import net.minecraft.commands.arguments.coordinates.Vec3Argument;
import net.minecraft.server.permissions.Permissions;
import org.jspecify.annotations.Nullable;
import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal; import static net.minecraft.commands.Commands.literal;
public class SpawnSubcommand { public class SpawnSubcommand {
public static final LiteralArgumentBuilder<CommandSourceStack> SPAWN = literal("spawn") public static final LiteralArgumentBuilder<CommandSourceStack> SPAWN = literal("spawn")
.requires(source -> source.hasPermission(2)) .requires(source -> source.permissions().hasPermission(Permissions.COMMANDS_GAMEMASTER))
.then(argument("minion", StringArgumentType.word()) .then(argument("minion", StringArgumentType.word())
.suggests(MinionArgument.SUGGESTION_PROVIDER) .suggests(MinionArgument.SUGGESTION_PROVIDER)
.then(argument("pos", Vec3Argument.vec3()) .then(argument("pos", Vec3Argument.vec3())
@@ -47,7 +49,7 @@ public class SpawnSubcommand {
)) ))
); );
public static int spawnCommand(CommandSourceStack source, String minion, Coordinates pos, boolean force) throws CommandSyntaxException { public static int spawnCommand(CommandSourceStack source, String minion, @Nullable Coordinates pos, boolean force) throws CommandSyntaxException {
MinionData data = MinionArgument.parse(source.getServer(), minion); MinionData data = MinionArgument.parse(source.getServer(), minion);
MinionFakePlayer.spawnMinion(data, source.getLevel(), pos != null ? pos.getPosition(source) : null, pos != null ? pos.getRotation(source) : null, force); MinionFakePlayer.spawnMinion(data, source.getLevel(), pos != null ? pos.getPosition(source) : null, pos != null ? pos.getRotation(source) : null, force);
return 0; return 0;
@@ -3,8 +3,6 @@ package io.github.skippyall.minions.command;
import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import io.github.skippyall.minions.Minions; import io.github.skippyall.minions.Minions;
import java.util.Collection;
import java.util.HashSet;
import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument; import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@@ -13,6 +11,9 @@ import net.minecraft.network.chat.Component;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.Blocks;
import java.util.Collection;
import java.util.HashSet;
import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal; import static net.minecraft.commands.Commands.literal;
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.command;
import org.jspecify.annotations.NullMarked;
@@ -4,11 +4,12 @@ import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder; import com.mojang.serialization.codecs.RecordCodecBuilder;
import io.github.skippyall.minions.registration.MinionRegistries; import io.github.skippyall.minions.registration.MinionRegistries;
import java.util.List;
import java.util.function.Function;
import net.minecraft.core.RegistryAccess; import net.minecraft.core.RegistryAccess;
import net.minecraft.server.dialog.body.DialogBody; import net.minecraft.server.dialog.body.DialogBody;
import java.util.List;
import java.util.function.Function;
public interface DocsEntry { public interface DocsEntry {
Codec<DocsEntry> CODEC = MinionRegistries.DOCS_ENTRY_TYPES.byNameCodec().dispatch(DocsEntry::getCodec, Function.identity()); Codec<DocsEntry> CODEC = MinionRegistries.DOCS_ENTRY_TYPES.byNameCodec().dispatch(DocsEntry::getCodec, Function.identity());
@@ -3,11 +3,11 @@ package io.github.skippyall.minions.docs;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
import com.mojang.serialization.JsonOps; import com.mojang.serialization.JsonOps;
import io.github.skippyall.minions.Minions; import io.github.skippyall.minions.Minions;
import net.fabricmc.fabric.api.resource.SimpleResourceReloadListener; import net.fabricmc.fabric.api.resource.v1.reloader.SimpleReloadListener;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.Identifier;
import net.minecraft.server.dialog.ActionButton; import net.minecraft.server.dialog.ActionButton;
import net.minecraft.server.dialog.CommonButtonData; import net.minecraft.server.dialog.CommonButtonData;
import net.minecraft.server.dialog.CommonDialogData; import net.minecraft.server.dialog.CommonDialogData;
@@ -16,9 +16,10 @@ import net.minecraft.server.dialog.MultiActionDialog;
import net.minecraft.server.dialog.action.StaticAction; import net.minecraft.server.dialog.action.StaticAction;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.StrictJsonParser; import net.minecraft.util.StrictJsonParser;
import net.minecraft.util.Tuple; import net.minecraft.util.Tuple;
import org.jspecify.annotations.Nullable;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import java.util.ArrayList; import java.util.ArrayList;
@@ -27,18 +28,16 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
public class DocsManager implements SimpleResourceReloadListener<Tuple<Map<ResourceLocation, DocsEntry>, DocsTree>> { public class DocsManager extends SimpleReloadListener<Tuple<Map<Identifier, DocsEntry>, DocsTree>> {
private static Map<ResourceLocation, DocsEntry> docs; private static @Nullable Map<Identifier, DocsEntry> docs;
private static DocsTree tree; private static @Nullable DocsTree tree;
public static DocsTree getTree() { public static @Nullable DocsTree getTree() {
return tree; return tree;
} }
public static void showDocsEntry(ServerPlayer player, ResourceLocation id) { public static void showDocsEntry(ServerPlayer player, Identifier id) {
DocsEntry entry = getDocsEntry(id); DocsEntry entry = getDocsEntry(id);
if(entry == null) { if(entry == null) {
return; return;
@@ -48,11 +47,11 @@ public class DocsManager implements SimpleResourceReloadListener<Tuple<Map<Resou
if(tree != null) { if(tree != null) {
DocsTree.DocElement element = tree.getElement(id); DocsTree.DocElement element = tree.getElement(id);
if (element.previous() != null) { if (element.previous() != null) {
ResourceLocation previousId = element.previous().getId(); Identifier previousId = element.previous().getId();
buttons.add(getDialogButton(Component.literal("<- ").append(Component.translatable(getDocsEntry(previousId).getMetadata().titleKey())), previousId.toString())); buttons.add(getDialogButton(Component.literal("<- ").append(Component.translatable(getDocsEntry(previousId).getMetadata().titleKey())), previousId.toString()));
} }
if (element.next() != null) { if (element.next() != null) {
ResourceLocation nextId = element.next().getId(); Identifier nextId = element.next().getId();
buttons.add(getDialogButton(Component.translatable(getDocsEntry(nextId).getMetadata().titleKey()).append(Component.literal(" ->")), nextId.toString())); buttons.add(getDialogButton(Component.translatable(getDocsEntry(nextId).getMetadata().titleKey()).append(Component.literal(" ->")), nextId.toString()));
} }
} }
@@ -87,21 +86,28 @@ public class DocsManager implements SimpleResourceReloadListener<Tuple<Map<Resou
); );
} }
public static DocsEntry getDocsEntry(ResourceLocation id) { public static @Nullable DocsEntry getDocsEntry(Identifier id) {
if(docs != null) {
return docs.get(id); return docs.get(id);
} else {
return null;
}
} }
public static Collection<ResourceLocation> getDocsEntryIds() { public static @Nullable Collection<Identifier> getDocsEntryIds() {
if (docs != null) {
return docs.keySet(); return docs.keySet();
} else {
return null;
}
} }
@Override @Override
public CompletableFuture<Tuple<Map<ResourceLocation, DocsEntry>, DocsTree>> load(ResourceManager resourceManager, Executor executor) { public Tuple<Map<Identifier, DocsEntry>, DocsTree> prepare(SharedState state) {
return CompletableFuture.supplyAsync(() -> { Map<Identifier, Resource> resources = state.resourceManager().listResources("docs", id -> id.getNamespace().equals(Minions.MOD_ID) && id.getPath().endsWith(".json"));
Map<ResourceLocation, Resource> resources = resourceManager.listResources("docs", id -> id.getNamespace().equals(Minions.MOD_ID) && id.getPath().endsWith(".json"));
final DocsTree.BranchElement[] root = {null}; final DocsTree. @Nullable BranchElement[] root = {null};
Map<ResourceLocation, DocsEntry> docsEntries = new HashMap<>(); Map<Identifier, DocsEntry> docsEntries = new HashMap<>();
resources.forEach((id, resource) -> { resources.forEach((id, resource) -> {
try(Reader reader = resource.openAsReader()) { try(Reader reader = resource.openAsReader()) {
if(id.getPath().equals("docs/tree.json")) { if(id.getPath().equals("docs/tree.json")) {
@@ -109,7 +115,7 @@ public class DocsManager implements SimpleResourceReloadListener<Tuple<Map<Resou
.ifSuccess(entry -> root[0] = entry.getFirst()) .ifSuccess(entry -> root[0] = entry.getFirst())
.ifError(error -> Minions.LOGGER.warn("Could not parse docs tree {}: {}", id, error.message())); .ifError(error -> Minions.LOGGER.warn("Could not parse docs tree {}: {}", id, error.message()));
} else { } else {
ResourceLocation docId = ResourceLocation.fromNamespaceAndPath(id.getNamespace(), id.getPath().substring("docs/".length(), id.getPath().length() - ".json".length())); Identifier docId = Identifier.fromNamespaceAndPath(id.getNamespace(), id.getPath().substring("docs/".length(), id.getPath().length() - ".json".length()));
DocsEntry.CODEC.decode(JsonOps.INSTANCE, StrictJsonParser.parse(reader)) DocsEntry.CODEC.decode(JsonOps.INSTANCE, StrictJsonParser.parse(reader))
.ifSuccess(entry -> docsEntries.put(docId, entry.getFirst())) .ifSuccess(entry -> docsEntries.put(docId, entry.getFirst()))
.ifError(error -> Minions.LOGGER.warn("Could not parse docs entry {}: {}", id, error.message())); .ifError(error -> Minions.LOGGER.warn("Could not parse docs entry {}: {}", id, error.message()));
@@ -124,20 +130,11 @@ public class DocsManager implements SimpleResourceReloadListener<Tuple<Map<Resou
} else { } else {
return new Tuple<>(docsEntries, null); return new Tuple<>(docsEntries, null);
} }
}, executor);
} }
@Override @Override
public CompletableFuture<Void> apply(Tuple<Map<ResourceLocation, DocsEntry>, DocsTree> o, ResourceManager resourceManager, Executor executor) { public void apply(Tuple<Map<Identifier, DocsEntry>, DocsTree> o, SharedState state) {
return CompletableFuture.supplyAsync(() -> {
docs = o.getA(); docs = o.getA();
tree = o.getB(); tree = o.getB();
return null;
});
}
@Override
public ResourceLocation getFabricId() {
return ResourceLocation.fromNamespaceAndPath(Minions.MOD_ID, "docs");
} }
} }
@@ -2,15 +2,17 @@ package io.github.skippyall.minions.docs;
import com.mojang.datafixers.util.Either; import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import net.minecraft.resources.Identifier;
import org.jspecify.annotations.Nullable;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
import net.minecraft.resources.ResourceLocation;
public class DocsTree { public class DocsTree {
private final BranchElement root; private final BranchElement root;
private final Map<ResourceLocation, DocElement> entries = new HashMap<>(); private final Map<Identifier, DocElement> entries = new HashMap<>();
public DocsTree(BranchElement root) { public DocsTree(BranchElement root) {
this.root = root; this.root = root;
@@ -29,14 +31,14 @@ public class DocsTree {
return root; return root;
} }
public DocElement getElement(ResourceLocation id) { public DocElement getElement(Identifier id) {
return entries.get(id); return entries.get(id);
} }
public static abstract sealed class Element { public static abstract sealed class Element {
private BranchElement parent; private @Nullable BranchElement parent;
public BranchElement getParent() { public @Nullable BranchElement getParent() {
return parent; return parent;
} }
@@ -44,25 +46,33 @@ public class DocsTree {
this.parent = parent; this.parent = parent;
} }
public DocElement next() { public @Nullable DocElement next() {
if (parent != null) {
return parent.next(this); return parent.next(this);
} else {
return null;
}
} }
public DocElement previous() { public @Nullable DocElement previous() {
if (parent != null) {
return parent.previous(this); return parent.previous(this);
} else {
return null;
}
} }
} }
public static final class DocElement extends Element { public static final class DocElement extends Element {
public static final Codec<DocElement> CODEC = ResourceLocation.CODEC.xmap(DocElement::new, DocElement::getId); public static final Codec<DocElement> CODEC = Identifier.CODEC.xmap(DocElement::new, DocElement::getId);
private final ResourceLocation id; private final Identifier id;
public DocElement(ResourceLocation element) { public DocElement(Identifier element) {
this.id = element; this.id = element;
} }
public ResourceLocation getId() { public Identifier getId() {
return id; return id;
} }
} }
@@ -100,7 +110,7 @@ public class DocsTree {
}; };
} }
public DocElement next(Element current) { public @Nullable DocElement next(Element current) {
int nextIndex = e.indexOf(current) + 1; int nextIndex = e.indexOf(current) + 1;
if(nextIndex < e.size()) { if(nextIndex < e.size()) {
return switch (e.get(nextIndex)) { return switch (e.get(nextIndex)) {
@@ -116,7 +126,7 @@ public class DocsTree {
} }
} }
public DocElement previous(Element current) { public @Nullable DocElement previous(Element current) {
int previousIndex = e.indexOf(current) - 1; int previousIndex = e.indexOf(current) - 1;
if(previousIndex >= 0) { if(previousIndex >= 0) {
return switch (e.get(previousIndex)) { return switch (e.get(previousIndex)) {
@@ -4,26 +4,28 @@ import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec; import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder; import com.mojang.serialization.codecs.RecordCodecBuilder;
import io.github.skippyall.minions.gui.GuiDisplay; import io.github.skippyall.minions.gui.GuiDisplay;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import net.minecraft.core.RegistryAccess; import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries; import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentSerialization; import net.minecraft.network.chat.ComponentSerialization;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.dialog.body.DialogBody; import net.minecraft.server.dialog.body.DialogBody;
import net.minecraft.server.dialog.body.ItemBody; import net.minecraft.server.dialog.body.ItemBody;
import net.minecraft.server.dialog.body.PlainMessage; import net.minecraft.server.dialog.body.PlainMessage;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import org.jspecify.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public record ReferenceEntry(Metadata metadata, ResourceKey<?> object, Component shortDescription, Component longDescription) implements DocsEntry { public record ReferenceEntry(Metadata metadata, ResourceKey<?> object, Component shortDescription, Component longDescription) implements DocsEntry {
private static final Codec<ResourceKey<?>> REGISTRY_KEY_CODEC = RecordCodecBuilder.create(instance -> private static final Codec<ResourceKey<?>> REGISTRY_KEY_CODEC = RecordCodecBuilder.create(instance ->
instance.group( instance.group(
ResourceLocation.CODEC.fieldOf("registry").forGetter(ResourceKey::registry), Identifier.CODEC.fieldOf("registry").forGetter(ResourceKey::registry),
ResourceLocation.CODEC.fieldOf("value").forGetter(ResourceKey::location) Identifier.CODEC.fieldOf("value").forGetter(ResourceKey::identifier)
).apply(instance, (registry, value) -> ResourceKey.create(ResourceKey.createRegistryKey(registry), value)) ).apply(instance, (registry, value) -> ResourceKey.create(ResourceKey.createRegistryKey(registry), value))
); );
@@ -46,28 +48,28 @@ public record ReferenceEntry(Metadata metadata, ResourceKey<?> object, Component
GuiDisplay display = getObjectDisplay(manager); GuiDisplay display = getObjectDisplay(manager);
if(display != null) { if(display != null) {
bodyElements.add(new ItemBody(display.createItemStack(), Optional.empty(), false, false, 16, 16)); bodyElements.add(new ItemBody(display.createItemStackTemplate(), Optional.empty(), false, false, 16, 16));
} }
bodyElements.add(new PlainMessage(Component.translatable(object.location().toLanguageKey(object.registry().getPath())), 200)); bodyElements.add(new PlainMessage(Component.translatable(object.identifier().toLanguageKey(object.registry().getPath())), 200));
bodyElements.add(new PlainMessage(longDescription, 200)); bodyElements.add(new PlainMessage(longDescription, 200));
return bodyElements; return bodyElements;
} }
public GuiDisplay getObjectDisplay(RegistryAccess manager) { public @Nullable GuiDisplay getObjectDisplay(RegistryAccess manager) {
GuiDisplay display = GuiDisplay.DEFAULT_DISPLAY; GuiDisplay display = GuiDisplay.DEFAULT_DISPLAY;
if(object.isFor(Registries.ITEM) || object.isFor(Registries.BLOCK)) { if(object.isFor(Registries.ITEM) || object.isFor(Registries.BLOCK)) {
Item item; Item item;
if(object.isFor(Registries.ITEM)) { if(object.isFor(Registries.ITEM)) {
item = BuiltInRegistries.ITEM.getValue(object.location()); item = BuiltInRegistries.ITEM.getValue(object.identifier());
} else { } else {
item = BuiltInRegistries.BLOCK.getValue(object.location()).asItem(); item = BuiltInRegistries.BLOCK.getValue(object.identifier()).asItem();
} }
if(item != null) { if(item != null) {
display = new GuiDisplay.ItemBased(item); display = new GuiDisplay.ItemBased(item);
} }
} else { } else {
ResourceLocation displayId = object.location().withPrefix(object.registry().getPath() + "/"); Identifier displayId = object.identifier().withPrefix(object.registry().getPath() + "/");
display = GuiDisplay.getGuiDisplay(displayId, manager); display = GuiDisplay.getGuiDisplay(displayId, manager);
} }
return display; return display;
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.docs;
import org.jspecify.annotations.NullMarked;
@@ -1,41 +1,55 @@
package io.github.skippyall.minions.gui; package io.github.skippyall.minions.gui;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import io.github.skippyall.minions.registration.MinionRegistries; import io.github.skippyall.minions.registration.MinionRegistries;
import io.github.skippyall.minions.util.TranslationUtil; import io.github.skippyall.minions.util.TranslationUtil;
import it.unimi.dsi.fastutil.objects.ReferenceSortedSets;
import java.util.Optional;
import java.util.UUID;
import net.minecraft.ChatFormatting; import net.minecraft.ChatFormatting;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess; import net.minecraft.core.RegistryAccess;
import net.minecraft.core.UUIDUtil; import net.minecraft.core.UUIDUtil;
import net.minecraft.core.component.DataComponentPatch;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.core.component.DataComponents; import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.Identifier;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.ItemStackTemplate;
import net.minecraft.world.item.Items; import net.minecraft.world.item.Items;
import net.minecraft.world.item.Rarity; import net.minecraft.world.item.Rarity;
import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.item.component.ResolvableProfile;
import net.minecraft.world.item.component.TooltipDisplay; import net.minecraft.world.item.component.TooltipDisplay;
import java.util.LinkedHashSet;
import java.util.UUID;
public interface GuiDisplay { public interface GuiDisplay {
Codec<GuiDisplay> CODEC = MinionRegistries.GUI_DISPLAY_TYPE.byNameCodec().dispatch(GuiDisplay::getCodec, codec -> codec.fieldOf("data")); Codec<GuiDisplay> CODEC = MinionRegistries.GUI_DISPLAY_TYPE.byNameCodec().dispatch(GuiDisplay::getCodec, codec -> codec.fieldOf("data"));
GuiDisplay DEFAULT_DISPLAY = new ItemBased(Items.BARRIER); GuiDisplay DEFAULT_DISPLAY = new ItemBased(Items.BARRIER);
static GuiDisplay getGuiDisplay(ResourceLocation id, RegistryAccess manager) { TooltipDisplay TOOLTIP_HIDE_ALL_COMPONENTS = createHideAllTooltip();
private static TooltipDisplay createHideAllTooltip() {
LinkedHashSet<DataComponentType<?>> set = new LinkedHashSet<>();
for(DataComponentType<?> type : BuiltInRegistries.DATA_COMPONENT_TYPE) {
if(type != DataComponents.LORE) {
set.add(type);
}
}
return new TooltipDisplay(false, set);
}
static GuiDisplay getGuiDisplay(Identifier id, RegistryAccess manager) {
return manager.lookup(MinionRegistries.GUI_DISPLAY).map(registry -> registry.getValue(id)).orElse(DEFAULT_DISPLAY); return manager.lookup(MinionRegistries.GUI_DISPLAY).map(registry -> registry.getValue(id)).orElse(DEFAULT_DISPLAY);
} }
static <T> GuiDisplay getGuiDisplayFor(Registry<T> registry, T element, RegistryAccess manager) { static <T> GuiDisplay getGuiDisplayFor(Registry<T> registry, T element, RegistryAccess manager) {
ResourceLocation elementId = registry.getKey(element); Identifier elementId = registry.getKey(element);
if(elementId == null) { if(elementId == null) {
return DEFAULT_DISPLAY; return DEFAULT_DISPLAY;
} }
ResourceLocation displayId = elementId.withPrefix(registry.key().location().getPath() + "/"); Identifier displayId = elementId.withPrefix(registry.key().identifier().getPath() + "/");
return getGuiDisplay(displayId, manager); return getGuiDisplay(displayId, manager);
} }
@@ -50,24 +64,29 @@ public interface GuiDisplay {
return stack; return stack;
} }
ItemStack createItemStack(); ItemStackTemplate createItemStackTemplate();
default ItemStack createItemStack() {
return createItemStackTemplate().create();
}
Codec<? extends GuiDisplay> getCodec(); Codec<? extends GuiDisplay> getCodec();
class ModelBased implements GuiDisplay { class ModelBased implements GuiDisplay {
public static final Codec<ModelBased> CODEC = ResourceLocation.CODEC.xmap(ModelBased::new, display -> display.model); public static final Codec<ModelBased> CODEC = Identifier.CODEC.xmap(ModelBased::new, display -> display.model);
private final ResourceLocation model; private final Identifier model;
public ModelBased(ResourceLocation model) { public ModelBased(Identifier model) {
this.model = model; this.model = model;
} }
@Override @Override
public ItemStack createItemStack() { public ItemStackTemplate createItemStackTemplate() {
ItemStack stack = new ItemStack(Items.BARRIER); return new ItemStackTemplate(Items.BARRIER, DataComponentPatch.builder()
stack.set(DataComponents.ITEM_MODEL, model); .set(DataComponents.ITEM_MODEL, model)
return stack; .build()
);
} }
@Override @Override
@@ -86,11 +105,11 @@ public interface GuiDisplay {
} }
@Override @Override
public ItemStack createItemStack() { public ItemStackTemplate createItemStackTemplate() {
ItemStack stack = new ItemStack(item); return new ItemStackTemplate(item, DataComponentPatch.builder()
stack.set(DataComponents.TOOLTIP_DISPLAY, new TooltipDisplay(true, ReferenceSortedSets.emptySet())); .set(DataComponents.TOOLTIP_DISPLAY, TOOLTIP_HIDE_ALL_COMPONENTS)
stack.set(DataComponents.RARITY, Rarity.COMMON); .set(DataComponents.RARITY, Rarity.COMMON)
return stack; .build());
} }
@Override @Override
@@ -109,10 +128,12 @@ public interface GuiDisplay {
} }
@Override @Override
public ItemStack createItemStack() { public ItemStackTemplate createItemStackTemplate() {
ItemStack stack = new ItemStack(Items.PLAYER_HEAD); return new ItemStackTemplate(Items.PLAYER_HEAD, DataComponentPatch.builder()
stack.set(DataComponents.PROFILE, new ResolvableProfile(Optional.empty(), Optional.of(uuid), new PropertyMap())); .set(DataComponents.PROFILE, ResolvableProfile.createUnresolved(uuid))
return stack; .set(DataComponents.TOOLTIP_DISPLAY, TOOLTIP_HIDE_ALL_COMPONENTS)
.build()
);
} }
@Override @Override
@@ -122,17 +143,17 @@ public interface GuiDisplay {
} }
class StackBased implements GuiDisplay { class StackBased implements GuiDisplay {
public static final Codec<StackBased> CODEC = ItemStack.CODEC.xmap(StackBased::new, StackBased::createItemStack); public static final Codec<StackBased> CODEC = ItemStackTemplate.CODEC.xmap(StackBased::new, StackBased::createItemStackTemplate);
private final ItemStack stack; private final ItemStackTemplate template;
public StackBased(ItemStack stack) { public StackBased(ItemStackTemplate template) {
this.stack = stack; this.template = template;
} }
@Override @Override
public ItemStack createItemStack() { public ItemStackTemplate createItemStackTemplate() {
return stack; return template;
} }
@Override @Override
@@ -1,95 +0,0 @@
package io.github.skippyall.minions.gui;
import eu.pb4.sgui.api.elements.GuiElementBuilder;
import eu.pb4.sgui.api.gui.SimpleGui;
import io.github.skippyall.minions.gui.input.TextInput;
import io.github.skippyall.minions.minion.MinionData;
import io.github.skippyall.minions.minion.MinionItem;
import io.github.skippyall.minions.minion.MinionProfileUtils;
import io.github.skippyall.minions.minion.skin.SkinProvider;
import io.github.skippyall.minions.registration.MinionRegistries;
import io.github.skippyall.minions.registration.SkinProviders;
import java.util.Optional;
import net.minecraft.core.component.DataComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.component.ResolvableProfile;
public class MinionLookGui extends SimpleGui {
private ItemStack minionItem;
private SkinProvider currentSkinProvider;
public MinionLookGui(ServerPlayer player, ItemStack minionItem) {
super(MenuType.GENERIC_9x3, player, false);
this.minionItem = minionItem;
this.currentSkinProvider = SkinProviders.NAME;
}
public void update() {
updateName();
updateSkin();
updateSkinProvider();
}
private void updateName() {
setSlot(10, new GuiElementBuilder()
.setItem(Items.OAK_SIGN)
.setName(Component.literal(getData().name()))
.setCallback(() -> {
openRenameGui(player, minionItem);
})
);
}
private void updateSkin() {
GuiElementBuilder builder = new GuiElementBuilder()
.setItem(Items.PLAYER_HEAD)
.setCallback(() -> currentSkinProvider.openSkinMenu(player).thenAccept(skin -> {
MinionItem.setData(player.getServer(), getData().withSkin(skin), minionItem);
}));
if(MinionItem.getData(player.getServer(), minionItem) != null && MinionItem.getData(player.getServer(), minionItem).skin().isPresent()) {
builder.setComponent(DataComponents.PROFILE, new ResolvableProfile(Optional.empty(), Optional.empty(), getData().skin().get()));
}
setSlot(16, builder);
}
private void cycleSkinProvider() {
int currentId = MinionRegistries.SKIN_PROVIDERS.getId(currentSkinProvider);
currentId++;
if(MinionRegistries.SKIN_PROVIDERS.size() == currentId) {
currentId = 0;
}
currentSkinProvider = MinionRegistries.SKIN_PROVIDERS.byId(currentId);
updateSkinProvider();
}
private void updateSkinProvider() {
setSlot(25, new GuiElementBuilder()
.setItem(Items.GREEN_STAINED_GLASS_PANE)
.setComponent(DataComponents.CUSTOM_NAME, currentSkinProvider.getDisplayName())
.setCallback(this::cycleSkinProvider)
);
}
private MinionData getData() {
return MinionItem.getDataOrDefault(player.getServer(), minionItem);
}
public static void open(ServerPlayer player, ItemStack minionItem) {
MinionLookGui gui = new MinionLookGui(player, minionItem);
gui.update();
gui.open();
}
public void openRenameGui(ServerPlayer player, ItemStack minionItem) {
TextInput.inputSync(player, Component.translatable("minions.gui.look.rename.title"), "Minion", name -> MinionProfileUtils.checkMinionNameWithoutPrefix(player.getServer(), name))
.thenAccept(name -> {
MinionItem.setData(player.getServer(), getData().withName(MinionProfileUtils.getPrefix() + name), minionItem);
open();
});
}
}
@@ -0,0 +1,131 @@
package io.github.skippyall.minions.gui
import com.mojang.authlib.GameProfile
import eu.pb4.sgui.api.elements.GuiElementBuilder
import eu.pb4.sgui.api.gui.SimpleGui
import io.github.skippyall.minions.gui.input.TextInput
import io.github.skippyall.minions.minion.MinionData
import io.github.skippyall.minions.minion.MinionItem
import io.github.skippyall.minions.minion.MinionProfileUtils
import io.github.skippyall.minions.minion.skin.SkinProvider
import io.github.skippyall.minions.registration.MinionRegistries
import io.github.skippyall.minions.registration.SkinProviders
import kotlinx.coroutines.future.await
import kotlinx.coroutines.launch
import net.fabricmc.fabric.api.entity.FakePlayer
import net.minecraft.core.component.DataComponents
import net.minecraft.network.chat.Component
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.inventory.MenuType
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.Items
import net.minecraft.world.item.component.ResolvableProfile
import java.util.*
class MinionLookGui(
viewer: ServerPlayer,
private val minionItem: ItemStack
) : MinionsGui(viewer) {
private lateinit var gui: SimpleGui
private var currentSkinProvider: SkinProvider = SkinProviders.NAME
private val data: MinionData
get() = MinionItem.getDataOrDefault(viewer.level().server, minionItem)
init {
open()
}
override fun open() {
gui = object : SimpleGui(MenuType.GENERIC_9x3, viewer, false) {
override fun onPlayerClose(success: Boolean) {
onBackingClosed()
}
}
update()
gui.open()
}
override fun closeBacking() {
gui.close()
}
fun update() {
updateName()
updateSkin()
updateSkinProvider()
}
private fun updateName() {
gui.setSlot(
10, GuiElementBuilder()
.setItem(Items.OAK_SIGN)
.setName(Component.literal(this.data.name))
.setCallback(this::openRenameGui)
)
}
private fun updateSkin() {
val builder = GuiElementBuilder()
.setItem(Items.PLAYER_HEAD)
.setCallback(this::openSkinGui)
if (MinionItem.getData(viewer.level().server, minionItem)?.skin?.isPresent ?: false) {
builder.setComponent(
DataComponents.PROFILE,
ResolvableProfile.createResolved(GameProfile(FakePlayer.DEFAULT_UUID, "", this.data.skin.get()))
)
}
gui.setSlot(16, builder)
}
private fun updateSkinProvider() {
gui.setSlot(
25, GuiElementBuilder()
.setItem(Items.GREEN_STAINED_GLASS_PANE)
.setComponent(DataComponents.CUSTOM_NAME, currentSkinProvider.getDisplayName())
.setCallback(Runnable { this.cycleSkinProvider() })
)
}
fun openSkinGui() {
scope.launch {
val profile = currentSkinProvider.openSkinMenu(this@MinionLookGui).await()
val skin = profile?.resolveProfile(viewer.level().server.services().profileResolver())?.await()
data.skin = Optional.ofNullable(skin?.properties())
updateSkin()
}
}
private fun cycleSkinProvider() {
var currentId = MinionRegistries.SKIN_PROVIDERS.getId(currentSkinProvider)
currentId++
if (MinionRegistries.SKIN_PROVIDERS.size() == currentId) {
currentId = 0
}
currentSkinProvider = MinionRegistries.SKIN_PROVIDERS.byId(currentId)!!
updateSkinProvider()
}
fun openRenameGui() {
scope.launch {
val newName = TextInput.input(
this@MinionLookGui,
Component.translatable("minions.gui.look.rename.title"),
"Minion",
) { name ->
MinionProfileUtils.checkMinionNameWithoutPrefix(viewer.level().server, name)
}.await()
if(newName != null) {
data.name = newName
updateName()
}
}
}
}
@@ -1,65 +0,0 @@
package io.github.skippyall.minions.gui;
import net.minecraft.server.level.ServerPlayer;
import org.jetbrains.annotations.Nullable;
public abstract class MinionsGui {
protected final @Nullable MinionsGui parent;
protected final ServerPlayer viewer;
protected @Nullable MinionsGui child = null;
private boolean open = true;
public MinionsGui(MinionsGui parent) {
this.viewer = parent.viewer;
this.parent = parent;
parent.child = this;
}
public MinionsGui(ServerPlayer viewer) {
this.viewer = viewer;
this.parent = null;
}
public ServerPlayer getViewer() {
return viewer;
}
protected abstract void open();
protected void reopen() {
open();
}
public void onBackingClosed() {
if(child != null && child.open) {
return;
}
close();
}
public void close() {
if(open) {
if(parent != null) {
parent.child = null;
parent.reopen();
}
closeNoOpen(parent == null);
}
}
private void closeNoOpen(boolean closeBacking) {
if(child != null) {
child.closeNoOpen(closeBacking);
}
if(parent != null) {
parent.child = null;
}
if(closeBacking) {
closeBacking();
}
open = false;
}
protected abstract void closeBacking();
}
@@ -0,0 +1,84 @@
package io.github.skippyall.minions.gui
import eu.pb4.sgui.api.elements.GuiElementBuilder
import kotlinx.coroutines.CompletableJob
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import net.minecraft.network.chat.Component
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.item.Items
abstract class MinionsGui {
protected val parent: MinionsGui?
@JvmField
val viewer: ServerPlayer
protected var child: MinionsGui? = null
private var open = true
private val job: CompletableJob
val scope: CoroutineScope
constructor(parent: MinionsGui) {
this.viewer = parent.viewer
this.parent = parent
parent.child = this
job = Job(parent.job)
scope = CoroutineScope(Dispatchers.Unconfined.plus(CoroutineName("MinionsGui")).plus(job))
}
constructor(viewer: ServerPlayer) {
this.viewer = viewer
this.parent = null
job = Job(null)
scope = CoroutineScope(Dispatchers.Unconfined.plus(CoroutineName("MinionsGui")).plus(job))
}
protected abstract fun open()
protected open fun reopen() {
open()
}
fun onBackingClosed() {
if (child != null && child!!.open) {
return
}
close(true)
}
@JvmOverloads
fun close(alreadyClosed: Boolean = false) {
if (open) {
scope.cancel(null)
open = false
if (child != null) {
child!!.close(alreadyClosed)
} else if (!alreadyClosed) {
closeBacking()
}
}
}
fun goBack() {
if (parent != null) {
open = false
parent.child = null
parent.reopen()
close(true)
} else {
close(false)
}
}
fun backButton(): GuiElementBuilder? {
return GuiElementBuilder(Items.MANGROVE_DOOR)
.setName(Component.translatable("gui.back"))
.setCallback(Runnable { this.goBack() })
}
protected abstract fun closeBacking()
}
@@ -2,12 +2,16 @@ package io.github.skippyall.minions.gui;
import eu.pb4.sgui.api.elements.GuiElementBuilder; import eu.pb4.sgui.api.elements.GuiElementBuilder;
import eu.pb4.sgui.api.gui.SimpleGui; import eu.pb4.sgui.api.gui.SimpleGui;
import java.util.List;
import java.util.function.BiFunction;
import net.minecraft.core.IdMap; import net.minecraft.core.IdMap;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.Items; import net.minecraft.world.item.Items;
import org.jspecify.annotations.Nullable;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import java.util.function.Function;
public class PaginatedList extends MinionsGui { public class PaginatedList extends MinionsGui {
private int page = 0; private int page = 0;
@@ -15,6 +19,7 @@ public class PaginatedList extends MinionsGui {
private final Component title; private final Component title;
private final int size; private final int size;
private final BiFunction<Integer, PaginatedList, GuiElementBuilder> display; private final BiFunction<Integer, PaginatedList, GuiElementBuilder> display;
private @Nullable Runnable onClose = null;
public PaginatedList(MinionsGui parent, Component title, int size, BiFunction<Integer, PaginatedList, GuiElementBuilder> display) { public PaginatedList(MinionsGui parent, Component title, int size, BiFunction<Integer, PaginatedList, GuiElementBuilder> display) {
super(parent); super(parent);
@@ -24,15 +29,25 @@ public class PaginatedList extends MinionsGui {
open(); open();
} }
public PaginatedList(MinionsGui parent, Component title, int size, BiFunction<Integer, PaginatedList, GuiElementBuilder> display, Runnable onClose) {
this(parent, title, size, display);
this.onClose = onClose;
}
@Override @Override
protected void open() { protected void open() {
gui = new SimpleGui(MenuType.GENERIC_9x4, viewer, false) { gui = new SimpleGui(MenuType.GENERIC_9x6, viewer, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
onBackingClosed(); onBackingClosed();
if(onClose != null) {
onClose.run();
}
} }
}; };
gui.setTitle(title); gui.setTitle(title);
gui.setSlot(8, backButton());
addItems(); addItems();
gui.open(); gui.open();
} }
@@ -50,13 +65,26 @@ public class PaginatedList extends MinionsGui {
new PaginatedList(parent, title, list.size(), (i, gui) -> display.apply(list.byId(i), gui)); new PaginatedList(parent, title, list.size(), (i, gui) -> display.apply(list.byId(i), gui));
} }
public static <T> CompletableFuture<T> createListFuture(MinionsGui parent, Component title, List<T> list, Function<T, GuiElementBuilder> display) {
CompletableFuture<T> future = new CompletableFuture<>();
new PaginatedList(parent, title, list.size(), (i, me) -> display.apply(list.get(i))
.setCallback(() -> {
future.complete(list.get(i));
me.goBack();
})
);
return future;
}
private void addItems() { private void addItems() {
for(int i = 27 * page; i < Math.min(27 * (page + 1), size); i++) { int slot = 9;
gui.addSlot(display.apply(i, this)); for(int i = 36 * page; i < Math.min(36 * (page + 1), size); i++) {
gui.setSlot(slot, display.apply(i, this));
slot++;
} }
if(page > 0) { if(page > 0) {
gui.setSlot(30, new GuiElementBuilder(Items.SPECTRAL_ARROW) gui.setSlot(48, new GuiElementBuilder(Items.SPECTRAL_ARROW)
.setItemName(Component.translatable("book.page_button.previous")) .setItemName(Component.translatable("book.page_button.previous"))
.setCallback(() -> { .setCallback(() -> {
page--; page--;
@@ -64,11 +92,11 @@ public class PaginatedList extends MinionsGui {
}) })
); );
} else { } else {
gui.clearSlot(30); gui.clearSlot(48);
} }
if(27 * (page + 1) < size) { if(27 * (page + 1) < size) {
gui.setSlot(32, new GuiElementBuilder(Items.ARROW) gui.setSlot(50, new GuiElementBuilder(Items.ARROW)
.setItemName(Component.translatable("book.page_button.next")) .setItemName(Component.translatable("book.page_button.next"))
.setCallback(() -> { .setCallback(() -> {
page++; page++;
@@ -76,7 +104,7 @@ public class PaginatedList extends MinionsGui {
}) })
); );
} else { } else {
gui.clearSlot(32); gui.clearSlot(50);
} }
} }
} }
@@ -0,0 +1,55 @@
package io.github.skippyall.minions.gui.input
import eu.pb4.sgui.api.elements.GuiElementBuilder
import eu.pb4.sgui.api.gui.SimpleGui
import io.github.skippyall.minions.gui.MinionsGui
import io.github.skippyall.minions.gui.minion.SimpleMinionsGui
import net.minecraft.network.chat.Component
import net.minecraft.world.inventory.MenuType
import net.minecraft.world.item.Items
import java.util.concurrent.CompletableFuture
object BooleanInput {
@JvmStatic
@JvmOverloads
fun confirm(
parent: MinionsGui,
title: Component,
falseText: Component = Component.translatable("minions.gui.abort"),
trueText: Component = Component.translatable("minions.gui.confirm")
): CompletableFuture<Boolean> {
val future = CompletableFuture<Boolean>()
SimpleMinionsGui(parent) { onClose: Runnable, me: SimpleMinionsGui ->
val gui: SimpleGui = object : SimpleGui(MenuType.GENERIC_3x3, parent.viewer, false) {
override fun onPlayerClose(success: Boolean) {
future.complete(false)
onClose.run()
}
}
gui.setTitle(title)
gui.setSlot(
3, GuiElementBuilder(Items.REDSTONE_BLOCK)
.setName(falseText)
.setCallback(Runnable {
future.complete(false)
me.goBack()
})
)
gui.setSlot(
5, GuiElementBuilder(Items.EMERALD_BLOCK)
.setName(trueText)
.setCallback(Runnable {
future.complete(true)
me.goBack()
})
)
gui.open()
gui
}
return future
}
}
@@ -1,116 +0,0 @@
package io.github.skippyall.minions.gui.input;
import eu.pb4.sgui.api.elements.GuiElementBuilder;
import eu.pb4.sgui.api.gui.SimpleGui;
import io.github.skippyall.minions.gui.Displayable;
import io.github.skippyall.minions.gui.GuiDisplay;
import io.github.skippyall.minions.gui.MinionsGui;
import io.github.skippyall.minions.gui.minion.SimpleMinionsGui;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import java.util.function.Function;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.Items;
public class ChoiceInput {
public static <T> BiFunction<ServerPlayer, T, CompletableFuture<T>> createDialogOpener(MenuType<?> screen, Component title, Function<T, GuiDisplay> displayFunction, T[] values, @Nullable T fallback) {
return (player, object) -> {
CompletableFuture<T> future = new CompletableFuture<>();
SimpleGui gui = new SimpleGui(screen, player, false) {
@Override
public void onClose() {
if(fallback == null) {
future.cancel(false);
} else {
future.complete(fallback);
}
}
};
gui.setTitle(title);
for(T value : values) {
gui.addSlot(new GuiElementBuilder(displayFunction.apply(value).createItemStack())
.setCallback(() -> future.complete(value))
);
}
gui.open();
return future;
};
}
public static <T extends Displayable> BiFunction<ServerPlayer, T, CompletableFuture<T>> createDialogOpener(T[] values) {
return createDialogOpener(MenuType.GENERIC_9x3, Component.empty(), t -> t != null ? t.getDisplay() : null, values, null);
}
public static CompletableFuture<Void> confirm(ServerPlayer player, Component title) {
CompletableFuture<Void> future = new CompletableFuture<>();
SimpleGui gui = new SimpleGui(MenuType.GENERIC_3x3, player, false) {
@Override
public void onClose() {
future.cancel(false);
}
};
gui.setTitle(title);
gui.setSlot(3, new GuiElementBuilder(Items.REDSTONE_BLOCK)
.setName(Component.translatable("minions.gui.abort"))
.setCallback(() -> future.cancel(false))
);
gui.setSlot(5, new GuiElementBuilder(Items.EMERALD_BLOCK)
.setName(Component.translatable("minions.gui.confirm"))
.setCallback(() -> future.complete(null))
);
gui.open();
return future;
}
public static CompletableFuture<Void> confirm(MinionsGui parent, Component title) {
CompletableFuture<Void> future = new CompletableFuture<>();
new SimpleMinionsGui(parent, (onClose, me) -> {
SimpleGui gui = new SimpleGui(MenuType.GENERIC_3x3, parent.getViewer(), false) {
@Override
public void onClose() {
future.cancel(false);
onClose.run();
}
};
gui.setTitle(title);
gui.setSlot(3, new GuiElementBuilder(Items.REDSTONE_BLOCK)
.setName(Component.translatable("minions.gui.abort"))
.setCallback(() -> future.cancel(false))
);
gui.setSlot(5, new GuiElementBuilder(Items.EMERALD_BLOCK)
.setName(Component.translatable("minions.gui.confirm"))
.setCallback(() -> future.complete(null))
);
gui.open();
return gui;
});
return future;
}
public static BiFunction<ServerPlayer, Boolean, CompletableFuture<Boolean>> inputBoolean(Component title) {
return createDialogOpener(MenuType.GENERIC_3x3, title, value -> {
if(value) {
return new GuiDisplay.ItemBased(Items.EMERALD_BLOCK);
} else {
return new GuiDisplay.ItemBased(Items.REDSTONE_BLOCK);
}
}, new Boolean[]{false, true}, false);
}
}
@@ -1,14 +1,13 @@
package io.github.skippyall.minions.gui.input; package io.github.skippyall.minions.gui.input;
import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.Nullable;
import org.jetbrains.annotations.Nullable;
import java.util.Optional; import java.util.Optional;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier; import java.util.function.Supplier;
public interface Result<T, E> { public sealed interface Result<T, E> permits Result.Success, Result.Error {
static <T> Result<T, String> wrap(UnsafeOperation<T> toWrap) { static <T> Result<T, String> wrap(UnsafeOperation<T> toWrap) {
return wrapCustomError(toWrap, Exception::getMessage); return wrapCustomError(toWrap, Exception::getMessage);
} }
@@ -27,7 +26,7 @@ public interface Result<T, E> {
static <T, E> Result<T, E> ofNullable(@Nullable T value, E error) { static <T, E> Result<T, E> ofNullable(@Nullable T value, E error) {
if(value != null) { if(value != null) {
return new Success<>(value); return new Success<T, E>(value);
} else { } else {
return new Error<>(error); return new Error<>(error);
} }
@@ -35,7 +34,7 @@ public interface Result<T, E> {
static <T, E> Result<T, E> ofNullable(@Nullable T value, Supplier<E> error) { static <T, E> Result<T, E> ofNullable(@Nullable T value, Supplier<E> error) {
if(value != null) { if(value != null) {
return new Success<>(value); return new Success<T, E>(value);
} else { } else {
return new Error<>(error.get()); return new Error<>(error.get());
} }
@@ -49,13 +48,13 @@ public interface Result<T, E> {
E getErrorOrThrow(); E getErrorOrThrow();
@NotNull Optional<T> getOptional(); Optional<T> getOptional();
@NotNull Optional<E> getOptionalError(); Optional<E> getOptionalError();
void ifSuccess(@NotNull Consumer<T> handler); void ifSuccess(Consumer<T> handler);
void ifError(@NotNull Consumer<Error<T, E>> handler); void ifError(Consumer<Error<T, E>> handler);
<U> Result<U,E> map(Function<T, U> mapper); <U> Result<U,E> map(Function<T, U> mapper);
@@ -75,7 +74,7 @@ public interface Result<T, E> {
} }
@Override @Override
public @NotNull Optional<E> getOptionalError() { public Optional<E> getOptionalError() {
return Optional.empty(); return Optional.empty();
} }
@@ -90,17 +89,17 @@ public interface Result<T, E> {
} }
@Override @Override
public @NotNull Optional<T> getOptional() { public Optional<T> getOptional() {
return Optional.ofNullable(result); return Optional.ofNullable(result);
} }
@Override @Override
public void ifSuccess(@NotNull Consumer<T> handler) { public void ifSuccess(Consumer<T> handler) {
handler.accept(result); handler.accept(result);
} }
@Override @Override
public void ifError(@NotNull Consumer<Error<T, E>> handler) { public void ifError(Consumer<Error<T, E>> handler) {
} }
@@ -143,22 +142,22 @@ public interface Result<T, E> {
} }
@Override @Override
public @NotNull Optional<T> getOptional() { public Optional<T> getOptional() {
return Optional.empty(); return Optional.empty();
} }
@Override @Override
public @NotNull Optional<E> getOptionalError() { public Optional<E> getOptionalError() {
return Optional.ofNullable(message); return Optional.ofNullable(message);
} }
@Override @Override
public void ifSuccess(@NotNull Consumer<T> handler) { public void ifSuccess(Consumer<T> handler) {
} }
@Override @Override
public void ifError(@NotNull Consumer<Error<T, E>> handler) { public void ifError(Consumer<Error<T, E>> handler) {
handler.accept(this); handler.accept(this);
} }
@@ -1,122 +0,0 @@
package io.github.skippyall.minions.gui.input;
import eu.pb4.sgui.api.elements.GuiElementBuilder;
import eu.pb4.sgui.api.gui.AnvilInputGui;
import io.github.skippyall.minions.gui.MinionsGui;
import io.github.skippyall.minions.gui.minion.SimpleMinionsGui;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.inventory.AnvilMenu;
import net.minecraft.world.item.Items;
public class TextInput<T> extends AnvilInputGui {
private final GuiElementBuilder valid = new GuiElementBuilder()
.setItem(Items.EMERALD_BLOCK)
.setName(Component.literal("OK"))
.setCallback(this::onConfirm);
private final GuiElementBuilder invalid = new GuiElementBuilder()
.setItem(Items.REDSTONE_BLOCK);
private final Function<String, CompletableFuture<Result<T, Component>>> parser;
private final CompletableFuture<T> future;
private Result<T, Component> result;
private boolean isConfirm;
public TextInput(ServerPlayer player, Component title, String defaultValue, Function<String, CompletableFuture<Result<T, Component>>> parser, CompletableFuture<T> future) {
super(player, false);
setTitle(title);
setDefaultInputValue(defaultValue);
this.parser = parser;
this.future = future;
updateConfirmButton(defaultValue);
}
public static <T> CompletableFuture<T> inputSync(ServerPlayer player, Component title, String defaultValue, Function<String, Result<T, Component>> parser) {
return input(player, title, defaultValue, (String string) -> CompletableFuture.completedFuture(parser.apply(string)));
}
public static <T> CompletableFuture<T> inputSync(MinionsGui gui, Component title, String defaultValue, Function<String, Result<T, Component>> parser) {
return input(gui, title, defaultValue, (String string) -> CompletableFuture.completedFuture(parser.apply(string)));
}
public static <T> CompletableFuture<T> input(ServerPlayer player, Component title, String defaultValue, Function<String, CompletableFuture<Result<T, Component>>> parser) {
CompletableFuture<T> future = new CompletableFuture<>();
new TextInput<>(player, title, defaultValue, parser, future).open();
return future;
}
public static <T> CompletableFuture<T> input(MinionsGui gui, Component title, String defaultValue, Function<String, CompletableFuture<Result<T, Component>>> parser) {
CompletableFuture<T> future = new CompletableFuture<>();
new SimpleMinionsGui(gui, (onClose, me) -> {
TextInput<T> input = new TextInput<>(gui.getViewer(), title, defaultValue, parser, future);
future.handle((v, e) -> {
onClose.run();
return null;
});
input.open();
return input;
});
return future;
}
public static CompletableFuture<String> inputString(ServerPlayer player, Component title, String defaultValue) {
return inputSync(player, title, defaultValue, Result.Success::new);
}
public static CompletableFuture<String> inputString(MinionsGui gui, Component title, String defaultValue) {
return inputSync(gui, title, defaultValue, Result.Success::new);
}
public static CompletableFuture<Long> inputLong(ServerPlayer player, Component title, String defaultValue) {
return inputSync(player, title, defaultValue, string -> Result.wrapCustomError(() -> Long.valueOf(string), Component.translatable("minions.command.input.int.fail")));
}
public static CompletableFuture<Long> inputLong(MinionsGui gui, Component title, String defaultValue) {
return inputSync(gui, title, defaultValue, string -> Result.wrapCustomError(() -> Long.valueOf(string), Component.translatable("minions.command.input.int.fail")));
}
public static CompletableFuture<Double> inputDouble(ServerPlayer player, Component title, String defaultValue) {
return inputSync(player, title, defaultValue, string -> Result.wrapCustomError(() -> Double.valueOf(string), Component.translatable("minions.command.input.float.fail")));
}
public static CompletableFuture<Double> inputDouble(MinionsGui gui, Component title, String defaultValue) {
return inputSync(gui, title, defaultValue, string -> Result.wrapCustomError(() -> Double.valueOf(string), Component.translatable("minions.command.input.float.fail")));
}
@Override
public void onInput(String input) {
updateConfirmButton(input);
}
public void updateConfirmButton(String input) {
parser.apply(input).thenAccept(result -> {
this.result = result;
if(result.isSuccess()) {
setSlot(AnvilMenu.RESULT_SLOT, valid);
} else {
Component text = result.getErrorOrThrow();
setSlot(AnvilMenu.RESULT_SLOT, invalid.setName(text));
}
});
}
@Override
public void onClose() {
if(!future.isDone() && !isConfirm) {
future.cancel(false);
}
}
public void onConfirm() {
if(result != null) {
result.ifSuccess(success -> {
isConfirm = true;
close();
future.complete(success);
});
}
}
}
@@ -0,0 +1,149 @@
package io.github.skippyall.minions.gui.input
import eu.pb4.sgui.api.elements.GuiElementBuilder
import eu.pb4.sgui.api.gui.AnvilInputGui
import io.github.skippyall.minions.gui.MinionsGui
import kotlinx.coroutines.launch
import net.minecraft.network.chat.Component
import net.minecraft.world.inventory.AnvilMenu
import net.minecraft.world.item.Items
import java.util.concurrent.CompletableFuture
class TextInput<T : Any>(
parent: MinionsGui,
val title: Component,
val defaultValue: String,
val parser: suspend (String) -> Result<T, Component>
) : MinionsGui(parent) {
private val valid: GuiElementBuilder = GuiElementBuilder()
.setItem(Items.EMERALD_BLOCK)
.setName(Component.literal("OK"))
.setCallback(Runnable { this.onConfirm() })
private val invalid: GuiElementBuilder = GuiElementBuilder()
.setItem(Items.REDSTONE_BLOCK)
private lateinit var gui: AnvilInputGui
private var result: Result<T, Component>? = null
val future = CompletableFuture<T?>()
init {
open()
}
override fun open() {
gui = object : AnvilInputGui(viewer, false) {
override fun onInput(input: String) {
updateConfirmButton(input)
}
override fun onPlayerClose(success: Boolean) {
onBackingClosed()
if (!future.isDone) {
future.complete(null)
}
}
}
gui.setTitle(title)
gui.setDefaultInputValue(defaultValue)
updateConfirmButton(defaultValue)
gui.open()
}
override fun closeBacking() {
gui.close()
}
fun updateConfirmButton(input: String) {
scope.launch {
val result = parser(input)
this@TextInput.result = result
if (result.isSuccess()) {
gui.setSlot(AnvilMenu.RESULT_SLOT, valid)
} else {
val text = result.getErrorOrThrow()
gui.setSlot(AnvilMenu.RESULT_SLOT, invalid.setName(text))
}
}
}
fun onConfirm() {
result?.ifSuccess { success: T ->
future.complete(success)
goBack()
}
}
companion object {
@JvmStatic
fun <T : Any>input(
gui: MinionsGui,
title: Component,
defaultValue: String,
parser: suspend (String) -> Result<T, Component>,
): CompletableFuture<T?> {
val input = TextInput(
parent = gui,
title = title,
defaultValue = defaultValue,
parser = parser,
)
return input.future
}
@JvmStatic
fun inputString(
gui: MinionsGui,
title: Component,
defaultValue: String,
): CompletableFuture<String?> {
return input<String>(
gui = gui,
title = title,
defaultValue = defaultValue,
parser = { result -> Result.Success(result) },
)
}
@JvmStatic
fun inputLong(
gui: MinionsGui,
title: Component,
defaultValue: Long,
): CompletableFuture<Long?> {
return input<Long>(
gui = gui,
title = title,
defaultValue = defaultValue.toString(),
parser = { string ->
Result.wrapCustomError<Long, Component>(
{ string.toLong() },
Component.translatable("value_type.minions.long.not_long")
)
},
)
}
@JvmStatic
fun inputDouble(
gui: MinionsGui,
title: Component,
defaultValue: Double,
): CompletableFuture<Double?> {
return input<Double>(
gui = gui,
title = title,
defaultValue = defaultValue.toString(),
parser = { string ->
Result.wrapCustomError<Double, Component>(
{ string.toDouble() },
Component.translatable("value_type.minions.long.not_long")
)
},
)
}
}
}
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.gui.input;
import org.jspecify.annotations.NullMarked;
@@ -7,7 +7,6 @@ import io.github.skippyall.minions.gui.MinionsGui;
import io.github.skippyall.minions.gui.PaginatedList; import io.github.skippyall.minions.gui.PaginatedList;
import io.github.skippyall.minions.gui.minion.GuiContext; import io.github.skippyall.minions.gui.minion.GuiContext;
import io.github.skippyall.minions.minion.MinionRuntime; import io.github.skippyall.minions.minion.MinionRuntime;
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction; import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
import io.github.skippyall.minions.program.supplier.Parameter; import io.github.skippyall.minions.program.supplier.Parameter;
import io.github.skippyall.minions.program.supplier.ValueSupplier; import io.github.skippyall.minions.program.supplier.ValueSupplier;
@@ -19,30 +18,26 @@ import net.minecraft.network.chat.Component;
import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items; import net.minecraft.world.item.Items;
import org.jetbrains.annotations.Nullable; import org.jspecify.annotations.Nullable;
public class ArgumentGui extends MinionsGui { public class ArgumentGui extends MinionsGui {
private final GuiContext.ValueSupplier context; private final GuiContext.ValueSupplier context;
private final MinionFakePlayer minion;
private final ConfiguredInstruction<MinionRuntime> instruction; private final ConfiguredInstruction<MinionRuntime> instruction;
private final Parameter<?> parameter; private final Parameter<?> parameter;
private SimpleGui gui; private SimpleGui gui;
private @Nullable ValueSupplierType<MinionRuntime> argumentType; private @Nullable ValueSupplierType<MinionRuntime> argumentType;
private @Nullable ValueSupplierList.ValueSupplierEntry<?, MinionRuntime> entry; private ValueSupplierList. @Nullable ValueSupplierEntry<?, MinionRuntime> entry;
public ArgumentGui(MinionsGui parent, GuiContext.ValueSupplier context) { public ArgumentGui(MinionsGui parent, GuiContext.ValueSupplier context) {
super(parent); super(parent);
minion = context.getMinion();
instruction = context.getInstruction(); instruction = context.getInstruction();
this.parameter = context.getParameter(); this.parameter = context.getParameter();
this.context = context; this.context = context;
this.entry = instruction.getArguments().getEntry(parameter); this.entry = instruction.getArguments().getEntry(parameter);
if(entry != null) {
this.argumentType = entry.getSupplier().getType(); this.argumentType = entry.getSupplier().getType();
}
open(); open();
} }
@@ -61,7 +56,7 @@ public class ArgumentGui extends MinionsGui {
protected void open() { protected void open() {
gui = new SimpleGui(MenuType.GENERIC_3x3, viewer, false) { gui = new SimpleGui(MenuType.GENERIC_3x3, viewer, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
onBackingClosed(); onBackingClosed();
} }
}; };
@@ -71,6 +66,8 @@ public class ArgumentGui extends MinionsGui {
Component.translatable(TranslationUtil.getTranslationKey(parameter.type(), MinionRegistries.VALUE_TYPES)) Component.translatable(TranslationUtil.getTranslationKey(parameter.type(), MinionRegistries.VALUE_TYPES))
)); ));
gui.setSlot(2, backButton());
updateTypeConfiguration(); updateTypeConfiguration();
updateArgumentConfiguration(); updateArgumentConfiguration();
updateConverterConfiguration(); updateConverterConfiguration();
@@ -102,12 +99,7 @@ public class ArgumentGui extends MinionsGui {
.setName(Component.translatable("minions.gui.instruction.argument.configure.data")) .setName(Component.translatable("minions.gui.instruction.argument.configure.data"))
.addLoreLine(getArgument() != null ? getArgument().getDisplayText() : Component.translatable("minions.gui.not_set")) .addLoreLine(getArgument() != null ? getArgument().getDisplayText() : Component.translatable("minions.gui.not_set"))
.setCallback(() -> argumentType.openConfiguration(this, parameter.type(), getArgument()) .setCallback(() -> argumentType.openConfiguration(this, parameter.type(), getArgument())
.thenAccept(newArgument -> { .thenAccept(this::setArgument)
setArgument(newArgument);
if(child != null) {
child.close();
}
})
) )
); );
} }
@@ -149,7 +141,7 @@ public class ArgumentGui extends MinionsGui {
new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_SUPPLIER_TYPES, type, viewer.registryAccess())) new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_SUPPLIER_TYPES, type, viewer.registryAccess()))
.setCallback(() -> { .setCallback(() -> {
setArgumentType(type); setArgumentType(type);
me.close(); me.goBack();
}) })
); );
} }
@@ -4,7 +4,7 @@ import eu.pb4.sgui.api.elements.GuiElementBuilder;
import eu.pb4.sgui.api.gui.SimpleGui; import eu.pb4.sgui.api.gui.SimpleGui;
import io.github.skippyall.minions.clipboard.ClipboardItem; import io.github.skippyall.minions.clipboard.ClipboardItem;
import io.github.skippyall.minions.gui.MinionsGui; import io.github.skippyall.minions.gui.MinionsGui;
import io.github.skippyall.minions.gui.input.ChoiceInput; import io.github.skippyall.minions.gui.input.BooleanInput;
import io.github.skippyall.minions.gui.minion.GuiContext; import io.github.skippyall.minions.gui.minion.GuiContext;
import io.github.skippyall.minions.minion.MinionListener; import io.github.skippyall.minions.minion.MinionListener;
import io.github.skippyall.minions.minion.MinionRuntime; import io.github.skippyall.minions.minion.MinionRuntime;
@@ -13,11 +13,14 @@ import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
import io.github.skippyall.minions.program.instruction.ConfiguredInstructionListener; import io.github.skippyall.minions.program.instruction.ConfiguredInstructionListener;
import io.github.skippyall.minions.program.supplier.Parameter; import io.github.skippyall.minions.program.supplier.Parameter;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket;
import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource; import net.minecraft.sounds.SoundSource;
import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.Items; import net.minecraft.world.item.Items;
import java.util.List;
public class ConfigureInstructionGui extends MinionsGui implements ConfiguredInstructionListener, MinionListener { public class ConfigureInstructionGui extends MinionsGui implements ConfiguredInstructionListener, MinionListener {
private String name; private String name;
private final ConfiguredInstruction<MinionRuntime> instruction; private final ConfiguredInstruction<MinionRuntime> instruction;
@@ -42,30 +45,36 @@ public class ConfigureInstructionGui extends MinionsGui implements ConfiguredIns
protected void open() { protected void open() {
gui = new SimpleGui(MenuType.GENERIC_9x3, viewer, false) { gui = new SimpleGui(MenuType.GENERIC_9x3, viewer, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
onBackingClosed(); onBackingClosed();
} }
}; };
gui.setTitle(Component.literal(name)); gui.setTitle(Component.literal(name));
gui.setSlot(7, new GuiElementBuilder(Items.ANVIL) gui.setSlot(6, new GuiElementBuilder(Items.ANVIL)
.setName(Component.translatable("minions.gui.instruction.configure.rename")) .setName(Component.translatable("minions.gui.instruction.configure.rename"))
.setCallback(() -> InstructionGui.inputInstructionName(this, context, name).thenAccept(newName -> { .setCallback(() -> InstructionGui.inputInstructionName(this, context, name).thenAccept(newName -> {
if(newName != null) {
minion.getInstructionManager().setInstructionName(name, newName); minion.getInstructionManager().setInstructionName(name, newName);
}
reopen(); reopen();
})) }))
); );
gui.setSlot(8, new GuiElementBuilder(Items.LAVA_BUCKET) gui.setSlot(7, new GuiElementBuilder(Items.LAVA_BUCKET)
.setName(Component.translatable("minions.gui.instruction.configure.delete")) .setName(Component.translatable("minions.gui.instruction.configure.delete"))
.setCallback(() -> ChoiceInput.confirm(this, Component.translatable("minions.gui.instruction.configure.delete.confirm", name)) .setCallback(() -> BooleanInput.confirm(this, Component.translatable("minions.gui.instruction.configure.delete.confirm", name))
.thenAccept(v -> { .thenAccept((confirmed) -> {
if(confirmed) {
minion.getInstructionManager().removeInstruction(name); minion.getInstructionManager().removeInstruction(name);
close(); goBack();
}
})) }))
); );
gui.setSlot(8, backButton());
updateSuppliers(); updateSuppliers();
gui.setSlot(13, InstructionGui.createInstructionElement(instruction.getInstruction(), viewer.registryAccess())); gui.setSlot(13, InstructionGui.createInstructionElement(instruction.getInstruction(), viewer.registryAccess()));
@@ -75,10 +84,11 @@ public class ConfigureInstructionGui extends MinionsGui implements ConfiguredIns
.addLoreLine(Component.translatable("minions.gui.instruction.configure.copy.description")) .addLoreLine(Component.translatable("minions.gui.instruction.configure.copy.description"))
.setCallback(() -> { .setCallback(() -> {
viewer.getInventory().placeItemBackInInventory(ClipboardItem.createInstructionReference(minion, name), true); viewer.getInventory().placeItemBackInInventory(ClipboardItem.createInstructionReference(minion, name), true);
viewer.playNotifySound(SoundEvents.NOTE_BLOCK_CHIME.value(), SoundSource.BLOCKS, 1, 1); viewer.connection.send(new ClientboundSoundEntityPacket(SoundEvents.NOTE_BLOCK_CHIME, SoundSource.BLOCKS, viewer, 1, 1, 0));
}) })
); );
updateLastError();
updateRunSlot(); updateRunSlot();
gui.open(); gui.open();
} }
@@ -100,6 +110,7 @@ public class ConfigureInstructionGui extends MinionsGui implements ConfiguredIns
@Override @Override
public void onRun(ConfiguredInstruction<?> instruction) { public void onRun(ConfiguredInstruction<?> instruction) {
updateRunSlot(); updateRunSlot();
updateLastError();
} }
@Override @Override
@@ -113,7 +124,9 @@ public class ConfigureInstructionGui extends MinionsGui implements ConfiguredIns
} }
private void updateRunSlot() { private void updateRunSlot() {
if(!instruction.isRunning()) { List<Component> errors = instruction.preCheck();
if(errors.isEmpty()) {
if (!instruction.isRunning()) {
gui.setSlot(26, new GuiElementBuilder(Items.ARROW) gui.setSlot(26, new GuiElementBuilder(Items.ARROW)
.setName(Component.translatable("minions.gui.instruction.run")) .setName(Component.translatable("minions.gui.instruction.run"))
.setCallback(() -> instruction.run(minion.getInstructionManager())) .setCallback(() -> instruction.run(minion.getInstructionManager()))
@@ -124,6 +137,26 @@ public class ConfigureInstructionGui extends MinionsGui implements ConfiguredIns
.setCallback(() -> instruction.stop(minion.getInstructionManager())) .setCallback(() -> instruction.stop(minion.getInstructionManager()))
); );
} }
} else {
GuiElementBuilder builder = new GuiElementBuilder(Items.RED_WOOL)
.setName(Component.translatable("minions.gui.instruction.errors"));
for(Component error : errors) {
builder.addLoreLine(error);
}
gui.setSlot(26, builder);
}
}
private void updateLastError() {
List<Component> errors = instruction.getLastErrors();
if(!errors.isEmpty()) {
GuiElementBuilder builder = new GuiElementBuilder(Items.RED_WOOL)
.setName(Component.translatable("minions.gui.instruction.last_errors"));
for(Component error : errors) {
builder.addLoreLine(error);
}
gui.setSlot(17, builder);
}
} }
private void updateSuppliers() { private void updateSuppliers() {
@@ -14,7 +14,7 @@ import net.minecraft.core.RegistryAccess;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.Items; import net.minecraft.world.item.Items;
import org.jetbrains.annotations.Nullable; import org.jspecify.annotations.Nullable;
public class ConverterGui extends MinionsGui { public class ConverterGui extends MinionsGui {
private @Nullable ValueConverterType<?> valueConverterType; private @Nullable ValueConverterType<?> valueConverterType;
@@ -28,7 +28,6 @@ public class ConverterGui extends MinionsGui {
public ConverterGui(MinionsGui parent, @Nullable ValueConverter<?,?> converter, ValueType<?> from, ValueType<?> to, ConverterList list, boolean isNew, int index) { public ConverterGui(MinionsGui parent, @Nullable ValueConverter<?,?> converter, ValueType<?> from, ValueType<?> to, ConverterList list, boolean isNew, int index) {
super(parent); super(parent);
open();
this.converter = converter; this.converter = converter;
if(converter != null) { if(converter != null) {
this.valueConverterType = converter.getType(); this.valueConverterType = converter.getType();
@@ -38,13 +37,15 @@ public class ConverterGui extends MinionsGui {
this.list = list; this.list = list;
this.isNew = isNew; this.isNew = isNew;
this.index = index; this.index = index;
open();
} }
@Override @Override
protected void open() { protected void open() {
gui = new SimpleGui(MenuType.GENERIC_3x3, viewer, false) { gui = new SimpleGui(MenuType.GENERIC_3x3, viewer, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
onBackingClosed(); onBackingClosed();
} }
}; };
@@ -53,15 +54,11 @@ public class ConverterGui extends MinionsGui {
updateTypeDisplay(); updateTypeDisplay();
updateConverterDisplay(); updateConverterDisplay();
gui.setSlot(8, backButton());
gui.open(); gui.open();
} }
@Override
protected void reopen() {
gui.open();
}
private void updateTypeDisplay() { private void updateTypeDisplay() {
gui.setSlot(3, new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_CONVERTER_TYPES, valueConverterType, viewer.registryAccess())) gui.setSlot(3, new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_CONVERTER_TYPES, valueConverterType, viewer.registryAccess()))
.setCallback(this::configureType) .setCallback(this::configureType)
@@ -106,7 +103,7 @@ public class ConverterGui extends MinionsGui {
GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_CONVERTER_TYPES, type, viewer.registryAccess()) GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_CONVERTER_TYPES, type, viewer.registryAccess())
).setCallback(() -> { ).setCallback(() -> {
setType(type); setType(type);
me.close(); me.goBack();
}) })
); );
} }
@@ -114,12 +111,7 @@ public class ConverterGui extends MinionsGui {
private void configureData() { private void configureData() {
if(valueConverterType != null) { if(valueConverterType != null) {
valueConverterType.configure(this, from, to, converter) valueConverterType.configure(this, from, to, converter)
.thenAccept(newConverter -> { .thenAccept(this::setConverter);
setConverter(newConverter);
if(child != null) {
child.close();
}
});
} }
} }
@@ -12,6 +12,7 @@ import io.github.skippyall.minions.util.TranslationUtil;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.Items; import net.minecraft.world.item.Items;
import org.jspecify.annotations.Nullable;
public class ConverterListGui extends MinionsGui { public class ConverterListGui extends MinionsGui {
private ConverterList converters; private ConverterList converters;
@@ -34,7 +35,7 @@ public class ConverterListGui extends MinionsGui {
protected void open() { protected void open() {
gui = new SimpleGui(MenuType.GENERIC_9x3, viewer, false) { gui = new SimpleGui(MenuType.GENERIC_9x3, viewer, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
onBackingClosed(); onBackingClosed();
} }
}; };
@@ -54,51 +55,121 @@ public class ConverterListGui extends MinionsGui {
gui.setSlot(23, new GuiElementBuilder(Items.ARROW) gui.setSlot(23, new GuiElementBuilder(Items.ARROW)
.setCallback(() -> { .setCallback(() -> {
if(page * 4 + 4 < converters.getConverters().size()) { if(page * 4 + 4 < converters.getConverters().size() + 1) {
page++; page++;
updateConverters(); updateConverters();
} }
}) })
); );
gui.setSlot(26, backButton());
gui.open(); gui.open();
} }
private ValueType<?> getInputTypeOfConverter(int converterIndex) {
if(converterIndex < converters.getConverters().size() && converterIndex >= 0) {
return converters.getConverters().get(converterIndex).getFrom();
} else if(converterIndex == converters.getConverters().size()) {
return outputType;
} else {
throw new IndexOutOfBoundsException("Can't get input type of converter " + converterIndex + ", list size " + converters.getConverters().size());
}
}
private ValueType<?> getOutputTypeOfConverter(int converterIndex) {
if(converterIndex < converters.getConverters().size() && converterIndex >= 0) {
return converters.getConverters().get(converterIndex).getTo();
} else if(converterIndex == -1) {
return inputType;
} else {
throw new IndexOutOfBoundsException("Can't get output type of converter " + converterIndex + ", list size " + converters.getConverters().size());
}
}
public void updateConverters() { public void updateConverters() {
for(int slot = 0; slot < 18; slot++) {
gui.clearSlot(slot);
}
int lastConverter = Math.min(5, converters.getConverters().size() + 2 - page * 4); int lastConverter = Math.min(5, converters.getConverters().size() + 2 - page * 4);
for(int i = 0; i < lastConverter; i++) { for(int i = 0; i < lastConverter; i++) {
//Each page has 5 converters, but the last is displayed on the next page as well //Each page has 5 converters, but the last is displayed on the next page as well
int converterIndex = page * 4 + i; //The input element index is -1, the output element index is the list size
//without input element int converterIndex = page * 4 + i - 1;
int actualConverterIndex = converterIndex - 1;
int slot = 9 + 2 * i; int slot = 9 + 2 * i;
if(converterIndex == 0) {
gui.setSlot(slot, new GuiElementBuilder(Items.DROPPER)); if(converterIndex == converters.getConverters().size()) {
} else if(converterIndex == converters.getConverters().size() + 1) {
gui.setSlot(slot, new GuiElementBuilder(Items.HOPPER)); gui.setSlot(slot, new GuiElementBuilder(Items.HOPPER));
} else { } else {
ValueConverter<?, ?> converter = converters.getConverters().get(actualConverterIndex); ValueType<?> thisConverterOutput = getOutputTypeOfConverter(converterIndex);
ValueType<?> fromType = actualConverterIndex >= 1 ? converters.getConverters().get(actualConverterIndex - 1).getTo() : inputType; ValueType<?> nextConverterInput = getInputTypeOfConverter(converterIndex + 1);
ValueType<?> toType = actualConverterIndex < converters.getConverters().size() - 1 ? converters.getConverters().get(actualConverterIndex + 1).getFrom() : outputType;
gui.setSlot(slot, new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_CONVERTER_TYPES, converter.getType(), viewer.registryAccess())) //What should be shown at the converter's slot
.addLoreLine(converter.getDisplayText()) if (converterIndex == -1) {
.setCallback(() -> new ConverterGui(this, converter, fromType, toType, converters, false, actualConverterIndex)) gui.setSlot(slot, new GuiElementBuilder(Items.DROPPER));
); } else {
ValueType<?> previousConverterOutput = getOutputTypeOfConverter(converterIndex - 1);
ValueConverter<?, ?> converter = converters.getConverters().get(converterIndex);
gui.setSlot(slot, createConverterDisplay(converter, previousConverterOutput, nextConverterInput, converterIndex));
GuiElementBuilder warning = createConverterWarning(converter);
if (warning != null) {
gui.setSlot(slot - 8, warning);
}
} }
if(i != 4 && actualConverterIndex != converters.getConverters().size()) {
ValueType<?> fromType = actualConverterIndex >= 0 ? converters.getConverters().get(actualConverterIndex).getTo() : inputType;
ValueType<?> toType = actualConverterIndex < converters.getConverters().size() - 1 ? converters.getConverters().get(actualConverterIndex + 1).getFrom() : outputType;
gui.setSlot(slot + 1, new GuiElementBuilder(Items.MAGENTA_GLAZED_TERRACOTTA) //show cast in the next slot
if (i != 4 && converterIndex != converters.getConverters().size()) {
gui.setSlot(slot + 1, createCastDisplay(thisConverterOutput, nextConverterInput, converterIndex + 1));
GuiElementBuilder warning = createCastWarning(thisConverterOutput, nextConverterInput);
if (warning != null) {
gui.setSlot(slot - 8, warning);
}
}
}
}
}
private GuiElementBuilder createConverterDisplay(ValueConverter<?, ?> converter, ValueType<?> fromType, ValueType<?> toType, int converterIndex) {
return new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_CONVERTER_TYPES, converter.getType(), viewer.registryAccess()))
.addLoreLine(converter.getDisplayText())
.setCallback(() -> new ConverterGui(this, converter, fromType, toType, converters, false, converterIndex));
}
private GuiElementBuilder createCastDisplay(ValueType<?> fromType, ValueType<?> toType, int newConverterIndex) {
return new GuiElementBuilder(Items.MAGENTA_GLAZED_TERRACOTTA)
.setName(Component.translatable( .setName(Component.translatable(
"minions.gui.instruction.converters.cast", "minions.gui.instruction.converters.cast",
Component.translatable(TranslationUtil.getTranslationKey(fromType, MinionRegistries.VALUE_TYPES)), Component.translatable(TranslationUtil.getTranslationKey(fromType, MinionRegistries.VALUE_TYPES)),
Component.translatable(TranslationUtil.getTranslationKey(toType, MinionRegistries.VALUE_TYPES)) Component.translatable(TranslationUtil.getTranslationKey(toType, MinionRegistries.VALUE_TYPES))
)) ))
.setCallback(() -> new ConverterGui(this, null, fromType, toType, converters, true, actualConverterIndex + 1)) .setCallback(() -> new ConverterGui(this, null, fromType, toType, converters, true, newConverterIndex));
);
} }
private @Nullable GuiElementBuilder createCastWarning(ValueType<?> fromType, ValueType<?> toType) {
Component warning = ConverterList.createCastWarning(fromType, toType);
if(warning != null) {
return new GuiElementBuilder(Items.RED_BANNER)
.setName(Component.translatable("minions.generic.error"))
.addLoreLine(warning);
} else {
return null;
}
}
private @Nullable GuiElementBuilder createConverterWarning(ValueConverter<?,?> converter) {
Component warning = ConverterList.createConverterWarning(converter);
if(warning != null) {
return new GuiElementBuilder(Items.RED_BANNER)
.setName(Component.translatable("minions.generic.error"))
.addLoreLine(warning);
} else {
return null;
} }
} }
@@ -18,30 +18,31 @@ import io.github.skippyall.minions.program.supplier.ValueSupplier;
import io.github.skippyall.minions.registration.MinionComponentTypes; import io.github.skippyall.minions.registration.MinionComponentTypes;
import io.github.skippyall.minions.registration.MinionRegistries; import io.github.skippyall.minions.registration.MinionRegistries;
import io.github.skippyall.minions.util.TranslationUtil; import io.github.skippyall.minions.util.TranslationUtil;
import org.jetbrains.annotations.Nullable;
import java.util.NoSuchElementException;
import java.util.concurrent.CompletableFuture;
import net.minecraft.core.RegistryAccess; import net.minecraft.core.RegistryAccess;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items; import net.minecraft.world.item.Items;
import org.jspecify.annotations.Nullable;
import java.util.NoSuchElementException;
import java.util.concurrent.CompletableFuture;
public class InstructionGui { public class InstructionGui {
public static MinionsGui openInstructionMainMenu(MinionsGui parent, GuiContext.Minion context) { public static void openInstructionMainMenu(MinionsGui parent, GuiContext.Minion context) {
return new SimpleMinionsGui(parent, (onClose, me) -> { new SimpleMinionsGui(parent, (onClose, me) -> {
ServerPlayer player = parent.getViewer(); ServerPlayer player = parent.viewer;
SimpleGui gui = new SimpleGui(MenuType.GENERIC_3x3, player, false) { SimpleGui gui = new SimpleGui(MenuType.GENERIC_3x3, player, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
onClose.run(); onClose.run();
} }
}; };
gui.setTitle(Component.translatable("minions.gui.instruction.title")); gui.setTitle(Component.translatable("minions.gui.instruction.title"));
gui.setSlot(2, me.backButton());
gui.setSlot(3, new GuiElementBuilder() gui.setSlot(3, new GuiElementBuilder()
.setItem(Items.BOOK) .setItem(Items.BOOK)
.setName(Component.translatable("minions.gui.instruction.list")) .setName(Component.translatable("minions.gui.instruction.list"))
@@ -60,10 +61,10 @@ public class InstructionGui {
public static void createNewInstruction(MinionsGui parent, GuiContext.Minion context) { public static void createNewInstruction(MinionsGui parent, GuiContext.Minion context) {
MinionFakePlayer minion = context.getMinion(); MinionFakePlayer minion = context.getMinion();
ServerPlayer viewer = parent.getViewer(); ServerPlayer viewer = parent.viewer;
selectInstructionModuleMenu(parent, context).thenAccept(instructionType -> selectInstructionModuleMenu(parent, context).thenAccept(instructionType ->
inputInstructionName(parent, context, "Instruction").thenAccept(name -> { inputInstructionName(parent, context, "Instruction").thenAccept(name -> {
if (!minion.isRemoved() && !minion.hasDisconnected()) { if (!minion.isRemoved() && !minion.hasDisconnected() && name != null) {
ConfiguredInstruction<MinionRuntime> configuredInstruction = minion.getInstructionManager().createInstruction(name, instructionType); ConfiguredInstruction<MinionRuntime> configuredInstruction = minion.getInstructionManager().createInstruction(name, instructionType);
new ConfigureInstructionGui(parent, GuiContext.Instruction.create(context, configuredInstruction, name)); new ConfigureInstructionGui(parent, GuiContext.Instruction.create(context, configuredInstruction, name));
} }
@@ -71,8 +72,8 @@ public class InstructionGui {
); );
} }
public static CompletableFuture<String> inputInstructionName(MinionsGui parent, GuiContext.Minion context, String defaultValue) { public static CompletableFuture<@Nullable String> inputInstructionName(MinionsGui parent, GuiContext.Minion context, String defaultValue) {
return TextInput.inputSync(parent, Component.translatable("minions.gui.instruction.enter_name"), defaultValue, name -> { return TextInput.input(parent, Component.translatable("minions.gui.instruction.enter_name"), defaultValue, (name, _) -> {
if (context.getMinion().getInstructionManager().hasInstruction(name)) { if (context.getMinion().getInstructionManager().hasInstruction(name)) {
return new Result.Error<>(Component.translatable("minions.gui.instruction.name_already_used")); return new Result.Error<>(Component.translatable("minions.gui.instruction.name_already_used"));
} }
@@ -91,7 +92,7 @@ public class InstructionGui {
public static CompletableFuture<InstructionType<MinionRuntime>> selectInstructionModuleMenu(MinionsGui parent, GuiContext.Minion context) { public static CompletableFuture<InstructionType<MinionRuntime>> selectInstructionModuleMenu(MinionsGui parent, GuiContext.Minion context) {
MinionFakePlayer minion = context.getMinion(); MinionFakePlayer minion = context.getMinion();
ServerPlayer viewer = parent.getViewer(); ServerPlayer viewer = parent.viewer;
if (minion.getModuleInventory().getModules().isEmpty()) { if (minion.getModuleInventory().getModules().isEmpty()) {
viewer.sendSystemMessage(Component.translatable("minions.gui.instruction.no_modules")); viewer.sendSystemMessage(Component.translatable("minions.gui.instruction.no_modules"));
@@ -101,9 +102,9 @@ public class InstructionGui {
CompletableFuture<InstructionType<MinionRuntime>> future = new CompletableFuture<>(); CompletableFuture<InstructionType<MinionRuntime>> future = new CompletableFuture<>();
new SimpleMinionsGui(parent, (closeHandler, me) -> { new SimpleMinionsGui(parent, (closeHandler, me) -> {
SimpleGui gui = new SimpleGui(MenuType.GENERIC_9x3, viewer, false) { SimpleGui gui = new SimpleGui(MenuType.GENERIC_9x4, viewer, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
if (!future.isDone()) { if (!future.isDone()) {
future.cancel(false); future.cancel(false);
} }
@@ -112,11 +113,13 @@ public class InstructionGui {
}; };
gui.setTitle(Component.translatable("minions.gui.instruction.select_instruction")); gui.setTitle(Component.translatable("minions.gui.instruction.select_instruction"));
gui.setSlot(8, me.backButton());
for (int i = 0; i < minion.getModuleInventory().getContainerSize(); i++) { for (int i = 0; i < minion.getModuleInventory().getContainerSize(); i++) {
ItemStack moduleItem = minion.getModuleInventory().getItem(i); ItemStack moduleItem = minion.getModuleInventory().getItem(i);
MinionModule module = moduleItem.get(MinionComponentTypes.MODULE); MinionModule module = moduleItem.get(MinionComponentTypes.MODULE);
if (module != null && !module.instructions().isEmpty()) { if (module != null && !module.instructions().isEmpty()) {
gui.addSlot(new GuiElementBuilder(moduleItem) gui.setSlot(i + 9, new GuiElementBuilder(moduleItem)
.setCallback(() -> selectInstructionMenu(parent, context, module) .setCallback(() -> selectInstructionMenu(parent, context, module)
.thenApply(future::complete) .thenApply(future::complete)
) )
@@ -134,9 +137,9 @@ public class InstructionGui {
CompletableFuture<InstructionType<MinionRuntime>> future = new CompletableFuture<>(); CompletableFuture<InstructionType<MinionRuntime>> future = new CompletableFuture<>();
new SimpleMinionsGui(parent, (closeHandler, me) -> { new SimpleMinionsGui(parent, (closeHandler, me) -> {
SimpleGui gui = new SimpleGui(MenuType.GENERIC_9x3, parent.getViewer(), false) { SimpleGui gui = new SimpleGui(MenuType.GENERIC_9x4, parent.viewer, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
if (!future.isDone()) { if (!future.isDone()) {
future.cancel(false); future.cancel(false);
} }
@@ -145,10 +148,13 @@ public class InstructionGui {
}; };
gui.setTitle(Component.translatable("minions.gui.instruction.select_instruction")); gui.setTitle(Component.translatable("minions.gui.instruction.select_instruction"));
gui.setSlot(8, me.backButton());
int slot = 9;
for (InstructionType<MinionRuntime> instructionType : module.instructions()) { for (InstructionType<MinionRuntime> instructionType : module.instructions()) {
gui.addSlot(createInstructionElement(instructionType, parent.getViewer().registryAccess()) gui.setSlot(slot, createInstructionElement(instructionType, parent.viewer.registryAccess())
.setCallback(() -> future.complete(instructionType)) .setCallback(() -> future.complete(instructionType))
); );
slot++;
} }
gui.open(); gui.open();
@@ -157,7 +163,7 @@ public class InstructionGui {
return future; return future;
} }
public static GuiElementBuilder createInstructionElement(InstructionType<MinionRuntime> instructionType, RegistryAccess manager) { public static GuiElementBuilder createInstructionElement(@Nullable InstructionType<MinionRuntime> instructionType, RegistryAccess manager) {
GuiElementBuilder instructionBuilder; GuiElementBuilder instructionBuilder;
if (instructionType != null) { if (instructionType != null) {
instructionBuilder = new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.INSTRUCTION_TYPES, instructionType, manager)); instructionBuilder = new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.INSTRUCTION_TYPES, instructionType, manager));
@@ -33,19 +33,16 @@ public class InstructionListGui extends MinionsGui implements MinionListener {
@Override @Override
protected void open() { protected void open() {
minion.addMinionListener(this); minion.addMinionListener(this);
gui = new SimpleGui(MenuType.GENERIC_9x3, viewer, false) { gui = new SimpleGui(MenuType.GENERIC_9x4, viewer, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
onBackingClosed(); onBackingClosed();
} }
}; };
gui.setTitle(Component.translatable("minions.gui.instruction.title")); gui.setTitle(Component.translatable("minions.gui.instruction.title"));
resetInstructionList();
gui.open();
}
@Override gui.setSlot(8, backButton());
protected void reopen() { resetInstructionList();
gui.open(); gui.open();
} }
@@ -56,7 +53,7 @@ public class InstructionListGui extends MinionsGui implements MinionListener {
} }
private void resetInstructionList() { private void resetInstructionList() {
int i = 0; int i = 9;
for (String instructionName : minion.getInstructionManager().getInstructionNames()) { for (String instructionName : minion.getInstructionManager().getInstructionNames()) {
ConfiguredInstruction<MinionRuntime> instruction = minion.getInstructionManager().getInstruction(instructionName); ConfiguredInstruction<MinionRuntime> instruction = minion.getInstructionManager().getInstruction(instructionName);
gui.setSlot(i, new GuiElementBuilder(GuiDisplay.getGuiDisplayFor(MinionRegistries.INSTRUCTION_TYPES, instruction.getInstruction(), viewer.registryAccess()).createItemStack()) gui.setSlot(i, new GuiElementBuilder(GuiDisplay.getGuiDisplayFor(MinionRegistries.INSTRUCTION_TYPES, instruction.getInstruction(), viewer.registryAccess()).createItemStack())
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.gui.instruction;
import org.jspecify.annotations.NullMarked;
@@ -1,43 +0,0 @@
package io.github.skippyall.minions.gui.minion;
import io.github.skippyall.minions.minion.MinionRuntime;
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
import io.github.skippyall.minions.program.supplier.Parameter;
import net.minecraft.server.level.ServerPlayer;
public interface GuiContext {
ServerPlayer getViewer();
static GuiContext create(ServerPlayer viewer) {
return new GuiContextImpl(viewer);
}
interface Minion extends GuiContext {
MinionFakePlayer getMinion();
static GuiContext.Minion create(GuiContext context, MinionFakePlayer minion) {
return new GuiContextImpl.MinionImpl(context, minion);
}
}
interface Instruction extends Minion {
ConfiguredInstruction<MinionRuntime> getInstruction();
String getName();
void setName(String name);
static GuiContext.Instruction create(GuiContext.Minion context, ConfiguredInstruction<MinionRuntime> instruction, String name) {
return new GuiContextImpl.InstructionImpl(context, instruction, name);
}
}
interface ValueSupplier extends Instruction {
Parameter<?> getParameter();
static GuiContext.ValueSupplier create(GuiContext.Instruction context, Parameter<?> parameter) {
return new GuiContextImpl.ValueSupplierImpl(context, parameter);
}
}
}
@@ -0,0 +1,66 @@
package io.github.skippyall.minions.gui.minion
import io.github.skippyall.minions.gui.minion.GuiContextImpl.InstructionImpl
import io.github.skippyall.minions.gui.minion.GuiContextImpl.MinionImpl
import io.github.skippyall.minions.gui.minion.GuiContextImpl.ValueSupplierImpl
import io.github.skippyall.minions.minion.MinionRuntime
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction
import io.github.skippyall.minions.program.supplier.Parameter
import net.minecraft.server.level.ServerPlayer
interface GuiContext {
val viewer: ServerPlayer
companion object {
@JvmStatic
fun create(viewer: ServerPlayer): GuiContext {
return GuiContextImpl(viewer)
}
}
interface Minion : GuiContext {
val minion: MinionFakePlayer
companion object {
@JvmStatic
fun create(context: GuiContext, minion: MinionFakePlayer): Minion {
return MinionImpl(
if(context is MinionImpl) context.context else context,
minion
)
}
}
}
interface Instruction : Minion {
val instruction: ConfiguredInstruction<MinionRuntime>
var name: String
companion object {
@JvmStatic
fun create(context: Minion, instruction: ConfiguredInstruction<MinionRuntime>, name: String): Instruction {
return InstructionImpl(
if(context is InstructionImpl) context.context else context,
instruction,
name
)
}
}
}
interface ValueSupplier : Instruction {
val parameter: Parameter<*>
companion object {
@JvmStatic
fun create(context: Instruction, parameter: Parameter<*>): ValueSupplier {
return ValueSupplierImpl(
if(context is ValueSupplierImpl) context.context else context,
parameter
)
}
}
}
}
@@ -1,120 +0,0 @@
package io.github.skippyall.minions.gui.minion;
import io.github.skippyall.minions.minion.MinionRuntime;
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
import io.github.skippyall.minions.program.supplier.Parameter;
import net.minecraft.server.level.ServerPlayer;
//If only this mod was kotlin
public class GuiContextImpl implements GuiContext {
private final ServerPlayer viewer;
public GuiContextImpl(ServerPlayer viewer) {
this.viewer = viewer;
}
@Override
public ServerPlayer getViewer() {
return viewer;
}
public static class MinionImpl extends DelegatingGuiContextImpl<GuiContext> implements GuiContext.Minion {
private final MinionFakePlayer minion;
public MinionImpl(GuiContext context, MinionFakePlayer minion) {
super(context);
this.minion = minion;
}
@Override
public MinionFakePlayer getMinion() {
return minion;
}
}
public static class InstructionImpl extends DelegatingMinionImpl<GuiContext.Minion> implements GuiContext.Instruction {
private final ConfiguredInstruction<MinionRuntime> instruction;
private String name;
public InstructionImpl(GuiContext.Minion context, ConfiguredInstruction<MinionRuntime> instruction, String name) {
super(context);
this.instruction = instruction;
this.name = name;
}
@Override
public ConfiguredInstruction<MinionRuntime> getInstruction() {
return instruction;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
}
public static class ValueSupplierImpl extends DelegatingInstructionImpl<GuiContext.Instruction> implements GuiContext.ValueSupplier {
private final Parameter<?> parameter;
public ValueSupplierImpl(GuiContext.Instruction context, Parameter<?> parameter) {
super(context);
this.parameter = parameter;
}
@Override
public Parameter<?> getParameter() {
return parameter;
}
}
public static class DelegatingGuiContextImpl<C extends GuiContext> implements GuiContext {
protected final C context;
public DelegatingGuiContextImpl(C context) {
this.context = context;
}
@Override
public ServerPlayer getViewer() {
return context.getViewer();
}
}
public static class DelegatingMinionImpl<C extends GuiContext.Minion> extends DelegatingGuiContextImpl<C> implements GuiContext.Minion {
public DelegatingMinionImpl(C context) {
super(context);
}
@Override
public MinionFakePlayer getMinion() {
return context.getMinion();
}
}
public static class DelegatingInstructionImpl<C extends GuiContext.Instruction> extends DelegatingMinionImpl<C> implements GuiContext.Instruction {
public DelegatingInstructionImpl(C context) {
super(context);
}
@Override
public ConfiguredInstruction<MinionRuntime> getInstruction() {
return context.getInstruction();
}
@Override
public String getName() {
return context.getName();
}
@Override
public void setName(String name) {
context.setName(name);
}
}
}
@@ -0,0 +1,26 @@
package io.github.skippyall.minions.gui.minion
import io.github.skippyall.minions.minion.MinionRuntime
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction
import io.github.skippyall.minions.program.supplier.Parameter
import net.minecraft.server.level.ServerPlayer
//Thank you kotlin
class GuiContextImpl(override val viewer: ServerPlayer) : GuiContext {
class MinionImpl(
val context: GuiContext,
override val minion: MinionFakePlayer
) : GuiContext by context, GuiContext.Minion
class InstructionImpl(
val context: GuiContext.Minion,
override val instruction: ConfiguredInstruction<MinionRuntime>,
override var name: String
) : GuiContext.Minion by context, GuiContext.Instruction
class ValueSupplierImpl(
val context: GuiContext.Instruction,
override val parameter: Parameter<*>
) : GuiContext.Instruction by context, GuiContext.ValueSupplier
}
@@ -31,7 +31,7 @@ public class MinionGui extends MinionsGui implements MinionListener {
protected void open() { protected void open() {
gui = new SimpleGui(MenuType.GENERIC_3x3, viewer, false) { gui = new SimpleGui(MenuType.GENERIC_3x3, viewer, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
onBackingClosed(); onBackingClosed();
} }
}; };
@@ -65,11 +65,6 @@ public class MinionGui extends MinionsGui implements MinionListener {
gui.open(); gui.open();
} }
@Override
protected void reopen() {
gui.open();
}
@Override @Override
protected void closeBacking() { protected void closeBacking() {
gui.close(); gui.close();
@@ -29,7 +29,7 @@ public class MinionInventoryGui extends MinionsGui {
protected void open() { protected void open() {
gui = new SimpleGui(MenuType.GENERIC_9x6, viewer, false) { gui = new SimpleGui(MenuType.GENERIC_9x6, viewer, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
onBackingClosed(); onBackingClosed();
} }
}; };
@@ -45,18 +45,20 @@ public class MinionInventoryGui extends MinionsGui {
gui.setSlot(5, new ItemStack(Items.LEATHER_BOOTS)); gui.setSlot(5, new ItemStack(Items.LEATHER_BOOTS));
gui.setSlot(6, new ItemStack(Items.SHIELD)); gui.setSlot(6, new ItemStack(Items.SHIELD));
gui.setSlotRedirect(2 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.HEAD, EquipmentSlot.HEAD.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null)); gui.setSlot(8, backButton());
gui.setSlotRedirect(3 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.CHEST, EquipmentSlot.CHEST.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null));
gui.setSlotRedirect(4 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.LEGS, EquipmentSlot.LEGS.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null)); gui.setSlot(2 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.HEAD, EquipmentSlot.HEAD.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null));
gui.setSlotRedirect(5 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.FEET, EquipmentSlot.FEET.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null)); gui.setSlot(3 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.CHEST, EquipmentSlot.CHEST.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null));
gui.setSlotRedirect(6 + 9, new Slot(minion.getInventory(), Inventory.SLOT_OFFHAND, 0, 0)); gui.setSlot(4 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.LEGS, EquipmentSlot.LEGS.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null));
gui.setSlot(5 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.FEET, EquipmentSlot.FEET.getIndex(Inventory.INVENTORY_SIZE), 0, 0, null));
gui.setSlot(6 + 9, new Slot(minion.getInventory(), Inventory.SLOT_OFFHAND, 0, 0));
for (int i = Inventory.SELECTION_SIZE; i < Inventory.INVENTORY_SIZE; i++) { for (int i = Inventory.SELECTION_SIZE; i < Inventory.INVENTORY_SIZE; i++) {
gui.setSlotRedirect(i + 9, new Slot(minion.getInventory(), i, 0, 0)); gui.setSlot(i + 9, new Slot(minion.getInventory(), i, 0, 0));
} }
for (int i = 0; i < Inventory.SELECTION_SIZE; i++) { for (int i = 0; i < Inventory.SELECTION_SIZE; i++) {
gui.setSlotRedirect(i + 45, new Slot(minion.getInventory(), i, 0, 0)); gui.setSlot(i + 45, new Slot(minion.getInventory(), i, 0, 0));
} }
gui.open(); gui.open();
} }
@@ -1,15 +1,15 @@
package io.github.skippyall.minions.gui.minion; package io.github.skippyall.minions.gui.minion;
import eu.pb4.sgui.api.gui.GuiInterface; import eu.pb4.sgui.api.gui.GuiLike;
import io.github.skippyall.minions.gui.MinionsGui; import io.github.skippyall.minions.gui.MinionsGui;
import java.util.function.BiFunction; import java.util.function.BiFunction;
public class SimpleMinionsGui extends MinionsGui { public class SimpleMinionsGui extends MinionsGui {
private GuiInterface gui; private GuiLike gui;
private final BiFunction<Runnable, SimpleMinionsGui, GuiInterface> guiFactory; private final BiFunction<Runnable, SimpleMinionsGui, GuiLike> guiFactory;
public SimpleMinionsGui(MinionsGui parent, BiFunction<Runnable, SimpleMinionsGui, GuiInterface> guiFactory) { public SimpleMinionsGui(MinionsGui parent, BiFunction<Runnable, SimpleMinionsGui, GuiLike> guiFactory) {
super(parent); super(parent);
this.guiFactory = guiFactory; this.guiFactory = guiFactory;
open(); open();
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.gui.minion;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.gui;
import org.jspecify.annotations.NullMarked;
@@ -13,7 +13,7 @@ import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.entity.BlockEntityType;
import org.jetbrains.annotations.Nullable; import org.jspecify.annotations.Nullable;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
@@ -45,9 +45,9 @@ public abstract class BlockEntityMinionListener<E extends BlockEntity> implement
this.minion = null; this.minion = null;
} }
public static <T extends BlockEntityMinionListener<?>> T getListener(Level world, BlockPos pos, UUID minionUuid, Class<T> clazz) { public static <T extends BlockEntityMinionListener<?>> @Nullable T getListener(Level world, BlockPos pos, @Nullable UUID minionUuid, Class<T> clazz) {
if(minionUuid != null) { if(minionUuid != null) {
for (MinionListener listener : MinionPersistentState.get(world.getServer()).getMinionData(minionUuid).listeners()) { for (MinionListener listener : MinionPersistentState.get(world.getServer()).getMinionData(minionUuid).getListeners()) {
if (listener instanceof BlockEntityMinionListener<?> tl && tl.pos.equals(pos) && tl.worldKey.equals(world.dimension()) && clazz.isInstance(tl)) { if (listener instanceof BlockEntityMinionListener<?> tl && tl.pos.equals(pos) && tl.worldKey.equals(world.dimension()) && clazz.isInstance(tl)) {
return clazz.cast(tl); return clazz.cast(tl);
} }
@@ -95,13 +95,13 @@ public abstract class BlockEntityMinionListener<E extends BlockEntity> implement
} }
public void add(MinecraftServer server) { public void add(MinecraftServer server) {
MinionPersistentState.get(server).getMinionData(minionUuid).listeners().addListener(this); MinionPersistentState.get(server).getMinionData(minionUuid).getListeners().addListener(this);
MinionPersistentState.get(server).setDirty(); MinionPersistentState.get(server).setDirty();
this.minion = (MinionFakePlayer) server.getPlayerList().getPlayer(minionUuid); this.minion = (MinionFakePlayer) server.getPlayerList().getPlayer(minionUuid);
} }
public void remove(MinecraftServer server) { public void remove(MinecraftServer server) {
MinionPersistentState.get(server).getMinionData(minionUuid).listeners().removeListener(this); MinionPersistentState.get(server).getMinionData(minionUuid).getListeners().removeListener(this);
MinionPersistentState.get(server).setDirty(); MinionPersistentState.get(server).setDirty();
} }
@@ -1,37 +0,0 @@
package io.github.skippyall.minions.listener;
import org.jetbrains.annotations.NotNull;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
public class ListenerManager<T> implements Iterable<T> {
protected final Set<T> listeners;
public ListenerManager() {
this(new CopyOnWriteArraySet<>());
}
protected ListenerManager(Set<T> listeners) {
this.listeners = listeners;
}
public void addListener(T listener) {
listeners.add(listener);
}
public void removeListener(T listener) {
listeners.remove(listener);
}
@Override
public @NotNull Iterator<T> iterator() {
return listeners.iterator();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
@@ -0,0 +1,29 @@
package io.github.skippyall.minions.listener
import java.util.concurrent.CopyOnWriteArraySet
open class ListenerManager<T>(
protected val listeners: MutableSet<T> = CopyOnWriteArraySet(),
val onChange: () -> Unit = {},
) : MutableIterable<T> by listeners {
fun addListener(listener: T) {
listeners.add(listener)
onChange()
}
fun removeListener(listener: T) {
listeners.remove(listener)
onChange()
}
override fun iterator(): MutableIterator<T> {
val iterator = listeners.iterator()
return object : MutableIterator<T> by iterator {
override fun remove() {
iterator.remove()
onChange()
}
}
}
}
@@ -1,44 +0,0 @@
package io.github.skippyall.minions.listener;
import com.mojang.serialization.Codec;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation;
public class SerializableListenerManager<T extends SerializableListenerManager.SerializableListener> extends ListenerManager<T> {
public SerializableListenerManager() {
super();
}
protected SerializableListenerManager(Set<T> listeners) {
super(listeners);
}
public static <T extends SerializableListener> Codec<SerializableListenerManager<T>> getCodec(Registry<Codec<? extends T>> registry) {
return registry.byNameCodec().<T>dispatch(
listener -> listener.getCodecId().map(registry::getValue).orElse(Codec.unit(null)),
codec -> codec.fieldOf("data")
).listOf().xmap(
list -> new SerializableListenerManager<>(new CopyOnWriteArraySet<>(list)),
manager -> {
List<T> serializableListeners = new ArrayList<>();
for(T listener : manager.listeners) {
if(listener.getCodecId().isPresent()) {
serializableListeners.add(listener);
}
}
return serializableListeners;
}
);
}
public interface SerializableListener {
default Optional<ResourceLocation> getCodecId() {
return Optional.empty();
}
}
}
@@ -0,0 +1,47 @@
package io.github.skippyall.minions.listener
import com.mojang.serialization.Codec
import com.mojang.serialization.MapCodec
import io.github.skippyall.minions.listener.SerializableListenerManager.SerializableListener
import net.minecraft.core.Registry
import net.minecraft.resources.Identifier
import java.util.*
import java.util.concurrent.CopyOnWriteArraySet
class SerializableListenerManager<T : SerializableListener>(
listeners: MutableSet<T> = CopyOnWriteArraySet(),
onChange: () -> Unit = {},
) : ListenerManager<T>(listeners, onChange) {
interface SerializableListener {
val codecId: Optional<Identifier>
get() = Optional.empty<Identifier>()
}
companion object {
@JvmStatic
@JvmOverloads
fun <T : SerializableListener> getCodec(
registry: Registry<Codec<out T>>,
onChange: () -> Unit = {},
): Codec<SerializableListenerManager<T>> {
return registry.byNameCodec().dispatch(
{ listener -> listener.codecId.map(registry::getValue)
.orElseGet { MapCodec.unitCodec(null) }
},
{ codec -> codec.fieldOf("data") }
).listOf().xmap(
{ list -> SerializableListenerManager<T>(CopyOnWriteArraySet<T>(list), onChange) },
{ manager ->
val serializableListeners: MutableList<T> = mutableListOf()
for (listener in manager.listeners) {
if (listener.codecId.isPresent) {
serializableListeners.add(listener)
}
}
return@xmap serializableListeners
}
)
}
}
}
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.listener;
import org.jspecify.annotations.NullMarked;
@@ -2,10 +2,11 @@ package io.github.skippyall.minions.minion;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import io.github.skippyall.minions.registration.MinionRegistries; import io.github.skippyall.minions.registration.MinionRegistries;
import net.minecraft.resources.Identifier;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import net.minecraft.resources.ResourceLocation;
public class MinionConfig { public class MinionConfig {
public static final Codec<MinionConfig> CODEC = Codec.<Option<?>, Object>dispatchedMap( public static final Codec<MinionConfig> CODEC = Codec.<Option<?>, Object>dispatchedMap(
@@ -43,11 +44,11 @@ public class MinionConfig {
return Objects.hashCode(values); return Objects.hashCode(values);
} }
public static Option<Boolean> booleanOption(ResourceLocation key, boolean defaultValue) { public static Option<Boolean> booleanOption(Identifier key, boolean defaultValue) {
return new Option<>(key, defaultValue, Codec.BOOL); return new Option<>(key, defaultValue, Codec.BOOL);
} }
public record Option<T>(ResourceLocation key, T defaultValue, Codec<T> codec) { public record Option<T>(Identifier key, T defaultValue, Codec<T> codec) {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (!(o instanceof Option<?> option)) return false; if (!(o instanceof Option<?> option)) return false;
@@ -1,58 +0,0 @@
package io.github.skippyall.minions.minion;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import io.github.skippyall.minions.listener.SerializableListenerManager;
import io.github.skippyall.minions.registration.MinionRegistries;
import net.minecraft.core.UUIDUtil;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ExtraCodecs;
import java.util.Optional;
import java.util.UUID;
public record MinionData(
UUID uuid,
String name,
Optional<PropertyMap> skin,
boolean isSpawned,
SerializableListenerManager<MinionListener> listeners,
MinionConfig config
) {
public static final Codec<MinionData> CODEC = RecordCodecBuilder.create(instance ->
instance.group(
UUIDUtil.AUTHLIB_CODEC.fieldOf("uuid").forGetter(MinionData::uuid),
Codec.STRING.fieldOf("name").forGetter(MinionData::name),
ExtraCodecs.PROPERTY_MAP.optionalFieldOf("skin").forGetter(MinionData::skin),
Codec.BOOL.optionalFieldOf("isSpawned", false).forGetter(MinionData::isSpawned),
SerializableListenerManager.getCodec(MinionRegistries.MINION_LISTENER_CODECS).optionalFieldOf("listeners").xmap(
optional -> optional.orElseGet(SerializableListenerManager::new),
Optional::of
).forGetter(MinionData::listeners),
MinionConfig.CODEC.optionalFieldOf("config", new MinionConfig()).forGetter(MinionData::config)
).apply(instance, MinionData::new)
);
public static MinionData createDefault(MinecraftServer server) {
return new MinionData(
UUID.randomUUID(),
MinionProfileUtils.newDefaultMinionName(server),
Optional.empty(),
false,
new SerializableListenerManager<>(),
new MinionConfig()
);
}
public MinionData withName(String name) {
return new MinionData(uuid, name, skin, isSpawned, listeners, config);
}
public MinionData withSkin(Optional<PropertyMap> skin) {
return new MinionData(uuid, name, skin, isSpawned, listeners, config);
}
public MinionData withSpawned(boolean isSpawned) {
return new MinionData(uuid, name, skin, isSpawned, listeners, config);
}
}
@@ -0,0 +1,81 @@
package io.github.skippyall.minions.minion
import com.mojang.authlib.properties.PropertyMap
import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.RecordCodecBuilder
import io.github.skippyall.minions.listener.SerializableListenerManager
import io.github.skippyall.minions.registration.MinionRegistries
import net.minecraft.core.UUIDUtil
import net.minecraft.server.MinecraftServer
import net.minecraft.util.ExtraCodecs
import java.util.*
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class MinionData(
initialUuid: UUID,
initialName: String,
initialSkin: Optional<PropertyMap>,
initialIsSpawned: Boolean,
val listeners: SerializableListenerManager<MinionListener>,
initialConfig: MinionConfig,
var onDirty: Runnable = {},
) {
var uuid by DirtyProperty(initialUuid, this::setDirty)
var name by DirtyProperty(initialName, this::setDirty)
var skin by DirtyProperty(initialSkin, this::setDirty)
var isSpawned by DirtyProperty(initialIsSpawned, this::setDirty)
var config by DirtyProperty(initialConfig, this::setDirty)
fun setDirty() {
this@MinionData.onDirty.run()
}
companion object {
@JvmField
val CODEC: Codec<MinionData> =
RecordCodecBuilder.create { instance ->
instance.group(
UUIDUtil.AUTHLIB_CODEC.fieldOf("uuid").forGetter(MinionData::uuid),
Codec.STRING.fieldOf("name").forGetter(MinionData::name),
ExtraCodecs.PROPERTY_MAP.optionalFieldOf("skin").forGetter(MinionData::skin),
Codec.BOOL.optionalFieldOf("isSpawned", false).forGetter(MinionData::isSpawned),
SerializableListenerManager.getCodec<MinionListener>(MinionRegistries.MINION_LISTENER_CODECS)
.optionalFieldOf("listeners").xmap(
{ optional -> optional.orElseGet { SerializableListenerManager() } },
Optional<SerializableListenerManager<MinionListener>>::of
).forGetter(MinionData::listeners),
MinionConfig.CODEC.optionalFieldOf("config", MinionConfig())
.forGetter(MinionData::config)
).apply(
instance,
::MinionData
)
}
@JvmStatic
fun createDefault(server: MinecraftServer): MinionData {
return MinionData(
UUID.randomUUID(),
MinionProfileUtils.newDefaultMinionName(server),
Optional.empty<PropertyMap>(),
false,
SerializableListenerManager(),
MinionConfig()
) {
MinionPersistentState.get(server).isDirty = true
}
}
}
class DirtyProperty<V>(var value: V, val onDirty: () -> Unit) : ReadWriteProperty<Any?, V> {
override fun getValue(thisRef: Any?, property: KProperty<*>): V {
return value
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: V) {
this.value = value
onDirty()
}
}
}
@@ -1,13 +1,8 @@
package io.github.skippyall.minions.minion; package io.github.skippyall.minions.minion;
import eu.pb4.polymer.core.api.item.PolymerItem;
import eu.pb4.polymer.core.api.item.PolymerItemUtils;
import io.github.skippyall.minions.gui.MinionLookGui; import io.github.skippyall.minions.gui.MinionLookGui;
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer; import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.registration.MinionComponentTypes; import io.github.skippyall.minions.registration.MinionComponentTypes;
import net.minecraft.core.component.DataComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
@@ -16,52 +11,29 @@ import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.component.TooltipDisplay;
import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec2; import net.minecraft.world.phys.Vec2;
import org.jetbrains.annotations.Nullable; import org.jspecify.annotations.Nullable;
import xyz.nucleoid.packettweaker.PacketContext;
import java.util.function.Consumer; public class MinionItem extends Item {
public class MinionItem extends Item implements PolymerItem {
public MinionItem(Properties settings) { public MinionItem(Properties settings) {
super(settings); super(settings);
} }
@Override /*@Override
public @Nullable ResourceLocation getPolymerItemModel(ItemStack stack, PacketContext context) {
return null;
}
@Override
public Item getPolymerItem(ItemStack itemStack, PacketContext player) {
return Items.ARMOR_STAND;
}
@Override
public ItemStack getPolymerItemStack(ItemStack stack, TooltipFlag tooltipType, PacketContext player) {
ItemStack out = PolymerItemUtils.createItemStack(stack, tooltipType, player);
out.set(DataComponents.ENCHANTMENT_GLINT_OVERRIDE, true);
return out;
}
@Override
public void appendHoverText(ItemStack stack, TooltipContext context, TooltipDisplay component, Consumer<Component> tooltip, TooltipFlag type) { public void appendHoverText(ItemStack stack, TooltipContext context, TooltipDisplay component, Consumer<Component> tooltip, TooltipFlag type) {
MinionData data = null /*getData(stack)*/; //MinionData data = getData(stack);
if(data != null) { //if(data != null) {
tooltip.accept(Component.translatable("minions.minion_item.tooltip", data.name())); // tooltip.accept(Component.translatable("minions.minion_item.tooltip", data.name()));
} //}
} }*/
@Override @Override
public InteractionResult use(Level world, Player user, InteractionHand hand) { public InteractionResult use(Level world, Player user, InteractionHand hand) {
if(user instanceof ServerPlayer serverPlayer) { if(user instanceof ServerPlayer serverPlayer) {
ItemStack stack = user.getItemInHand(hand); ItemStack stack = user.getItemInHand(hand);
MinionLookGui.open(serverPlayer, stack); new MinionLookGui(serverPlayer, stack);
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
@@ -70,7 +42,7 @@ public class MinionItem extends Item implements PolymerItem {
@Override @Override
public InteractionResult useOn(UseOnContext context) { public InteractionResult useOn(UseOnContext context) {
if(!context.getLevel().isClientSide) { if(!context.getLevel().isClientSide()) {
MinionData data = getDataOrDefault(context.getLevel().getServer(), context.getItemInHand()); MinionData data = getDataOrDefault(context.getLevel().getServer(), context.getItemInHand());
MinionFakePlayer.spawnMinion(data, (ServerLevel) context.getLevel(), context.getClickedPos().getCenter().add(0,0.5,0), new Vec2(0, 0)); MinionFakePlayer.spawnMinion(data, (ServerLevel) context.getLevel(), context.getClickedPos().getCenter().add(0,0.5,0), new Vec2(0, 0));
} }
@@ -79,7 +51,7 @@ public class MinionItem extends Item implements PolymerItem {
} }
public static void setData(MinecraftServer server, MinionData data, ItemStack item) { public static void setData(MinecraftServer server, MinionData data, ItemStack item) {
item.set(MinionComponentTypes.MINION_DATA, data.uuid()); item.set(MinionComponentTypes.MINION_DATA, data.getUuid());
MinionPersistentState.get(server).updateMinionData(data); MinionPersistentState.get(server).updateMinionData(data);
} }
@@ -3,7 +3,7 @@ package io.github.skippyall.minions.minion;
import io.github.skippyall.minions.listener.SerializableListenerManager; import io.github.skippyall.minions.listener.SerializableListenerManager;
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer; import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction; import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
import org.jetbrains.annotations.Nullable; import org.jspecify.annotations.Nullable;
public interface MinionListener extends SerializableListenerManager.SerializableListener { public interface MinionListener extends SerializableListenerManager.SerializableListener {
default void onMinionSpawn(MinionFakePlayer minion) {} default void onMinionSpawn(MinionFakePlayer minion) {}
@@ -1,10 +1,14 @@
package io.github.skippyall.minions.minion; package io.github.skippyall.minions.minion;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import io.github.skippyall.minions.Minions;
import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.saveddata.SavedData; import net.minecraft.world.level.saveddata.SavedData;
import net.minecraft.world.level.saveddata.SavedDataType; import net.minecraft.world.level.saveddata.SavedDataType;
import org.jspecify.annotations.Nullable;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -14,7 +18,12 @@ import java.util.UUID;
public class MinionPersistentState extends SavedData { public class MinionPersistentState extends SavedData {
public static final Codec<MinionPersistentState> CODEC = MinionData.CODEC.listOf().xmap(MinionPersistentState::new, MinionPersistentState::getMinionDataList); public static final Codec<MinionPersistentState> CODEC = MinionData.CODEC.listOf().xmap(MinionPersistentState::new, MinionPersistentState::getMinionDataList);
public static SavedDataType<MinionPersistentState> TYPE = new SavedDataType<>("minion", MinionPersistentState::new, MinionPersistentState.CODEC, null); public static SavedDataType<MinionPersistentState> TYPE = new SavedDataType<>(
Identifier.fromNamespaceAndPath(Minions.MOD_ID, "minion"),
MinionPersistentState::new,
MinionPersistentState.CODEC,
null
);
private final Map<UUID, MinionData> minionData = new HashMap<>(); private final Map<UUID, MinionData> minionData = new HashMap<>();
@@ -24,11 +33,12 @@ public class MinionPersistentState extends SavedData {
public MinionPersistentState(List<MinionData> dataList) { public MinionPersistentState(List<MinionData> dataList) {
for (MinionData data : dataList) { for (MinionData data : dataList) {
minionData.put(data.uuid(), data); data.setOnDirty(this::setDirty);
minionData.put(data.getUuid(), data);
} }
} }
public MinionData getMinionData(UUID uuid) { public @Nullable MinionData getMinionData(UUID uuid) {
return minionData.get(uuid); return minionData.get(uuid);
} }
@@ -41,7 +51,8 @@ public class MinionPersistentState extends SavedData {
} }
public void updateMinionData(MinionData data) { public void updateMinionData(MinionData data) {
minionData.put(data.uuid(), data); minionData.put(data.getUuid(), data);
data.setOnDirty(this::setDirty);
setDirty(); setDirty();
} }
@@ -55,7 +66,7 @@ public class MinionPersistentState extends SavedData {
public Optional<MinionData> getMinionWithName(String name) { public Optional<MinionData> getMinionWithName(String name) {
return minionData.values().stream() return minionData.values().stream()
.filter(data -> data.name().equals(name)) .filter(data -> data.getName().equals(name))
.findFirst(); .findFirst();
} }
@@ -8,6 +8,8 @@ import io.github.skippyall.minions.gui.input.Result;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.util.StringUtil; import net.minecraft.util.StringUtil;
import org.jspecify.annotations.Nullable;
import java.util.UUID; import java.util.UUID;
import static io.github.skippyall.minions.Minions.LOGGER; import static io.github.skippyall.minions.Minions.LOGGER;
@@ -17,15 +19,12 @@ public class MinionProfileUtils {
return MinionsConfig.get().minion.minionPrefix; return MinionsConfig.get().minion.minionPrefix;
} }
public static GameProfile makeNewMinionProfile(UUID uuidMinion, String username, PropertyMap skin) { public static GameProfile makeNewMinionProfile(@Nullable UUID uuidMinion, String username, @Nullable PropertyMap skin) {
if(uuidMinion == null) { if(uuidMinion == null) {
uuidMinion = UUID.randomUUID(); uuidMinion = UUID.randomUUID();
} }
GameProfile newProfile = new GameProfile(uuidMinion, username); GameProfile newProfile = new GameProfile(uuidMinion, username, skin != null ? skin : PropertyMap.EMPTY);
if (skin != null) {
newProfile.getProperties().putAll(skin);
}
LOGGER.info("Minion Profile: {}", newProfile); LOGGER.info("Minion Profile: {}", newProfile);
return newProfile; return newProfile;
} }
@@ -8,13 +8,14 @@ import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
import io.github.skippyall.minions.program.instruction.InstructionType; import io.github.skippyall.minions.program.instruction.InstructionType;
import io.github.skippyall.minions.program.supplier.ValueSupplierType; import io.github.skippyall.minions.program.supplier.ValueSupplierType;
import io.github.skippyall.minions.registration.MinionRegistries; import io.github.skippyall.minions.registration.MinionRegistries;
import net.minecraft.core.Registry;
import net.minecraft.world.level.storage.ValueInput;
import net.minecraft.world.level.storage.ValueOutput;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import net.minecraft.core.Registry;
import net.minecraft.world.level.storage.ValueInput;
import net.minecraft.world.level.storage.ValueOutput;
public class MinionRuntime implements InstructionRuntime<MinionRuntime> { public class MinionRuntime implements InstructionRuntime<MinionRuntime> {
private final MinionFakePlayer minion; private final MinionFakePlayer minion;
@@ -115,7 +116,7 @@ public class MinionRuntime implements InstructionRuntime<MinionRuntime> {
for (ValueInput inner : list) { for (ValueInput inner : list) {
Optional<String> name = inner.getString("name"); Optional<String> name = inner.getString("name");
if(name.isEmpty()) { if(name.isEmpty()) {
Minions.LOGGER.error("Tried deserializing configured instruction without a name of minion \"{}\":", minion.getGameProfile().getName()); Minions.LOGGER.error("Tried deserializing configured instruction without a name of minion \"{}\":", minion.getGameProfile().name());
continue; continue;
} }
@@ -123,7 +124,7 @@ public class MinionRuntime implements InstructionRuntime<MinionRuntime> {
ConfiguredInstruction<MinionRuntime> instruction = ConfiguredInstruction.load(inner, this); ConfiguredInstruction<MinionRuntime> instruction = ConfiguredInstruction.load(inner, this);
configuredInstructions.put(name.get(), instruction); configuredInstructions.put(name.get(), instruction);
} catch (Exception e) { } catch (Exception e) {
Minions.LOGGER.error("Could not deserialize configured instruction \"{}\" of minion \"{}\":", name.get(), minion.getGameProfile().getName(), e); Minions.LOGGER.error("Could not deserialize configured instruction \"{}\" of minion \"{}\":", name.get(), minion.getGameProfile().name(), e);
} }
} }
} }
@@ -3,10 +3,6 @@ package io.github.skippyall.minions.minion.fakeplayer;
import io.github.skippyall.minions.mixins.EntityAccessor; import io.github.skippyall.minions.mixins.EntityAccessor;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.commands.arguments.EntityAnchorArgument; import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
@@ -18,11 +14,11 @@ import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.animal.horse.AbstractHorse; import net.minecraft.world.entity.animal.equine.AbstractHorse;
import net.minecraft.world.entity.decoration.ItemFrame; import net.minecraft.world.entity.decoration.ItemFrame;
import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.vehicle.Boat; import net.minecraft.world.entity.vehicle.boat.Boat;
import net.minecraft.world.entity.vehicle.Minecart; import net.minecraft.world.entity.vehicle.minecart.Minecart;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
@@ -31,6 +27,11 @@ import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec2; import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EntityPlayerActionPack public class EntityPlayerActionPack
{ {
private final MinionFakePlayer player; private final MinionFakePlayer player;
@@ -215,7 +216,7 @@ public class EntityPlayerActionPack
if (closest instanceof AbstractHorse && onlyRideables) if (closest instanceof AbstractHorse && onlyRideables)
((AbstractHorse) closest).mobInteract(player, InteractionHand.MAIN_HAND); ((AbstractHorse) closest).mobInteract(player, InteractionHand.MAIN_HAND);
else else
player.startRiding(closest, !onlyRideables); player.startRiding(closest, !onlyRideables, true);
return this; return this;
} }
public EntityPlayerActionPack dismount() public EntityPlayerActionPack dismount()
@@ -352,13 +353,13 @@ public class EntityPlayerActionPack
boolean handWasEmpty = player.getItemInHand(hand).isEmpty(); boolean handWasEmpty = player.getItemInHand(hand).isEmpty();
boolean itemFrameEmpty = (entity instanceof ItemFrame) && ((ItemFrame) entity).getItem().isEmpty(); boolean itemFrameEmpty = (entity instanceof ItemFrame) && ((ItemFrame) entity).getItem().isEmpty();
Vec3 relativeHitPos = entityHit.getLocation().subtract(entity.getX(), entity.getY(), entity.getZ()); Vec3 relativeHitPos = entityHit.getLocation().subtract(entity.getX(), entity.getY(), entity.getZ());
if (entity.interactAt(player, relativeHitPos, hand).consumesAction()) if (entity.interact(player, hand, relativeHitPos).consumesAction())
{ {
ap.itemUseCooldown = 3; ap.itemUseCooldown = 3;
return true; return true;
} }
// fix for SS itemframe always returns CONSUME even if no action is performed // fix for SS itemframe always returns CONSUME even if no action is performed
if (player.interactOn(entity, hand).consumesAction() && !(handWasEmpty && itemFrameEmpty)) if (player.interactOn(entity, hand, relativeHitPos).consumesAction() && !(handWasEmpty && itemFrameEmpty))
{ {
ap.itemUseCooldown = 3; ap.itemUseCooldown = 3;
return true; return true;
@@ -485,7 +486,8 @@ public class EntityPlayerActionPack
{ {
if (action.limit == 1) if (action.limit == 1)
{ {
if (player.onGround()) player.jumpFromGround(); // onGround if (player.onGround()) player.jumpFromGround();
else if (!player.onClimbable()) player.tryToStartFallFlying();
} }
else else
{ {
@@ -1,11 +1,14 @@
//code from https://github.com/gnembon/fabric-carpet //code from https://github.com/gnembon/fabric-carpet
package io.github.skippyall.minions.minion.fakeplayer; package io.github.skippyall.minions.minion.fakeplayer;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import net.minecraft.network.Connection; import net.minecraft.network.Connection;
import net.minecraft.network.PacketListener; import net.minecraft.network.PacketListener;
import net.minecraft.network.ProtocolInfo; import net.minecraft.network.ProtocolInfo;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketFlow; import net.minecraft.network.protocol.PacketFlow;
import org.jspecify.annotations.Nullable;
public class FakeClientConnection extends Connection { public class FakeClientConnection extends Connection {
public FakeClientConnection(PacketFlow p) public FakeClientConnection(PacketFlow p)
@@ -16,6 +19,11 @@ public class FakeClientConnection extends Connection {
((ClientConnectionInterface)this).setChannel(new EmbeddedChannel()); ((ClientConnectionInterface)this).setChannel(new EmbeddedChannel());
} }
@Override
public void send(Packet<?> packet, @Nullable ChannelFutureListener listener, boolean flush) {
}
@Override @Override
public void setReadOnly() public void setReadOnly()
{ {
@@ -3,6 +3,7 @@ package io.github.skippyall.minions.minion.fakeplayer;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.PropertyMap; import com.mojang.authlib.properties.PropertyMap;
import io.github.skippyall.minions.Minions;
import io.github.skippyall.minions.gui.minion.MinionGui; import io.github.skippyall.minions.gui.minion.MinionGui;
import io.github.skippyall.minions.listener.SerializableListenerManager; import io.github.skippyall.minions.listener.SerializableListenerManager;
import io.github.skippyall.minions.minion.MinionData; import io.github.skippyall.minions.minion.MinionData;
@@ -15,6 +16,7 @@ import io.github.skippyall.minions.module.ModuleInventory;
import io.github.skippyall.minions.registration.MinionConfigOptions; import io.github.skippyall.minions.registration.MinionConfigOptions;
import io.github.skippyall.minions.registration.MinionItems; import io.github.skippyall.minions.registration.MinionItems;
import io.github.skippyall.minions.registration.SpecialAbilities; import io.github.skippyall.minions.registration.SpecialAbilities;
import net.fabricmc.fabric.impl.networking.context.PacketContextImpl;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.network.DisconnectionDetails; import net.minecraft.network.DisconnectionDetails;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
@@ -29,6 +31,7 @@ import net.minecraft.server.level.ClientInformation;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.CommonListenerCookie; import net.minecraft.server.network.CommonListenerCookie;
import net.minecraft.util.ProblemReporter;
import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResult;
import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.damagesource.DamageSource;
@@ -37,21 +40,25 @@ import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.vehicle.AbstractBoat; import net.minecraft.world.entity.vehicle.boat.AbstractBoat;
import net.minecraft.world.food.FoodData; import net.minecraft.world.food.FoodData;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.GameType; import net.minecraft.world.level.GameType;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.portal.TeleportTransition; import net.minecraft.world.level.portal.TeleportTransition;
import net.minecraft.world.level.storage.TagValueInput;
import net.minecraft.world.level.storage.ValueInput; import net.minecraft.world.level.storage.ValueInput;
import net.minecraft.world.level.storage.ValueOutput; import net.minecraft.world.level.storage.ValueOutput;
import net.minecraft.world.phys.Vec2; import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.Nullable; import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
@NullMarked
public class MinionFakePlayer extends ServerPlayer { public class MinionFakePlayer extends ServerPlayer {
public Runnable fixStartingPosition = () -> {}; public Runnable fixStartingPosition = () -> {};
@@ -68,21 +75,31 @@ public class MinionFakePlayer extends ServerPlayer {
if(!data.isSpawned() || force) { if(!data.isSpawned() || force) {
MinecraftServer server = level.getServer(); MinecraftServer server = level.getServer();
PropertyMap skin = data.skin().orElse(null); PropertyMap skin = data.getSkin().orElse(null);
GameProfile profile = MinionProfileUtils.makeNewMinionProfile(data.uuid(), data.name(), skin); GameProfile profile = MinionProfileUtils.makeNewMinionProfile(data.getUuid(), data.getName(), skin);
server.schedule(server.wrapRunnable(() -> doSpawn(data, profile, server, level, pos, rot))); server.schedule(server.wrapRunnable(() -> doSpawn(data, profile, server, level, pos, rot)));
} }
} }
private static void doSpawn(MinionData data, GameProfile profile, MinecraftServer server, ServerLevel level, @Nullable Vec3 pos, @Nullable Vec2 rot) { private static void doSpawn(MinionData data, GameProfile profile, MinecraftServer server, ServerLevel level, @Nullable Vec3 pos, @Nullable Vec2 rot) {
MinionFakePlayer instance = new MinionFakePlayer(server, level, profile, ClientInformation.createDefault()); MinionFakePlayer instance = new MinionFakePlayer(server, level, profile, ClientInformation.createDefault());
MinionPersistentState.get(server).updateMinionData(data.withSpawned(true)); data.setSpawned(true);
if(pos != null && rot != null) { if(pos != null && rot != null) {
instance.fixStartingPosition = () -> instance.snapTo(pos.x, pos.y, pos.z, rot.x, rot.y); instance.fixStartingPosition = () -> instance.snapTo(pos.x, pos.y, pos.z, rot.x, rot.y);
} }
server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), instance, new CommonListenerCookie(profile, 0, instance.clientInformation(), false)); FakeClientConnection connection = new FakeClientConnection(PacketFlow.SERVERBOUND);
//noinspection UnstableApiUsage
connection.getPacketContext().set(PacketContextImpl.REGISTRY_ACCESS, server.registryAccess());
//noinspection UnstableApiUsage
connection.getPacketContext().set(PacketContextImpl.SERVER_INSTANCE, server);
//noinspection UnstableApiUsage
connection.getPacketContext().set(PacketContextImpl.GAME_PROFILE, profile);
server.getPlayerList().placeNewPlayer(connection, instance, new CommonListenerCookie(profile, 0, instance.clientInformation(), false));
loadPlayerData(instance);
instance.stopRiding(); // otherwise the created fake player will be on the vehicle
System.out.println(instance.position()); System.out.println(instance.position());
if(pos != null && rot != null) { if(pos != null && rot != null) {
instance.teleportTo(level, pos.x, pos.y, pos.z, Set.of(), rot.x, rot.y, true); instance.teleportTo(level, pos.x, pos.y, pos.z, Set.of(), rot.x, rot.y, true);
@@ -102,6 +119,19 @@ public class MinionFakePlayer extends ServerPlayer {
instance.listeners().forEach(listener -> listener.onMinionSpawn(instance)); instance.listeners().forEach(listener -> listener.onMinionSpawn(instance));
} }
private static void loadPlayerData(MinionFakePlayer player)
{
try (ProblemReporter.ScopedCollector scopedCollector = new ProblemReporter.ScopedCollector(player.problemPath(), Minions.LOGGER))
{
Optional<ValueInput> optional = player.level().getServer().getPlayerList().loadPlayerData(player.nameAndId()).map((compoundTag) -> TagValueInput.create(scopedCollector, player.registryAccess(), compoundTag));
optional.ifPresent( valueInput -> {
player.load(valueInput);
player.loadAndSpawnEnderPearls(valueInput);
player.loadAndSpawnParentVehicle(valueInput);
});
}
}
public static MinionFakePlayer respawnFake(MinecraftServer server, ServerLevel level, GameProfile profile, ClientInformation cli) public static MinionFakePlayer respawnFake(MinecraftServer server, ServerLevel level, GameProfile profile, ClientInformation cli)
{ {
return new MinionFakePlayer(server, level, profile, cli); return new MinionFakePlayer(server, level, profile, cli);
@@ -130,7 +160,7 @@ public class MinionFakePlayer extends ServerPlayer {
} }
public SerializableListenerManager<MinionListener> listeners() { public SerializableListenerManager<MinionListener> listeners() {
return getData().listeners(); return getData().getListeners();
} }
public void addMinionListener(MinionListener listener) { public void addMinionListener(MinionListener listener) {
@@ -146,26 +176,25 @@ public class MinionFakePlayer extends ServerPlayer {
} }
public boolean canSpawnMobs() { public boolean canSpawnMobs() {
return moduleInventory.hasAbility(SpecialAbilities.MOB_SPAWNING) || getData().config().getOption(MinionConfigOptions.spawnAndDespawnMobs); return moduleInventory.hasAbility(SpecialAbilities.MOB_SPAWNING) || getData().getConfig().getOption(MinionConfigOptions.spawnAndDespawnMobs);
} }
public boolean canDespawnMobs() { public boolean canDespawnMobs() {
return canSpawnMobs(); return canSpawnMobs();
} }
public MinecraftServer getServer() {
return level().getServer();
}
@Override @Override
public InteractionResult interact(Player player, InteractionHand hand) { public InteractionResult interact(Player player, InteractionHand hand, Vec3 location) {
if(player instanceof ServerPlayer spe) { if(player instanceof ServerPlayer spe) {
new MinionGui(spe, this); new MinionGui(spe, this);
} }
return InteractionResult.CONSUME; return InteractionResult.CONSUME;
} }
@Override
public InteractionResult interactAt(Player player, Vec3 hitPos, InteractionHand hand) {
return interact(player, hand);
}
@Override @Override
public void onEquipItem(final EquipmentSlot slot, final ItemStack previous, final ItemStack stack) public void onEquipItem(final EquipmentSlot slot, final ItemStack previous, final ItemStack stack)
{ {
@@ -186,7 +215,7 @@ public class MinionFakePlayer extends ServerPlayer {
})); }));
} }
MinionPersistentState.get(getServer()).updateMinionData(getData().withSpawned(false)); getData().setSpawned(false);
} }
@Override @Override
@@ -213,8 +242,8 @@ public class MinionFakePlayer extends ServerPlayer {
} }
@Override @Override
public boolean startRiding(Entity entityToRide, boolean force) { public boolean startRiding(Entity entityToRide, boolean force, boolean sendEventAndTriggers) {
if (super.startRiding(entityToRide, force)) { if (super.startRiding(entityToRide, force, sendEventAndTriggers)) {
// from ClientPacketListener.handleSetEntityPassengersPacket // from ClientPacketListener.handleSetEntityPassengersPacket
if (entityToRide instanceof AbstractBoat) { if (entityToRide instanceof AbstractBoat) {
this.yRotO = entityToRide.getYRot(); this.yRotO = entityToRide.getYRot();
@@ -283,6 +312,7 @@ public class MinionFakePlayer extends ServerPlayer {
public void dropAllDeathLoot(ServerLevel world, DamageSource damageSource) { public void dropAllDeathLoot(ServerLevel world, DamageSource damageSource) {
super.dropAllDeathLoot(world, damageSource); super.dropAllDeathLoot(world, damageSource);
ItemEntity entity = drop(toItemStack(world.getServer()), true, false); ItemEntity entity = drop(toItemStack(world.getServer()), true, false);
//noinspection ConstantValue (Wrong nullability of drop)
if (entity != null) { if (entity != null) {
entity.setUnlimitedLifetime(); entity.setUnlimitedLifetime();
} }
@@ -4,13 +4,13 @@ package io.github.skippyall.minions.minion.fakeplayer;
import net.minecraft.network.Connection; import net.minecraft.network.Connection;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.contents.TranslatableContents; import net.minecraft.network.chat.contents.TranslatableContents;
import net.minecraft.network.protocol.Packet;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.CommonListenerCookie; import net.minecraft.server.network.CommonListenerCookie;
import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.world.entity.PositionMoveRotation; import net.minecraft.world.entity.PositionMoveRotation;
import net.minecraft.world.entity.Relative; import net.minecraft.world.entity.Relative;
import java.util.Set; import java.util.Set;
public class NetHandlerPlayServerFake extends ServerGamePacketListenerImpl public class NetHandlerPlayServerFake extends ServerGamePacketListenerImpl
@@ -20,11 +20,6 @@ public class NetHandlerPlayServerFake extends ServerGamePacketListenerImpl
super(minecraftServer, connection, serverPlayer, i); super(minecraftServer, connection, serverPlayer, i);
} }
@Override
public void send(final Packet<?> packetIn)
{
}
@Override @Override
public void disconnect(Component message) public void disconnect(Component message)
{ {
@@ -1,8 +1,6 @@
//code from https://github.com/gnembon/fabric-carpet //code from https://github.com/gnembon/fabric-carpet
package io.github.skippyall.minions.minion.fakeplayer; package io.github.skippyall.minions.minion.fakeplayer;
import java.util.Optional;
import java.util.function.Predicate;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
@@ -12,6 +10,9 @@ import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
import java.util.Optional;
import java.util.function.Predicate;
public class Tracer public class Tracer
{ {
public static HitResult rayTrace(Entity source, float partialTicks, double reach, boolean fluids) public static HitResult rayTrace(Entity source, float partialTicks, double reach, boolean fluids)
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.minion;
import org.jspecify.annotations.NullMarked;
@@ -16,9 +16,10 @@ import net.minecraft.world.level.storage.ValueInput;
import net.minecraft.world.level.storage.ValueOutput; import net.minecraft.world.level.storage.ValueOutput;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.HitResult;
import org.jspecify.annotations.Nullable;
public class MineBlockExecution implements InstructionExecution<MinionRuntime> { public class MineBlockExecution implements InstructionExecution<MinionRuntime> {
private BlockPos currentBlock; private @Nullable BlockPos currentBlock;
private float currentBlockDamage = 0; private float currentBlockDamage = 0;
private boolean first = true; private boolean first = true;
private boolean done = false; private boolean done = false;
@@ -38,7 +39,6 @@ public class MineBlockExecution implements InstructionExecution<MinionRuntime> {
} }
if (player.blockActionRestricted(player.level(), hit.getBlockPos(), player.gameMode.getGameModeForPlayer())) { if (player.blockActionRestricted(player.level(), hit.getBlockPos(), player.gameMode.getGameModeForPlayer())) {
done = true; done = true;
return;
} }
} else { } else {
done = true; done = true;
@@ -8,7 +8,7 @@ import io.github.skippyall.minions.program.supplier.Parameter;
import io.github.skippyall.minions.program.supplier.ParameterValueList; import io.github.skippyall.minions.program.supplier.ParameterValueList;
import io.github.skippyall.minions.registration.ValueTypes; import io.github.skippyall.minions.registration.ValueTypes;
import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.ClickType; import net.minecraft.world.inventory.ContainerInput;
import net.minecraft.world.inventory.Slot; import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.ValueInput; import net.minecraft.world.level.storage.ValueInput;
@@ -93,7 +93,7 @@ public class SwapItemExecution implements InstructionExecution<MinionRuntime> {
AbstractContainerMenu screenHandler = getScreen(minion, screen); AbstractContainerMenu screenHandler = getScreen(minion, screen);
ItemStack previousCursor = screenHandler.getCarried(); ItemStack previousCursor = screenHandler.getCarried();
screenHandler.setCarried(cursor); screenHandler.setCarried(cursor);
screenHandler.clicked(slotIndex, 0, ClickType.SWAP, minion); screenHandler.clicked(slotIndex, 0, ContainerInput.SWAP, minion);
cursor = screenHandler.getCarried(); cursor = screenHandler.getCarried();
screenHandler.setCarried(previousCursor); screenHandler.setCarried(previousCursor);
} }
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.minion.program.instruction.inventory;
import org.jspecify.annotations.NullMarked;
@@ -3,9 +3,10 @@ package io.github.skippyall.minions.minion.program.instruction.move;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import io.github.skippyall.minions.gui.Displayable; import io.github.skippyall.minions.gui.Displayable;
import io.github.skippyall.minions.gui.GuiDisplay; import io.github.skippyall.minions.gui.GuiDisplay;
import java.util.UUID;
import net.minecraft.util.StringRepresentable; import net.minecraft.util.StringRepresentable;
import java.util.UUID;
public enum TurnDirection implements StringRepresentable, Displayable { public enum TurnDirection implements StringRepresentable, Displayable {
LEFT("left", -1, 0), LEFT("left", -1, 0),
UP("up", 0, -1), UP("up", 0, -1),
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.minion.program.instruction.move;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.minion.program.instruction;
import org.jspecify.annotations.NullMarked;
@@ -16,15 +16,15 @@ import io.github.skippyall.minions.registration.MinionComponentTypes;
import io.github.skippyall.minions.registration.MinionItems; import io.github.skippyall.minions.registration.MinionItems;
import io.github.skippyall.minions.registration.ValueSuppliers; import io.github.skippyall.minions.registration.ValueSuppliers;
import io.github.skippyall.minions.registration.ValueTypes; import io.github.skippyall.minions.registration.ValueTypes;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.CompletableFuture;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import org.jspecify.annotations.Nullable;
import java.util.concurrent.CompletableFuture;
public class AnalogInputSupplier implements ValueSupplier<Long, MinionRuntime> { public class AnalogInputSupplier implements ValueSupplier<Long, MinionRuntime> {
public static final Codec<AnalogInputSupplier> CODEC = RecordCodecBuilder.create(instance -> public static final Codec<AnalogInputSupplier> CODEC = RecordCodecBuilder.create(instance ->
@@ -63,7 +63,7 @@ public class AnalogInputSupplier implements ValueSupplier<Long, MinionRuntime> {
@Override @Override
public Component getDisplayText() { public Component getDisplayText() {
return Component.translatable("value_supplier.minions.analog_input.display", analogInputPos.toShortString(), analogInputWorld.location().toString()); return Component.translatable("value_supplier.minions.analog_input.display", analogInputPos.toShortString(), analogInputWorld.identifier().toString());
} }
public static class AnalogInputSupplierType extends ValueSupplierType<MinionRuntime> { public static class AnalogInputSupplierType extends ValueSupplierType<MinionRuntime> {
@@ -79,19 +79,21 @@ public class AnalogInputSupplier implements ValueSupplier<Long, MinionRuntime> {
public <T> CompletableFuture<ValueSupplier<?, MinionRuntime>> openConfiguration(MinionsGui parent, ValueType<T> valueType, @Nullable ValueSupplier<?, MinionRuntime> previous) { public <T> CompletableFuture<ValueSupplier<?, MinionRuntime>> openConfiguration(MinionsGui parent, ValueType<T> valueType, @Nullable ValueSupplier<?, MinionRuntime> previous) {
CompletableFuture<ValueSupplier<?, MinionRuntime>> future = new CompletableFuture<>(); CompletableFuture<ValueSupplier<?, MinionRuntime>> future = new CompletableFuture<>();
new SimpleMinionsGui(parent, (onClose, me) -> { new SimpleMinionsGui(parent, (onClose, me) -> {
SimpleGui gui = new SimpleGui(MenuType.GENERIC_3x3, parent.getViewer(), false) { SimpleGui gui = new SimpleGui(MenuType.GENERIC_3x3, parent.viewer, false) {
@Override @Override
public void onClose() { public void onPlayerClose(boolean success) {
onClose.run(); onClose.run();
} }
}; };
gui.setTitle(Component.translatable("value_supplier.minions.analog_input")); gui.setTitle(Component.translatable("value_supplier.minions.analog_input"));
gui.setSlot(2, me.backButton());
gui.setSlot(4, new GuiElementBuilder(MinionItems.REFERENCE_ITEM) gui.setSlot(4, new GuiElementBuilder(MinionItems.REFERENCE_ITEM)
.setCallback(() -> { .setCallback(() -> {
ItemStack cursor = parent.getViewer().containerMenu.getCarried(); ItemStack cursor = parent.viewer.containerMenu.getCarried();
if (cursor.is(MinionItems.REFERENCE_ITEM) && cursor.get(MinionComponentTypes.REFERENCE) instanceof BlockPosClipboard pos) { if (cursor.is(MinionItems.REFERENCE_ITEM) && cursor.get(MinionComponentTypes.REFERENCE) instanceof BlockPosClipboard pos) {
future.complete(new AnalogInputSupplier(pos.world(), pos.pos())); future.complete(new AnalogInputSupplier(pos.world(), pos.pos()));
me.goBack();
} }
}) })
.setItemName(Component.translatable("value_supplier.minions.analog_input.config.click_with_reference")) .setItemName(Component.translatable("value_supplier.minions.analog_input.config.click_with_reference"))
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.minion.program.supplier;
import org.jspecify.annotations.NullMarked;
@@ -1,20 +1,19 @@
package io.github.skippyall.minions.minion.skin; package io.github.skippyall.minions.minion.skin;
import com.google.common.collect.ImmutableMultimap;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property; import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap; import com.mojang.authlib.properties.PropertyMap;
import io.github.skippyall.minions.Minions; import io.github.skippyall.minions.Minions;
import java.util.HashMap; import io.github.skippyall.minions.gui.MinionsGui;
import java.util.List; import net.fabricmc.fabric.api.entity.FakePlayer;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.registries.Registries; import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag; import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.dialog.ActionButton; import net.minecraft.server.dialog.ActionButton;
import net.minecraft.server.dialog.CommonButtonData; import net.minecraft.server.dialog.CommonButtonData;
import net.minecraft.server.dialog.CommonDialogData; import net.minecraft.server.dialog.CommonDialogData;
@@ -24,20 +23,26 @@ import net.minecraft.server.dialog.Input;
import net.minecraft.server.dialog.NoticeDialog; import net.minecraft.server.dialog.NoticeDialog;
import net.minecraft.server.dialog.action.CustomAll; import net.minecraft.server.dialog.action.CustomAll;
import net.minecraft.server.dialog.input.TextInput; import net.minecraft.server.dialog.input.TextInput;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.component.ResolvableProfile;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public class Base64SkinProvider implements SkinProvider { public class Base64SkinProvider implements SkinProvider {
public static final ResourceKey<Dialog> DIALOG = ResourceKey.create(Registries.DIALOG, ResourceLocation.fromNamespaceAndPath(Minions.MOD_ID, "base_64_input")); public static final ResourceKey<Dialog> DIALOG = ResourceKey.create(Registries.DIALOG, Identifier.fromNamespaceAndPath(Minions.MOD_ID, "base_64_input"));
public static final ResourceLocation CUSTOM_DIALOG_ACTION = ResourceLocation.fromNamespaceAndPath(Minions.MOD_ID, "base_64_submit"); public static final Identifier CUSTOM_DIALOG_ACTION = Identifier.fromNamespaceAndPath(Minions.MOD_ID, "base_64_submit");
private static long dialogIdCounter = 0; private static long dialogIdCounter = 0;
private static Map<Long, CompletableFuture<Optional<PropertyMap>>> futures = new HashMap<>(); private static Map<Long, CompletableFuture<ResolvableProfile>> futures = new HashMap<>();
@Override @Override
public CompletableFuture<Optional<PropertyMap>> openSkinMenu(ServerPlayer player) { public CompletableFuture<ResolvableProfile> openSkinMenu(MinionsGui parent) {
dialogIdCounter++; dialogIdCounter++;
player.openDialog(getDialog()); parent.viewer.openDialog(getDialog());
CompletableFuture<Optional<PropertyMap>> future = new CompletableFuture<>(); CompletableFuture<ResolvableProfile> future = new CompletableFuture<>();
futures.put(dialogIdCounter, future); futures.put(dialogIdCounter, future);
return future; return future;
} }
@@ -48,10 +53,11 @@ public class Base64SkinProvider implements SkinProvider {
Optional<String> base64 = compound.getString("base_64"); Optional<String> base64 = compound.getString("base_64");
if(id.isPresent() && base64.isPresent() && !base64.get().isBlank()) { if(id.isPresent() && base64.isPresent() && !base64.get().isBlank()) {
if(futures.containsKey(id.get())) { if(futures.containsKey(id.get())) {
PropertyMap map = new PropertyMap(); PropertyMap map = new PropertyMap(ImmutableMultimap.of(
map.put("textures", new Property("textures", base64.get().strip())); "textures", new Property("textures", base64.get().strip())
));
futures.get(id.get()).complete(Optional.of(map)); futures.get(id.get()).complete(ResolvableProfile.createResolved(new GameProfile(FakePlayer.DEFAULT_UUID, "", map)));
futures.remove(id.get()); futures.remove(id.get());
} }
} }
@@ -1,20 +1,18 @@
package io.github.skippyall.minions.minion.skin; package io.github.skippyall.minions.minion.skin;
import com.mojang.authlib.GameProfile; import io.github.skippyall.minions.gui.MinionsGui;
import com.mojang.authlib.properties.PropertyMap;
import io.github.skippyall.minions.gui.input.TextInput; import io.github.skippyall.minions.gui.input.TextInput;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.component.ResolvableProfile;
import net.minecraft.world.level.block.entity.SkullBlockEntity; import org.jspecify.annotations.Nullable;
import java.util.concurrent.CompletableFuture;
public class NameSkinProvider implements SkinProvider { public class NameSkinProvider implements SkinProvider {
@Override @Override
public CompletableFuture<Optional<PropertyMap>> openSkinMenu(ServerPlayer player) { public CompletableFuture<@Nullable ResolvableProfile> openSkinMenu(MinionsGui parent) {
return TextInput.inputString(player, Component.translatable("minions.gui.look.skin.name.title"), "") return TextInput.inputString(parent, Component.translatable("minions.gui.look.skin.name.title"), "")
.thenCompose(SkullBlockEntity::fetchGameProfile) .thenApply(name -> name != null ? ResolvableProfile.createUnresolved(name) : null);
.thenApply(gameProfile -> gameProfile.map(GameProfile::getProperties));
} }
@Override @Override
@@ -1,13 +1,14 @@
package io.github.skippyall.minions.minion.skin; package io.github.skippyall.minions.minion.skin;
import com.mojang.authlib.properties.PropertyMap; import io.github.skippyall.minions.gui.MinionsGui;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.component.ResolvableProfile;
import org.jspecify.annotations.Nullable;
import java.util.concurrent.CompletableFuture;
public interface SkinProvider { public interface SkinProvider {
CompletableFuture<Optional<PropertyMap>> openSkinMenu(ServerPlayer player); CompletableFuture<@Nullable ResolvableProfile> openSkinMenu(MinionsGui parent);
Component getDisplayName(); Component getDisplayName();
} }
@@ -1,21 +1,18 @@
package io.github.skippyall.minions.minion.skin; package io.github.skippyall.minions.minion.skin;
import com.mojang.authlib.GameProfile; import io.github.skippyall.minions.gui.MinionsGui;
import com.mojang.authlib.properties.PropertyMap;
import io.github.skippyall.minions.gui.input.TextInput; import io.github.skippyall.minions.gui.input.TextInput;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.component.ResolvableProfile;
import net.minecraft.world.level.block.entity.SkullBlockEntity; import org.jspecify.annotations.Nullable;
import java.util.concurrent.CompletableFuture;
public class UUIDSkinProvider implements SkinProvider { public class UUIDSkinProvider implements SkinProvider {
@Override @Override
public CompletableFuture<Optional<PropertyMap>> openSkinMenu(ServerPlayer player) { public CompletableFuture<@Nullable ResolvableProfile> openSkinMenu(MinionsGui parent) {
return TextInput.inputString(player, Component.translatable("minions.gui.look.skin.uuid.title"), "") return TextInput.inputString(parent, Component.translatable("minions.gui.look.skin.uuid.title"), "")
.thenCompose(uuidString -> SkullBlockEntity.fetchGameProfile(UUID.fromString(uuidString))) .thenApply(name -> name != null ? ResolvableProfile.createUnresolved(name) : null);
.thenApply(gameProfile -> gameProfile.map(GameProfile::getProperties));
} }
@Override @Override
@@ -0,0 +1,4 @@
@NullMarked
package io.github.skippyall.minions.minion.skin;
import org.jspecify.annotations.NullMarked;
@@ -1,8 +1,9 @@
package io.github.skippyall.minions.mixinhelper; package io.github.skippyall.minions.mixinhelper;
import java.util.function.Predicate;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import java.util.function.Predicate;
public class EntityViewMixinHelper { public class EntityViewMixinHelper {
public static final ThreadLocal<Predicate<Entity>> ADDITIONAL_PREDICATE = ThreadLocal.withInitial(() -> entity -> true); public static final ThreadLocal<Predicate<Entity>> ADDITIONAL_PREDICATE = ThreadLocal.withInitial(() -> entity -> true);
} }
@@ -13,7 +13,7 @@ import org.spongepowered.asm.mixin.injection.ModifyArg;
public class ClientboundPlayerInfoUpdatePacket$EntryMixin { public class ClientboundPlayerInfoUpdatePacket$EntryMixin {
@ModifyArg(method = "<init>(Lnet/minecraft/server/level/ServerPlayer;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/protocol/game/ClientboundPlayerInfoUpdatePacket$Entry;<init>(Ljava/util/UUID;Lcom/mojang/authlib/GameProfile;ZILnet/minecraft/world/level/GameType;Lnet/minecraft/network/chat/Component;ZILnet/minecraft/network/chat/RemoteChatSession$Data;)V"), index = 2) @ModifyArg(method = "<init>(Lnet/minecraft/server/level/ServerPlayer;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/protocol/game/ClientboundPlayerInfoUpdatePacket$Entry;<init>(Ljava/util/UUID;Lcom/mojang/authlib/GameProfile;ZILnet/minecraft/world/level/GameType;Lnet/minecraft/network/chat/Component;ZILnet/minecraft/network/chat/RemoteChatSession$Data;)V"), index = 2)
private static boolean removeMinionFromTabList(boolean original, @Local(argsOnly = true) ServerPlayer player) { private static boolean removeMinionFromTabList(boolean original, @Local(argsOnly = true) ServerPlayer player) {
if(player instanceof MinionFakePlayer minion && !minion.getData().config().getOption(MinionConfigOptions.showInTabList)) { if(player instanceof MinionFakePlayer minion && !minion.getData().getConfig().getOption(MinionConfigOptions.showInTabList)) {
return false; return false;
} }
@@ -1,10 +1,10 @@
package io.github.skippyall.minions.mixins; package io.github.skippyall.minions.mixins;
import net.minecraft.world.entity.Entity;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.gen.Invoker;
import java.util.stream.Stream; import java.util.stream.Stream;
import net.minecraft.world.entity.Entity;
@Mixin(Entity.class) @Mixin(Entity.class)
public interface EntityAccessor { public interface EntityAccessor {
@@ -12,5 +12,5 @@ public interface EntityAccessor {
boolean minions$canAddPassenger(Entity other); boolean minions$canAddPassenger(Entity other);
@Invoker("getIndirectPassengersStream") @Invoker("getIndirectPassengersStream")
Stream<Entity> minions$streamIntoPassengers(); Stream<Entity> minions$getIndirectPassengersStream();
} }

Some files were not shown because too many files have changed in this diff Show More