10 Commits

Author SHA1 Message Date
skippyall 271d584161 Update ActionModules.java 2024-09-20 10:15:49 +02:00
skippyall 82dbf9ca95 Update ActionModules.java 2024-09-19 10:14:28 +02:00
skippyall 09a7b7c0ff Add stop(ActionType) 2024-09-19 10:10:57 +02:00
skippyall 6526f92a67 Actually start actions 2024-09-18 21:21:18 +02:00
skippyall d6a324a93f e 2024-09-17 10:46:43 +02:00
skippyall 1dd6914454 e 2024-09-17 09:55:43 +02:00
skippyall c497884884 e 2024-09-13 19:37:38 +02:00
skippyall a236abdd5c Recipe 2024-09-01 19:52:35 +02:00
skippyall b4d8df9e8e Merge spawnMinion and spawnMinionAt 2024-09-01 18:49:33 +02:00
skippyall 2ee3d946ec Merge pull request #1 from Mineattack-Foxgalaxy/master
ErfinderLabyrinth's changes
2024-09-01 17:35:12 +02:00
49 changed files with 1038 additions and 554 deletions
+13 -2
View File
@@ -27,8 +27,9 @@ dependencies {
// Fabric API. This is technically optional, but you probably want it anyway. // Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
modImplementation include("eu.pb4:polymer-core:${project.polymer_version}") modImplementation "eu.pb4:polymer-core:${project.polymer_version}"
modImplementation include("eu.pb4:sgui:${project.sgui_version}") modImplementation include("eu.pb4:sgui:${project.sgui_version}")
modImplementation include("xyz.nucleoid:server-translations-api:${project.server_translations_version}")
} }
processResources { processResources {
@@ -76,7 +77,7 @@ jar {
// configure the maven publication // configure the maven publication
publishing { publishing {
publications { publications {
mavenJava(MavenPublication) { minions (MavenPublication) {
from components.java from components.java
} }
} }
@@ -87,5 +88,15 @@ publishing {
// Notice: This block does NOT have the same function as the block in the top level. // 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 // The repositories here will be used for publishing your artifact, not for
// retrieving dependencies. // retrieving dependencies.
maven {
def release = "https://maven.foxgalaxy.de/private-releases"
def snapshot = "https://maven.foxgalaxy.de/private-snapshot"
url = version.endsWith('SNAPSHOT') ? snapshot : release
credentials {
username = "${maven_user}"
password = "${maven_password}"
}
}
} }
} }
+2 -1
View File
@@ -8,7 +8,7 @@ org.gradle.jvmargs=-Xmx1G
yarn_mappings=1.21.1+build.3 yarn_mappings=1.21.1+build.3
# Mod Properties # Mod Properties
mod_version = 0.0.1 mod_version = 0.0.1-SNAPSHOT
maven_group = io.github.skippyall maven_group = io.github.skippyall
archives_base_name = Minions archives_base_name = Minions
@@ -18,3 +18,4 @@ org.gradle.jvmargs=-Xmx1G
polymer_version=0.9.12+1.21.1 polymer_version=0.9.12+1.21.1
sgui_version=1.6.0+1.21 sgui_version=1.6.0+1.21
server_translations_version=2.3.1+1.21-pre2
@@ -1,12 +1,16 @@
package io.github.skippyall.minions; package io.github.skippyall.minions;
import eu.pb4.polymer.core.api.entity.PolymerEntityUtils; import eu.pb4.polymer.core.api.entity.PolymerEntityUtils;
import eu.pb4.polymer.core.api.item.SimplePolymerItem;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer; import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.minion.MinionItem; import io.github.skippyall.minions.minion.MinionItem;
import io.github.skippyall.minions.minion.MinionPersistentState; import io.github.skippyall.minions.minion.MinionPersistentState;
import io.github.skippyall.minions.module.Modules;
import net.fabricmc.api.ModInitializer; import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.minecraft.item.Item;
import net.minecraft.item.Items;
import net.minecraft.registry.Registries; import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry; import net.minecraft.registry.Registry;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
@@ -20,6 +24,7 @@ import java.util.List;
public class Minions implements ModInitializer { public class Minions implements ModInitializer {
public static final String MOD_ID = "minions"; public static final String MOD_ID = "minions";
public static final MinionItem MINION_ITEM = Registry.register(Registries.ITEM, Identifier.of(MOD_ID, "minion"), new MinionItem(false)); public static final MinionItem MINION_ITEM = Registry.register(Registries.ITEM, Identifier.of(MOD_ID, "minion"), new MinionItem(false));
public static final SimplePolymerItem BASIC_UPGRADE_BASE = Registry.register(Registries.ITEM, Identifier.of(MOD_ID, "basic_upgrade_base"), new SimplePolymerItem(new Item.Settings(), Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE));
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
@@ -33,7 +38,7 @@ public class Minions implements ModInitializer {
MinionPersistentState.create(server); MinionPersistentState.create(server);
MinionPersistentState.INSTANCE.getMinionData().forEach(data -> { MinionPersistentState.INSTANCE.getMinionData().forEach(data -> {
System.out.println("spawn Minion " + data.name); System.out.println("spawn Minion " + data.name);
MinionFakePlayer.spawnMinion(data, server.getOverworld()); MinionFakePlayer.spawnMinionAt(data, server.getOverworld(), null, null);
}); });
}); });
ServerTickEvents.START_SERVER_TICK.register(server -> { ServerTickEvents.START_SERVER_TICK.register(server -> {
@@ -44,6 +49,8 @@ public class Minions implements ModInitializer {
executeOnNextTick.clear(); executeOnNextTick.clear();
}); });
}); });
Modules.register();
} }
private static synchronized void exec(Runnable run) { private static synchronized void exec(Runnable run) {
@@ -0,0 +1,10 @@
package io.github.skippyall.minions.command;
import net.minecraft.item.Item;
import net.minecraft.text.Text;
public interface Command extends CommandExecutor {
Text getName();
Text getDescription();
Item getItemRepresentation();
}
@@ -0,0 +1,8 @@
package io.github.skippyall.minions.command;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import net.minecraft.server.network.ServerPlayerEntity;
public interface CommandExecutor {
void execute(ServerPlayerEntity player, MinionFakePlayer minion);
}
@@ -0,0 +1,40 @@
package io.github.skippyall.minions.command;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import net.minecraft.item.Item;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
public class SimpleCommand implements Command {
private final Text name;
private final Text description;
private final Item itemRepresentation;
private final CommandExecutor executor;
public SimpleCommand(Text name, Text description, Item itemRepresentation, CommandExecutor executor) {
this.name = name;
this.description = description;
this.itemRepresentation = itemRepresentation;
this.executor = executor;
}
@Override
public Text getName() {
return name;
}
@Override
public Text getDescription() {
return description;
}
@Override
public Item getItemRepresentation() {
return itemRepresentation;
}
@Override
public void execute(ServerPlayerEntity player, MinionFakePlayer minion) {
executor.execute(player, minion);
}
}
@@ -5,6 +5,8 @@ import java.util.EnumMap;
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 io.github.skippyall.minions.mixins.EntityAccessor;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.command.argument.EntityAnchorArgumentType; import net.minecraft.command.argument.EntityAnchorArgumentType;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
@@ -157,6 +159,12 @@ public class EntityPlayerActionPack
return this; return this;
} }
public EntityPlayerActionPack stop(ActionType type) {
type.stop(player, actions.get(type));
actions.remove(type);
return this;
}
public EntityPlayerActionPack stopAll() public EntityPlayerActionPack stopAll()
{ {
@@ -167,12 +175,13 @@ public class EntityPlayerActionPack
public EntityPlayerActionPack mount(boolean onlyRideables) public EntityPlayerActionPack mount(boolean onlyRideables)
{ {
//test what happens //test what happens
List<Entity> entities; List<Entity> entities;
if (onlyRideables) if (onlyRideables)
{ {
entities = player.getWorld().getOtherEntities(player, player.getBoundingBox().expand(3.0D, 1.0D, 3.0D), entities = player.getWorld().getOtherEntities(player, player.getBoundingBox().expand(3.0D, 1.0D, 3.0D),
e -> e instanceof MinecartEntity || e instanceof BoatEntity || e instanceof AbstractHorseEntity); e -> (e instanceof MinecartEntity || e instanceof BoatEntity || e instanceof AbstractHorseEntity) && ((EntityAccessor)e).invokeCanAddPassenger(player));
} }
else else
{ {
@@ -198,7 +207,7 @@ public class EntityPlayerActionPack
if (closest instanceof AbstractHorseEntity && onlyRideables) if (closest instanceof AbstractHorseEntity && onlyRideables)
((AbstractHorseEntity) closest).interactMob(player, Hand.MAIN_HAND); ((AbstractHorseEntity) closest).interactMob(player, Hand.MAIN_HAND);
else else
player.startRiding(closest,true); player.startRiding(closest, !onlyRideables);
return this; return this;
} }
public EntityPlayerActionPack dismount() public EntityPlayerActionPack dismount()
@@ -1,16 +1,15 @@
package io.github.skippyall.minions.fakeplayer; package io.github.skippyall.minions.fakeplayer;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import com.mojang.authlib.yggdrasil.ProfileResult;
import io.github.skippyall.minions.Minions; import io.github.skippyall.minions.Minions;
import io.github.skippyall.minions.minion.MinionInventory; import io.github.skippyall.minions.minion.MinionData;
import io.github.skippyall.minions.gui.MinionGui;
import io.github.skippyall.minions.minion.MinionItem; import io.github.skippyall.minions.minion.MinionItem;
import io.github.skippyall.minions.minion.MinionPersistentState; import io.github.skippyall.minions.minion.MinionPersistentState;
import io.github.skippyall.minions.minion.ModuleInventory; import io.github.skippyall.minions.minion.MinionProfileUtils;
import io.github.skippyall.minions.mixins.GameProfileMixin; import io.github.skippyall.minions.gui.ModuleInventory;
import io.github.skippyall.minions.program.runtime.MinionRuntime; import io.github.skippyall.minions.program.runtime.MinionRuntime;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.component.ComponentType;
import net.minecraft.component.DataComponentTypes; import net.minecraft.component.DataComponentTypes;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EquipmentSlot; import net.minecraft.entity.EquipmentSlot;
@@ -27,7 +26,6 @@ import net.minecraft.network.packet.c2s.common.SyncedClientOptions;
import net.minecraft.network.packet.c2s.play.ClientStatusC2SPacket; import net.minecraft.network.packet.c2s.play.ClientStatusC2SPacket;
import net.minecraft.network.packet.s2c.play.EntityPositionS2CPacket; import net.minecraft.network.packet.s2c.play.EntityPositionS2CPacket;
import net.minecraft.network.packet.s2c.play.EntitySetHeadYawS2CPacket; import net.minecraft.network.packet.s2c.play.EntitySetHeadYawS2CPacket;
import net.minecraft.network.packet.s2c.play.PlayerListS2CPacket;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.ServerTask; import net.minecraft.server.ServerTask;
import net.minecraft.server.network.ConnectedClientData; import net.minecraft.server.network.ConnectedClientData;
@@ -38,16 +36,17 @@ import net.minecraft.text.TranslatableTextContent;
import net.minecraft.util.ActionResult; import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand; import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec2f;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.world.GameMode; import net.minecraft.world.GameMode;
import net.minecraft.world.TeleportTarget; import net.minecraft.world.TeleportTarget;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class MinionFakePlayer extends ServerPlayerEntity { public class MinionFakePlayer extends ServerPlayerEntity {
public Runnable fixStartingPosition = () -> {}; public Runnable fixStartingPosition = () -> {};
public boolean isAShadow;
private float moveForward; private float moveForward;
private float moveSideways; private float moveSideways;
@@ -56,29 +55,29 @@ public class MinionFakePlayer extends ServerPlayerEntity {
private final ModuleInventory moduleInventory = new ModuleInventory(); private final ModuleInventory moduleInventory = new ModuleInventory();
private final MinionRuntime runtime = new MinionRuntime(this); private final MinionRuntime runtime = new MinionRuntime(this);
public static void createMinion(String username, ServerWorld level, ServerPlayerEntity owner, boolean canProgram, Vec3d pos, double yaw, double pitch) { private UUID skinUuid = null;
public static void createMinion(MinionData data, ServerWorld level, ServerPlayerEntity owner, boolean canProgram, Vec3d pos, double yaw, double pitch) {
MinecraftServer server = level.getServer(); MinecraftServer server = level.getServer();
server.getUserCache().findByNameAsync(username).thenAcceptAsync((optional) -> {
try { CompletableFuture<GameProfile> future;
GameProfile profile = null; if(data.skinUuid != null) {
if(optional.isPresent()){ future = MinionProfileUtils.getSkinOwnerProfile(server, data.skinUuid);
UUID uuid = optional.get().getId(); } else {
ProfileResult result = server.getSessionService().fetchProfile(uuid, true); future = MinionProfileUtils.lookupSkinOwnerProfile(server, data.name);
if(result != null) {
profile = result.profile();
} }
}
if(profile == null) { future.thenAccept(skinProfile -> {
profile = new GameProfile(new UUID(0,0), username); GameProfile profile = MinionProfileUtils.makeNewMinionProfile(null, data.name, skinProfile);
}
GameProfile newProfile = new GameProfile(UUID.randomUUID(), username);
newProfile.getProperties().putAll(profile.getProperties());
GameProfile finalProfile = newProfile;
((GameProfileMixin)finalProfile).setId(UUID.randomUUID());
Minions.addExecuteOnNextTick(() -> { Minions.addExecuteOnNextTick(() -> {
MinionFakePlayer instance = new MinionFakePlayer(server, level, finalProfile, SyncedClientOptions.createDefault(), false, canProgram); MinionFakePlayer instance = new MinionFakePlayer(server, level, profile, SyncedClientOptions.createDefault());
if(skinProfile != null) {
instance.skinUuid = skinProfile.getId();
}
instance.programmable = canProgram;
instance.fixStartingPosition = () -> instance.refreshPositionAndAngles(pos.x, pos.y, pos.z, (float) yaw, (float) pitch); instance.fixStartingPosition = () -> instance.refreshPositionAndAngles(pos.x, pos.y, pos.z, (float) yaw, (float) pitch);
server.getPlayerManager().onPlayerConnect(new FakeClientConnection(NetworkSide.SERVERBOUND), instance, new ConnectedClientData(finalProfile, 0, instance.getClientOptions(), false)); server.getPlayerManager().onPlayerConnect(new FakeClientConnection(NetworkSide.SERVERBOUND), instance, new ConnectedClientData(profile, 0, instance.getClientOptions(), false));
instance.teleport(level, pos.x, pos.y, pos.z, (float) yaw, (float) pitch); instance.teleport(level, pos.x, pos.y, pos.z, (float) yaw, (float) pitch);
instance.setHealth(20.0F); instance.setHealth(20.0F);
instance.unsetRemoved(); instance.unsetRemoved();
@@ -91,70 +90,34 @@ public class MinionFakePlayer extends ServerPlayerEntity {
instance.getAbilities().flying = false; instance.getAbilities().flying = false;
MinionPersistentState.INSTANCE.addMinion(instance); MinionPersistentState.INSTANCE.addMinion(instance);
}); });
}catch (Throwable ex) {
ex.printStackTrace();
}
}); });
} }
public static void spawnMinion(MinionPersistentState.MinionData data, ServerWorld level) { public static void spawnMinionAt(MinionData data, ServerWorld level, @Nullable Vec3d pos, @Nullable Vec2f rot) {
MinecraftServer server = level.getServer(); MinecraftServer server = level.getServer();
server.getUserCache().findByNameAsync(data.name).thenAcceptAsync((optional) -> {
GameProfile profile = null; CompletableFuture<GameProfile> future;
if (optional.isPresent()) { if(data.skinUuid != null) {
ProfileResult result = server.getSessionService().fetchProfile(optional.get().getId(), true); future = MinionProfileUtils.getSkinOwnerProfile(server, data.skinUuid);
if (result != null) { } else {
profile = result.profile(); future = MinionProfileUtils.lookupSkinOwnerProfile(server, data.name);
}
}
if (profile == null) {
profile = new GameProfile(new UUID(0, 0), data.name);
}
GameProfile newProfile = new GameProfile(data.uuid, data.name);
newProfile.getProperties().putAll(profile.getProperties());
GameProfile finalProfile = newProfile;
((GameProfileMixin)finalProfile).setId(data.uuid);
Minions.addExecuteOnNextTick(() -> {
MinionFakePlayer instance = new MinionFakePlayer(server, level, finalProfile, SyncedClientOptions.createDefault(), false, data.programmable);
System.out.println(instance.getPos());
server.getPlayerManager().onPlayerConnect(new FakeClientConnection(NetworkSide.SERVERBOUND), instance, new ConnectedClientData(finalProfile, 0, instance.getClientOptions(), false));
System.out.println(instance.getPos());
instance.setHealth(20.0F);
instance.unsetRemoved();
instance.interactionManager.changeGameMode(GameMode.SURVIVAL);
server.getPlayerManager().sendToDimension(new EntitySetHeadYawS2CPacket(instance, (byte) (instance.headYaw * 256 / 360)), level.getRegistryKey());//instance.dimension);
server.getPlayerManager().sendToDimension(new EntityPositionS2CPacket(instance), level.getRegistryKey());//instance.dimension);
//instance.world.getChunkManager(). updatePosition(instance);
instance.dataTracker.set(PLAYER_MODEL_PARTS, (byte) 0x7f); // show all model layers (incl. capes)
instance.getAbilities().flying = false;
});
});
} }
public static void spawnMinionAt(MinionPersistentState.MinionData data, ServerWorld level, Vec3d pos, double yaw, double pitch) { future.thenAccept((skinProfile) -> {
MinecraftServer server = level.getServer(); GameProfile profile = MinionProfileUtils.makeNewMinionProfile(data.uuid, data.name, skinProfile);
server.getUserCache().findByNameAsync(data.name).thenAcceptAsync((optional) -> {
GameProfile profile = null;
if (optional.isPresent()) {
ProfileResult result = server.getSessionService().fetchProfile(optional.get().getId(), true);
if (result != null) {
profile = result.profile();
}
}
if (profile == null) {
profile = new GameProfile(new UUID(0, 0), data.name);
}
GameProfile newProfile = new GameProfile(data.uuid, data.name);
newProfile.getProperties().putAll(profile.getProperties());
GameProfile finalProfile = newProfile;
((GameProfileMixin)finalProfile).setId(data.uuid);
Minions.addExecuteOnNextTick(() -> { Minions.addExecuteOnNextTick(() -> {
MinionFakePlayer instance = new MinionFakePlayer(server, level, finalProfile, SyncedClientOptions.createDefault(), false, data.programmable); MinionFakePlayer instance = new MinionFakePlayer(server, level, profile, SyncedClientOptions.createDefault());
instance.fixStartingPosition = () -> instance.refreshPositionAndAngles(pos.x, pos.y, pos.z, (float) yaw, (float) pitch); if (skinProfile != null) {
instance.skinUuid = skinProfile.getId();
}
if(pos != null && rot != null) {
instance.fixStartingPosition = () -> instance.refreshPositionAndAngles(pos.x, pos.y, pos.z, rot.x, rot.y);
}
server.getPlayerManager().onPlayerConnect(new FakeClientConnection(NetworkSide.SERVERBOUND), instance, new ConnectedClientData(profile, 0, instance.getClientOptions(), false));
System.out.println(instance.getPos()); System.out.println(instance.getPos());
server.getPlayerManager().onPlayerConnect(new FakeClientConnection(NetworkSide.SERVERBOUND), instance, new ConnectedClientData(finalProfile, 0, instance.getClientOptions(), false)); if(pos != null && rot != null) {
System.out.println(instance.getPos()); instance.teleport(level, pos.x, pos.y, pos.z, rot.x, rot.y);
instance.teleport(level, pos.x, pos.y, pos.z, (float) yaw, (float) pitch); }
instance.setVelocity(0,0,0); instance.setVelocity(0,0,0);
instance.setHealth(20.0F); instance.setHealth(20.0F);
instance.unsetRemoved(); instance.unsetRemoved();
@@ -168,47 +131,24 @@ public class MinionFakePlayer extends ServerPlayerEntity {
}); });
} }
@SuppressWarnings("unused") //Don't know if I'll need this public static MinionFakePlayer respawnFake(MinecraftServer server, ServerWorld level, GameProfile profile, SyncedClientOptions cli)
public static MinionFakePlayer createShadow(MinecraftServer server, ServerPlayerEntity player)
{ {
player.getServer().getPlayerManager().remove(player); return new MinionFakePlayer(server, level, profile, cli);
player.networkHandler.disconnect(Text.translatable("multiplayer.disconnect.duplicate_login"));
ServerWorld worldIn = player.getServerWorld();//.getWorld(player.dimension);
GameProfile gameprofile = player.getGameProfile();
MinionFakePlayer playerShadow = new MinionFakePlayer(server, worldIn, gameprofile, player.getClientOptions(), true, false);
playerShadow.setSession(player.getSession());
server.getPlayerManager().onPlayerConnect(new FakeClientConnection(NetworkSide.SERVERBOUND), playerShadow, new ConnectedClientData(gameprofile, 0, player.getClientOptions(), false));
playerShadow.setHealth(player.getHealth());
playerShadow.networkHandler.requestTeleport(player.getX(), player.getY(), player.getZ(), player.getYaw(), player.getPitch());
playerShadow.interactionManager.changeGameMode(player.interactionManager.getGameMode());
((ServerPlayerInterface) playerShadow).getActionPack().copyFrom(((ServerPlayerInterface) player).getActionPack());
playerShadow.dataTracker.set(PLAYER_MODEL_PARTS, player.getDataTracker().get(PLAYER_MODEL_PARTS));
server.getPlayerManager().sendToDimension(new EntitySetHeadYawS2CPacket(playerShadow, (byte) (player.headYaw * 256 / 360)), playerShadow.getWorld().getRegistryKey());
server.getPlayerManager().sendToAll(new PlayerListS2CPacket(PlayerListS2CPacket.Action.ADD_PLAYER, playerShadow));
//player.world.getChunkManager().updatePosition(playerShadow);
playerShadow.getAbilities().flying = player.getAbilities().flying;
return playerShadow;
} }
public static MinionFakePlayer respawnFake(MinecraftServer server, ServerWorld level, GameProfile profile, SyncedClientOptions cli, boolean programmable) private MinionFakePlayer(MinecraftServer server, ServerWorld worldIn, GameProfile profile, SyncedClientOptions cli)
{
return new MinionFakePlayer(server, level, profile, cli, false, programmable);
}
private MinionFakePlayer(MinecraftServer server, ServerWorld worldIn, GameProfile profile, SyncedClientOptions cli, boolean shadow, boolean programmable)
{ {
super(server, worldIn, profile, cli); super(server, worldIn, profile, cli);
isAShadow = shadow;
this.programmable = programmable;
} }
public boolean isProgrammable() { public boolean isProgrammable() {
return programmable; return programmable;
} }
public void setProgrammable(boolean programmable) {
this.programmable = programmable;
}
public ModuleInventory getModuleInventory() { public ModuleInventory getModuleInventory() {
return moduleInventory; return moduleInventory;
} }
@@ -224,7 +164,7 @@ public class MinionFakePlayer extends ServerPlayerEntity {
@Override @Override
public ActionResult interact(PlayerEntity player, Hand hand) { public ActionResult interact(PlayerEntity player, Hand hand) {
if(player instanceof ServerPlayerEntity spe) { if(player instanceof ServerPlayerEntity spe) {
MinionInventory.openInventory(spe, this); MinionGui.openInventory(spe, this);
} }
return ActionResult.CONSUME; return ActionResult.CONSUME;
} }
@@ -376,16 +316,12 @@ public class MinionFakePlayer extends ServerPlayerEntity {
@Override @Override
protected void drop(ServerWorld world, DamageSource damageSource) { protected void drop(ServerWorld world, DamageSource damageSource) {
super.drop(world, damageSource); super.drop(world, damageSource);
dropItem(toItemStack(), true, false); dropStack(toItemStack());
for(ItemStack item : moduleInventory.getItems()) {
dropItem(item, true, false);
}
moduleInventory.clear();
} }
private ItemStack toItemStack() { private ItemStack toItemStack() {
ItemStack stack = new ItemStack(Minions.MINION_ITEM); ItemStack stack = new ItemStack(Minions.MINION_ITEM);
MinionItem.setData(MinionPersistentState.MinionData.fromMinion(this), stack); MinionItem.setData(MinionData.fromMinion(this), stack);
if (!getMinionName().equals("Minion")) { if (!getMinionName().equals("Minion")) {
stack.set(DataComponentTypes.CUSTOM_NAME, Text.of(getMinionName())); stack.set(DataComponentTypes.CUSTOM_NAME, Text.of(getMinionName()));
} }
@@ -396,15 +332,21 @@ public class MinionFakePlayer extends ServerPlayerEntity {
public void writeCustomDataToNbt(NbtCompound nbt) { public void writeCustomDataToNbt(NbtCompound nbt) {
super.writeCustomDataToNbt(nbt); super.writeCustomDataToNbt(nbt);
nbt.put("modules", moduleInventory.writeNbt(new NbtCompound(), getRegistryManager())); nbt.put("modules", moduleInventory.writeNbt(new NbtCompound(), getRegistryManager()));
nbt.putBoolean("programmable", programmable);
} }
@Override @Override
public void readCustomDataFromNbt(NbtCompound nbt) { public void readCustomDataFromNbt(NbtCompound nbt) {
super.readCustomDataFromNbt(nbt); super.readCustomDataFromNbt(nbt);
moduleInventory.readNbt(nbt.getCompound("modules"), getRegistryManager()); moduleInventory.readNbt(nbt.getCompound("modules"), getRegistryManager());
programmable = nbt.getBoolean("programmable");
} }
public String getMinionName() { public String getMinionName() {
return getGameProfile().getName(); return getGameProfile().getName();
} }
public UUID getSkinUuid() {
return skinUuid;
}
} }
@@ -0,0 +1,52 @@
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.command.Command;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.module.ModuleItem;
import net.minecraft.screen.ScreenHandlerType;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import java.util.List;
public class CommandsGui {
public static void openServerModuleCommandGui(ServerPlayerEntity player, MinionFakePlayer minion) {
List<ModuleItem> modules = minion.getModuleInventory().getModuleItems();
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_9X3, player, false);
gui.setTitle(Text.translatable("minions.gui.module_commands.title"));
for (int i = 0; i < modules.size(); i++) {
ModuleItem module = modules.get(i);
gui.setSlot(i, new GuiElementBuilder()
.setItem(module.asItem())
.setCallback(() -> openServerCommandGui(player, minion, module))
);
}
gui.open();
}
public static void openServerCommandGui(ServerPlayerEntity player, MinionFakePlayer minion, ModuleItem module) {
List<Command> commands = module.getCommands();
SimpleGui commandGui = new SimpleGui(ScreenHandlerType.GENERIC_9X3, player, false);
commandGui.setTitle(Text.translatable("minions.gui.commands.title", module.asItem().getName()));
for(int j = 0; j < commands.size(); j++) {
Command command = commands.get(j);
commandGui.setSlot(j, new GuiElementBuilder()
.setItem(command.getItemRepresentation())
.setName(command.getName())
.addLoreLine(command.getDescription())
.setCallback(() -> command.execute(player, minion))
);
}
commandGui.open();
}
}
@@ -1,4 +1,4 @@
package io.github.skippyall.minions.minion; 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;
@@ -11,18 +11,18 @@ import net.minecraft.screen.slot.Slot;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text; import net.minecraft.text.Text;
public class MinionInventory { public class MinionGui {
public static void openInventory(ServerPlayerEntity player, MinionFakePlayer minion) { public static void openInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
openServerSideInventory(player, minion); openServerSideInventory(player, minion);
} }
public static void openServerSideInventory(ServerPlayerEntity player, MinionFakePlayer minion) { public static void openServerSideInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_3X3, player, false); SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_3X3, player, false);
gui.setTitle(Text.literal("Minion")); gui.setTitle(minion.getName());
gui.setSlot(1, new GuiElementBuilder() gui.setSlot(1, new GuiElementBuilder()
.setItem(Items.COMMAND_BLOCK) .setItem(Items.COMMAND_BLOCK)
.setName(Text.literal("Commands")) .setName(Text.translatable("minions.gui.main.commands"))
.setCallback((i, clickType, slotActionType) -> { .setCallback((i, clickType, slotActionType) -> {
openCommandsGui(player, minion); openCommandsGui(player, minion);
}) })
@@ -30,7 +30,7 @@ public class MinionInventory {
if(minion.isProgrammable()) { if(minion.isProgrammable()) {
gui.setSlot(4, new GuiElementBuilder() gui.setSlot(4, new GuiElementBuilder()
.setItem(Items.REDSTONE) .setItem(Items.REDSTONE)
.setName(Text.literal("Programming")) .setName(Text.translatable("minions.gui.main.programming"))
.setCallback((i, clickType, slotActionType) -> { .setCallback((i, clickType, slotActionType) -> {
openProgrammingInventory(player, minion); openProgrammingInventory(player, minion);
}) })
@@ -38,14 +38,14 @@ public class MinionInventory {
} }
gui.setSlot(3, new GuiElementBuilder() gui.setSlot(3, new GuiElementBuilder()
.setItem(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE) .setItem(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE)
.setName(Text.literal("Modules and Detectors")) .setName(Text.translatable("minions.gui.main.modules"))
.setCallback((i, clickType, slotActionType) -> { .setCallback((i, clickType, slotActionType) -> {
openModuleInventory(player, minion); ModuleInventory.openModuleInventory(player, minion);
}) })
); );
gui.setSlot(5, new GuiElementBuilder() gui.setSlot(5, new GuiElementBuilder()
.setItem(Items.CHEST) .setItem(Items.CHEST)
.setName(Text.literal("Inventory")) .setName(Text.translatable("minions.gui.main.inventory"))
.setCallback((i, clickType, slotActionType) -> { .setCallback((i, clickType, slotActionType) -> {
openMinionInventory(player, minion); openMinionInventory(player, minion);
}) })
@@ -54,20 +54,16 @@ public class MinionInventory {
} }
public static void openCommandsGui(ServerPlayerEntity player, MinionFakePlayer minion) { public static void openCommandsGui(ServerPlayerEntity player, MinionFakePlayer minion) {
CommandsInventory.openServerCommandsInventory(player, minion); CommandsGui.openServerModuleCommandGui(player, minion);
} }
public static void openProgrammingInventory(ServerPlayerEntity player, MinionFakePlayer minion) { public static void openProgrammingInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
} }
public static void openModuleInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
player.openHandledScreen(new SimpleNamedScreenHandlerFactory((syncId, playerInventory, player2) -> GenericContainerScreenHandler.createGeneric9x3(syncId, playerInventory, minion.getModuleInventory()), Text.literal("")));
}
public static void openMinionInventory(ServerPlayerEntity player, MinionFakePlayer minion) { public static void openMinionInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_9X5, player, false); SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_9X5, player, false);
gui.setTitle(Text.literal("Minion")); gui.setTitle(Text.translatable("minions.gui.inventory.title", minion.getName()));
for (int i = 0; i < minion.getInventory().size(); i++) { for (int i = 0; i < minion.getInventory().size(); i++) {
gui.setSlotRedirect(i, new Slot(minion.getInventory(), i, 0, 0)); gui.setSlotRedirect(i, new Slot(minion.getInventory(), i, 0, 0));
} }
@@ -0,0 +1,84 @@
package io.github.skippyall.minions.gui;
import io.github.skippyall.minions.command.Command;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.module.ModuleItem;
import io.github.skippyall.minions.program.block.CodeBlock;
import net.minecraft.inventory.Inventories;
import net.minecraft.inventory.SimpleInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.registry.RegistryWrapper;
import net.minecraft.screen.SimpleNamedScreenHandlerFactory;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import java.util.ArrayList;
import java.util.List;
public class ModuleInventory extends SimpleInventory {
public ModuleInventory() {
super(27);
}
public static void openModuleInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
player.openHandledScreen(new SimpleNamedScreenHandlerFactory((syncId, playerInventory, player2) -> new ModuleInventoryScreenHandler(syncId, playerInventory, minion.getModuleInventory()), Text.translatable("minions.gui.modules.title", minion.getName())));
}
@Override
public int getMaxCountPerStack() {
return 1;
}
@Override
public boolean isValid(int slot, ItemStack stack) {
return (stack.getCount() <= getMaxCountPerStack()) && stack.getItem() instanceof ModuleItem;
}
public void readNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup lookup) {
Inventories.readNbt(nbt, heldStacks, lookup);
}
public NbtCompound writeNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup lookup) {
return Inventories.writeNbt(nbt, heldStacks, lookup);
}
public boolean hasModule(ModuleItem module) {
for(ItemStack stack : heldStacks) {
if(stack.getItem() instanceof ModuleItem module2 && module2 == module) {
return true;
}
}
return false;
}
public List<ModuleItem> getModuleItems() {
ArrayList<ModuleItem> modules = new ArrayList<>();
for(ItemStack stack : heldStacks) {
if(stack.getItem() instanceof ModuleItem module) {
modules.add(module);
}
}
return modules;
}
public List<Command> getAllCommands() {
ArrayList<Command> commands = new ArrayList<>();
for(ItemStack stack : heldStacks) {
if(stack.getItem() instanceof ModuleItem module) {
commands.addAll(module.getCommands());
}
}
return commands;
}
public List<CodeBlock<?,?>> getAllCodeBlocks() {
ArrayList<CodeBlock<?,?>> commands = new ArrayList<>();
for(ItemStack stack : heldStacks) {
if(stack.getItem() instanceof ModuleItem module) {
commands.addAll(module.getCodeBlocks());
}
}
return commands;
}
}
@@ -0,0 +1,80 @@
package io.github.skippyall.minions.gui;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.screen.GenericContainerScreenHandler;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.screen.ScreenHandlerType;
import net.minecraft.screen.slot.Slot;
public class ModuleInventoryScreenHandler extends ScreenHandler {
private final int rows = 3;
private final ModuleInventory inventory;
public ModuleInventoryScreenHandler(int syncId, ModuleInventory inventory) {
super(ScreenHandlerType.GENERIC_9X3, syncId);
this.inventory = inventory;
}
public ModuleInventoryScreenHandler(int syncId, PlayerInventory playerInventory, ModuleInventory inventory) {
super(ScreenHandlerType.GENERIC_9X3, syncId);
int k;
int j;
GenericContainerScreenHandler.checkSize(inventory, 3 * 9);
this.inventory = inventory;
inventory.onOpen(playerInventory.player);
int i = (rows - 4) * 18;
for (j = 0; j < rows; ++j) {
for (k = 0; k < 9; ++k) {
this.addSlot(new Slot(inventory, k + j * 9, 8 + k * 18, 18 + j * 18) {
@Override
public boolean canInsert(ItemStack stack) {
return super.canInsert(stack) && inventory.isValid(getIndex(), stack);
}
});
}
}
for (j = 0; j < 3; ++j) {
for (k = 0; k < 9; ++k) {
this.addSlot(new Slot(playerInventory, k + j * 9 + 9, 8 + k * 18, 103 + j * 18 + i));
}
}
for (j = 0; j < 9; ++j) {
this.addSlot(new Slot(playerInventory, j, 8 + j * 18, 161 + i));
}
}
@Override
public boolean canUse(PlayerEntity player) {
return this.inventory.canPlayerUse(player);
}
@Override
public ItemStack quickMove(PlayerEntity player, int slot) {
ItemStack itemStack = ItemStack.EMPTY;
Slot slot2 = this.slots.get(slot);
if (slot2 != null && slot2.hasStack()) {
ItemStack itemStack2 = slot2.getStack();
itemStack = itemStack2.copy();
if (slot < this.rows * 9 ? !this.insertItem(itemStack2, this.rows * 9, this.slots.size(), true) : !this.insertItem(itemStack2, 0, this.rows * 9, false)) {
return ItemStack.EMPTY;
}
if (itemStack2.isEmpty()) {
slot2.setStack(ItemStack.EMPTY);
} else {
slot2.markDirty();
}
}
return itemStack;
}
@Override
public void onClosed(PlayerEntity player) {
super.onClosed(player);
this.inventory.onClose(player);
}
public ModuleInventory getInventory() {
return inventory;
}
}
@@ -0,0 +1,27 @@
package io.github.skippyall.minions.input;
import eu.pb4.sgui.api.elements.GuiElementBuilder;
import eu.pb4.sgui.api.gui.AnvilInputGui;
import net.minecraft.item.Items;
import net.minecraft.screen.AnvilScreenHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import java.util.concurrent.CompletableFuture;
public class TextInput {
public static CompletableFuture<String> inputText(ServerPlayerEntity player, Text title, String defaultText) {
CompletableFuture<String> future = new CompletableFuture<>();
AnvilInputGui gui = new AnvilInputGui(player, false);
gui.setSlot(AnvilScreenHandler.OUTPUT_ID, new GuiElementBuilder()
.setItem(Items.EMERALD_BLOCK)
.setName(Text.literal("OK"))
.setCallback(() -> future.complete(gui.getInput()))
);
gui.setTitle(title);
gui.setDefaultInputValue(defaultText);
gui.open();
return future;
}
}
@@ -1,25 +0,0 @@
package io.github.skippyall.minions.minion;
import eu.pb4.sgui.api.elements.GuiElementBuilder;
import eu.pb4.sgui.api.gui.SimpleGui;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import net.minecraft.item.Items;
import net.minecraft.screen.ScreenHandlerType;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
public class CommandsInventory {
public static void openServerCommandsInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_9X3, player, false);
gui.setSlot(0, new GuiElementBuilder()
.setItem(Items.MINECART)
.setName(Text.literal("Get into minecart"))
.setCallback(() -> {
minion.getMinionActionPack().mount(true);
})
);
gui.open();
}
}
@@ -1,132 +0,0 @@
package io.github.skippyall.minions.minion;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.Inventories;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.collection.DefaultedList;
/**
* A simple {@code Inventory} implementation with only default methods + an item list getter.
*
* Originally by Juuz
*/
public interface ImplementedInventory extends Inventory {
/**
* Retrieves the item list of this inventory.
* Must return the same instance every time it's called.
*/
DefaultedList<ItemStack> getItems();
/**
* Creates an inventory from the item list.
*/
static ImplementedInventory of(DefaultedList<ItemStack> items) {
return () -> items;
}
/**
* Creates a new inventory with the specified size.
*/
static ImplementedInventory ofSize(int size) {
return of(DefaultedList.ofSize(size, ItemStack.EMPTY));
}
/**
* Returns the inventory size.
*/
@Override
default int size() {
return getItems().size();
}
/**
* Checks if the inventory is empty.
* @return true if this inventory has only empty stacks, false otherwise.
*/
@Override
default boolean isEmpty() {
for (int i = 0; i < size(); i++) {
ItemStack stack = getStack(i);
if (!stack.isEmpty()) {
return false;
}
}
return true;
}
/**
* Retrieves the item in the slot.
*/
@Override
default ItemStack getStack(int slot) {
return getItems().get(slot);
}
/**
* Removes items from an inventory slot.
* @param slot The slot to remove from.
* @param count How many items to remove. If there are less items in the slot than what are requested,
* takes all items in that slot.
*/
@Override
default ItemStack removeStack(int slot, int count) {
ItemStack result = Inventories.splitStack(getItems(), slot, count);
if (!result.isEmpty()) {
markDirty();
}
return result;
}
/**
* Removes all items from an inventory slot.
* @param slot The slot to remove from.
*/
@Override
default ItemStack removeStack(int slot) {
return Inventories.removeStack(getItems(), slot);
}
/**
* Replaces the current stack in an inventory slot with the provided stack.
* @param slot The inventory slot of which to replace the itemstack.
* @param stack The replacing itemstack. If the stack is too big for
* this inventory ({@link Inventory#getMaxCountPerStack()}),
* it gets resized to this inventory's maximum amount.
*/
@Override
default void setStack(int slot, ItemStack stack) {
getItems().set(slot, stack);
if (stack.getCount() > stack.getMaxCount()) {
stack.setCount(stack.getMaxCount());
}
}
/**
* Clears the inventory.
*/
@Override
default void clear() {
getItems().clear();
}
/**
* Marks the state as dirty.
* Must be called after changes in the inventory, so that the game can properly save
* the inventory contents and notify neighboring blocks of inventory changes.
*/
@Override
default void markDirty() {
// Override if you want behavior.
}
/**
* @return true if the player can use the inventory, false otherwise.
*/
@Override
default boolean canPlayerUse(PlayerEntity player) {
return true;
}
}
@@ -0,0 +1,14 @@
package io.github.skippyall.minions.minion;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.component.ComponentType;
public class MinionComponent {
/*public static final Codec<MinionComponent> CODEC = RecordCodecBuilder.create(instance ->
instance.group()
);
public static final ComponentType<MinionComponent> TYPE = ComponentType.<MinionComponent>builder().codec(CODEC).build();
*/
}
@@ -0,0 +1,45 @@
package io.github.skippyall.minions.minion;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import net.minecraft.nbt.NbtCompound;
import java.util.UUID;
public class MinionData {
public UUID uuid;
public String name;
public UUID skinUuid;
public MinionData(UUID uuid, String name, UUID skinUuid) {
this.uuid = uuid;
this.name = name;
this.skinUuid = skinUuid;
}
public NbtCompound writeNbt() {
NbtCompound nbt = new NbtCompound();
nbt.putUuid("uuid", uuid);
nbt.putString("name", name);
if(skinUuid != null) {
nbt.putUuid("skinUuid", skinUuid);
}
return nbt;
}
public static MinionData readNbt(NbtCompound nbt) {
UUID uuid = nbt.getUuid("uuid");
String name = nbt.getString("name");
UUID skinUuid = null;
if(nbt.contains("skinUuid")) {
skinUuid = nbt.getUuid("skinUuid");
}
return new MinionData(uuid, name, skinUuid);
}
public static MinionData fromMinion(MinionFakePlayer minion) {
return new MinionData(minion.getUuid(), minion.getMinionName(), minion.getSkinUuid());
}
}
@@ -3,11 +3,12 @@ package io.github.skippyall.minions.minion;
import eu.pb4.polymer.core.api.item.PolymerItem; import eu.pb4.polymer.core.api.item.PolymerItem;
import eu.pb4.polymer.core.api.item.PolymerItemUtils; import eu.pb4.polymer.core.api.item.PolymerItemUtils;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer; import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import net.minecraft.client.render.VertexFormatElement;
import net.minecraft.component.ComponentType;
import net.minecraft.component.DataComponentTypes; import net.minecraft.component.DataComponentTypes;
import net.minecraft.component.type.NbtComponent; import net.minecraft.component.type.NbtComponent;
import net.minecraft.item.*; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.item.Items;
import net.minecraft.item.tooltip.TooltipType; import net.minecraft.item.tooltip.TooltipType;
import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtElement; import net.minecraft.nbt.NbtElement;
@@ -15,10 +16,12 @@ import net.minecraft.registry.RegistryWrapper;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld; import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.ActionResult; import net.minecraft.util.ActionResult;
import net.minecraft.util.math.Vec2f;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class MinionItem extends Item implements PolymerItem { public class MinionItem extends Item implements PolymerItem {
private final boolean canProgram; private final boolean canProgram;
public MinionItem(boolean canProgram) { public MinionItem(boolean canProgram) {
super(new Item.Settings()); super(new Item.Settings());
this.canProgram = canProgram; this.canProgram = canProgram;
@@ -40,34 +43,41 @@ public class MinionItem extends Item implements PolymerItem {
public ActionResult useOnBlock(ItemUsageContext context) { public ActionResult useOnBlock(ItemUsageContext context) {
String contents = context.getStack().getName().getLiteralString(); String contents = context.getStack().getName().getLiteralString();
String name; String name;
if(contents != null) { if(contents != null && contents.length() <= 16) {
name = contents; name = contents;
} else { } else {
name = "Minion"; name = "Minion";
} }
if(!context.getWorld().isClient) { if(!context.getWorld().isClient) {
MinionPersistentState.MinionData data = getData(context.getStack()); MinionData data = getData(context.getStack());
if(data == null) { if(data == null) {
MinionFakePlayer.createMinion(name, (ServerWorld) context.getWorld(), (ServerPlayerEntity) context.getPlayer(), canProgram, context.getBlockPos().toCenterPos().add(0,0.5,0), 0, 0); data = new MinionData(null, name, null);
}
if (data.uuid == null) {
MinionFakePlayer.createMinion(data, (ServerWorld) context.getWorld(), (ServerPlayerEntity) context.getPlayer(), canProgram, context.getBlockPos().toCenterPos().add(0,0.5,0), 0, 0);
}else { }else {
MinionFakePlayer.spawnMinionAt(data, (ServerWorld) context.getWorld(), context.getBlockPos().toCenterPos().add(0,0.5,0), 0, 0); data.name = name;
MinionFakePlayer.spawnMinionAt(data, (ServerWorld) context.getWorld(), context.getBlockPos().toCenterPos().add(0,0.5,0), new Vec2f(0, 0));
MinionPersistentState.INSTANCE.addMinion(data); MinionPersistentState.INSTANCE.addMinion(data);
} }
} }
context.getStack().decrement(1);
return ActionResult.SUCCESS; return ActionResult.SUCCESS;
} }
public static void setData(MinionPersistentState.MinionData data, ItemStack item) { public static void setData(MinionData data, ItemStack item) {
NbtCompound nbt = item.getOrDefault(DataComponentTypes.CUSTOM_DATA, NbtComponent.DEFAULT).copyNbt(); NbtCompound nbt = item.getOrDefault(DataComponentTypes.CUSTOM_DATA, NbtComponent.DEFAULT).copyNbt();
nbt.put("data", data.writeNbt()); nbt.put("data", data.writeNbt());
item.set(DataComponentTypes.CUSTOM_DATA, NbtComponent.of(nbt)); item.set(DataComponentTypes.CUSTOM_DATA, NbtComponent.of(nbt));
} }
@Nullable @Nullable
public static MinionPersistentState.MinionData getData(ItemStack item) { public static MinionData getData(ItemStack item) {
NbtCompound nbt = item.getOrDefault(DataComponentTypes.CUSTOM_DATA, NbtComponent.DEFAULT).copyNbt(); NbtCompound nbt = item.getOrDefault(DataComponentTypes.CUSTOM_DATA, NbtComponent.DEFAULT).copyNbt();
if (nbt.getType("data") == NbtElement.COMPOUND_TYPE) { if (nbt.getType("data") == NbtElement.COMPOUND_TYPE) {
return MinionPersistentState.MinionData.readNbt(nbt.getCompound("data")); return MinionData.readNbt(nbt.getCompound("data"));
} }
return null; return null;
} }
@@ -1,7 +1,9 @@
package io.github.skippyall.minions.minion; package io.github.skippyall.minions.minion;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer; import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import net.minecraft.nbt.*; import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtElement;
import net.minecraft.nbt.NbtList;
import net.minecraft.registry.RegistryWrapper; import net.minecraft.registry.RegistryWrapper;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.world.PersistentState; import net.minecraft.world.PersistentState;
@@ -71,60 +73,4 @@ public class MinionPersistentState extends PersistentState {
public static void create(MinecraftServer server) { public static void create(MinecraftServer server) {
INSTANCE = server.getWorld(World.OVERWORLD).getPersistentStateManager().getOrCreate(TYPE, "minion"); INSTANCE = server.getWorld(World.OVERWORLD).getPersistentStateManager().getOrCreate(TYPE, "minion");
} }
public static class MinionData {
public UUID uuid;
public String name;
public boolean programmable;
public MinionData(UUID uuid, String name, boolean programmable) {
this.uuid = uuid;
this.name = name;
this.programmable = programmable;
}
public NbtCompound writeNbt() {
NbtCompound nbt = new NbtCompound();
/*NbtList posList = new NbtList();
posList.add(NbtDouble.of(pos.getX()));
posList.add(NbtDouble.of(pos.getY()));
posList.add(NbtDouble.of(pos.getZ()));
nbt.put("pos", posList);
NbtList rotList = new NbtList();
rotList.add(NbtFloat.of(rot.x));
rotList.add(NbtFloat.of(rot.y));
nbt.put("rotation", rotList);*/
nbt.putUuid("uuid", uuid);
nbt.putString("name", name);
nbt.putBoolean("programmable", programmable);
return nbt;
}
public static MinionData readNbt(NbtCompound nbt) {
/*NbtList posList = nbt.getList("pos", NbtElement.DOUBLE_TYPE);
double x = posList.getDouble(0);
double y = posList.getDouble(1);
double z = posList.getDouble(2);
Vec3d pos = new Vec3d(x, y, z);
NbtList rotList = nbt.getList("rotation", NbtElement.FLOAT_TYPE);
float yaw = rotList.getFloat(0);
float pitch = rotList.getFloat(1);
Vec2f rot = new Vec2f(yaw, pitch);*/
UUID uuid = nbt.getUuid("uuid");
String name = nbt.getString("name");
boolean programmable = nbt.getBoolean("programmable");
return new MinionData(uuid, name, programmable);
}
public static MinionData fromMinion(MinionFakePlayer minion) {
return new MinionData(minion.getUuid(), minion.getMinionName(), minion.isProgrammable());
}
}
} }
@@ -0,0 +1,71 @@
package io.github.skippyall.minions.minion;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.ProfileLookupCallback;
import com.mojang.authlib.yggdrasil.ProfileResult;
import net.minecraft.server.MinecraftServer;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ForkJoinPool;
import static io.github.skippyall.minions.Minions.LOGGER;
public class MinionProfileUtils {
public static CompletableFuture<@Nullable GameProfile> lookupSkinOwnerProfile(MinecraftServer server, String username) {
CompletableFuture<GameProfile> future = new CompletableFuture<>();
ForkJoinPool.commonPool().execute(() -> {
try {
server.getGameProfileRepo().findProfilesByNames(new String[]{username}, new ProfileLookupCallback() {
@Override
public void onProfileLookupSucceeded(GameProfile found) {
LOGGER.info("SkinProfile: {}", found);
try {
getSkinOwnerProfile(server, found.getId()).thenAccept(future::complete);
} catch (Throwable ex) {
LOGGER.warn("Exception during Game Profile creation", ex);
}
}
@Override
public void onProfileLookupFailed(String profileName, Exception exception) {
LOGGER.warn("Lookup Error: ", exception);
future.complete(null);
}
});
} catch (Throwable e) {
LOGGER.warn("Failed to get UUID for username " + username, e);
future.complete(null);
}
});
return future;
}
public static CompletableFuture<@Nullable GameProfile> getSkinOwnerProfile(MinecraftServer server, @Nullable UUID uuid) {
CompletableFuture<GameProfile> future = new CompletableFuture<>();
future.completeAsync(() -> {
GameProfile profile = null;
if(uuid != null) {
ProfileResult result = server.getSessionService().fetchProfile(uuid, true);
if (result != null) {
profile = result.profile();
LOGGER.info("Full SkinProfile: {}", profile);
}
}
return profile;
});
return future;
}
public static GameProfile makeNewMinionProfile(@Nullable UUID uuidMinion, String username, @Nullable GameProfile skinProfile) {
GameProfile newProfile = new GameProfile(uuidMinion != null ? uuidMinion : UUID.randomUUID(), username);
if (skinProfile != null) {
newProfile.getProperties().putAll(skinProfile.getProperties());
}
LOGGER.info("Minion Profile: {}", newProfile);
return newProfile;
}
}
@@ -1,43 +0,0 @@
package io.github.skippyall.minions.minion;
import io.github.skippyall.minions.Minions;
import net.minecraft.inventory.Inventories;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.RegistryWrapper;
import net.minecraft.registry.tag.TagKey;
import net.minecraft.util.Identifier;
import net.minecraft.util.collection.DefaultedList;
public class ModuleInventory implements ImplementedInventory {
private static final TagKey<Item> MODULES = TagKey.of(RegistryKeys.ITEM, Identifier.of(Minions.MOD_ID,"modules"));
private DefaultedList<ItemStack> stacks = DefaultedList.ofSize(27, ItemStack.EMPTY);
public ModuleInventory() {
}
@Override
public int getMaxCountPerStack() {
return 1;
}
@Override
public boolean isValid(int slot, ItemStack stack) {
return (stack.getCount() <= getMaxCountPerStack()) && stack.isIn(MODULES);
}
@Override
public DefaultedList<ItemStack> getItems() {
return stacks;
}
public void readNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup lookup) {
Inventories.readNbt(nbt, stacks, lookup);
}
public NbtCompound writeNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup lookup) {
return Inventories.writeNbt(nbt, stacks, lookup);
}
}
@@ -7,9 +7,9 @@ import net.minecraft.server.world.ChunkTicketManager;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
@Mixin(value = ChunkTicketManager.class, remap = false) @Mixin(value = ChunkTicketManager.class)
public class ChunkTicketManagerFixMixin { public class ChunkTicketManagerFixMixin {
@WrapOperation(method = "handleChunkLeave", at = @At(value = "INVOKE", target = "Lit/unimi/dsi/fastutil/objects/ObjectSet;remove(Ljava/lang/Object;)Z")) @WrapOperation(method = "handleChunkLeave", at = @At(value = "INVOKE", target = "Lit/unimi/dsi/fastutil/objects/ObjectSet;remove(Ljava/lang/Object;)Z", remap = false))
public boolean filterIfNull(ObjectSet instance, Object o, Operation<Boolean> original) { public boolean filterIfNull(ObjectSet instance, Object o, Operation<Boolean> original) {
if (instance != null) { if (instance != null) {
return original.call(instance, o); return original.call(instance, o);
@@ -18,7 +18,7 @@ public class ChunkTicketManagerFixMixin {
return false;//Unused return false;//Unused
} }
@WrapOperation(method = "handleChunkLeave", at = @At(value = "INVOKE", target = "Lit/unimi/dsi/fastutil/objects/ObjectSet;isEmpty()Z")) @WrapOperation(method = "handleChunkLeave", at = @At(value = "INVOKE", target = "Lit/unimi/dsi/fastutil/objects/ObjectSet;isEmpty()Z", remap = false))
public boolean filterIfNull(ObjectSet instance, Operation<Boolean> original) { public boolean filterIfNull(ObjectSet instance, Operation<Boolean> original) {
if (instance != null) { if (instance != null) {
return original.call(instance); return original.call(instance);
@@ -1,24 +0,0 @@
package io.github.skippyall.minions.mixins;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.world.PlayerSaveHandler;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Optional;
@Mixin(PlayerSaveHandler.class)
public class Debug2Mixin {
@Inject(method = "method_55788", at = @At("HEAD"))
public void debug(PlayerEntity playerEntity, NbtCompound nbt, CallbackInfoReturnable<NbtCompound> cir) {
System.out.println("loadPlayerData " + playerEntity.getNameForScoreboard());
}
@Inject(method = "loadPlayerData(Lnet/minecraft/entity/player/PlayerEntity;Ljava/lang/String;)Ljava/util/Optional;", at = @At("RETURN"))
public void debug(PlayerEntity player, String extension, CallbackInfoReturnable<Optional<NbtCompound>> cir) {
System.out.println(cir.getReturnValue().isEmpty() + player.getUuidAsString());
}
}
@@ -1,32 +0,0 @@
package io.github.skippyall.minions.mixins;
import com.llamalad7.mixinextras.sugar.Local;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NbtCompound;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
//@Mixin(SectionedEntityCache.class)
@Mixin(Entity.class)
public class DebugMixin {
/*@Inject(method = "forEachInBox", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/math/ChunkSectionPos;asLong(III)J", shift = At.Shift.BEFORE, ordinal = 0))
private void debug(Box box, LazyIterationConsumer<EntityTrackingSection<?>> consumer, CallbackInfo ci) {
System.out.println("call");
}*/
@Inject(method = "readNbt", at = @At("HEAD"))
public void debug(NbtCompound nbt, CallbackInfo ci) {
if ((Object) this instanceof MinionFakePlayer) {
System.out.println("readNBT");
}
}
@Inject(method = "setPos", at = @At("HEAD"))
public void debug(double x, double y, double z, CallbackInfo ci) {
if ((Object) this instanceof MinionFakePlayer) {
System.out.println("Set Minion Pos to " + x + " " + y + " " + z);
}
}
}
@@ -0,0 +1,11 @@
package io.github.skippyall.minions.mixins;
import net.minecraft.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(Entity.class)
public interface EntityAccessor {
@Invoker("canAddPassenger")
boolean invokeCanAddPassenger(Entity other);
}
@@ -1,15 +0,0 @@
package io.github.skippyall.minions.mixins;
import com.mojang.authlib.GameProfile;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.UUID;
@Mixin(value = GameProfile.class, remap = false)
public interface GameProfileMixin{
@Mutable
@Accessor("id")
void setId(UUID id);
}
@@ -0,0 +1,29 @@
package io.github.skippyall.minions.mixins;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.module.MobSpawningModule;
import net.minecraft.entity.Entity;
import net.minecraft.entity.mob.MobEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.predicate.entity.EntityPredicates;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(MobEntity.class)
public abstract class MobEntityMixin {
@Redirect(method = "checkDespawn", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getClosestPlayer(Lnet/minecraft/entity/Entity;D)Lnet/minecraft/entity/player/PlayerEntity;"))
public PlayerEntity checkMobDespawningMinion(World instance, Entity entity, double maxDistance) {
return instance.getClosestPlayer(entity.getX(), entity.getY(), entity.getZ(), maxDistance, EntityPredicates.EXCEPT_SPECTATOR.and(entity1 -> {
if(entity1 instanceof ServerPlayerEntity player) {
if(player instanceof MinionFakePlayer minion) {
return MobSpawningModule.canMinionDespawnMobs(minion);
}
return true;
}
return false;
}));
}
}
@@ -1,5 +1,6 @@
package io.github.skippyall.minions.mixins; package io.github.skippyall.minions.mixins;
import com.llamalad7.mixinextras.injector.ModifyReceiver;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.llamalad7.mixinextras.sugar.Local; import com.llamalad7.mixinextras.sugar.Local;
@@ -16,14 +17,15 @@ import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld; import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.Text; import net.minecraft.text.Text;
import org.apache.logging.log4j.core.jmx.Server;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Mixin(PlayerManager.class) @Mixin(PlayerManager.class)
public class PlayerListMixin { public class PlayerListMixin {
@@ -49,7 +51,7 @@ public class PlayerListMixin {
@WrapOperation(method = "respawnPlayer", at = @At(value = "NEW", target = "(Lnet/minecraft/server/MinecraftServer;Lnet/minecraft/server/world/ServerWorld;Lcom/mojang/authlib/GameProfile;Lnet/minecraft/network/packet/c2s/common/SyncedClientOptions;)Lnet/minecraft/server/network/ServerPlayerEntity;")) @WrapOperation(method = "respawnPlayer", at = @At(value = "NEW", target = "(Lnet/minecraft/server/MinecraftServer;Lnet/minecraft/server/world/ServerWorld;Lcom/mojang/authlib/GameProfile;Lnet/minecraft/network/packet/c2s/common/SyncedClientOptions;)Lnet/minecraft/server/network/ServerPlayerEntity;"))
public ServerPlayerEntity makePlayerForRespawn(MinecraftServer minecraftServer, ServerWorld serverLevel, GameProfile gameProfile, SyncedClientOptions clientInformation, Operation<ServerPlayerEntity> original, ServerPlayerEntity serverPlayer, boolean bl) { public ServerPlayerEntity makePlayerForRespawn(MinecraftServer minecraftServer, ServerWorld serverLevel, GameProfile gameProfile, SyncedClientOptions clientInformation, Operation<ServerPlayerEntity> original, ServerPlayerEntity serverPlayer, boolean bl) {
if (serverPlayer instanceof MinionFakePlayer minion) { if (serverPlayer instanceof MinionFakePlayer minion) {
return MinionFakePlayer.respawnFake(minecraftServer, serverLevel, gameProfile, clientInformation, minion.isProgrammable()); return MinionFakePlayer.respawnFake(minecraftServer, serverLevel, gameProfile, clientInformation);
} }
return original.call(minecraftServer, serverLevel, gameProfile, clientInformation); return original.call(minecraftServer, serverLevel, gameProfile, clientInformation);
} }
@@ -60,4 +62,11 @@ public class PlayerListMixin {
original.call(instance, message, overlay); original.call(instance, message, overlay);
} }
} }
@ModifyReceiver(method = "checkCanJoin", at = @At(value = "INVOKE", target = "Ljava/util/List;size()I"))
public List<ServerPlayerEntity> noMinionCounting(List<ServerPlayerEntity> instance) {
return instance.stream()
.filter(player -> !(player instanceof MinionFakePlayer))
.collect(Collectors.toCollection(ArrayList::new));
}
} }
@@ -0,0 +1,21 @@
package io.github.skippyall.minions.mixins;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.SleepManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
@Mixin(SleepManager.class)
public class SleepManagerMixin {
@WrapOperation(method = "update", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayerEntity;isSpectator()Z"))
public boolean excludeMinions(ServerPlayerEntity instance, Operation<Boolean> original) {
if (instance instanceof MinionFakePlayer) {
return true;
} else {
return original.call(instance);
}
}
}
@@ -0,0 +1,28 @@
package io.github.skippyall.minions.mixins;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.module.MobSpawningModule;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.predicate.entity.EntityPredicates;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.world.SpawnHelper;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(SpawnHelper.class)
public class SpawnHelperMixin {
@Redirect(method = "spawnEntitiesInChunk(Lnet/minecraft/entity/SpawnGroup;Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/world/chunk/Chunk;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/world/SpawnHelper$Checker;Lnet/minecraft/world/SpawnHelper$Runner;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/world/ServerWorld;getClosestPlayer(DDDDZ)Lnet/minecraft/entity/player/PlayerEntity;"))
private static PlayerEntity checkMobSpawningMinion(ServerWorld instance, double x, double y, double z, double maxDistance, boolean b) {
return instance.getClosestPlayer(x, y, z, maxDistance, EntityPredicates.EXCEPT_SPECTATOR.and(entity -> {
if(entity instanceof ServerPlayerEntity player) {
if(player instanceof MinionFakePlayer minion) {
return MobSpawningModule.canMinionSpawnMobs(minion);
}
return true;
}
return false;
}));
}
}
@@ -0,0 +1,69 @@
package io.github.skippyall.minions.module;
import eu.pb4.sgui.api.elements.GuiElementBuilder;
import eu.pb4.sgui.api.gui.SimpleGui;
import io.github.skippyall.minions.command.CommandExecutor;
import io.github.skippyall.minions.fakeplayer.EntityPlayerActionPack;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import io.github.skippyall.minions.input.TextInput;
import net.minecraft.item.Items;
import net.minecraft.screen.ScreenHandlerType;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
public class ActionModules {
public static ModuleItem makeModule(EntityPlayerActionPack.ActionType actionType, Text actionName, Item vanillaItem, Text name, Text description) {
return new SimpleModuleItem(List.of(), List.of(new SimpleCommand(name, description, vanillaItem, detailSelectionExecutor(actionType, actionName))), vanillaItem);
}
public static void executeOnce(EntityPlayerActionPack.ActionType actionType, ServerPlayerEntity player, MinionFakePlayer minion) {
minion.getMinionActionPack().start(actionType, EntityPlayerActionPack.Action.once());
}
public static void executeInterval(EntityPlayerActionPack.ActionType actionType, ServerPlayerEntity player, MinionFakePlayer minion) {
TextInput.inputText(player, Text.translatable("minions.command.action.interval.enter_interval"), "1")
.thenAccept(string -> {
try {
int ticks = Integer.parseInt(string);
minion.getMinionActionPack().start(actionType, EntityPlayerActionPack.Action.interval(ticks));
} catch (NumberFormatException ignored) {}
});
}
public static void executeContinuous(EntityPlayerActionPack.ActionType actionType, ServerPlayerEntity player, MinionFakePlayer minion) {
minion.getMinionActionPack().start(actionType, EntityPlayerActionPack.Action.continuous());
}
public static void stop(EntityPlayerActionPack.ActionType actionType, ServerPlayerEntity player, MinionFakePlayer minion) {
minion.getMinionActionPack().stop(actionType);
}
public static CommandExecutor detailSelectionExecutor(EntityPlayerActionPack.ActionType actionType, Text actionName) {
return (player, minion) -> {
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_3X3, player, false);
gui.setTitle(Text.translatable("minions.command.action.details", actionName));
gui.setSlot(3, new GuiElementBuilder()
.setItem(Items.COMMAND_BLOCK)
.setName(Text.translatable("minions.command.action.once", actionName))
.setCallback(() -> executeOnce(actionType, player, minion))
);
gui.setSlot(4, new GuiElementBuilder()
.setItem(Items.CHAIN_COMMAND_BLOCK)
.setName(Text.translatable("minions.command.action.interval", actionName))
.setCallback(() -> executeInterval(actionType, player, minion))
);
gui.setSlot(5, new GuiElementBuilder()
.setItem(Items.REPEATING_COMMAND_BLOCK)
.setName(Text.translatable("minions.command.action.continuous", actionName))
.setCallback(() -> executeContinuous())
);
gui.setSlot(7, new GuiElementBuilder()
.setItem(Items.BARRIER)
.setName(Text.translatable("minions.command.action.stop", actionName))
.setCallback(() -> stop(actionType, player, minion))
);
};
}
}
@@ -0,0 +1,22 @@
package io.github.skippyall.minions.module;
import io.github.skippyall.minions.Minions;
import io.github.skippyall.minions.command.SimpleCommand;
import net.minecraft.item.Items;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import java.util.ArrayList;
import java.util.Arrays;
import static io.github.skippyall.minions.module.Modules.register;
public class ChatModule {
public static final SimpleModuleItem CHAT_MODULE = register(Identifier.of(Minions.MOD_ID, "chat_module"),
new SimpleModuleItem(new ArrayList<>(), Arrays.asList(
new SimpleCommand(Text.of("Message"), Text.of("Send Message in Public Chat"), Items.PAPER, (player, minion) -> minion.getServer().getPlayerManager().broadcast(Text.of("message"), true)),
new SimpleCommand(Text.of("Prvt-Message"), Text.of("Send Message to one Person"), Items.TRIAL_KEY, (player, minion) -> {})
), Items.PAPER));
public static void registerMe() {}
}
@@ -0,0 +1,24 @@
package io.github.skippyall.minions.module;
import io.github.skippyall.minions.Minions;
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
import net.minecraft.item.Items;
import net.minecraft.util.Identifier;
import java.util.List;
import static io.github.skippyall.minions.module.Modules.register;
public class MobSpawningModule {
public static final SimpleModuleItem MOB_SPAWNING_MODULE = register(Identifier.of(Minions.MOD_ID, "mob_spawning_module"), new SimpleModuleItem(List.of(), List.of(), Items.SPAWNER));
public static boolean canMinionSpawnMobs(MinionFakePlayer minion) {
return minion.getModuleInventory().hasModule(MOB_SPAWNING_MODULE);
}
public static boolean canMinionDespawnMobs(MinionFakePlayer minion) {
return minion.getModuleInventory().hasModule(MOB_SPAWNING_MODULE);
}
public static void registerMe() {}
}
@@ -0,0 +1,13 @@
package io.github.skippyall.minions.module;
import io.github.skippyall.minions.command.Command;
import io.github.skippyall.minions.program.block.CodeBlock;
import net.minecraft.item.ItemConvertible;
import java.util.List;
public interface ModuleItem extends ItemConvertible {
List<CodeBlock<?,?>> getCodeBlocks();
List<Command> getCommands();
}
@@ -0,0 +1,19 @@
package io.github.skippyall.minions.module;
import net.minecraft.item.Item;
import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry;
import net.minecraft.util.Identifier;
public class Modules {
public static void register() {
ChatModule.registerMe();
MountModule.registerMe();
MoveModule.registerMe();
MobSpawningModule.registerMe();
}
public static <T extends Item & ModuleItem> T register(Identifier id, T item) {
return Registry.register(Registries.ITEM, id, item);
}
}
@@ -0,0 +1,24 @@
package io.github.skippyall.minions.module;
import io.github.skippyall.minions.Minions;
import io.github.skippyall.minions.command.SimpleCommand;
import net.minecraft.item.Items;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import java.util.ArrayList;
import java.util.Arrays;
import static io.github.skippyall.minions.module.Modules.register;
public class MountModule {
public static final SimpleModuleItem MOUNT_MODULE = register(Identifier.of(Minions.MOD_ID, "mount_module"),
new SimpleModuleItem(new ArrayList<>(), Arrays.asList(
new SimpleCommand(Text.of("Mount"), Text.of("Mount the minion to the nearest mountable Entity"), Items.MINECART, (player, minion) -> minion.getMinionActionPack().mount(true)),
new SimpleCommand(Text.of("Dismount"), Text.of("Dismount the minion"), Items.BARRIER, (player, minion) -> minion.getMinionActionPack().dismount())
), Items.MINECART)
);
public static void registerMe() {}
}
@@ -0,0 +1,54 @@
package io.github.skippyall.minions.module;
import io.github.skippyall.minions.Minions;
import io.github.skippyall.minions.command.SimpleCommand;
import io.github.skippyall.minions.input.TextInput;
import net.minecraft.item.Items;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import java.util.List;
import static io.github.skippyall.minions.module.Modules.register;
public class MoveModule {
public static final SimpleCommand WALK_COMMAND = new SimpleCommand(Text.literal("Walk"), Text.literal("Walk a specific amount of blocks forward"), Items.IRON_BOOTS, (player, minion) -> {
TextInput.inputText(player, Text.literal("Amount of Blocks"), "1")
.thenAccept(string -> {
try {
float blocks = Float.parseFloat(string);
minion.moveForward(blocks);
} catch (NumberFormatException e) {
player.sendMessage(Text.literal("No valid number"));
}
});
});
public static final SimpleCommand TURN_RIGHT_COMMAND = new SimpleCommand(Text.literal("Turn Right"), Text.literal("Turn a specific amount of degrees right"), Items.COMPASS, ((player, minion) -> {
TextInput.inputText(player, Text.literal("Degrees"), "90")
.thenAccept(string -> {
try {
float degrees = Float.parseFloat(string);
minion.getMinionActionPack().turn(degrees, 0);
} catch (NumberFormatException e) {
player.sendMessage(Text.literal("No valid number"));
}
});
}));
public static final SimpleCommand TURN_LEFT_COMMAND = new SimpleCommand(Text.literal("Turn Left"), Text.literal("Turn a specific amount of degrees left"), Items.COMPASS, ((player, minion) -> {
TextInput.inputText(player, Text.literal("Degrees"), "90")
.thenAccept(string -> {
try {
float degrees = Float.parseFloat(string);
minion.getMinionActionPack().turn(-degrees, 0);
} catch (NumberFormatException e) {
player.sendMessage(Text.literal("No valid number"));
}
});
}));
public static final SimpleModuleItem MOVE_MODULE = register(Identifier.of(Minions.MOD_ID, "move_module"), new SimpleModuleItem(List.of(), List.of(WALK_COMMAND, TURN_RIGHT_COMMAND, TURN_LEFT_COMMAND), Items.IRON_BOOTS));
public static void registerMe() {}
}
@@ -0,0 +1,39 @@
package io.github.skippyall.minions.module;
import eu.pb4.polymer.core.api.item.PolymerItem;
import io.github.skippyall.minions.command.Command;
import io.github.skippyall.minions.program.block.CodeBlock;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.server.network.ServerPlayerEntity;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class SimpleModuleItem extends Item implements PolymerItem, ModuleItem {
private final List<CodeBlock<?,?>> codeBlocks;
private final List<Command> commands;
private final Item vanillaItem;
public SimpleModuleItem(List<CodeBlock<?,?>> codeBlocks, List<Command> commands, Item vanillaItem) {
super(new Item.Settings().maxCount(1));
this.codeBlocks = codeBlocks;
this.commands = commands;
this.vanillaItem = vanillaItem;
}
@Override
public List<CodeBlock<?, ?>> getCodeBlocks() {
return codeBlocks;
}
@Override
public List<Command> getCommands() {
return commands;
}
@Override
public Item getPolymerItem(ItemStack itemStack, @Nullable ServerPlayerEntity player) {
return vanillaItem;
}
}
@@ -1,21 +0,0 @@
package io.github.skippyall.minions.program.module;
import eu.pb4.polymer.core.api.item.PolymerItem;
import io.github.skippyall.minions.program.block.CodeBlock;
import net.minecraft.item.Item;
import java.util.List;
public abstract class Module extends Item implements PolymerItem {
private final String name;
public Module(String name) {
super(new Item.Settings().maxCount(1));
this.name = name;
}
public String getModuleName() {
return name;
}
public abstract List<CodeBlock<?,?>> getCodeBlocks();
}
@@ -1,5 +0,0 @@
package io.github.skippyall.minions.program.module;
public class Modules {
MoveModule MOVE = new MoveModule();
}
@@ -1,29 +0,0 @@
package io.github.skippyall.minions.program.module;
import io.github.skippyall.minions.program.block.CodeBlock;
import io.github.skippyall.minions.program.block.CodeBlocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.server.network.ServerPlayerEntity;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class MoveModule extends Module {
MoveModule() {
super("Movement");
}
public List<CodeBlock<?,?>> getCodeBlocks() {
List<CodeBlock<?,?>> codeBlocks = new ArrayList<>();
codeBlocks.add(CodeBlocks.GO);
return codeBlocks;
}
@Override
public Item getPolymerItem(ItemStack itemStack, @Nullable ServerPlayerEntity player) {
return Items.PURPLE_GLAZED_TERRACOTTA;
}
}
@@ -0,0 +1,14 @@
{
"minions.gui.main.commands": "Commands",
"minions.gui.main.programming": "Programming",
"minions.gui.main.modules": "Modules",
"minions.gui.main.inventory": "Inventory",
"minions.gui.inventory.title": "%s's Inventory",
"minions.gui.module_commands.title": "Commands",
"minions.gui.commands.title": "%s's Commands",
"minions.gui.modules.title": "%s's Modules",
"minions.command.action.details": "Set how to %s",
"minions.command.action.once": "%s once",
"minions.command.action.continuous": "%s continuously",
"minions.command.action.interval": "%s every x seconds"
}
@@ -0,0 +1,23 @@
{
"type": "minecraft:crafting_shaped",
"pattern": [
"RGR",
"GDG",
"RGR"
],
"key": {
"R": {
"item":"minecraft:redstone_block"
},
"G": {
"item": "minecraft:gold_ingot"
},
"D": {
"item": "minecraft:diamond_block"
}
},
"result": {
"id": "minions:basic_upgrade_base",
"count": 1
}
}
@@ -0,0 +1,26 @@
{
"type": "minecraft:crafting_shaped",
"pattern": [
" H ",
"RAR",
" L "
],
"key": {
"H": {
"tag": "minecraft:skulls"
},
"R": {
"item": "minecraft:redstone_torch"
},
"A": {
"item": "minecraft:armor_stand"
},
"L": {
"item":"minecraft:lodestone"
}
},
"result": {
"id": "minions:minion",
"count": 1
}
}
@@ -0,0 +1,15 @@
{
"type": "minecraft:smithing_transform",
"base": {
"item": "minions:basic_upgrade_base"
},
"addition": {
"item": "minecraft:minecart"
},
"template": {
"item": "minecraft:netherite_upgrade_smithing_template"
},
"result": {
"id": "minions:mount_module"
}
}
@@ -0,0 +1,15 @@
{
"type": "minecraft:smithing_transform",
"base": {
"item": "minions:basic_upgrade_base"
},
"addition": {
"item": "minecraft:iron_boots"
},
"template": {
"item": "minecraft:netherite_upgrade_smithing_template"
},
"result": {
"id": "minions:move_module"
}
}
+3 -2
View File
@@ -26,8 +26,9 @@
"minions.mixins.json" "minions.mixins.json"
], ],
"depends": { "depends": {
"fabricloader": ">=${loader_version}", "fabricloader": "*",
"fabric": "*", "fabric": "*",
"minecraft": "${minecraft_version}" "minecraft": "~1.21",
"polymer-core": "*"
} }
} }
+5 -4
View File
@@ -6,14 +6,15 @@
"mixins": [ "mixins": [
"ChunkTicketManagerFixMixin", "ChunkTicketManagerFixMixin",
"ConnectionMixin", "ConnectionMixin",
"Debug2Mixin", "EntityAccessor",
"DebugMixin",
"GameProfileMixin",
"MinecraftServerMixin", "MinecraftServerMixin",
"MobEntityMixin",
"PlayerListEntryS2CPacket$EntryMixin", "PlayerListEntryS2CPacket$EntryMixin",
"PlayerListMixin", "PlayerListMixin",
"ServerPlayerMixin", "ServerPlayerMixin",
"ServerPlayNetworkHandlerMixin" "ServerPlayNetworkHandlerMixin",
"SleepManagerMixin",
"SpawnHelperMixin"
], ],
"client": [], "client": [],
"server": [], "server": [],
Binary file not shown.