Compare commits
48 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bc6bbc448a | |||
| 9b61dba4c7 | |||
| 0382798a5d | |||
| 1e430ef506 | |||
| 5bd7c08f83 | |||
| 017b2ec590 | |||
| 382b394523 | |||
| 3f2a52fd0a | |||
| c5b3c883ca | |||
| b413592abf | |||
| cc1320d5c6 | |||
| da4351cff2 | |||
| 640e6f801a | |||
| bcfb406547 | |||
| b6f7bfc57b | |||
| e27b1698e4 | |||
| 216855d9c9 | |||
| e42e3adf84 | |||
| 66cbad38cb | |||
| 6640f95291 | |||
| 362bf15a19 | |||
| 2d64426496 | |||
| f5e0c1d426 | |||
| ec31e090b9 | |||
| 935b2225c9 | |||
| cdd0a594f3 | |||
| a9d0b7fd94 | |||
| 1931848068 | |||
| a2a189a0c1 | |||
| d2d96b3f67 | |||
| 08e7952e34 | |||
| cc69b22aba | |||
| c7ff6de42b | |||
| d3b25b595a | |||
| 8007778c39 | |||
| fc70b2fe5a | |||
| 2f35493580 | |||
| 6526f92a67 | |||
| d6a324a93f | |||
| 1dd6914454 | |||
| c497884884 | |||
| a236abdd5c | |||
| b4d8df9e8e | |||
| 2ee3d946ec | |||
| ea5411450c | |||
| f533ae8515 | |||
| d84190ee3c | |||
| ac4f58b9a2 |
@@ -1,5 +1,6 @@
|
||||
# User-specific stuff
|
||||
.idea/
|
||||
urlaub/
|
||||
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
+53
-5
@@ -1,5 +1,5 @@
|
||||
plugins {
|
||||
id 'fabric-loom' version '1.5-SNAPSHOT'
|
||||
id 'net.fabricmc.fabric-loom-remap' version '1.14-SNAPSHOT'
|
||||
id 'maven-publish'
|
||||
}
|
||||
|
||||
@@ -10,6 +10,22 @@ 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
|
||||
@@ -17,6 +33,18 @@ repositories {
|
||||
// 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 {
|
||||
@@ -27,8 +55,18 @@ dependencies {
|
||||
|
||||
// Fabric API. This is technically optional, but you probably want it anyway.
|
||||
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 "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}")
|
||||
compileOnly("io.netty:netty-codec-http:${project.netty_version}.Final")
|
||||
|
||||
modCompileOnly "maven.modrinth:universal-graves:${project.universal_graves_version}"
|
||||
}
|
||||
|
||||
processResources {
|
||||
@@ -44,7 +82,7 @@ processResources {
|
||||
}
|
||||
}
|
||||
|
||||
def targetJavaVersion = 17
|
||||
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
|
||||
@@ -69,14 +107,14 @@ java {
|
||||
|
||||
jar {
|
||||
from("LICENSE") {
|
||||
rename { "${it}_${project.archivesBaseName}"}
|
||||
rename { "${it}_${project.archives_base_name}"}
|
||||
}
|
||||
}
|
||||
|
||||
// configure the maven publication
|
||||
publishing {
|
||||
publications {
|
||||
mavenJava(MavenPublication) {
|
||||
maven (MavenPublication) {
|
||||
from components.java
|
||||
}
|
||||
}
|
||||
@@ -87,5 +125,15 @@ publishing {
|
||||
// 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.
|
||||
if(project.hasProperty("foxgalaxy_user_name") && project.hasProperty("foxgalaxy_password")) {
|
||||
maven {
|
||||
url = "https://maven.foxgalaxy.de/private"
|
||||
|
||||
credentials {
|
||||
username = project.property("foxgalaxy_user_name")
|
||||
password = project.property("foxgalaxy_password")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
-7
@@ -3,18 +3,24 @@ org.gradle.jvmargs=-Xmx1G
|
||||
|
||||
# Fabric Properties
|
||||
# check these on https://modmuss50.me/fabric.html
|
||||
minecraft_version=1.20.4
|
||||
loader_version=0.15.6
|
||||
yarn_mappings=1.20.4+build.3
|
||||
minecraft_version=1.21.7
|
||||
loader_version=0.16.14
|
||||
yarn_mappings=1.21.7+build.2
|
||||
|
||||
# Mod Properties
|
||||
mod_version = 0.0.1
|
||||
mod_version = 1.0.0-SNAPSHOT-1
|
||||
maven_group = io.github.skippyall
|
||||
archives_base_name = Minions
|
||||
|
||||
# Dependencies
|
||||
# check this on https://modmuss50.me/fabric.html
|
||||
fabric_version=0.95.4+1.20.4
|
||||
fabric_version=0.128.1+1.21.7
|
||||
|
||||
polymer_version=0.7.5+1.20.4
|
||||
sgui_version=1.4.1+1.20.4
|
||||
polymer_version=0.13.3+1.21.6
|
||||
sgui_version=1.10.0+1.21.6
|
||||
server_translations_version=2.5.1+1.21.5
|
||||
|
||||
night_config_version=3.8.3
|
||||
netty_version=4.1.130
|
||||
|
||||
universal_graves_version=3.8.0+1.21.6
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
package io.github.skippyall.minions;
|
||||
|
||||
import eu.pb4.sgui.api.ClickType;
|
||||
import eu.pb4.sgui.api.elements.GuiElement;
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import eu.pb4.sgui.api.elements.GuiElementInterface;
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import eu.pb4.sgui.api.gui.SlotGuiInterface;
|
||||
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
|
||||
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;
|
||||
|
||||
public class MinionInventory {
|
||||
public static void openInventory(ServerPlayer player, MinionFakePlayer minion) {
|
||||
|
||||
}
|
||||
|
||||
public static void openServerSideInventory(ServerPlayer player, MinionFakePlayer minion) {
|
||||
SimpleGui gui = new SimpleGui(MenuType.GENERIC_3x3, player, false);
|
||||
gui.setTitle(Component.literal("Minion"));
|
||||
gui.setSlot(4, new GuiElementBuilder()
|
||||
.setItem(Items.REDSTONE)
|
||||
.setName(Component.literal("Programming"))
|
||||
.setCallback((i, clickType, clickType1) -> {
|
||||
openProgrammingInventory(player, minion);
|
||||
})
|
||||
);
|
||||
gui.setSlot(3, new GuiElementBuilder()
|
||||
.setItem(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE)
|
||||
.setName(Component.literal("Modules and Detectors"))
|
||||
.setCallback((i, clickType, clickType1) -> {
|
||||
|
||||
})
|
||||
);
|
||||
gui.open();
|
||||
}
|
||||
|
||||
public static void openProgrammingInventory(ServerPlayer player, MinionFakePlayer minion) {
|
||||
|
||||
}
|
||||
|
||||
public static void open
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package io.github.skippyall.minions;
|
||||
|
||||
import eu.pb4.polymer.core.api.item.PolymerItem;
|
||||
import eu.pb4.polymer.core.api.item.PolymerItemUtils;
|
||||
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
|
||||
import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
|
||||
import net.minecraft.network.chat.ComponentContents;
|
||||
import net.minecraft.network.chat.contents.PlainTextContents;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.TooltipFlag;
|
||||
import net.minecraft.world.item.context.UseOnContext;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class MinionItem extends Item implements PolymerItem {
|
||||
public MinionItem() {
|
||||
super(new FabricItemSettings());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Item getPolymerItem(ItemStack itemStack, @Nullable ServerPlayer player) {
|
||||
return Items.PLAYER_HEAD;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getPolymerItemStack(ItemStack stack, TooltipFlag flag, ServerPlayer player) {
|
||||
ItemStack out = PolymerItemUtils.createItemStack(stack, flag, player);
|
||||
//CompoundTag tag = out.getOrCreateTag();
|
||||
//PlayerHeadItem.TAG_SKULL_OWNER;
|
||||
return out;
|
||||
}
|
||||
|
||||
/*@Override
|
||||
public int getPolymerCustomModelData(ItemStack itemStack, @Nullable ServerPlayer player) {
|
||||
return 10;
|
||||
}*/
|
||||
|
||||
public InteractionResult useOn(UseOnContext context) {
|
||||
System.out.println("Minion spawned "+ context.getItemInHand().getDisplayName());
|
||||
ComponentContents contents = context.getItemInHand().getHoverName().getContents();
|
||||
String name;
|
||||
if(contents instanceof PlainTextContents plainContents) {
|
||||
name = plainContents.text();
|
||||
} else {
|
||||
name = "Minion";
|
||||
}
|
||||
if(!context.getLevel().isClientSide) {
|
||||
MinionFakePlayer.createMinion(name, (ServerLevel) context.getLevel(), (ServerPlayer) context.getPlayer(), context.getClickedPos().getCenter().add(0,0.5,0), 0, 0);
|
||||
}
|
||||
return InteractionResult.SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package io.github.skippyall.minions;
|
||||
|
||||
import eu.pb4.polymer.core.api.entity.PolymerEntityUtils;
|
||||
import io.github.skippyall.minions.networking.ClientToServerNetworking;
|
||||
import net.fabricmc.api.EnvType;
|
||||
import net.fabricmc.api.ModInitializer;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerConfigurationNetworking;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerLoginConnectionEvents;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.network.ServerLoginPacketListenerImpl;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Minions implements ModInitializer {
|
||||
public static final String MOD_ID = "minions";
|
||||
public static final MinionItem MINION_ITEM = Registry.register(BuiltInRegistries.ITEM, new ResourceLocation(MOD_ID, "minion"), new MinionItem());
|
||||
|
||||
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
|
||||
@Override
|
||||
public void onInitialize() {
|
||||
PolymerEntityUtils.registerType();
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package io.github.skippyall.minions.client;
|
||||
|
||||
import io.github.skippyall.minions.networking.ClientToServerNetworking;
|
||||
import net.fabricmc.api.ClientModInitializer;
|
||||
import net.fabricmc.fabric.api.client.networking.v1.ClientConfigurationConnectionEvents;
|
||||
import net.fabricmc.fabric.api.client.networking.v1.ClientLoginConnectionEvents;
|
||||
|
||||
public class MinionsClient implements ClientModInitializer {
|
||||
/**
|
||||
* Runs the mod initializer on the client environment.
|
||||
*/
|
||||
@Override
|
||||
public void onInitializeClient() {
|
||||
ClientConfigurationConnectionEvents.INIT.register(ClientToServerNetworking::onConfigurationInit);
|
||||
}
|
||||
}
|
||||
@@ -1,626 +0,0 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
|
||||
|
||||
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.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetCarriedItemPacket;
|
||||
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.animal.horse.AbstractHorse;
|
||||
import net.minecraft.world.entity.decoration.ItemFrame;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.entity.vehicle.Boat;
|
||||
import net.minecraft.world.entity.vehicle.Minecart;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.phys.EntityHitResult;
|
||||
import net.minecraft.world.phys.HitResult;
|
||||
import net.minecraft.world.phys.Vec2;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class EntityPlayerActionPack
|
||||
{
|
||||
private final ServerPlayer player;
|
||||
|
||||
private final Map<ActionType, Action> actions = new EnumMap<>(ActionType.class);
|
||||
|
||||
private BlockPos currentBlock;
|
||||
private int blockHitDelay;
|
||||
private boolean isHittingBlock;
|
||||
private float curBlockDamageMP;
|
||||
|
||||
private boolean sneaking;
|
||||
private boolean sprinting;
|
||||
private float forward;
|
||||
private float strafing;
|
||||
|
||||
private int itemUseCooldown;
|
||||
|
||||
public EntityPlayerActionPack(ServerPlayer playerIn)
|
||||
{
|
||||
player = playerIn;
|
||||
stopAll();
|
||||
}
|
||||
public void copyFrom(EntityPlayerActionPack other)
|
||||
{
|
||||
actions.putAll(other.actions);
|
||||
currentBlock = other.currentBlock;
|
||||
blockHitDelay = other.blockHitDelay;
|
||||
isHittingBlock = other.isHittingBlock;
|
||||
curBlockDamageMP = other.curBlockDamageMP;
|
||||
|
||||
sneaking = other.sneaking;
|
||||
sprinting = other.sprinting;
|
||||
forward = other.forward;
|
||||
strafing = other.strafing;
|
||||
|
||||
itemUseCooldown = other.itemUseCooldown;
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack start(ActionType type, Action action)
|
||||
{
|
||||
Action previous = actions.remove(type);
|
||||
if (previous != null) type.stop(player, previous);
|
||||
if (action != null)
|
||||
{
|
||||
actions.put(type, action);
|
||||
type.start(player, action); // noop
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack setSneaking(boolean doSneak)
|
||||
{
|
||||
sneaking = doSneak;
|
||||
player.setShiftKeyDown(doSneak);
|
||||
if (sprinting && sneaking)
|
||||
setSprinting(false);
|
||||
return this;
|
||||
}
|
||||
public EntityPlayerActionPack setSprinting(boolean doSprint)
|
||||
{
|
||||
sprinting = doSprint;
|
||||
player.setSprinting(doSprint);
|
||||
if (sneaking && sprinting)
|
||||
setSneaking(false);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack setForward(float value)
|
||||
{
|
||||
forward = value;
|
||||
return this;
|
||||
}
|
||||
public EntityPlayerActionPack setStrafing(float value)
|
||||
{
|
||||
strafing = value;
|
||||
return this;
|
||||
}
|
||||
public EntityPlayerActionPack look(Direction direction)
|
||||
{
|
||||
return switch (direction)
|
||||
{
|
||||
case NORTH -> look(180, 0);
|
||||
case SOUTH -> look(0, 0);
|
||||
case EAST -> look(-90, 0);
|
||||
case WEST -> look(90, 0);
|
||||
case UP -> look(player.getYRot(), -90);
|
||||
case DOWN -> look(player.getYRot(), 90);
|
||||
};
|
||||
}
|
||||
public EntityPlayerActionPack look(Vec2 rotation)
|
||||
{
|
||||
return look(rotation.x, rotation.y);
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack look(float yaw, float pitch)
|
||||
{
|
||||
player.setYRot(yaw % 360); //setYaw
|
||||
player.setXRot(Mth.clamp(pitch, -90, 90)); // setPitch
|
||||
// maybe player.moveTo(player.getX(), player.getY(), player.getZ(), yaw, Mth.clamp(pitch,-90.0F, 90.0F));
|
||||
return this;
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack lookAt(Vec3 position)
|
||||
{
|
||||
player.lookAt(EntityAnchorArgument.Anchor.EYES, position);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack turn(float yaw, float pitch)
|
||||
{
|
||||
return look(player.getYRot() + yaw, player.getXRot() + pitch);
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack turn(Vec2 rotation)
|
||||
{
|
||||
return turn(rotation.x, rotation.y);
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack stopMovement()
|
||||
{
|
||||
setSneaking(false);
|
||||
setSprinting(false);
|
||||
forward = 0.0F;
|
||||
strafing = 0.0F;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public EntityPlayerActionPack stopAll()
|
||||
{
|
||||
for (ActionType type : actions.keySet()) type.stop(player, actions.get(type));
|
||||
actions.clear();
|
||||
return stopMovement();
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack mount(boolean onlyRideables)
|
||||
{
|
||||
//test what happens
|
||||
List<Entity> entities;
|
||||
if (onlyRideables)
|
||||
{
|
||||
entities = player.level().getEntities(player, player.getBoundingBox().inflate(3.0D, 1.0D, 3.0D),
|
||||
e -> e instanceof Minecart || e instanceof Boat || e instanceof AbstractHorse);
|
||||
}
|
||||
else
|
||||
{
|
||||
entities = player.level().getEntities(player, player.getBoundingBox().inflate(3.0D, 1.0D, 3.0D));
|
||||
}
|
||||
if (entities.size()==0)
|
||||
return this;
|
||||
Entity closest = null;
|
||||
double distance = Double.POSITIVE_INFINITY;
|
||||
Entity currentVehicle = player.getVehicle();
|
||||
for (Entity e: entities)
|
||||
{
|
||||
if (e == player || (currentVehicle == e))
|
||||
continue;
|
||||
double dd = player.distanceToSqr(e);
|
||||
if (dd<distance)
|
||||
{
|
||||
distance = dd;
|
||||
closest = e;
|
||||
}
|
||||
}
|
||||
if (closest == null) return this;
|
||||
if (closest instanceof AbstractHorse && onlyRideables)
|
||||
((AbstractHorse) closest).mobInteract(player, InteractionHand.MAIN_HAND);
|
||||
else
|
||||
player.startRiding(closest,true);
|
||||
return this;
|
||||
}
|
||||
public EntityPlayerActionPack dismount()
|
||||
{
|
||||
player.stopRiding();
|
||||
return this;
|
||||
}
|
||||
|
||||
public void onUpdate()
|
||||
{
|
||||
Map<ActionType, Boolean> actionAttempts = new HashMap<>();
|
||||
actions.values().removeIf(e -> e.done);
|
||||
for (Map.Entry<ActionType, Action> e : actions.entrySet())
|
||||
{
|
||||
ActionType type = e.getKey();
|
||||
Action action = e.getValue();
|
||||
// skipping attack if use was successful
|
||||
if (!(actionAttempts.getOrDefault(ActionType.USE, false) && type == ActionType.ATTACK))
|
||||
{
|
||||
Boolean actionStatus = action.tick(this, type);
|
||||
if (actionStatus != null)
|
||||
actionAttempts.put(type, actionStatus);
|
||||
}
|
||||
// optionally retrying use after successful attack and unsuccessful use
|
||||
if (type == ActionType.ATTACK
|
||||
&& actionAttempts.getOrDefault(ActionType.ATTACK, false)
|
||||
&& !actionAttempts.getOrDefault(ActionType.USE, true) )
|
||||
{
|
||||
// according to MinecraftClient.handleInputEvents
|
||||
Action using = actions.get(ActionType.USE);
|
||||
if (using != null) // this is always true - we know use worked, but just in case
|
||||
{
|
||||
using.retry(this, ActionType.USE);
|
||||
}
|
||||
}
|
||||
}
|
||||
float vel = sneaking?0.3F:1.0F;
|
||||
// The != 0.0F checks are needed given else real players can't control minecarts, however it works with fakes and else they don't stop immediately
|
||||
if (forward != 0.0F || player instanceof MinionFakePlayer) {
|
||||
player.zza = forward * vel;
|
||||
}
|
||||
if (strafing != 0.0F || player instanceof MinionFakePlayer) {
|
||||
player.xxa = strafing * vel;
|
||||
}
|
||||
}
|
||||
|
||||
static HitResult getTarget(ServerPlayer player)
|
||||
{
|
||||
double reach = player.gameMode.isCreative() ? 5 : 4.5f;
|
||||
return Tracer.rayTrace(player, 1, reach, false);
|
||||
}
|
||||
|
||||
private void dropItemFromSlot(int slot, boolean dropAll)
|
||||
{
|
||||
Inventory inv = player.getInventory(); // getInventory;
|
||||
if (!inv.getItem(slot).isEmpty())
|
||||
player.drop(inv.removeItem(slot,
|
||||
dropAll ? inv.getItem(slot).getCount() : 1
|
||||
), false, true); // scatter, keep owner
|
||||
}
|
||||
|
||||
public void drop(int selectedSlot, boolean dropAll)
|
||||
{
|
||||
Inventory inv = player.getInventory(); // getInventory;
|
||||
if (selectedSlot == -2) // all
|
||||
{
|
||||
for (int i = inv.getContainerSize(); i >= 0; i--)
|
||||
dropItemFromSlot(i, dropAll);
|
||||
}
|
||||
else // one slot
|
||||
{
|
||||
if (selectedSlot == -1)
|
||||
selectedSlot = inv.selected;
|
||||
dropItemFromSlot(selectedSlot, dropAll);
|
||||
}
|
||||
}
|
||||
|
||||
public void setSlot(int slot)
|
||||
{
|
||||
player.getInventory().selected = slot-1;
|
||||
player.connection.send(new ClientboundSetCarriedItemPacket(slot-1));
|
||||
}
|
||||
|
||||
public enum ActionType
|
||||
{
|
||||
USE(true)
|
||||
{
|
||||
@Override
|
||||
boolean execute(ServerPlayer player, Action action)
|
||||
{
|
||||
EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack();
|
||||
if (ap.itemUseCooldown > 0)
|
||||
{
|
||||
ap.itemUseCooldown--;
|
||||
return true;
|
||||
}
|
||||
if (player.isUsingItem())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
HitResult hit = getTarget(player);
|
||||
for (InteractionHand hand : InteractionHand.values())
|
||||
{
|
||||
switch (hit.getType())
|
||||
{
|
||||
case BLOCK:
|
||||
{
|
||||
player.resetLastActionTime();
|
||||
ServerLevel world = player.serverLevel();
|
||||
BlockHitResult blockHit = (BlockHitResult) hit;
|
||||
BlockPos pos = blockHit.getBlockPos();
|
||||
Direction side = blockHit.getDirection();
|
||||
if (pos.getY() < player.level().getMaxBuildHeight() - (side == Direction.UP ? 1 : 0) && world.mayInteract(player, pos))
|
||||
{
|
||||
InteractionResult result = player.gameMode.useItemOn(player, world, player.getItemInHand(hand), hand, blockHit);
|
||||
if (result.consumesAction())
|
||||
{
|
||||
if (result.shouldSwing()) player.swing(hand);
|
||||
ap.itemUseCooldown = 3;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ENTITY:
|
||||
{
|
||||
player.resetLastActionTime();
|
||||
EntityHitResult entityHit = (EntityHitResult) hit;
|
||||
Entity entity = entityHit.getEntity();
|
||||
boolean handWasEmpty = player.getItemInHand(hand).isEmpty();
|
||||
boolean itemFrameEmpty = (entity instanceof ItemFrame) && ((ItemFrame) entity).getItem().isEmpty();
|
||||
Vec3 relativeHitPos = entityHit.getLocation().subtract(entity.getX(), entity.getY(), entity.getZ());
|
||||
if (entity.interactAt(player, relativeHitPos, hand).consumesAction())
|
||||
{
|
||||
ap.itemUseCooldown = 3;
|
||||
return true;
|
||||
}
|
||||
// fix for SS itemframe always returns CONSUME even if no action is performed
|
||||
if (player.interactOn(entity, hand).consumesAction() && !(handWasEmpty && itemFrameEmpty))
|
||||
{
|
||||
ap.itemUseCooldown = 3;
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
ItemStack handItem = player.getItemInHand(hand);
|
||||
if (player.gameMode.useItem(player, player.level(), handItem, hand).consumesAction())
|
||||
{
|
||||
ap.itemUseCooldown = 3;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
void inactiveTick(ServerPlayer player, Action action)
|
||||
{
|
||||
EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack();
|
||||
ap.itemUseCooldown = 0;
|
||||
player.releaseUsingItem();
|
||||
}
|
||||
},
|
||||
ATTACK(true) {
|
||||
@Override
|
||||
boolean execute(ServerPlayer player, Action action) {
|
||||
HitResult hit = getTarget(player);
|
||||
switch (hit.getType()) {
|
||||
case ENTITY: {
|
||||
EntityHitResult entityHit = (EntityHitResult) hit;
|
||||
if (!action.isContinuous)
|
||||
{
|
||||
player.attack(entityHit.getEntity());
|
||||
player.swing(InteractionHand.MAIN_HAND);
|
||||
}
|
||||
player.resetAttackStrengthTicker();
|
||||
player.resetLastActionTime();
|
||||
return true;
|
||||
}
|
||||
case BLOCK: {
|
||||
EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack();
|
||||
if (ap.blockHitDelay > 0)
|
||||
{
|
||||
ap.blockHitDelay--;
|
||||
return false;
|
||||
}
|
||||
BlockHitResult blockHit = (BlockHitResult) hit;
|
||||
BlockPos pos = blockHit.getBlockPos();
|
||||
Direction side = blockHit.getDirection();
|
||||
if (player.blockActionRestricted(player.level(), pos, player.gameMode.getGameModeForPlayer())) return false;
|
||||
if (ap.currentBlock != null && player.level().getBlockState(ap.currentBlock).isAir())
|
||||
{
|
||||
ap.currentBlock = null;
|
||||
return false;
|
||||
}
|
||||
BlockState state = player.level().getBlockState(pos);
|
||||
boolean blockBroken = false;
|
||||
if (player.gameMode.getGameModeForPlayer().isCreative())
|
||||
{
|
||||
player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, side, player.level().getMaxBuildHeight(), -1);
|
||||
ap.blockHitDelay = 5;
|
||||
blockBroken = true;
|
||||
}
|
||||
else if (ap.currentBlock == null || !ap.currentBlock.equals(pos))
|
||||
{
|
||||
if (ap.currentBlock != null)
|
||||
{
|
||||
player.gameMode.handleBlockBreakAction(ap.currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, side, player.level().getMaxBuildHeight(), -1);
|
||||
}
|
||||
player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, side, player.level().getMaxBuildHeight(), -1);
|
||||
boolean notAir = !state.isAir();
|
||||
if (notAir && ap.curBlockDamageMP == 0)
|
||||
{
|
||||
state.attack(player.level(), pos, player);
|
||||
}
|
||||
if (notAir && state.getDestroyProgress(player, player.level(), pos) >= 1)
|
||||
{
|
||||
ap.currentBlock = null;
|
||||
//instamine??
|
||||
blockBroken = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
ap.currentBlock = pos;
|
||||
ap.curBlockDamageMP = 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ap.curBlockDamageMP += state.getDestroyProgress(player, player.level(), pos);
|
||||
if (ap.curBlockDamageMP >= 1)
|
||||
{
|
||||
player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, side, player.level().getMaxBuildHeight(), -1);
|
||||
ap.currentBlock = null;
|
||||
ap.blockHitDelay = 5;
|
||||
blockBroken = true;
|
||||
}
|
||||
player.level().destroyBlockProgress(-1, pos, (int) (ap.curBlockDamageMP * 10));
|
||||
|
||||
}
|
||||
player.resetLastActionTime();
|
||||
player.swing(InteractionHand.MAIN_HAND);
|
||||
return blockBroken;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
void inactiveTick(ServerPlayer player, Action action)
|
||||
{
|
||||
EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack();
|
||||
if (ap.currentBlock == null) return;
|
||||
player.level().destroyBlockProgress(-1, ap.currentBlock, -1);
|
||||
player.gameMode.handleBlockBreakAction(ap.currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.level().getMaxBuildHeight(), -1);
|
||||
ap.currentBlock = null;
|
||||
}
|
||||
},
|
||||
JUMP(true)
|
||||
{
|
||||
@Override
|
||||
boolean execute(ServerPlayer player, Action action)
|
||||
{
|
||||
if (action.limit == 1)
|
||||
{
|
||||
if (player.onGround()) player.jumpFromGround(); // onGround
|
||||
}
|
||||
else
|
||||
{
|
||||
player.setJumping(true);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
void inactiveTick(ServerPlayer player, Action action)
|
||||
{
|
||||
player.setJumping(false);
|
||||
}
|
||||
},
|
||||
DROP_ITEM(true)
|
||||
{
|
||||
@Override
|
||||
boolean execute(ServerPlayer player, Action action)
|
||||
{
|
||||
player.resetLastActionTime();
|
||||
player.drop(false); // dropSelectedItem
|
||||
return false;
|
||||
}
|
||||
},
|
||||
DROP_STACK(true)
|
||||
{
|
||||
@Override
|
||||
boolean execute(ServerPlayer player, Action action)
|
||||
{
|
||||
player.resetLastActionTime();
|
||||
player.drop(true); // dropSelectedItem
|
||||
return false;
|
||||
}
|
||||
},
|
||||
SWAP_HANDS(true)
|
||||
{
|
||||
@Override
|
||||
boolean execute(ServerPlayer player, Action action)
|
||||
{
|
||||
player.resetLastActionTime();
|
||||
ItemStack itemStack_1 = player.getItemInHand(InteractionHand.OFF_HAND);
|
||||
player.setItemInHand(InteractionHand.OFF_HAND, player.getItemInHand(InteractionHand.MAIN_HAND));
|
||||
player.setItemInHand(InteractionHand.MAIN_HAND, itemStack_1);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
public final boolean preventSpectator;
|
||||
|
||||
ActionType(boolean preventSpectator)
|
||||
{
|
||||
this.preventSpectator = preventSpectator;
|
||||
}
|
||||
|
||||
void start(ServerPlayer player, Action action) {}
|
||||
abstract boolean execute(ServerPlayer player, Action action);
|
||||
void inactiveTick(ServerPlayer player, Action action) {}
|
||||
void stop(ServerPlayer player, Action action)
|
||||
{
|
||||
inactiveTick(player, action);
|
||||
}
|
||||
}
|
||||
|
||||
public static class Action
|
||||
{
|
||||
public boolean done = false;
|
||||
public final int limit;
|
||||
public final int interval;
|
||||
public final int offset;
|
||||
private int count;
|
||||
private int next;
|
||||
private final boolean isContinuous;
|
||||
|
||||
private Action(int limit, int interval, int offset, boolean continuous)
|
||||
{
|
||||
this.limit = limit;
|
||||
this.interval = interval;
|
||||
this.offset = offset;
|
||||
next = interval + offset;
|
||||
isContinuous = continuous;
|
||||
}
|
||||
|
||||
public static Action once()
|
||||
{
|
||||
return new Action(1, 1, 0, false);
|
||||
}
|
||||
|
||||
public static Action continuous()
|
||||
{
|
||||
return new Action(-1, 1, 0, true);
|
||||
}
|
||||
|
||||
public static Action interval(int interval)
|
||||
{
|
||||
return new Action(-1, interval, 0, false);
|
||||
}
|
||||
|
||||
public static Action interval(int interval, int offset)
|
||||
{
|
||||
return new Action(-1, interval, offset, false);
|
||||
}
|
||||
|
||||
Boolean tick(EntityPlayerActionPack actionPack, ActionType type)
|
||||
{
|
||||
next--;
|
||||
Boolean cancel = null;
|
||||
if (next <= 0)
|
||||
{
|
||||
if (interval == 1 && !isContinuous)
|
||||
{
|
||||
// need to allow entity to tick, otherwise won't have effect (bow)
|
||||
// actions are 20 tps, so need to clear status mid tick, allowing entities process it till next time
|
||||
if (!type.preventSpectator || !actionPack.player.isSpectator())
|
||||
{
|
||||
type.inactiveTick(actionPack.player, this);
|
||||
}
|
||||
}
|
||||
|
||||
if (!type.preventSpectator || !actionPack.player.isSpectator())
|
||||
{
|
||||
cancel = type.execute(actionPack.player, this);
|
||||
}
|
||||
count++;
|
||||
if (count == limit)
|
||||
{
|
||||
type.stop(actionPack.player, null);
|
||||
done = true;
|
||||
return cancel;
|
||||
}
|
||||
next = interval;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!type.preventSpectator || !actionPack.player.isSpectator())
|
||||
{
|
||||
type.inactiveTick(actionPack.player, this);
|
||||
}
|
||||
}
|
||||
return cancel;
|
||||
}
|
||||
|
||||
void retry(EntityPlayerActionPack actionPack, ActionType type)
|
||||
{
|
||||
//assuming action run but was unsuccesful that tick, but opportunity emerged to retry it, lets retry it.
|
||||
if (!type.preventSpectator || !actionPack.player.isSpectator())
|
||||
{
|
||||
type.execute(actionPack.player, this);
|
||||
}
|
||||
count++;
|
||||
if (count == limit)
|
||||
{
|
||||
type.stop(actionPack.player, null);
|
||||
done = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
|
||||
import io.netty.channel.embedded.EmbeddedChannel;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.PacketListener;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.PacketFlow;
|
||||
|
||||
public class FakeClientConnection extends Connection {
|
||||
public FakeClientConnection(PacketFlow p)
|
||||
{
|
||||
super(p);
|
||||
// compat with adventure-platform-fabric. This does NOT trigger other vanilla handlers for establishing a channel
|
||||
// also makes #isOpen return true, allowing enderpearls to teleport fake players
|
||||
((ClientConnectionInterface)this).setChannel(new EmbeddedChannel());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setReadOnly()
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleDisconnection() {
|
||||
getPacketListener().onDisconnect(getDisconnectedReason()==null ? Component.literal("Disconnected"): getDisconnectedReason());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setListenerForServerboundHandshake(PacketListener packetListener)
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setListener(PacketListener packetListener) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.authlib.yggdrasil.ProfileResult;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.UUIDUtil;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.contents.TranslatableContents;
|
||||
import net.minecraft.network.protocol.PacketFlow;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ServerboundClientCommandPacket;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.TickTask;
|
||||
import net.minecraft.server.level.ClientInformation;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.network.CommonListenerCookie;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.food.FoodData;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class MinionFakePlayer extends ServerPlayer {
|
||||
public Runnable fixStartingPosition = () -> {};
|
||||
public boolean isAShadow;
|
||||
public static void createMinion(String username, ServerLevel level, ServerPlayer owner, Vec3 pos, double yaw, double pitch) {
|
||||
MinecraftServer server = level.getServer();
|
||||
server.getProfileCache().getAsync(username).thenAcceptAsync((optional) -> {
|
||||
GameProfile profile = null;
|
||||
if(optional.isPresent()){
|
||||
UUID uuid = optional.get().getId();
|
||||
ProfileResult result = server.getSessionService().fetchProfile(uuid, true);
|
||||
if(result != null) {
|
||||
profile = result.profile();
|
||||
}
|
||||
}
|
||||
if(profile == null) {
|
||||
profile = new GameProfile(UUIDUtil.createOfflinePlayerUUID(username), username);
|
||||
}
|
||||
MinionFakePlayer instance = new MinionFakePlayer(server, level, profile, ClientInformation.createDefault(), false);
|
||||
instance.fixStartingPosition = () -> instance.moveTo(pos.x, pos.y, pos.z, (float) yaw, (float) pitch);
|
||||
server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), instance, new CommonListenerCookie(profile, 0, instance.clientInformation()));
|
||||
instance.teleportTo(level, pos.x, pos.y, pos.z, (float) yaw, (float) pitch);
|
||||
instance.setHealth(20.0F);
|
||||
instance.unsetRemoved();
|
||||
instance.gameMode.changeGameModeForPlayer(GameType.SURVIVAL);
|
||||
server.getPlayerList().broadcastAll(new ClientboundRotateHeadPacket(instance, (byte) (instance.yHeadRot * 256 / 360)), level.dimension());//instance.dimension);
|
||||
server.getPlayerList().broadcastAll(new ClientboundTeleportEntityPacket(instance), level.dimension());//instance.dimension);
|
||||
//instance.world.getChunkManager(). updatePosition(instance);
|
||||
instance.entityData.set(DATA_PLAYER_MODE_CUSTOMISATION, (byte) 0x7f); // show all model layers (incl. capes)
|
||||
instance.getAbilities().flying = false;
|
||||
instance.setMaxUpStep(0.6F);
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused") //Don't know if I'll need this
|
||||
public static MinionFakePlayer createShadow(MinecraftServer server, ServerPlayer player)
|
||||
{
|
||||
player.getServer().getPlayerList().remove(player);
|
||||
player.connection.disconnect(Component.translatable("multiplayer.disconnect.duplicate_login"));
|
||||
ServerLevel worldIn = player.serverLevel();//.getWorld(player.dimension);
|
||||
GameProfile gameprofile = player.getGameProfile();
|
||||
MinionFakePlayer playerShadow = new MinionFakePlayer(server, worldIn, gameprofile, player.clientInformation(), true);
|
||||
playerShadow.setChatSession(player.getChatSession());
|
||||
server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), playerShadow, new CommonListenerCookie(gameprofile, 0, player.clientInformation()));
|
||||
|
||||
playerShadow.setHealth(player.getHealth());
|
||||
playerShadow.connection.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot());
|
||||
playerShadow.gameMode.changeGameModeForPlayer(player.gameMode.getGameModeForPlayer());
|
||||
((ServerPlayerInterface) playerShadow).getActionPack().copyFrom(((ServerPlayerInterface) player).getActionPack());
|
||||
playerShadow.entityData.set(DATA_PLAYER_MODE_CUSTOMISATION, player.getEntityData().get(DATA_PLAYER_MODE_CUSTOMISATION));
|
||||
|
||||
|
||||
server.getPlayerList().broadcastAll(new ClientboundRotateHeadPacket(playerShadow, (byte) (player.yHeadRot * 256 / 360)), playerShadow.level().dimension());
|
||||
server.getPlayerList().broadcastAll(new ClientboundPlayerInfoUpdatePacket(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER, playerShadow));
|
||||
//player.world.getChunkManager().updatePosition(playerShadow);
|
||||
playerShadow.getAbilities().flying = player.getAbilities().flying;
|
||||
return playerShadow;
|
||||
}
|
||||
|
||||
public static MinionFakePlayer respawnFake(MinecraftServer server, ServerLevel level, GameProfile profile, ClientInformation cli)
|
||||
{
|
||||
return new MinionFakePlayer(server, level, profile, cli, false);
|
||||
}
|
||||
|
||||
private MinionFakePlayer(MinecraftServer server, ServerLevel worldIn, GameProfile profile, ClientInformation cli, boolean shadow)
|
||||
{
|
||||
super(server, worldIn, profile, cli);
|
||||
isAShadow = shadow;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEquipItem(final EquipmentSlot slot, final ItemStack previous, final ItemStack stack)
|
||||
{
|
||||
if (!isUsingItem()) super.onEquipItem(slot, previous, stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void kill()
|
||||
{
|
||||
kill(Component.literal("Killed"));
|
||||
}
|
||||
|
||||
public void kill(Component reason)
|
||||
{
|
||||
shakeOff();
|
||||
|
||||
if (reason.getContents() instanceof TranslatableContents text && text.getKey().equals("multiplayer.disconnect.duplicate_login")) {
|
||||
this.connection.onDisconnect(reason);
|
||||
} else {
|
||||
this.server.tell(new TickTask(this.server.getTickCount(), () -> {
|
||||
this.connection.onDisconnect(reason);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick()
|
||||
{
|
||||
if (this.getServer().getTickCount() % 10 == 0)
|
||||
{
|
||||
this.connection.resetPosition();
|
||||
this.serverLevel().getChunkSource().move(this);
|
||||
}
|
||||
try
|
||||
{
|
||||
super.tick();
|
||||
this.doTick();
|
||||
}
|
||||
catch (NullPointerException ignored)
|
||||
{
|
||||
// happens with that paper port thingy - not sure what that would fix, but hey
|
||||
// the game not gonna crash violently.
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void shakeOff()
|
||||
{
|
||||
if (getVehicle() instanceof Player) stopRiding();
|
||||
for (Entity passenger : getIndirectPassengers())
|
||||
{
|
||||
if (passenger instanceof Player) passenger.stopRiding();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void die(DamageSource cause)
|
||||
{
|
||||
shakeOff();
|
||||
super.die(cause);
|
||||
setHealth(20);
|
||||
this.foodData = new FoodData();
|
||||
kill(this.getCombatTracker().getDeathMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIpAddress()
|
||||
{
|
||||
return "127.0.0.1";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean allowsListing() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void checkFallDamage(double y, boolean onGround, BlockState state, BlockPos pos) {
|
||||
doCheckFallDamage(0.0, y, 0.0, onGround);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Entity changeDimension(ServerLevel serverLevel)
|
||||
{
|
||||
super.changeDimension(serverLevel);
|
||||
if (wonGame) {
|
||||
ServerboundClientCommandPacket p = new ServerboundClientCommandPacket(ServerboundClientCommandPacket.Action.PERFORM_RESPAWN);
|
||||
connection.handleClientCommand(p);
|
||||
}
|
||||
|
||||
// If above branch was taken, *this* has been removed and replaced, the new instance has been set
|
||||
// on 'our' connection (which is now theirs, but we still have a ref).
|
||||
if (connection.player.isChangingDimension()) {
|
||||
connection.player.hasChangedDimension();
|
||||
}
|
||||
return connection.player;
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.contents.TranslatableContents;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.network.CommonListenerCookie;
|
||||
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
||||
import net.minecraft.world.entity.RelativeMovement;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class NetHandlerPlayServerFake extends ServerGamePacketListenerImpl
|
||||
{
|
||||
public NetHandlerPlayServerFake(final MinecraftServer minecraftServer, final Connection connection, final ServerPlayer serverPlayer, final CommonListenerCookie i)
|
||||
{
|
||||
super(minecraftServer, connection, serverPlayer, i);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(final Packet<?> packetIn)
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnect(Component message)
|
||||
{
|
||||
if (message.getContents() instanceof TranslatableContents text && (text.getKey().equals("multiplayer.disconnect.idling") || text.getKey().equals("multiplayer.disconnect.duplicate_login")))
|
||||
{
|
||||
((MinionFakePlayer) player).kill(message);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void teleport(double d, double e, double f, float g, float h, Set<RelativeMovement> set)
|
||||
{
|
||||
super.teleport(d, e, f, g, h, set);
|
||||
if (player.serverLevel().getPlayerByUUID(player.getUUID()) != null) {
|
||||
resetPosition();
|
||||
player.serverLevel().getChunkSource().move(player);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
|
||||
import io.github.skippyall.minions.fakeplayer.EntityPlayerActionPack;
|
||||
|
||||
public interface ServerPlayerInterface
|
||||
{
|
||||
EntityPlayerActionPack getActionPack();
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.level.ClipContext;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.phys.EntityHitResult;
|
||||
import net.minecraft.world.phys.HitResult;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class Tracer
|
||||
{
|
||||
public static HitResult rayTrace(Entity source, float partialTicks, double reach, boolean fluids)
|
||||
{
|
||||
BlockHitResult blockHit = rayTraceBlocks(source, partialTicks, reach, fluids);
|
||||
double maxSqDist = reach * reach;
|
||||
if (blockHit != null)
|
||||
{
|
||||
maxSqDist = blockHit.getLocation().distanceToSqr(source.getEyePosition(partialTicks));
|
||||
}
|
||||
EntityHitResult entityHit = rayTraceEntities(source, partialTicks, reach, maxSqDist);
|
||||
return entityHit == null ? blockHit : entityHit;
|
||||
}
|
||||
|
||||
public static BlockHitResult rayTraceBlocks(Entity source, float partialTicks, double reach, boolean fluids)
|
||||
{
|
||||
Vec3 pos = source.getEyePosition(partialTicks);
|
||||
Vec3 rotation = source.getViewVector(partialTicks);
|
||||
Vec3 reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach);
|
||||
return source.level().clip(new ClipContext(pos, reachEnd, ClipContext.Block.OUTLINE, fluids ?
|
||||
ClipContext.Fluid.ANY : ClipContext.Fluid.NONE, source));
|
||||
}
|
||||
|
||||
public static EntityHitResult rayTraceEntities(Entity source, float partialTicks, double reach, double maxSqDist)
|
||||
{
|
||||
Vec3 pos = source.getEyePosition(partialTicks);
|
||||
Vec3 reachVec = source.getViewVector(partialTicks).scale(reach);
|
||||
AABB box = source.getBoundingBox().expandTowards(reachVec).inflate(1);
|
||||
return rayTraceEntities(source, pos, pos.add(reachVec), box, e -> !e.isSpectator() && e.isPickable(), maxSqDist);
|
||||
}
|
||||
|
||||
public static EntityHitResult rayTraceEntities(Entity source, Vec3 start, Vec3 end, AABB box, Predicate<Entity> predicate, double maxSqDistance)
|
||||
{
|
||||
Level world = source.level();
|
||||
double targetDistance = maxSqDistance;
|
||||
Entity target = null;
|
||||
Vec3 targetHitPos = null;
|
||||
for (Entity current : world.getEntities(source, box, predicate))
|
||||
{
|
||||
AABB currentBox = current.getBoundingBox().inflate(current.getPickRadius());
|
||||
Optional<Vec3> currentHit = currentBox.clip(start, end);
|
||||
if (currentBox.contains(start))
|
||||
{
|
||||
if (targetDistance >= 0)
|
||||
{
|
||||
target = current;
|
||||
targetHitPos = currentHit.orElse(start);
|
||||
targetDistance = 0;
|
||||
}
|
||||
}
|
||||
else if (currentHit.isPresent())
|
||||
{
|
||||
Vec3 currentHitPos = currentHit.get();
|
||||
double currentDistance = start.distanceToSqr(currentHitPos);
|
||||
if (currentDistance < targetDistance || targetDistance == 0)
|
||||
{
|
||||
if (current.getRootVehicle() == source.getRootVehicle())
|
||||
{
|
||||
if (targetDistance == 0)
|
||||
{
|
||||
target = current;
|
||||
targetHitPos = currentHitPos;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
target = current;
|
||||
targetHitPos = currentHitPos;
|
||||
targetDistance = currentDistance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return target == null ? null : new EntityHitResult(target, targetHitPos);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package io.github.skippyall.minions.mixins;
|
||||
|
||||
import io.github.skippyall.minions.fakeplayer.ClientConnectionInterface;
|
||||
import io.netty.channel.Channel;
|
||||
import net.minecraft.network.Connection;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.gen.Accessor;
|
||||
|
||||
@Mixin(Connection.class)
|
||||
public abstract class ConnectionMixin implements ClientConnectionInterface {
|
||||
@Override
|
||||
@Accessor //Compat with adventure-platform-fabric
|
||||
public abstract void setChannel(Channel channel);
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package io.github.skippyall.minions.mixins;
|
||||
|
||||
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
|
||||
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import io.github.skippyall.minions.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.fakeplayer.NetHandlerPlayServerFake;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ClientInformation;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.network.CommonListenerCookie;
|
||||
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
||||
import net.minecraft.server.players.PlayerList;
|
||||
import org.spongepowered.asm.mixin.Final;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Shadow;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
@Mixin(PlayerList.class)
|
||||
public class PlayerListMixin {
|
||||
@Shadow
|
||||
@Final
|
||||
private MinecraftServer server;
|
||||
|
||||
@Inject(method = "load", at = @At(value = "RETURN", shift = At.Shift.BEFORE))
|
||||
private void fixStartingPos(ServerPlayer serverPlayerEntity_1, CallbackInfoReturnable<CompoundTag> cir)
|
||||
{
|
||||
if (serverPlayerEntity_1 instanceof MinionFakePlayer)
|
||||
{
|
||||
((MinionFakePlayer) serverPlayerEntity_1).fixStartingPosition.run();
|
||||
}
|
||||
}
|
||||
|
||||
@WrapOperation(method = "placeNewPlayer", at = @At(value = "NEW", target = "(Lnet/minecraft/server/MinecraftServer;Lnet/minecraft/network/Connection;Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/server/network/CommonListenerCookie;)Lnet/minecraft/server/network/ServerGamePacketListenerImpl;"))
|
||||
private ServerGamePacketListenerImpl replaceNetworkHandler(MinecraftServer minecraftServer, Connection connection, ServerPlayer serverPlayer, CommonListenerCookie commonListenerCookie, Operation<ServerGamePacketListenerImpl> original)
|
||||
{
|
||||
if (serverPlayer instanceof MinionFakePlayer fake) {
|
||||
return new NetHandlerPlayServerFake(this.server, connection, fake, commonListenerCookie);
|
||||
} else {
|
||||
return original.call(minecraftServer, connection, serverPlayer, commonListenerCookie);
|
||||
}
|
||||
}
|
||||
|
||||
@WrapOperation(method = "respawn", at = @At(value = "NEW", target = "(Lnet/minecraft/server/MinecraftServer;Lnet/minecraft/server/level/ServerLevel;Lcom/mojang/authlib/GameProfile;Lnet/minecraft/server/level/ClientInformation;)Lnet/minecraft/server/level/ServerPlayer;"))
|
||||
public ServerPlayer makePlayerForRespawn(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ClientInformation clientInformation, Operation<ServerPlayer> original, ServerPlayer serverPlayer, boolean bl) {
|
||||
if (serverPlayer instanceof MinionFakePlayer) {
|
||||
return MinionFakePlayer.respawnFake(minecraftServer, serverLevel, gameProfile, clientInformation);
|
||||
}
|
||||
return original.call(minecraftServer, serverLevel, gameProfile, clientInformation);
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package io.github.skippyall.minions.mixins;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import io.github.skippyall.minions.fakeplayer.EntityPlayerActionPack;
|
||||
import io.github.skippyall.minions.fakeplayer.ServerPlayerInterface;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ClientInformation;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Unique;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ServerPlayer.class)
|
||||
public abstract class ServerPlayerMixin implements ServerPlayerInterface {
|
||||
@Unique
|
||||
public EntityPlayerActionPack actionPack;
|
||||
@Override
|
||||
public EntityPlayerActionPack getActionPack()
|
||||
{
|
||||
return actionPack;
|
||||
}
|
||||
|
||||
@Inject(method = "<init>", at = @At(value = "RETURN"))
|
||||
private void onServerPlayerEntityContructor(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ClientInformation clientInformation, CallbackInfo ci)
|
||||
{
|
||||
this.actionPack = new EntityPlayerActionPack((ServerPlayer) (Object) this);
|
||||
}
|
||||
|
||||
@Inject(method = "tick", at = @At(value = "HEAD"))
|
||||
private void onTick(CallbackInfo ci)
|
||||
{
|
||||
actionPack.onUpdate();
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package io.github.skippyall.minions.networking;
|
||||
|
||||
import io.github.skippyall.minions.Minions;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import net.fabricmc.api.EnvType;
|
||||
import net.fabricmc.api.Environment;
|
||||
import net.fabricmc.fabric.api.client.networking.v1.ClientConfigurationNetworking;
|
||||
import net.fabricmc.fabric.api.networking.v1.PacketSender;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ClientConfigurationPacketListenerImpl;
|
||||
import net.minecraft.client.multiplayer.ClientHandshakePacketListenerImpl;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.network.ServerConfigurationPacketListenerImpl;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
|
||||
public class ClientToServerNetworking {
|
||||
public static final ResourceLocation RL = new ResourceLocation(Minions.MOD_ID, "network");
|
||||
@Environment(EnvType.CLIENT)
|
||||
public static void sendJoinPacket(Player player) {
|
||||
FriendlyByteBuf pbf = new FriendlyByteBuf(Unpooled.buffer());
|
||||
pbf.writeUtf("BN|Init|V0.1");
|
||||
ClientConfigurationNetworking.send(RL, pbf);
|
||||
}
|
||||
|
||||
@Environment(EnvType.CLIENT)
|
||||
public static void onConfigurationInit(ClientConfigurationPacketListenerImpl handler, Minecraft client) {
|
||||
sendJoinPacket(client.player);
|
||||
}
|
||||
|
||||
@Environment(EnvType.SERVER)
|
||||
public static void receive(MinecraftServer server, ServerConfigurationPacketListenerImpl handler, FriendlyByteBuf buf, PacketSender responseSender) {
|
||||
String message = buf.readUtf();
|
||||
if (!message.startsWith("BN|")) {
|
||||
Minions.LOGGER.debug("Message with wrong format: " + message);
|
||||
}
|
||||
String[] parts = message.split("|");
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package io.github.skippyall.minions.networking;
|
||||
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public class VersionChecker {
|
||||
protected static List<UUID> hasSupportedMod = new ArrayList<>();
|
||||
public static boolean supportVersion(String version) {
|
||||
return version.equals("v0.1");
|
||||
}
|
||||
|
||||
public static boolean useSupportedMod(Player p) {
|
||||
return hasSupportedMod.contains(p.getUUID());
|
||||
}
|
||||
|
||||
public static void resetPlayer(UUID uuid) {
|
||||
hasSupportedMod.remove(uuid);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package io.github.skippyall.minions.program.block;
|
||||
|
||||
import io.github.skippyall.minions.program.variables.Type;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public abstract class CodeBlock {
|
||||
public CodeBlock(String name, List<Type> arguments) {
|
||||
}
|
||||
|
||||
public abstract Object execute(Object... args);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package io.github.skippyall.minions.program.block;
|
||||
|
||||
public class CodeBlocks {
|
||||
public static final ForwardBlock FORWARD = new ForwardBlock();
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package io.github.skippyall.minions.program.block;
|
||||
|
||||
import io.github.skippyall.minions.program.variables.IntegerType;
|
||||
import io.github.skippyall.minions.program.variables.Type;
|
||||
import io.github.skippyall.minions.program.variables.Types;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class ForwardBlock extends CodeBlock{
|
||||
public ForwardBlock() {
|
||||
super("forward", Arrays.asList(Types.INTEGER));
|
||||
}
|
||||
|
||||
public Object execute(Object... args) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +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 java.util.List;
|
||||
|
||||
public abstract class Modul implements PolymerItem {
|
||||
private final String name;
|
||||
Modul(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public abstract List<CodeBlock> getCodeBlocks();
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package io.github.skippyall.minions.program.module;
|
||||
|
||||
public class Modules {
|
||||
MoveModul MOVE = new MoveModul();
|
||||
}
|
||||
@@ -1,30 +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 io.github.skippyall.minions.program.block.ForwardBlock;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class MoveModul extends Modul{
|
||||
MoveModul() {
|
||||
super("Movement");
|
||||
}
|
||||
|
||||
public List<CodeBlock> getCodeBlocks() {
|
||||
List<CodeBlock> codeBlocks = new ArrayList<>();
|
||||
codeBlocks.add(CodeBlocks.FORWARD);
|
||||
return codeBlocks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Item getPolymerItem(ItemStack itemStack, @Nullable ServerPlayer player) {
|
||||
return Items.PURPLE_GLAZED_TERRACOTTA;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package io.github.skippyall.minions.program.variables;
|
||||
|
||||
public class IntegerType extends Type{
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package io.github.skippyall.minions.program.variables;
|
||||
|
||||
public abstract class Type {
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package io.github.skippyall.minions.program.variables;
|
||||
|
||||
public class Types {
|
||||
public static final IntegerType INTEGER = new IntegerType();
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package io.github.skippyall.minions.server;
|
||||
|
||||
import io.github.skippyall.minions.networking.ClientToServerNetworking;
|
||||
import io.github.skippyall.minions.networking.VersionChecker;
|
||||
import net.fabricmc.api.DedicatedServerModInitializer;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerConfigurationConnectionEvents;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerConfigurationNetworking;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.network.ServerConfigurationPacketListenerImpl;
|
||||
|
||||
public class MinionsServer implements DedicatedServerModInitializer {
|
||||
@Override
|
||||
public void onInitializeServer() {
|
||||
ServerConfigurationNetworking.registerGlobalReceiver(ClientToServerNetworking.RL, ClientToServerNetworking::receive);
|
||||
ServerConfigurationConnectionEvents.CONFIGURE.register(new ServerConfigurationConnectionEvents.Configure() {
|
||||
@Override
|
||||
public void onSendConfiguration(ServerConfigurationPacketListenerImpl handler, MinecraftServer server) {
|
||||
VersionChecker.resetPlayer(handler.getOwner().getId());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package io.github.skippyall.minions.client;
|
||||
|
||||
import eu.pb4.polymer.networking.api.client.PolymerClientNetworking;
|
||||
import io.github.skippyall.minions.registration.MinionBlocks;
|
||||
import io.github.skippyall.minions.util.PolymerUtil;
|
||||
import net.fabricmc.api.ClientModInitializer;
|
||||
import net.fabricmc.fabric.api.client.rendering.v1.BlockRenderLayerMap;
|
||||
import net.minecraft.client.render.BlockRenderLayer;
|
||||
|
||||
public class MinionsClient implements ClientModInitializer {
|
||||
@Override
|
||||
public void onInitializeClient() {
|
||||
BlockRenderLayerMap.putBlock(MinionBlocks.MINION_TRIGGER_BLOCK, BlockRenderLayer.TRANSLUCENT);
|
||||
|
||||
PolymerClientNetworking.registerCommonHandler(PolymerUtil.VersionSyncPayload.class, (client, handler, payload) -> {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package io.github.skippyall.minions;
|
||||
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
|
||||
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class MinionMixinConfigPlugin implements IMixinConfigPlugin {
|
||||
@Override
|
||||
public void onLoad(String mixinPackage) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRefMapperConfig() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldApplyMixin(String targetClassName, String mixinClassName) {
|
||||
if(mixinClassName.startsWith("io.github.skippyall.mixins.compat.universal_graves.")) {
|
||||
return MinionsConfig.get().compat.enableGravesCompat && FabricLoader.getInstance().isModLoaded("universal-graves");
|
||||
}
|
||||
if(mixinClassName.startsWith("io.github.skippyall.mixins.antimobcap.")) {
|
||||
return MinionsConfig.get().minion.enableMobCapHacks;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) {}
|
||||
|
||||
@Override
|
||||
public List<String> getMixins() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {}
|
||||
|
||||
@Override
|
||||
public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {}
|
||||
}
|
||||
@@ -1,21 +1,46 @@
|
||||
package io.github.skippyall.minions;
|
||||
|
||||
import eu.pb4.polymer.core.api.entity.PolymerEntityUtils;
|
||||
import io.github.skippyall.minions.minion.MinionItem;
|
||||
import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils;
|
||||
import io.github.skippyall.minions.command.MinionsCommand;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import io.github.skippyall.minions.registration.MinionRegistration;
|
||||
import io.github.skippyall.minions.util.PolymerUtil;
|
||||
import net.fabricmc.api.ModInitializer;
|
||||
import net.minecraft.registry.Registries;
|
||||
import net.minecraft.registry.Registry;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Minions implements ModInitializer {
|
||||
public static final String MOD_ID = "minions";
|
||||
public static final MinionItem MINION_ITEM = Registry.register(Registries.ITEM, new Identifier(MOD_ID, "minion"), new MinionItem());
|
||||
|
||||
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
|
||||
|
||||
@Override
|
||||
public void onInitialize() {
|
||||
PolymerEntityUtils.registerType();
|
||||
MinionsConfig.get();
|
||||
|
||||
MinionRegistration.register();
|
||||
|
||||
PolymerUtil.register();
|
||||
|
||||
ServerLifecycleEvents.SERVER_STARTED.register(server -> {
|
||||
MinionPersistentState.get(server).getMinionData().forEach((uuid, data) -> {
|
||||
if(data.isSpawned()) {
|
||||
MinionFakePlayer.spawnMinion(data, server.getOverworld(), null, null, true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
CommandRegistrationCallback.EVENT.register(MinionsCommand::register);
|
||||
|
||||
/*ServerBlockEntityEvents.BLOCK_ENTITY_LOAD.register((blockEntity, world) -> {
|
||||
if(blockEntity instanceof MinionTriggerBlockEntity) {
|
||||
world.updateComparators(blockEntity.getPos(), MinionBlocks.MINION_TRIGGER_BLOCK);
|
||||
}
|
||||
});*/
|
||||
|
||||
PolymerResourcePackUtils.addModAssets(Minions.MOD_ID);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package io.github.skippyall.minions;
|
||||
|
||||
import com.electronwill.nightconfig.core.CommentedConfig;
|
||||
import com.electronwill.nightconfig.core.io.ParsingException;
|
||||
import com.electronwill.nightconfig.core.io.WritingException;
|
||||
import com.electronwill.nightconfig.core.io.WritingMode;
|
||||
import com.electronwill.nightconfig.core.serde.ObjectDeserializer;
|
||||
import com.electronwill.nightconfig.core.serde.ObjectSerializer;
|
||||
import com.electronwill.nightconfig.core.serde.SerdeException;
|
||||
import com.electronwill.nightconfig.core.serde.annotations.SerdeComment;
|
||||
import com.electronwill.nightconfig.core.serde.annotations.SerdeSkipDeserializingIf;
|
||||
import com.electronwill.nightconfig.toml.TomlFormat;
|
||||
import com.electronwill.nightconfig.toml.TomlParser;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static com.electronwill.nightconfig.core.serde.annotations.SerdeSkipDeserializingIf.SkipDeIf.IS_MISSING;
|
||||
|
||||
public class MinionsConfig {
|
||||
private static MinionsConfig INSTANCE;
|
||||
|
||||
@SerdeSkipDeserializingIf(IS_MISSING)
|
||||
public Minion minion = new Minion();
|
||||
|
||||
public static class Minion {
|
||||
@SerdeComment("The prefix for all minion names")
|
||||
@SerdeSkipDeserializingIf(IS_MISSING)
|
||||
public String minionPrefix = "+";
|
||||
|
||||
@SerdeComment("Makes minions not raise the mob cap if they can't spawn mobs.")
|
||||
@SerdeComment("Might cause incompatibilities.")
|
||||
@SerdeSkipDeserializingIf(IS_MISSING)
|
||||
public boolean enableMobCapHacks = true;
|
||||
}
|
||||
|
||||
@SerdeSkipDeserializingIf(IS_MISSING)
|
||||
public Compat compat = new Compat();
|
||||
|
||||
public static class Compat {
|
||||
@SerdeComment("Enables compat with Universal Graves, which allows everyone to pick up graves from minions")
|
||||
@SerdeSkipDeserializingIf(IS_MISSING)
|
||||
public boolean enableGravesCompat = true;
|
||||
}
|
||||
|
||||
private static Path getPath() {
|
||||
Path minionsDir = FabricLoader.getInstance().getConfigDir().resolve("minions");
|
||||
if(!Files.isDirectory(minionsDir)) {
|
||||
try {
|
||||
Files.createDirectory(minionsDir);
|
||||
} catch (IOException e) {
|
||||
Minions.LOGGER.error("Could not create config dir", e);
|
||||
}
|
||||
}
|
||||
return minionsDir.resolve(Minions.MOD_ID + ".toml");
|
||||
}
|
||||
|
||||
public static MinionsConfig get() {
|
||||
if(INSTANCE == null) {
|
||||
loadConfig();
|
||||
}
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public static void loadConfig() {
|
||||
try {
|
||||
CommentedConfig config = new TomlParser().parse(getPath(), (file, configFormat) -> {
|
||||
CommentedConfig defaultConfig = ObjectSerializer.standard().serializeFields(new MinionsConfig(), TomlFormat::newConfig);
|
||||
configFormat.createWriter().write(defaultConfig, file, WritingMode.REPLACE);
|
||||
return true;
|
||||
});
|
||||
|
||||
INSTANCE = ObjectDeserializer.standard().deserializeFields(config, MinionsConfig::new);
|
||||
} catch (SerdeException | ParsingException | WritingException e) {
|
||||
Minions.LOGGER.error("Error while reading config", e);
|
||||
INSTANCE = new MinionsConfig();
|
||||
}
|
||||
}
|
||||
|
||||
/*public static void saveConfig() {
|
||||
try {
|
||||
CommentedConfig config = ObjectSerializer.standard().serializeFields(INSTANCE, TomlFormat::newConfig);
|
||||
new TomlWriter().write(config, getPath(), WritingMode.REPLACE);
|
||||
} catch (SerdeException | ParsingException | WritingException e) {
|
||||
System.out.println("[minions] Error while writing config");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}*/
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
package io.github.skippyall.minions.block.miniontrigger;
|
||||
|
||||
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.registration.MinionBlocks;
|
||||
import io.github.skippyall.minions.Minions;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import io.github.skippyall.minions.clipboard.InstructionClipboard;
|
||||
import io.github.skippyall.minions.registration.MinionComponentTypes;
|
||||
import io.github.skippyall.minions.util.PolymerUtil;
|
||||
import net.minecraft.block.AbstractRedstoneGateBlock;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.block.BlockWithEntity;
|
||||
import net.minecraft.block.ShapeContext;
|
||||
import net.minecraft.block.SideShapeType;
|
||||
import net.minecraft.block.entity.BlockEntity;
|
||||
import net.minecraft.component.DataComponentTypes;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.server.network.ServerPlayNetworkHandler;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.sound.SoundCategory;
|
||||
import net.minecraft.sound.SoundEvents;
|
||||
import net.minecraft.state.StateManager;
|
||||
import net.minecraft.state.property.BooleanProperty;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.ActionResult;
|
||||
import net.minecraft.util.Hand;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.hit.BlockHitResult;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Direction;
|
||||
import net.minecraft.util.shape.VoxelShape;
|
||||
import net.minecraft.world.BlockView;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.WorldView;
|
||||
import net.minecraft.world.block.WireOrientation;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xyz.nucleoid.packettweaker.PacketContext;
|
||||
|
||||
public class MinionTriggerBlock extends BlockWithEntity implements PolymerBlock, PolymerKeepModel, PolymerClientDecoded, BlockWithElementHolder {
|
||||
public static final MapCodec<MinionTriggerBlock> CODEC = createCodec(MinionTriggerBlock::new);
|
||||
|
||||
public static final BooleanProperty POWERED = BooleanProperty.of("powered");
|
||||
public static final VoxelShape SHAPE = Block.createColumnShape(16.0, 0.0, 2.0);
|
||||
|
||||
public MinionTriggerBlock(Settings settings) {
|
||||
super(settings);
|
||||
setDefaultState(getDefaultState().with(POWERED, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected VoxelShape getOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) {
|
||||
return SHAPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean canPlaceAt(BlockState state, WorldView world, BlockPos pos) {
|
||||
BlockPos blockPos = pos.down();
|
||||
return this.canPlaceAbove(world, blockPos, world.getBlockState(blockPos));
|
||||
}
|
||||
|
||||
protected boolean canPlaceAbove(WorldView world, BlockPos pos, BlockState state) {
|
||||
return state.isSideSolid(world, pos, Direction.UP, SideShapeType.RIGID);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStateReplaced(BlockState state, ServerWorld world, BlockPos pos, boolean moved) {
|
||||
super.onStateReplaced(state, world, pos, moved);
|
||||
world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).ifPresent(MinionTriggerBlockEntity::removeListener);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {
|
||||
builder.add(POWERED);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ActionResult onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
|
||||
if(stack.get(MinionComponentTypes.REFERENCE) instanceof InstructionClipboard instruction) {
|
||||
world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).ifPresent(be -> {
|
||||
be.setInstruction(instruction.selectedMinion(), instruction.selectedInstruction());
|
||||
player.playSoundToPlayer(SoundEvents.BLOCK_NOTE_BLOCK_CHIME.value(), SoundCategory.BLOCKS, 1, 1);
|
||||
stack.decrement(1);
|
||||
});
|
||||
return ActionResult.SUCCESS;
|
||||
}
|
||||
|
||||
return super.onUseWithItem(stack, state, world, pos, player, hand, hit);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, BlockHitResult hit) {
|
||||
if(world.isClient()) {
|
||||
return ActionResult.CONSUME;
|
||||
}
|
||||
|
||||
world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).ifPresent(be -> {
|
||||
String name = MinionPersistentState.get(world.getServer()).getMinionData(be.getMinionUuid()).name();
|
||||
player.sendMessage(Text.translatable("minions.reference.instruction.tooltip", name, be.getInstructionName()), true);
|
||||
});
|
||||
return ActionResult.SUCCESS;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void neighborUpdate(BlockState state, World world, BlockPos pos, Block sourceBlock, @Nullable WireOrientation wireOrientation, boolean notify) {
|
||||
if(!canPlaceAt(state, world, pos)) {
|
||||
dropStacks(state, world, pos);
|
||||
world.removeBlock(pos, false);
|
||||
return;
|
||||
}
|
||||
|
||||
boolean newPower = world.isReceivingRedstonePower(pos);
|
||||
if(state.get(POWERED) != newPower) {
|
||||
world.setBlockState(pos, state.with(POWERED, newPower));
|
||||
world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).ifPresent(MinionTriggerBlockEntity::updatePower);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean hasComparatorOutput(BlockState state) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getComparatorOutput(BlockState state, World world, BlockPos pos) {
|
||||
return world.getBlockEntity(pos, MinionBlocks.MINION_TRIGGER_BE_TYPE).map(MinionTriggerBlockEntity::getComparatorOutput).orElse(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected MapCodec<? extends BlockWithEntity> getCodec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable BlockEntity createBlockEntity(BlockPos pos, BlockState state) {
|
||||
return new MinionTriggerBlockEntity(pos, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockState getPolymerBlockState(BlockState state, PacketContext context) {
|
||||
return PolymerUtil.isOnClient(context) ? state : net.minecraft.block.Blocks.COMPARATOR.getDefaultState().with(AbstractRedstoneGateBlock.POWERED, state.get(POWERED));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleMiningOnServer(ItemStack tool, BlockState state, BlockPos pos, ServerPlayerEntity player) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable ElementHolder createElementHolder(ServerWorld world, BlockPos pos, BlockState initialBlockState) {
|
||||
ElementHolder holder = new ElementHolder() {
|
||||
@Override
|
||||
public boolean startWatching(ServerPlayNetworkHandler player) {
|
||||
if(PolymerResourcePackUtils.hasMainPack(player)) {
|
||||
return super.startWatching(player);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
ItemStack stack = new ItemStack(Items.BARRIER);
|
||||
stack.set(DataComponentTypes.ITEM_MODEL, Identifier.of(Minions.MOD_ID, "minion_trigger_no_plate_" + (initialBlockState.get(MinionTriggerBlock.POWERED) ? "active" : "inactive")));
|
||||
|
||||
holder.addElement(new ItemDisplayElement(stack));
|
||||
return holder;
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package io.github.skippyall.minions.block.miniontrigger;
|
||||
|
||||
import io.github.skippyall.minions.listener.BlockEntityMinionListener;
|
||||
import io.github.skippyall.minions.registration.MinionBlocks;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.block.entity.BlockEntity;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
import net.minecraft.util.Uuids;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public class MinionTriggerBlockEntity extends BlockEntity {
|
||||
private UUID minionUuid;
|
||||
private String instructionName = "";
|
||||
|
||||
public MinionTriggerBlockEntity(BlockPos pos, BlockState state) {
|
||||
super(MinionBlocks.MINION_TRIGGER_BE_TYPE, pos, state);
|
||||
}
|
||||
|
||||
public void removeListener() {
|
||||
MinionTriggerMinionListener.removeListener(world, pos, minionUuid, instructionName);
|
||||
}
|
||||
|
||||
public void addListener() {
|
||||
MinionTriggerMinionListener.addListener(world, pos, minionUuid, instructionName);
|
||||
}
|
||||
|
||||
public void setInstruction(UUID minionUuid, String instructionName) {
|
||||
removeListener();
|
||||
this.minionUuid = minionUuid;
|
||||
this.instructionName = instructionName;
|
||||
addListener();
|
||||
markDirty();
|
||||
}
|
||||
|
||||
public void updatePower() {
|
||||
boolean powered = getCachedState().get(MinionTriggerBlock.POWERED);
|
||||
|
||||
MinionTriggerMinionListener listener = getListener();
|
||||
if(listener != null) {
|
||||
listener.incomingPowerCache = powered;
|
||||
}
|
||||
|
||||
getMinion().ifPresent(minion -> {
|
||||
getInstruction().ifPresent(instruction -> {
|
||||
if(powered) {
|
||||
instruction.run(minion.getInstructionManager());
|
||||
} else {
|
||||
instruction.stop(minion.getInstructionManager());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public int getComparatorOutput() {
|
||||
MinionTriggerMinionListener listener = getListener();
|
||||
if(listener != null && listener.runningCache) {
|
||||
return 15;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public Optional<MinionFakePlayer> getMinion() {
|
||||
if(minionUuid != null && world != null && world.getPlayerByUuid(minionUuid) instanceof MinionFakePlayer minion) {
|
||||
return Optional.of(minion);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public UUID getMinionUuid() {
|
||||
return minionUuid;
|
||||
}
|
||||
|
||||
public String getInstructionName() {
|
||||
return instructionName;
|
||||
}
|
||||
|
||||
public Optional<ConfiguredInstruction<MinionRuntime>> getInstruction(MinionFakePlayer minion) {
|
||||
return Optional.ofNullable(minion.getInstructionManager().getInstruction(instructionName));
|
||||
}
|
||||
|
||||
public Optional<ConfiguredInstruction<MinionRuntime>> getInstruction() {
|
||||
return getMinion().flatMap(this::getInstruction);
|
||||
}
|
||||
|
||||
public MinionTriggerMinionListener getListener() {
|
||||
return BlockEntityMinionListener.getListener(world, pos, minionUuid, MinionTriggerMinionListener.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void readData(ReadView view) {
|
||||
minionUuid = view.read("minionUuid", Uuids.CODEC).orElse(null);
|
||||
instructionName = view.getString("instructionName", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void writeData(WriteView view) {
|
||||
if(minionUuid != null) {
|
||||
view.put("minionUuid", Uuids.CODEC, minionUuid);
|
||||
}
|
||||
view.putString("instructionName", instructionName);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
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.block.Block;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.util.Identifier;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xyz.nucleoid.packettweaker.PacketContext;
|
||||
|
||||
public class MinionTriggerBlockItem extends PolymerBlockItem {
|
||||
public MinionTriggerBlockItem(Block block, Settings settings, Item polymerItem) {
|
||||
super(block, settings, polymerItem, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Identifier getPolymerItemModel(ItemStack stack, PacketContext context) {
|
||||
if(PolymerResourcePackUtils.hasMainPack(context)) {
|
||||
return super.getPolymerItemModel(stack, context);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package io.github.skippyall.minions.block.miniontrigger;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import io.github.skippyall.minions.Minions;
|
||||
import io.github.skippyall.minions.listener.BlockEntityMinionInstructionListener;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.registration.MinionBlocks;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstructionListener;
|
||||
import net.minecraft.registry.RegistryKey;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.Uuids;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public class MinionTriggerMinionListener extends BlockEntityMinionInstructionListener<MinionTriggerBlockEntity> {
|
||||
public static final Codec<MinionTriggerMinionListener> CODEC = RecordCodecBuilder.create(instance ->
|
||||
instance.group(
|
||||
World.CODEC.fieldOf("world").forGetter(listener -> listener.worldKey),
|
||||
BlockPos.CODEC.fieldOf("pos").forGetter(listener -> listener.pos),
|
||||
Uuids.CODEC.fieldOf("minionUuid").forGetter(listener -> listener.minionUuid),
|
||||
Codec.STRING.fieldOf("instructionName").forGetter(listener -> listener.instructionName)
|
||||
).apply(instance, MinionTriggerMinionListener::new));
|
||||
|
||||
String instructionName;
|
||||
final TriggerInstructionListener listener = new TriggerInstructionListener();
|
||||
|
||||
boolean runningCache;
|
||||
boolean incomingPowerCache;
|
||||
|
||||
private MinionTriggerMinionListener(RegistryKey<World> worldKey, BlockPos pos, UUID minionUuid, String instructionName) {
|
||||
super(worldKey, pos, minionUuid, MinionBlocks.MINION_TRIGGER_BE_TYPE);
|
||||
this.instructionName = Objects.requireNonNull(instructionName);
|
||||
}
|
||||
|
||||
public static void addListener(World world, BlockPos pos, UUID minion, String instructionName) {
|
||||
MinionTriggerMinionListener listener = new MinionTriggerMinionListener(world.getRegistryKey(), pos, minion, instructionName);
|
||||
listener.add(world.getServer());
|
||||
}
|
||||
|
||||
public static void removeListener(World world, BlockPos pos, UUID minion, String instructionName) {
|
||||
MinionTriggerMinionListener old = getListener(world, pos, minion, MinionTriggerMinionListener.class);
|
||||
if(old != null) {
|
||||
old.remove(world.getServer());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Map<String, ConfiguredInstructionListener> getInstructionListeners() {
|
||||
return Map.of(instructionName, listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMinionSpawn(MinionFakePlayer minion) {
|
||||
super.onMinionSpawn(minion);
|
||||
runningCache = minion.getInstructionManager().getInstruction(instructionName).isRunning();
|
||||
updateComparatorsIfLoaded(minion.getServer());
|
||||
|
||||
ConfiguredInstruction<MinionRuntime> instruction = minion.getInstructionManager().getInstruction(instructionName);
|
||||
if(instruction.isRunning() && !incomingPowerCache) {
|
||||
instruction.stop(minion.getInstructionManager());
|
||||
} else if (!instruction.isRunning() && incomingPowerCache) {
|
||||
instruction.run(minion.getInstructionManager());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMinionRemove(MinionFakePlayer minion) {
|
||||
super.onMinionRemove(minion);
|
||||
runningCache = false;
|
||||
updateComparatorsIfLoaded(minion.getServer());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInstructionRename(MinionFakePlayer minion, ConfiguredInstruction<?> instruction, String oldName, String newName) {
|
||||
super.onInstructionRename(minion, instruction, oldName, newName);
|
||||
if(instructionName.equals(oldName)) {
|
||||
instructionName = newName;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void add(MinecraftServer server) {
|
||||
super.add(server);
|
||||
runningCache = minion.getInstructionManager().getInstruction(instructionName).isRunning();
|
||||
updateComparatorsIfLoaded(server);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Identifier> getCodecId() {
|
||||
return Optional.of(Identifier.of(Minions.MOD_ID, "minion_trigger"));
|
||||
}
|
||||
|
||||
public void updateComparatorsIfLoaded(MinecraftServer server) {
|
||||
World world = server.getWorld(worldKey);
|
||||
if(world.isPosLoaded(pos)) {
|
||||
world.updateComparators(pos, MinionBlocks.MINION_TRIGGER_BLOCK);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isRunning() {
|
||||
return runningCache;
|
||||
}
|
||||
|
||||
public class TriggerInstructionListener implements ConfiguredInstructionListener {
|
||||
@Override
|
||||
public void onRun(ConfiguredInstruction<?> instruction) {
|
||||
runningCache = true;
|
||||
updateComparatorsIfLoaded(minion.getServer());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop(ConfiguredInstruction<?> instruction) {
|
||||
runningCache = false;
|
||||
updateComparatorsIfLoaded(minion.getServer());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package io.github.skippyall.minions.client;
|
||||
|
||||
import io.github.skippyall.minions.networking.ClientToServerNetworking;
|
||||
import net.fabricmc.api.ClientModInitializer;
|
||||
import net.fabricmc.fabric.api.client.networking.v1.ClientConfigurationConnectionEvents;
|
||||
import net.fabricmc.fabric.api.client.networking.v1.ClientLoginConnectionEvents;
|
||||
|
||||
public class MinionsClient implements ClientModInitializer {
|
||||
/**
|
||||
* Runs the mod initializer on the client environment.
|
||||
*/
|
||||
@Override
|
||||
public void onInitializeClient() {
|
||||
ClientConfigurationConnectionEvents.INIT.register(ClientToServerNetworking::onConfigurationInit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package io.github.skippyall.minions.clipboard;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import net.minecraft.item.tooltip.TooltipAppender;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public interface Clipboard extends TooltipAppender {
|
||||
Codec<Clipboard> CODEC = MinionRegistries.CLIPBOARD_TYPES.getCodec().dispatch(Clipboard::getCodec, Function.identity());
|
||||
|
||||
MapCodec<? extends Clipboard> getCodec();
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package io.github.skippyall.minions.clipboard;
|
||||
|
||||
import eu.pb4.polymer.core.api.item.PolymerItem;
|
||||
import io.github.skippyall.minions.registration.MinionComponentTypes;
|
||||
import io.github.skippyall.minions.registration.MinionItems;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import net.minecraft.component.DataComponentTypes;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.item.tooltip.TooltipType;
|
||||
import net.minecraft.util.Identifier;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xyz.nucleoid.packettweaker.PacketContext;
|
||||
|
||||
public class ClipboardItem extends Item implements PolymerItem {
|
||||
public ClipboardItem(Settings settings) {
|
||||
super(settings);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Item getPolymerItem(ItemStack itemStack, PacketContext context) {
|
||||
return Items.PAPER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Identifier getPolymerItemModel(ItemStack stack, PacketContext context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getPolymerItemStack(ItemStack itemStack, TooltipType tooltipType, PacketContext context) {
|
||||
ItemStack stack = PolymerItem.super.getPolymerItemStack(itemStack, tooltipType, context);
|
||||
stack.set(DataComponentTypes.ENCHANTMENT_GLINT_OVERRIDE, true);
|
||||
return stack;
|
||||
}
|
||||
|
||||
public static ItemStack createInstructionReference(MinionFakePlayer minion, String instructionName) {
|
||||
ItemStack stack = new ItemStack(MinionItems.REFERENCE_ITEM);
|
||||
stack.set(MinionComponentTypes.REFERENCE, new InstructionClipboard(minion.getUuid(), instructionName, minion.getGameProfile().getName()));
|
||||
return stack;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package io.github.skippyall.minions.clipboard;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import net.minecraft.component.ComponentsAccess;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.tooltip.TooltipType;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Uuids;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public record InstructionClipboard(UUID selectedMinion, String selectedInstruction, String visualMinionName) implements Clipboard {
|
||||
public static final MapCodec<InstructionClipboard> CODEC = RecordCodecBuilder.mapCodec(instance ->
|
||||
instance.group(
|
||||
Uuids.CODEC.fieldOf("selectedMinion").forGetter(InstructionClipboard::selectedMinion),
|
||||
Codec.STRING.fieldOf("selectedInstruction").forGetter(InstructionClipboard::selectedInstruction),
|
||||
Codec.STRING.fieldOf("visualMinionName").forGetter(InstructionClipboard::visualMinionName)
|
||||
).apply(instance, InstructionClipboard::new));
|
||||
|
||||
@Override
|
||||
public MapCodec<? extends Clipboard> getCodec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void appendTooltip(Item.TooltipContext context, Consumer<Text> textConsumer, TooltipType type, ComponentsAccess components) {
|
||||
textConsumer.accept(Text.translatable("minions.reference.instruction.tooltip", selectedInstruction, visualMinionName));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package io.github.skippyall.minions.command;
|
||||
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import io.github.skippyall.minions.minion.MinionData;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import static net.minecraft.server.command.CommandManager.literal;
|
||||
|
||||
public class ListSubcommand {
|
||||
public static final LiteralArgumentBuilder<ServerCommandSource> LIST = literal("list")
|
||||
.executes(ListSubcommand::list);
|
||||
|
||||
public static int list(CommandContext<ServerCommandSource> context) {
|
||||
Collection<MinionData> minions = MinionPersistentState.get(context.getSource().getServer()).getMinionData().values();
|
||||
for (MinionData minion : minions) {
|
||||
context.getSource().sendFeedback(() -> Text.literal(minion.name() + "(" + minion.uuid() + "):" + minion.isSpawned()), false);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package io.github.skippyall.minions.command;
|
||||
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
||||
import com.mojang.brigadier.suggestion.SuggestionProvider;
|
||||
import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import io.github.skippyall.minions.minion.MinionData;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import io.github.skippyall.minions.minion.MinionProfileUtils;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class MinionArgument {
|
||||
public static final SimpleCommandExceptionType MINION_NOT_PRESENT = new SimpleCommandExceptionType(Text.translatable("minions.command.minion.not_present"));
|
||||
|
||||
public static final MinionSuggestionProvider SUGGESTION_PROVIDER = new MinionSuggestionProvider();
|
||||
|
||||
public static MinionData parse(MinecraftServer server, String argument) throws CommandSyntaxException {
|
||||
Optional<MinionData> data = Optional.empty();
|
||||
if(argument.startsWith(MinionProfileUtils.getPrefix())) {
|
||||
data = MinionPersistentState.get(server).getMinionWithName(argument);
|
||||
} else {
|
||||
try {
|
||||
data = Optional.ofNullable(MinionPersistentState.get(server).getMinionData(UUID.fromString(argument)));
|
||||
} catch (IllegalArgumentException ignored) {}
|
||||
}
|
||||
|
||||
if(data.isEmpty()) {
|
||||
throw MINION_NOT_PRESENT.create();
|
||||
}
|
||||
return data.get();
|
||||
}
|
||||
|
||||
public static class MinionSuggestionProvider implements SuggestionProvider<ServerCommandSource> {
|
||||
@Override
|
||||
public CompletableFuture<Suggestions> getSuggestions(CommandContext<ServerCommandSource> context, SuggestionsBuilder builder) throws CommandSyntaxException {
|
||||
for (MinionData data : MinionPersistentState.get(context.getSource().getServer()).getMinionDataList()) {
|
||||
builder.suggest(data.name());
|
||||
}
|
||||
|
||||
return builder.buildFuture();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package io.github.skippyall.minions.command;
|
||||
|
||||
import com.mojang.brigadier.CommandDispatcher;
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import io.github.skippyall.minions.MinionsConfig;
|
||||
import net.minecraft.command.CommandRegistryAccess;
|
||||
import net.minecraft.server.command.CommandManager;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
|
||||
import static net.minecraft.server.command.CommandManager.literal;
|
||||
|
||||
public class MinionsCommand {
|
||||
public static void register(CommandDispatcher<ServerCommandSource> dispatcher, CommandRegistryAccess access, CommandManager.RegistrationEnvironment environment) {
|
||||
LiteralArgumentBuilder<ServerCommandSource> builder = literal("minions")
|
||||
.then(SpawnSubcommand.SPAWN)
|
||||
.then(ListSubcommand.LIST);
|
||||
|
||||
if(MinionsConfig.get().minion.enableMobCapHacks) {
|
||||
builder.then(MobCapDebugSubcommand.MOB_CAP_DEBUG);
|
||||
}
|
||||
|
||||
dispatcher.register(
|
||||
builder
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package io.github.skippyall.minions.command;
|
||||
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import io.github.skippyall.minions.mixinhelper.antimobcap.ChunkLevelManager$DistanceFromNearestPlayerTrackerAccessor;
|
||||
import io.github.skippyall.minions.mixinhelper.antimobcap.ChunkLevelManagerAccessor;
|
||||
import io.github.skippyall.minions.mixins.antimobcap.ServerChunkManagerAccessor;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.server.world.ChunkLevelManager;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import static net.minecraft.server.command.CommandManager.literal;
|
||||
|
||||
public class MobCapDebugSubcommand {
|
||||
public static final LiteralArgumentBuilder<ServerCommandSource> MOB_CAP_DEBUG = literal("mobcapdebug")
|
||||
.executes(MobCapDebugSubcommand::mobcapdebugCommand);
|
||||
|
||||
public static int mobcapdebugCommand(CommandContext<ServerCommandSource> context) {
|
||||
ChunkLevelManager levelManager = ((ServerChunkManagerAccessor)context.getSource().getWorld().getChunkManager()).getLevelManager();
|
||||
int tickedChunkCount = ((ChunkLevelManager$DistanceFromNearestPlayerTrackerAccessor)((ChunkLevelManagerAccessor)levelManager).minions$getMinionless()).minions$getTickedChunkCount();
|
||||
context.getSource().sendFeedback(() -> Text.of(String.valueOf(tickedChunkCount)), false);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package io.github.skippyall.minions.command;
|
||||
|
||||
import com.mojang.brigadier.arguments.BoolArgumentType;
|
||||
import com.mojang.brigadier.arguments.StringArgumentType;
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import io.github.skippyall.minions.minion.MinionData;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import net.minecraft.command.argument.PosArgument;
|
||||
import net.minecraft.command.argument.Vec3ArgumentType;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
|
||||
import static net.minecraft.server.command.CommandManager.argument;
|
||||
import static net.minecraft.server.command.CommandManager.literal;
|
||||
|
||||
public class SpawnSubcommand {
|
||||
public static final LiteralArgumentBuilder<ServerCommandSource> SPAWN = literal("spawn")
|
||||
.requires(source -> source.hasPermissionLevel(2))
|
||||
.then(argument("minion", StringArgumentType.word())
|
||||
.suggests(MinionArgument.SUGGESTION_PROVIDER)
|
||||
.then(argument("pos", Vec3ArgumentType.vec3())
|
||||
.executes(context ->
|
||||
spawnCommand(
|
||||
context.getSource(),
|
||||
StringArgumentType.getString(context, "minion"),
|
||||
Vec3ArgumentType.getPosArgument(context, "pos"),
|
||||
false
|
||||
)
|
||||
)
|
||||
.then(argument("force", BoolArgumentType.bool())
|
||||
.executes(context ->
|
||||
spawnCommand(
|
||||
context.getSource(),
|
||||
StringArgumentType.getString(context, "minion"),
|
||||
Vec3ArgumentType.getPosArgument(context, "pos"),
|
||||
BoolArgumentType.getBool(context, "force")
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
.executes(context ->
|
||||
spawnCommand(
|
||||
context.getSource(),
|
||||
StringArgumentType.getString(context, "minion"),
|
||||
null,
|
||||
false
|
||||
))
|
||||
);
|
||||
|
||||
public static int spawnCommand(ServerCommandSource source, String minion, PosArgument pos, boolean force) throws CommandSyntaxException {
|
||||
MinionData data = MinionArgument.parse(source.getServer(), minion);
|
||||
MinionFakePlayer.spawnMinion(data, source.getWorld(), pos != null ? pos.getPos(source) : null, pos != null ? pos.getRotation(source) : null, force);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package io.github.skippyall.minions.docs;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.text.TextCodecs;
|
||||
|
||||
public record ReferenceEntry(Text shortDescription, Text longDescription) {
|
||||
public static final Codec<ReferenceEntry> CODEC = RecordCodecBuilder.create(instance ->
|
||||
instance.group(
|
||||
TextCodecs.CODEC.fieldOf("shortDescription").forGetter(ReferenceEntry::shortDescription),
|
||||
TextCodecs.CODEC.fieldOf("longDescription").forGetter(ReferenceEntry::longDescription)
|
||||
).apply(instance, ReferenceEntry::new));
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
|
||||
public interface ClientConnectionInterface {
|
||||
void setChannel(Channel channel);
|
||||
}
|
||||
@@ -1,277 +0,0 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.authlib.yggdrasil.ProfileResult;
|
||||
import io.github.skippyall.minions.minion.MinionInventory;
|
||||
import io.github.skippyall.minions.minion.ModuleInventory;
|
||||
import net.fabricmc.fabric.api.entity.FakePlayer;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EquipmentSlot;
|
||||
import net.minecraft.entity.MovementType;
|
||||
import net.minecraft.entity.damage.DamageSource;
|
||||
import net.minecraft.entity.player.HungerManager;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.network.NetworkSide;
|
||||
import net.minecraft.network.packet.c2s.common.SyncedClientOptions;
|
||||
import net.minecraft.network.packet.c2s.play.ClientStatusC2SPacket;
|
||||
import net.minecraft.network.packet.s2c.play.EntityPositionS2CPacket;
|
||||
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.ServerTask;
|
||||
import net.minecraft.server.network.ConnectedClientData;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.text.TranslatableTextContent;
|
||||
import net.minecraft.util.ActionResult;
|
||||
import net.minecraft.util.Hand;
|
||||
import net.minecraft.util.Uuids;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.world.GameMode;
|
||||
import java.util.UUID;
|
||||
|
||||
public class MinionFakePlayer extends ServerPlayerEntity {
|
||||
public Runnable fixStartingPosition = () -> {};
|
||||
public boolean isAShadow;
|
||||
|
||||
private float moveForward;
|
||||
private float moveSideways;
|
||||
|
||||
private boolean programmable;
|
||||
private ModuleInventory moduleInventory = new ModuleInventory();
|
||||
|
||||
public static void createMinion(String username, ServerWorld level, ServerPlayerEntity owner, boolean canProgram, Vec3d pos, double yaw, double pitch) {
|
||||
MinecraftServer server = level.getServer();
|
||||
server.getUserCache().findByNameAsync(username).thenAcceptAsync((optional) -> {
|
||||
GameProfile profile = null;
|
||||
if(optional.isPresent()){
|
||||
UUID uuid = optional.get().getId();
|
||||
ProfileResult result = server.getSessionService().fetchProfile(uuid, true);
|
||||
if(result != null) {
|
||||
profile = result.profile();
|
||||
}
|
||||
}
|
||||
if(profile == null) {
|
||||
profile = new GameProfile(Uuids.getOfflinePlayerUuid(username), username);
|
||||
}
|
||||
MinionFakePlayer instance = new MinionFakePlayer(server, level, profile, SyncedClientOptions.createDefault(), false, canProgram);
|
||||
instance.fixStartingPosition = () -> instance.refreshPositionAndAngles(pos.x, pos.y, pos.z, (float) yaw, (float) pitch);
|
||||
server.getPlayerManager().onPlayerConnect(new FakeClientConnection(NetworkSide.SERVERBOUND), instance, new ConnectedClientData(profile, 0, instance.getClientOptions()));
|
||||
instance.teleport(level, pos.x, pos.y, pos.z, (float) yaw, (float) pitch);
|
||||
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;
|
||||
instance.setStepHeight(0.6F);
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused") //Don't know if I'll need this
|
||||
public static MinionFakePlayer createShadow(MinecraftServer server, ServerPlayerEntity player)
|
||||
{
|
||||
player.getServer().getPlayerManager().remove(player);
|
||||
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()));
|
||||
|
||||
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)
|
||||
{
|
||||
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);
|
||||
isAShadow = shadow;
|
||||
|
||||
}
|
||||
|
||||
public boolean isProgrammable() {
|
||||
return programmable;
|
||||
}
|
||||
|
||||
public ModuleInventory getModuleInventory() {
|
||||
return moduleInventory;
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack getActionPack() {
|
||||
return ((ServerPlayerInterface)this).getActionPack();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActionResult interact(PlayerEntity player, Hand hand) {
|
||||
if(player instanceof ServerPlayerEntity spe) {
|
||||
MinionInventory.openInventory(spe, this);
|
||||
}
|
||||
return ActionResult.CONSUME;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActionResult interactAt(PlayerEntity player, Vec3d hitPos, Hand hand) {
|
||||
return interact(player, hand);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEquipStack(final EquipmentSlot slot, final ItemStack previous, final ItemStack stack)
|
||||
{
|
||||
if (!isUsingItem()) super.onEquipStack(slot, previous, stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void kill()
|
||||
{
|
||||
kill(Text.literal("Killed"));
|
||||
}
|
||||
|
||||
public void kill(Text reason)
|
||||
{
|
||||
shakeOff();
|
||||
|
||||
if (reason.getContent() instanceof TranslatableTextContent text && text.getKey().equals("multiplayer.disconnect.duplicate_login")) {
|
||||
this.networkHandler.onDisconnected(reason);
|
||||
} else {
|
||||
this.server.send(new ServerTask(this.server.getTicks(), () -> {
|
||||
this.networkHandler.onDisconnected(reason);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick()
|
||||
{
|
||||
if (this.getServer().getTicks() % 10 == 0)
|
||||
{
|
||||
this.networkHandler.syncWithPlayerPosition();
|
||||
this.getServerWorld().getChunkManager().updatePosition(this);
|
||||
}
|
||||
try
|
||||
{
|
||||
super.tick();
|
||||
this.playerTick();
|
||||
}
|
||||
catch (NullPointerException ignored)
|
||||
{
|
||||
// happens with that paper port thingy - not sure what that would fix, but hey
|
||||
// the game not gonna crash violently.
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void shakeOff()
|
||||
{
|
||||
if (getVehicle() instanceof PlayerEntity) stopRiding();
|
||||
for (Entity passenger : getPassengersDeep())
|
||||
{
|
||||
if (passenger instanceof PlayerEntity) passenger.stopRiding();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeath(DamageSource cause)
|
||||
{
|
||||
shakeOff();
|
||||
super.onDeath(cause);
|
||||
setHealth(20);
|
||||
this.hungerManager = new HungerManager();
|
||||
kill(this.getDamageTracker().getDeathMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIp()
|
||||
{
|
||||
return "127.0.0.1";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean allowsServerListing() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void fall(double y, boolean onGround, BlockState state, BlockPos pos) {
|
||||
handleFall(0.0, y, 0.0, onGround);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Entity moveToWorld(ServerWorld serverLevel)
|
||||
{
|
||||
super.moveToWorld(serverLevel);
|
||||
if (notInAnyWorld) {
|
||||
ClientStatusC2SPacket p = new ClientStatusC2SPacket(ClientStatusC2SPacket.Mode.PERFORM_RESPAWN);
|
||||
networkHandler.onClientStatus(p);
|
||||
}
|
||||
|
||||
// If above branch was taken, *this* has been removed and replaced, the new instance has been set
|
||||
// on 'our' connection (which is now theirs, but we still have a ref).
|
||||
if (networkHandler.player.isInTeleportationState()) {
|
||||
networkHandler.player.onTeleportationDone();
|
||||
}
|
||||
return networkHandler.player;
|
||||
}
|
||||
|
||||
public void moveForward(float forward) {
|
||||
this.moveForward += forward;
|
||||
EntityPlayerActionPack actionPack = getActionPack();
|
||||
if (moveForward != 0) {
|
||||
actionPack.setForward(moveForward > 0 ? 1 : -1);
|
||||
}
|
||||
}
|
||||
|
||||
public void moveSideways(float sideways) {
|
||||
this.moveSideways += sideways;
|
||||
EntityPlayerActionPack actionPack = getActionPack();
|
||||
if (moveSideways != 0) {
|
||||
actionPack.setStrafing(moveSideways > 0 ? 1 : -1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void move(MovementType movementType, Vec3d movement) {
|
||||
float newForward = (float) (moveForward - movement.z);
|
||||
float newSideways = (float) (moveSideways - movement.x);
|
||||
Vec3d newMovement = movement;
|
||||
if ((newForward < 0 && moveForward >= 0) || (newForward > 0 && moveForward <= 0)) {
|
||||
newMovement = new Vec3d(newMovement.x, newMovement.y, moveForward);
|
||||
moveForward = 0;
|
||||
getActionPack().setForward(0);
|
||||
}else {
|
||||
moveForward = newForward;
|
||||
}
|
||||
if ((newSideways < 0 && moveSideways >= 0) || (newSideways > 0 && moveSideways <= 0)) {
|
||||
newMovement = new Vec3d(newMovement.x, newMovement.y, moveSideways);
|
||||
moveSideways = 0;
|
||||
getActionPack().setStrafing(0);
|
||||
}else {
|
||||
moveSideways = newSideways;
|
||||
}
|
||||
super.move(movementType, newMovement);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
|
||||
import io.github.skippyall.minions.fakeplayer.EntityPlayerActionPack;
|
||||
|
||||
public interface ServerPlayerInterface
|
||||
{
|
||||
EntityPlayerActionPack getActionPack();
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import eu.pb4.sgui.api.elements.GuiElementBuilder;
|
||||
import io.github.skippyall.minions.gui.input.ChoiceInput;
|
||||
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 io.github.skippyall.minions.clipboard.ClipboardItem;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.sound.SoundCategory;
|
||||
import net.minecraft.sound.SoundEvents;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
public class ConfigureInstructionGui extends InstructionBoundSimpleGui {
|
||||
private String name;
|
||||
|
||||
private ConfigureInstructionGui(ScreenHandlerType<?> type, ServerPlayerEntity player, MinionFakePlayer minion, ConfiguredInstruction<MinionRuntime> configuredInstruction, String name) {
|
||||
super(type, player, minion, configuredInstruction);
|
||||
this.name = name;
|
||||
init();
|
||||
}
|
||||
|
||||
public static void configureInstructionMenu(String name, ConfiguredInstruction<MinionRuntime> instruction, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
if(!InstructionGui.checkInstructionExists(name, instruction, minion, player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ConfigureInstructionGui gui = new ConfigureInstructionGui(ScreenHandlerType.GENERIC_9X3, player, minion, instruction, name);
|
||||
|
||||
gui.open();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
setTitle(Text.literal(name));
|
||||
|
||||
setSlot(7, new GuiElementBuilder(Items.ANVIL)
|
||||
.setName(Text.translatable("minions.gui.instruction.configure.rename"))
|
||||
.setCallback(() -> InstructionGui.inputInstructionName(minion, player, name).thenAccept(newName -> {
|
||||
minion.getInstructionManager().setInstructionName(name, newName);
|
||||
configureInstructionMenu(newName, instruction, minion, player);
|
||||
}))
|
||||
);
|
||||
|
||||
setSlot(8, new GuiElementBuilder(Items.LAVA_BUCKET)
|
||||
.setName(Text.translatable("minions.gui.instruction.configure.delete"))
|
||||
.setCallback(() -> ChoiceInput.confirm(player, Text.translatable("minions.gui.instruction.configure.delete.confirm", name))
|
||||
.thenAccept(v -> {
|
||||
minion.getInstructionManager().removeInstruction(name);
|
||||
InstructionGui.instructionList(minion, player);
|
||||
}))
|
||||
);
|
||||
|
||||
updateSuppliers();
|
||||
|
||||
setSlot(13, InstructionGui.createInstructionElement(instruction.getInstruction(), player.getRegistryManager()));
|
||||
|
||||
setSlot(25, new GuiElementBuilder(Items.FEATHER)
|
||||
.setName(Text.translatable("minions.gui.instruction.configure.copy"))
|
||||
.addLoreLine(Text.translatable("minions.gui.instruction.configure.copy.description"))
|
||||
.setCallback(() -> {
|
||||
player.getInventory().offer(ClipboardItem.createInstructionReference(minion, name), true);
|
||||
player.playSoundToPlayer(SoundEvents.BLOCK_NOTE_BLOCK_CHIME.value(), SoundCategory.BLOCKS, 1, 1);
|
||||
})
|
||||
);
|
||||
|
||||
updateRunSlot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInstructionRename(MinionFakePlayer minion, ConfiguredInstruction<?> instruction, String oldName, String newName) {
|
||||
this.setTitle(Text.literal(newName));
|
||||
name = newName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRun(ConfiguredInstruction<?> instruction) {
|
||||
updateRunSlot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop(ConfiguredInstruction<?> instruction) {
|
||||
updateRunSlot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSupplierChange(ConfiguredInstruction<?> instruction, Parameter<?> parameter) {
|
||||
updateSuppliers();
|
||||
}
|
||||
|
||||
private void updateRunSlot() {
|
||||
if(!instruction.isRunning()) {
|
||||
setSlot(26, new GuiElementBuilder(Items.ARROW)
|
||||
.setName(Text.translatable("minions.gui.instruction.run"))
|
||||
.setCallback(() -> instruction.run(minion.getInstructionManager()))
|
||||
);
|
||||
} else {
|
||||
setSlot(26, new GuiElementBuilder(Items.BARRIER)
|
||||
.setName(Text.translatable("minions.gui.instruction.stop"))
|
||||
.setCallback(() -> instruction.stop(minion.getInstructionManager()))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateSuppliers() {
|
||||
int slot = 12;
|
||||
for(Parameter<?> parameter : instruction.getInstruction().getParameters().reversed()) {
|
||||
setSlot(slot, InstructionGui.createParameterElement(parameter, instruction.getArguments().getArgument(parameter), player.getRegistryManager())
|
||||
.setCallback(() -> InstructionGui.configureArgumentMenu(name, instruction, parameter, minion, player))
|
||||
);
|
||||
slot--;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
public interface Displayable {
|
||||
GuiDisplay getDisplay();
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import com.mojang.authlib.properties.PropertyMap;
|
||||
import com.mojang.serialization.Codec;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import io.github.skippyall.minions.util.TranslationUtil;
|
||||
import it.unimi.dsi.fastutil.objects.ReferenceSortedSets;
|
||||
import net.minecraft.component.DataComponentTypes;
|
||||
import net.minecraft.component.type.ProfileComponent;
|
||||
import net.minecraft.component.type.TooltipDisplayComponent;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.registry.DynamicRegistryManager;
|
||||
import net.minecraft.registry.Registries;
|
||||
import net.minecraft.registry.Registry;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.Rarity;
|
||||
import net.minecraft.util.Uuids;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface GuiDisplay {
|
||||
Codec<GuiDisplay> CODEC = MinionRegistries.GUI_DISPLAY_TYPE.getCodec().dispatch(GuiDisplay::getCodec, codec -> codec.fieldOf("data"));
|
||||
GuiDisplay DEFAULT_DISPLAY = new ItemBased(Items.BARRIER);
|
||||
|
||||
static GuiDisplay getGuiDisplay(Identifier id, DynamicRegistryManager manager) {
|
||||
return manager.getOptional(MinionRegistries.GUI_DISPLAY).map(registry -> registry.get(id)).orElse(DEFAULT_DISPLAY);
|
||||
}
|
||||
|
||||
static <T> GuiDisplay getGuiDisplayFor(Registry<T> registry, T element, DynamicRegistryManager manager) {
|
||||
Identifier elementId = registry.getId(element);
|
||||
if(elementId == null) {
|
||||
return DEFAULT_DISPLAY;
|
||||
}
|
||||
Identifier displayId = elementId.withPrefixedPath(registry.getKey().getValue().getPath() + "/");
|
||||
|
||||
return getGuiDisplay(displayId, manager);
|
||||
}
|
||||
|
||||
static <T> ItemStack getDisplayStack(Registry<T> registry, T element, DynamicRegistryManager manager) {
|
||||
return getGuiDisplayFor(registry, element, manager).createItemStack();
|
||||
}
|
||||
|
||||
static <T> ItemStack getDisplayStackWithName(Registry<T> registry, T element, DynamicRegistryManager manager) {
|
||||
ItemStack stack = getDisplayStack(registry, element, manager);
|
||||
stack.set(DataComponentTypes.ITEM_NAME, Text.translatable(TranslationUtil.getTranslationKey(element, registry)));
|
||||
return stack;
|
||||
}
|
||||
|
||||
ItemStack createItemStack();
|
||||
|
||||
Codec<? extends GuiDisplay> getCodec();
|
||||
|
||||
class ModelBased implements GuiDisplay {
|
||||
public static final Codec<ModelBased> CODEC = Identifier.CODEC.xmap(ModelBased::new, display -> display.model);
|
||||
|
||||
private final Identifier model;
|
||||
|
||||
public ModelBased(Identifier model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack createItemStack() {
|
||||
ItemStack stack = new ItemStack(Items.BARRIER);
|
||||
stack.set(DataComponentTypes.ITEM_MODEL, model);
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends GuiDisplay> getCodec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
|
||||
class ItemBased implements GuiDisplay {
|
||||
public static final Codec<ItemBased> CODEC = Registries.ITEM.getCodec().xmap(ItemBased::new, display -> display.item);
|
||||
|
||||
private final Item item;
|
||||
|
||||
public ItemBased(Item item) {
|
||||
this.item = item;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack createItemStack() {
|
||||
ItemStack stack = new ItemStack(item);
|
||||
stack.set(DataComponentTypes.TOOLTIP_DISPLAY, new TooltipDisplayComponent(true, ReferenceSortedSets.emptySet()));
|
||||
stack.set(DataComponentTypes.RARITY, Rarity.COMMON);
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends GuiDisplay> getCodec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
|
||||
class HeadBased implements GuiDisplay {
|
||||
public static final Codec<HeadBased> CODEC = Uuids.CODEC.xmap(HeadBased::new, display -> display.uuid);
|
||||
|
||||
private final UUID uuid;
|
||||
|
||||
public HeadBased(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack createItemStack() {
|
||||
ItemStack stack = new ItemStack(Items.PLAYER_HEAD);
|
||||
stack.set(DataComponentTypes.PROFILE, new ProfileComponent(Optional.empty(), Optional.of(uuid), new PropertyMap()));
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends GuiDisplay> getCodec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
|
||||
class StackBased implements GuiDisplay {
|
||||
public static final Codec<StackBased> CODEC = ItemStack.CODEC.xmap(StackBased::new, StackBased::createItemStack);
|
||||
|
||||
private final ItemStack stack;
|
||||
|
||||
public StackBased(ItemStack stack) {
|
||||
this.stack = stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack createItemStack() {
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends GuiDisplay> getCodec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
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.ConfiguredInstructionListener;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
|
||||
public class InstructionBoundSimpleGui extends MinionBoundSimpleGui implements ConfiguredInstructionListener {
|
||||
protected final ConfiguredInstruction<MinionRuntime> instruction;
|
||||
|
||||
public InstructionBoundSimpleGui(ScreenHandlerType<?> type, ServerPlayerEntity player, MinionFakePlayer minion, ConfiguredInstruction<MinionRuntime> instruction) {
|
||||
super(type, player, minion);
|
||||
this.instruction = instruction;
|
||||
instruction.addListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInstructionRemove(ConfiguredInstruction<?> instruction) {
|
||||
close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose() {
|
||||
super.onClose();
|
||||
instruction.removeListener(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
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.program.value.ValueType;
|
||||
import io.github.skippyall.minions.registration.MinionComponentTypes;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import io.github.skippyall.minions.gui.input.Result;
|
||||
import io.github.skippyall.minions.gui.input.TextInput;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.module.MinionModule;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplier;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierType;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionType;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.util.TranslationUtil;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.registry.DynamicRegistryManager;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class InstructionGui {
|
||||
public static void openInstructionMainMenu(MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
SimpleGui gui = new MinionBoundSimpleGui(ScreenHandlerType.GENERIC_3X3, player, minion);
|
||||
gui.setTitle(Text.translatable("minions.gui.instruction.title"));
|
||||
|
||||
gui.setSlot(3, new GuiElementBuilder()
|
||||
.setItem(Items.BOOK)
|
||||
.setName(Text.translatable("minions.gui.instruction.list"))
|
||||
.setCallback(() -> instructionList(minion, player))
|
||||
);
|
||||
gui.setSlot(5, new GuiElementBuilder()
|
||||
.setItem(Items.WRITABLE_BOOK)
|
||||
.setName(Text.translatable("minions.gui.instruction.create"))
|
||||
.setCallback(() -> createNewInstruction(minion, player))
|
||||
);
|
||||
|
||||
gui.open();
|
||||
}
|
||||
|
||||
public static void instructionList(MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
SimpleGui gui = new MinionBoundSimpleGui(ScreenHandlerType.GENERIC_9X3, player, minion) {
|
||||
@Override
|
||||
public void onInstructionsUpdate(MinionFakePlayer minion) {
|
||||
resetInstructionList(this, minion, player);
|
||||
}
|
||||
};
|
||||
gui.setTitle(Text.translatable("minions.gui.instruction.title"));
|
||||
resetInstructionList(gui, minion, player);
|
||||
|
||||
gui.open();
|
||||
}
|
||||
|
||||
private static void resetInstructionList(SimpleGui gui, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
int i = 0;
|
||||
for (String instructionName : minion.getInstructionManager().getInstructionNames()) {
|
||||
ConfiguredInstruction<MinionRuntime> instruction = minion.getInstructionManager().getInstruction(instructionName);
|
||||
gui.setSlot(i, new GuiElementBuilder(GuiDisplay.getGuiDisplayFor(MinionRegistries.INSTRUCTION_TYPES, instruction.getInstruction(), player.getRegistryManager()).createItemStack())
|
||||
.setName(Text.literal(instructionName))
|
||||
.setCallback(() -> ConfigureInstructionGui.configureInstructionMenu(instructionName, instruction, minion, player))
|
||||
);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
public static void createNewInstruction(MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
selectInstructionModuleMenu(minion, player).thenAccept(instructionType ->
|
||||
inputInstructionName(minion, player, "Instruction").thenAccept(name -> {
|
||||
if (!minion.isRemoved() && !minion.isDisconnected()) {
|
||||
ConfiguredInstruction<MinionRuntime> configuredInstruction = minion.getInstructionManager().createInstruction(name, instructionType);
|
||||
ConfigureInstructionGui.configureInstructionMenu(name, configuredInstruction, minion, player);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public static CompletableFuture<String> inputInstructionName(MinionFakePlayer minion, ServerPlayerEntity player, String defaultValue) {
|
||||
return TextInput.inputSync(player, Text.translatable("minions.gui.instruction.enter_name"), defaultValue, name -> {
|
||||
if (minion.getInstructionManager().hasInstruction(name)) {
|
||||
return new Result.Error<>(Text.translatable("minions.gui.instruction.name_already_used"));
|
||||
}
|
||||
return new Result.Success<>(name);
|
||||
});
|
||||
}
|
||||
|
||||
public static boolean checkInstructionExists(String name, ConfiguredInstruction<?> instruction, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
boolean stillExists = !minion.isRemoved() && !minion.isDisconnected() && minion.getInstructionManager().getInstruction(name) == instruction;
|
||||
if (!stillExists) {
|
||||
player.closeHandledScreen();
|
||||
player.sendMessage(Text.translatable("minions.gui.instruction.removed"));
|
||||
}
|
||||
return stillExists;
|
||||
}
|
||||
|
||||
|
||||
public static <T, A extends ValueSupplier<T, MinionRuntime>> void configureArgumentMenu(String instructionName, ConfiguredInstruction<MinionRuntime> instruction, Parameter<T> parameter, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
if (!checkInstructionExists(instructionName, instruction, minion, player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@Nullable A argument = instruction.getArguments().getArgument(parameter);
|
||||
|
||||
if(argument == null) {
|
||||
configureTypeAndValue(instructionName, instruction, parameter, minion, player);
|
||||
return;
|
||||
}
|
||||
|
||||
SimpleGui gui = new InstructionBoundSimpleGui(ScreenHandlerType.GENERIC_3X3, player, minion, instruction);
|
||||
|
||||
ItemStack displayStack = GuiDisplay.getDisplayStack(MinionRegistries.VALUE_SUPPLIER_TYPES, argument.getType(), player.getRegistryManager());
|
||||
|
||||
gui.setSlot(3, new GuiElementBuilder(displayStack)
|
||||
.setName(Text.translatable("minions.gui.instruction.argument.configure.type", Text.translatable(TranslationUtil.getTranslationKey(argument.getType(), MinionRegistries.VALUE_SUPPLIER_TYPES, "minions.gui.instruction.argument.configure.type.unset"))))
|
||||
.setCallback(() -> configureTypeAndValue(instructionName, instruction, parameter, minion, player))
|
||||
);
|
||||
gui.setSlot(5, new GuiElementBuilder(Items.STRUCTURE_VOID)
|
||||
.setName(Text.literal("Configure"))
|
||||
.setCallback(() -> argument.getType().openConfiguration(player, argument.getValueType(), argument)
|
||||
.thenAccept(newArgument -> instruction.getArguments().setArgument(parameter, newArgument))
|
||||
)
|
||||
);
|
||||
gui.open();
|
||||
}
|
||||
|
||||
public static CompletableFuture<ValueSupplierType<MinionRuntime>> selectArgumentType(ServerPlayerEntity player, MinionFakePlayer minion, ValueType<?> valueType, ConfiguredInstruction<MinionRuntime> instruction) {
|
||||
CompletableFuture<ValueSupplierType<MinionRuntime>> future = new CompletableFuture<>();
|
||||
SimpleGui gui = new InstructionBoundSimpleGui(ScreenHandlerType.GENERIC_9X3, player, minion, instruction);
|
||||
for (ValueSupplierType<MinionRuntime> type : MinionRegistries.VALUE_SUPPLIER_TYPES) {
|
||||
if(type.isConfigurable(player, valueType, minion)) {
|
||||
gui.addSlot(new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.VALUE_SUPPLIER_TYPES, type, player.getRegistryManager()))
|
||||
.setCallback(() -> future.complete(type))
|
||||
);
|
||||
}
|
||||
}
|
||||
gui.open();
|
||||
return future;
|
||||
}
|
||||
|
||||
public static <T> void configureTypeAndValue(String name, ConfiguredInstruction<MinionRuntime> instruction, Parameter<T> parameter, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
selectArgumentType(player, minion, parameter.type(), instruction)
|
||||
.thenApply(type -> type.openConfiguration(player, parameter.type(), null)
|
||||
.thenAccept(newArgument -> {
|
||||
instruction.getArguments().setArgument(parameter, newArgument);
|
||||
configureArgumentMenu(name, instruction, parameter, minion, player);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public static CompletableFuture<InstructionType<MinionRuntime>> selectInstructionModuleMenu(MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
if (minion.getModuleInventory().getModules().isEmpty()) {
|
||||
player.sendMessage(Text.translatable("minions.gui.instruction.no_modules"));
|
||||
return CompletableFuture.failedFuture(new NoSuchElementException("No modules"));
|
||||
}
|
||||
|
||||
CompletableFuture<InstructionType<MinionRuntime>> future = new CompletableFuture<>();
|
||||
|
||||
SimpleGui gui = new MinionBoundSimpleGui(ScreenHandlerType.GENERIC_9X3, player, minion) {
|
||||
@Override
|
||||
public void onClose() {
|
||||
if (!future.isDone()) {
|
||||
future.cancel(false);
|
||||
}
|
||||
super.onClose();
|
||||
}
|
||||
};
|
||||
gui.setTitle(Text.translatable("minions.gui.instruction.select_instruction"));
|
||||
|
||||
for (int i = 0; i < minion.getModuleInventory().size(); i++) {
|
||||
ItemStack moduleItem = minion.getModuleInventory().getStack(i);
|
||||
MinionModule module = moduleItem.get(MinionComponentTypes.MODULE);
|
||||
if (module != null && !module.instructions().isEmpty()) {
|
||||
gui.addSlot(new GuiElementBuilder(moduleItem)
|
||||
.setCallback(() -> selectInstructionMenu(module, minion, player)
|
||||
.thenApply(future::complete)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
gui.open();
|
||||
return future;
|
||||
}
|
||||
|
||||
public static CompletableFuture<InstructionType<MinionRuntime>> selectInstructionMenu(MinionModule module, MinionFakePlayer minion, ServerPlayerEntity player) {
|
||||
CompletableFuture<InstructionType<MinionRuntime>> future = new CompletableFuture<>();
|
||||
|
||||
SimpleGui gui = new MinionBoundSimpleGui(ScreenHandlerType.GENERIC_9X3, player, minion) {
|
||||
@Override
|
||||
public void onClose() {
|
||||
if (!future.isDone()) {
|
||||
future.cancel(false);
|
||||
}
|
||||
super.onClose();
|
||||
}
|
||||
};
|
||||
gui.setTitle(Text.translatable("minions.gui.instruction.select_instruction"));
|
||||
|
||||
for (InstructionType<MinionRuntime> instructionType : module.instructions()) {
|
||||
gui.addSlot(createInstructionElement(instructionType, player.getRegistryManager())
|
||||
.setCallback(() -> future.complete(instructionType))
|
||||
);
|
||||
}
|
||||
|
||||
gui.open();
|
||||
return future;
|
||||
}
|
||||
|
||||
public static GuiElementBuilder createInstructionElement(InstructionType<MinionRuntime> instructionType, DynamicRegistryManager manager) {
|
||||
GuiElementBuilder instructionBuilder;
|
||||
if (instructionType != null) {
|
||||
instructionBuilder = new GuiElementBuilder(GuiDisplay.getDisplayStackWithName(MinionRegistries.INSTRUCTION_TYPES, instructionType, manager));
|
||||
} else {
|
||||
instructionBuilder = new GuiElementBuilder(Items.RED_WOOL)
|
||||
.setName(Text.translatable("minions.gui.instruction.no_instruction_set"));
|
||||
}
|
||||
return instructionBuilder;
|
||||
}
|
||||
|
||||
public static GuiElementBuilder createParameterElement(Parameter<?> parameter, @Nullable ValueSupplier<?,?> valueSupplier, DynamicRegistryManager manager) {
|
||||
GuiElementBuilder builder = new GuiElementBuilder(GuiDisplay.getDisplayStack(MinionRegistries.VALUE_TYPES, parameter.type(), manager))
|
||||
.setName(Text.translatable("minions.gui.instruction.parameter", parameter.name(), Text.translatable(TranslationUtil.getTranslationKey(parameter.type(), MinionRegistries.VALUE_TYPES))));
|
||||
if(valueSupplier != null) {
|
||||
builder.addLoreLine(Text.translatable("minions.gui.instruction.argument", valueSupplier.getDisplayText()));
|
||||
}
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package io.github.skippyall.minions.gui;
|
||||
|
||||
import eu.pb4.sgui.api.gui.SimpleGui;
|
||||
import io.github.skippyall.minions.minion.MinionListener;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
|
||||
public class MinionBoundSimpleGui extends SimpleGui implements MinionListener {
|
||||
protected final MinionFakePlayer minion;
|
||||
|
||||
public MinionBoundSimpleGui(ScreenHandlerType<?> type, ServerPlayerEntity player, MinionFakePlayer minion) {
|
||||
super(type, player, false);
|
||||
this.minion = minion;
|
||||
minion.addMinionListener(this);
|
||||
}
|
||||
|
||||
public MinionFakePlayer getMinion() {
|
||||
return minion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMinionRemove(MinionFakePlayer minion) {
|
||||
close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose() {
|
||||
minion.removeMinionListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof MinionBoundSimpleGui that)) return false;
|
||||
return minion == that.minion && player == that.player;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
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.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.module.ModuleInventory;
|
||||
import net.minecraft.entity.EquipmentSlot;
|
||||
import net.minecraft.entity.player.PlayerInventory;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.screen.slot.ArmorSlot;
|
||||
import net.minecraft.screen.slot.Slot;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
public class MinionGui {
|
||||
public static void openInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
|
||||
openServerSideInventory(player, minion);
|
||||
}
|
||||
|
||||
public static void openServerSideInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
|
||||
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_3X3, player, false);
|
||||
gui.setTitle(minion.getName());
|
||||
|
||||
gui.setSlot(1, new GuiElementBuilder()
|
||||
.setItem(Items.COMMAND_BLOCK)
|
||||
.setName(Text.translatable("minions.gui.main.instructions"))
|
||||
.setCallback((i, clickType, slotActionType) -> {
|
||||
InstructionGui.openInstructionMainMenu(minion, player);
|
||||
})
|
||||
);
|
||||
gui.setSlot(3, new GuiElementBuilder()
|
||||
.setItem(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE)
|
||||
.setName(Text.translatable("minions.gui.main.modules"))
|
||||
.setCallback(() -> {
|
||||
ModuleInventory.openModuleInventory(player, minion);
|
||||
})
|
||||
);
|
||||
gui.setSlot(5, new GuiElementBuilder()
|
||||
.setItem(Items.CHEST)
|
||||
.setName(Text.translatable("minions.gui.main.inventory"))
|
||||
.setCallback(() -> {
|
||||
openMinionInventory(player, minion);
|
||||
})
|
||||
);
|
||||
gui.setSlot(7, new GuiElementBuilder()
|
||||
.setItem(Items.BARRIER)
|
||||
.setName(Text.translatable("minions.gui.main.pickup"))
|
||||
.setCallback(() -> {
|
||||
minion.kill(minion.getWorld());
|
||||
})
|
||||
);
|
||||
gui.open();
|
||||
}
|
||||
|
||||
public static void openMinionInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
|
||||
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_9X6, player, false);
|
||||
gui.setTitle(Text.translatable("minions.gui.inventory.title"));
|
||||
|
||||
for(int i = 0; i < 18; i++) {
|
||||
gui.setSlot(i, new ItemStack(Items.BARRIER));
|
||||
}
|
||||
|
||||
gui.setSlot(2, new ItemStack(Items.LEATHER_HELMET));
|
||||
gui.setSlot(3, new ItemStack(Items.LEATHER_CHESTPLATE));
|
||||
gui.setSlot(4, new ItemStack(Items.LEATHER_LEGGINGS));
|
||||
gui.setSlot(5, new ItemStack(Items.LEATHER_BOOTS));
|
||||
gui.setSlot(6, new ItemStack(Items.SHIELD));
|
||||
|
||||
gui.setSlotRedirect(2 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.HEAD, EquipmentSlot.HEAD.getOffsetEntitySlotId(PlayerInventory.MAIN_SIZE), 0, 0, null));
|
||||
gui.setSlotRedirect(3 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.CHEST, EquipmentSlot.CHEST.getOffsetEntitySlotId(PlayerInventory.MAIN_SIZE), 0, 0, null));
|
||||
gui.setSlotRedirect(4 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.LEGS, EquipmentSlot.LEGS.getOffsetEntitySlotId(PlayerInventory.MAIN_SIZE), 0, 0, null));
|
||||
gui.setSlotRedirect(5 + 9, new ArmorSlot(minion.getInventory(), minion, EquipmentSlot.FEET, EquipmentSlot.FEET.getOffsetEntitySlotId(PlayerInventory.MAIN_SIZE), 0, 0, null));
|
||||
gui.setSlotRedirect(6 + 9, new Slot(minion.getInventory(), PlayerInventory.OFF_HAND_SLOT, 0, 0));
|
||||
|
||||
for (int i = PlayerInventory.HOTBAR_SIZE; i < PlayerInventory.MAIN_SIZE; i++) {
|
||||
gui.setSlotRedirect(i + 9, new Slot(minion.getInventory(), i, 0, 0));
|
||||
}
|
||||
|
||||
for (int i = 0; i < PlayerInventory.HOTBAR_SIZE; i++) {
|
||||
gui.setSlotRedirect(i + 45, new Slot(minion.getInventory(), i, 0, 0));
|
||||
}
|
||||
gui.open();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
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.registration.MinionRegistries;
|
||||
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.SkinProviders;
|
||||
import net.minecraft.component.DataComponentTypes;
|
||||
import net.minecraft.component.type.ProfileComponent;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class MinionLookGui extends SimpleGui {
|
||||
private ItemStack minionItem;
|
||||
private SkinProvider currentSkinProvider;
|
||||
|
||||
public MinionLookGui(ServerPlayerEntity player, ItemStack minionItem) {
|
||||
super(ScreenHandlerType.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(Text.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(DataComponentTypes.PROFILE, new ProfileComponent(Optional.empty(), Optional.empty(), getData().skin().get()));
|
||||
}
|
||||
setSlot(16, builder);
|
||||
}
|
||||
|
||||
private void cycleSkinProvider() {
|
||||
int currentId = MinionRegistries.SKIN_PROVIDERS.getRawId(currentSkinProvider);
|
||||
currentId++;
|
||||
if(MinionRegistries.SKIN_PROVIDERS.size() == currentId) {
|
||||
currentId = 0;
|
||||
}
|
||||
|
||||
currentSkinProvider = MinionRegistries.SKIN_PROVIDERS.get(currentId);
|
||||
updateSkinProvider();
|
||||
}
|
||||
|
||||
private void updateSkinProvider() {
|
||||
setSlot(25, new GuiElementBuilder()
|
||||
.setItem(Items.GREEN_STAINED_GLASS_PANE)
|
||||
.setComponent(DataComponentTypes.CUSTOM_NAME, currentSkinProvider.getDisplayName())
|
||||
.setCallback(this::cycleSkinProvider)
|
||||
);
|
||||
}
|
||||
|
||||
private MinionData getData() {
|
||||
return MinionItem.getDataOrDefault(player.getServer(), minionItem);
|
||||
}
|
||||
|
||||
public static void open(ServerPlayerEntity player, ItemStack minionItem) {
|
||||
MinionLookGui gui = new MinionLookGui(player, minionItem);
|
||||
gui.update();
|
||||
gui.open();
|
||||
}
|
||||
|
||||
public void openRenameGui(ServerPlayerEntity player, ItemStack minionItem) {
|
||||
TextInput.inputSync(player, Text.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,84 @@
|
||||
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 net.minecraft.item.Items;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ChoiceInput {
|
||||
public static <T> BiFunction<ServerPlayerEntity, T, CompletableFuture<T>> createDialogOpener(ScreenHandlerType<?> screen, Text 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<ServerPlayerEntity, T, CompletableFuture<T>> createDialogOpener(T[] values) {
|
||||
return createDialogOpener(ScreenHandlerType.GENERIC_9X3, Text.empty(), t -> t != null ? t.getDisplay() : null, values, null);
|
||||
}
|
||||
|
||||
public static CompletableFuture<Void> confirm(ServerPlayerEntity player, Text title) {
|
||||
CompletableFuture<Void> future = new CompletableFuture<>();
|
||||
|
||||
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_3X3, player, false) {
|
||||
@Override
|
||||
public void onClose() {
|
||||
future.cancel(false);
|
||||
}
|
||||
};
|
||||
|
||||
gui.setTitle(title);
|
||||
|
||||
gui.setSlot(3, new GuiElementBuilder(Items.REDSTONE_BLOCK)
|
||||
.setName(Text.translatable("minions.gui.abort"))
|
||||
.setCallback(() -> future.cancel(false))
|
||||
);
|
||||
|
||||
gui.setSlot(5, new GuiElementBuilder(Items.EMERALD_BLOCK)
|
||||
.setName(Text.translatable("minions.gui.confirm"))
|
||||
.setCallback(() -> future.complete(null))
|
||||
);
|
||||
|
||||
gui.open();
|
||||
return future;
|
||||
}
|
||||
|
||||
public static BiFunction<ServerPlayerEntity, Boolean, CompletableFuture<Boolean>> inputBoolean(Text title) {
|
||||
return createDialogOpener(ScreenHandlerType.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package io.github.skippyall.minions.gui.input;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public interface Result<T, E> {
|
||||
static <T> Result<T, String> wrap(UnsafeOperation<T> toWrap) {
|
||||
return wrapCustomError(toWrap, Exception::getMessage);
|
||||
}
|
||||
|
||||
static <T, E> Result<T, E> wrapCustomError(UnsafeOperation<T> toWrap, E error) {
|
||||
return wrapCustomError(toWrap, e -> error);
|
||||
}
|
||||
|
||||
static <T, E> Result<T, E> wrapCustomError(UnsafeOperation<T> toWrap, Function<Exception, E> errorTransformer) {
|
||||
try {
|
||||
return new Result.Success<>(toWrap.run());
|
||||
} catch (Exception e) {
|
||||
return new Result.Error<>(errorTransformer.apply(e));
|
||||
}
|
||||
}
|
||||
|
||||
boolean isSuccess();
|
||||
|
||||
@NotNull T getOrDefault(@NotNull T defaultValue);
|
||||
|
||||
@NotNull T getOrThrow();
|
||||
|
||||
@NotNull E getErrorOrThrow();
|
||||
|
||||
@NotNull Optional<T> getOptional();
|
||||
|
||||
void ifSuccess(@NotNull Consumer<T> handler);
|
||||
|
||||
void ifError(@NotNull Consumer<Error<T, E>> handler);
|
||||
|
||||
record Success<T, E>(@NotNull T result) implements Result<T, E> {
|
||||
@Override
|
||||
public boolean isSuccess() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull T getOrDefault(@NotNull T defaultValue) {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull T getOrThrow() {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull E getErrorOrThrow() {
|
||||
throw new RuntimeException("Result was not an Error");
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Optional<T> getOptional() {
|
||||
return Optional.of(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ifSuccess(@NotNull Consumer<T> handler) {
|
||||
handler.accept(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ifError(@NotNull Consumer<Error<T, E>> handler) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
record Error<T, E>(@NotNull E message) implements Result<T, E> {
|
||||
@Override
|
||||
public boolean isSuccess() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull T getOrDefault(@NotNull T defaultValue) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull T getOrThrow() {
|
||||
throw new RuntimeException("Result was an error: " + message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull E getErrorOrThrow() {
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Optional<T> getOptional() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ifSuccess(@NotNull Consumer<T> handler) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ifError(@NotNull Consumer<Error<T, E>> handler) {
|
||||
handler.accept(this);
|
||||
}
|
||||
}
|
||||
|
||||
interface UnsafeOperation<T> {
|
||||
T run() throws Exception;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package io.github.skippyall.minions.gui.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;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class TextInput<T> extends AnvilInputGui {
|
||||
private final GuiElementBuilder valid = new GuiElementBuilder()
|
||||
.setItem(Items.EMERALD_BLOCK)
|
||||
.setName(Text.literal("OK"))
|
||||
.setCallback(this::onConfirm);
|
||||
|
||||
private final GuiElementBuilder invalid = new GuiElementBuilder()
|
||||
.setItem(Items.REDSTONE_BLOCK);
|
||||
private final Function<String, CompletableFuture<Result<T, Text>>> parser;
|
||||
private final CompletableFuture<T> future;
|
||||
private Result<T, Text> result;
|
||||
private boolean isConfirm;
|
||||
|
||||
public TextInput(ServerPlayerEntity player, Text title, String defaultValue, Function<String, CompletableFuture<Result<T, Text>>> 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(ServerPlayerEntity player, Text title, String defaultValue, Function<String, Result<T, Text>> parser) {
|
||||
return input(player, title, defaultValue, (String string) -> CompletableFuture.completedFuture(parser.apply(string)));
|
||||
}
|
||||
|
||||
public static <T> CompletableFuture<T> input(ServerPlayerEntity player, Text title, String defaultValue, Function<String, CompletableFuture<Result<T, Text>>> parser) {
|
||||
CompletableFuture<T> future = new CompletableFuture<>();
|
||||
new TextInput<>(player, title, defaultValue, parser, future).open();
|
||||
return future;
|
||||
}
|
||||
|
||||
public static CompletableFuture<String> inputString(ServerPlayerEntity player, Text title, String defaultValue) {
|
||||
return inputSync(player, title, defaultValue, Result.Success::new);
|
||||
}
|
||||
|
||||
public static CompletableFuture<Long> inputLong(ServerPlayerEntity player, Text title, String defaultValue) {
|
||||
return inputSync(player, title, defaultValue, string -> Result.wrapCustomError(() -> Long.valueOf(string), Text.translatable("minions.command.input.int.fail")));
|
||||
}
|
||||
|
||||
public static CompletableFuture<Double> inputDouble(ServerPlayerEntity player, Text title, String defaultValue) {
|
||||
return inputSync(player, title, defaultValue, string -> Result.wrapCustomError(() -> Double.valueOf(string), Text.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(AnvilScreenHandler.OUTPUT_ID, valid);
|
||||
} else {
|
||||
Text text = result.getErrorOrThrow();
|
||||
setSlot(AnvilScreenHandler.OUTPUT_ID, 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,51 @@
|
||||
package io.github.skippyall.minions.instruction;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.EntityPlayerActionPack;
|
||||
import io.github.skippyall.minions.program.consumer.ValueConsumerList;
|
||||
import io.github.skippyall.minions.program.instruction.execution.ContinuousInstructionExecution;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
|
||||
public class ActionExecution implements ContinuousInstructionExecution<MinionRuntime> {
|
||||
private final EntityPlayerActionPack.ActionType action;
|
||||
|
||||
public ActionExecution(EntityPlayerActionPack.ActionType action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(MinionRuntime minion) {
|
||||
EntityPlayerActionPack ap = minion.getMinion().getMinionActionPack();
|
||||
if(!ap.hasAction(action)) {
|
||||
minion.getMinion().getMinionActionPack().start(action, EntityPlayerActionPack.Action.startContinuous());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop(MinionRuntime minion, ValueConsumerList<MinionRuntime> valueConsumers) {
|
||||
minion.getMinion().getMinionActionPack().stop(action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pause(MinionRuntime runtime) {
|
||||
runtime.getMinion().getMinionActionPack().stop(action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resume(MinionRuntime runtime) {
|
||||
runtime.getMinion().getMinionActionPack().start(action, EntityPlayerActionPack.Action.continuous());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> parameters, MinionRuntime minion) {}
|
||||
|
||||
@Override
|
||||
public void save(WriteView view, MinionRuntime minion) {}
|
||||
|
||||
@Override
|
||||
public void load(ReadView view, MinionRuntime runtime) {
|
||||
runtime.getMinion().getMinionActionPack().start(action, EntityPlayerActionPack.Action.continuous());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//partially code from https://github.com/gnembon/fabric-carpet (EntityPlayerActionPack)
|
||||
package io.github.skippyall.minions.instruction;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.EntityPlayerActionPack;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.consumer.ValueConsumerList;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionExecution;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
import net.minecraft.util.Hand;
|
||||
import net.minecraft.util.hit.BlockHitResult;
|
||||
import net.minecraft.util.hit.HitResult;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Direction;
|
||||
|
||||
public class MineBlockExecution implements InstructionExecution<MinionRuntime> {
|
||||
private BlockPos currentBlock;
|
||||
private float currentBlockDamage = 0;
|
||||
private boolean first = true;
|
||||
private boolean done = false;
|
||||
private boolean success = false;
|
||||
|
||||
@Override
|
||||
public void start(MinionRuntime runtime) {
|
||||
MinionFakePlayer player = runtime.getMinion();
|
||||
if(EntityPlayerActionPack.getTarget(player) instanceof BlockHitResult hit) {
|
||||
this.currentBlock = hit.getBlockPos();
|
||||
|
||||
EntityPlayerActionPack ap = player.getMinionActionPack();
|
||||
if (ap.blockHitDelay > 0) {
|
||||
ap.blockHitDelay--;
|
||||
done = true;
|
||||
return;
|
||||
}
|
||||
if (player.isBlockBreakingRestricted(player.getWorld(), hit.getBlockPos(), player.interactionManager.getGameMode())) {
|
||||
done = true;
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
done = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick(MinionRuntime runtime) {
|
||||
if(done) {
|
||||
return;
|
||||
}
|
||||
|
||||
MinionFakePlayer player = runtime.getMinion();
|
||||
EntityPlayerActionPack ap = player.getMinionActionPack();
|
||||
|
||||
HitResult newHit = EntityPlayerActionPack.getTarget(player);
|
||||
if(!(newHit instanceof BlockHitResult newBlockHit)) {
|
||||
done = true;
|
||||
return;
|
||||
}
|
||||
|
||||
BlockPos newPos = newBlockHit.getBlockPos();
|
||||
if(!newPos.equals(currentBlock)) {
|
||||
done = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (player.getWorld().getBlockState(currentBlock).isAir()) {
|
||||
done = true;
|
||||
return;
|
||||
}
|
||||
BlockState state = player.getWorld().getBlockState(currentBlock);
|
||||
boolean blockBroken = false;
|
||||
if (first) {
|
||||
first = false;
|
||||
player.interactionManager.processBlockBreakingAction(currentBlock, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, newBlockHit.getSide(), player.getWorld().getTopYInclusive(), -1);
|
||||
boolean notAir = !state.isAir();
|
||||
if (notAir)
|
||||
{
|
||||
state.onBlockBreakStart(player.getWorld(), currentBlock, player);
|
||||
}
|
||||
if (notAir && state.calcBlockBreakingDelta(player, player.getWorld(), currentBlock) >= 1)
|
||||
{
|
||||
//instamine??
|
||||
blockBroken = true;
|
||||
}
|
||||
} else {
|
||||
currentBlockDamage += state.calcBlockBreakingDelta(player, player.getWorld(), currentBlock);
|
||||
if (currentBlockDamage >= 1) {
|
||||
player.interactionManager.processBlockBreakingAction(currentBlock, PlayerActionC2SPacket.Action.STOP_DESTROY_BLOCK, newBlockHit.getSide(), player.getWorld().getTopYInclusive(), -1);
|
||||
ap.blockHitDelay = 5;
|
||||
blockBroken = true;
|
||||
}
|
||||
player.getWorld().setBlockBreakingInfo(-1, currentBlock, (int) (currentBlockDamage * 10));
|
||||
|
||||
}
|
||||
player.updateLastActionTime();
|
||||
player.swingHand(Hand.MAIN_HAND);
|
||||
|
||||
if(blockBroken) {
|
||||
done = true;
|
||||
success = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDone(MinionRuntime runtime) {
|
||||
return done;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop(MinionRuntime runtime, ValueConsumerList<MinionRuntime> valueConsumers) {
|
||||
MinionFakePlayer player = runtime.getMinion();
|
||||
EntityPlayerActionPack ap = player.getMinionActionPack();
|
||||
|
||||
if(currentBlock != null) {
|
||||
player.getWorld().setBlockBreakingInfo(-1, currentBlock, -1);
|
||||
player.interactionManager.processBlockBreakingAction(currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.getWorld().getTopYInclusive(), -1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> arguments, MinionRuntime runtime) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(WriteView view, MinionRuntime runtime) {
|
||||
view.put("currentBlock", BlockPos.CODEC, currentBlock);
|
||||
view.putFloat("currentBlockDamage", currentBlockDamage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(ReadView view, MinionRuntime runtime) {
|
||||
currentBlock = view.read("currentBlock", BlockPos.CODEC).orElse(null);
|
||||
currentBlockDamage = view.getFloat("currentBlockDamage", 0);
|
||||
if(currentBlock == null) {
|
||||
done = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package io.github.skippyall.minions.instruction.inventory;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.consumer.ValueConsumerList;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionExecution;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import io.github.skippyall.minions.registration.ValueTypes;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.screen.ScreenHandler;
|
||||
import net.minecraft.screen.slot.Slot;
|
||||
import net.minecraft.screen.slot.SlotActionType;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
|
||||
public class SwapItemExecution implements InstructionExecution<MinionRuntime> {
|
||||
public static final Parameter<Long> FROM_SLOT = new Parameter<>("from_slot", ValueTypes.LONG);
|
||||
public static final Parameter<Boolean> FROM_SCREEN = new Parameter<>("from_screen", ValueTypes.BOOLEAN);
|
||||
public static final Parameter<Long> TO_SLOT = new Parameter<>("to_slot", ValueTypes.LONG);
|
||||
public static final Parameter<Boolean> TO_SCREEN = new Parameter<>("to_screen", ValueTypes.BOOLEAN);
|
||||
|
||||
private int fromSlot;
|
||||
private boolean fromScreen;
|
||||
private int toSlot;
|
||||
private boolean toScreen;
|
||||
|
||||
private ItemStack cursor = ItemStack.EMPTY;
|
||||
|
||||
@Override
|
||||
public void start(MinionRuntime runtime) {
|
||||
MinionFakePlayer minion = runtime.getMinion();
|
||||
|
||||
if((fromScreen || toScreen) && minion.currentScreenHandler == null) {
|
||||
return;
|
||||
}
|
||||
if(!(checkBounds(minion, fromSlot, fromScreen) && checkBounds(minion, toSlot, toScreen))) {
|
||||
return;
|
||||
}
|
||||
|
||||
ItemStack fromStack = getStack(minion, fromSlot, fromScreen);
|
||||
ItemStack toStack = getStack(minion, toSlot, toScreen);
|
||||
|
||||
if(!(canExchange(minion, fromSlot, fromScreen, toStack) && canExchange(minion, toSlot, toScreen, fromStack))) {
|
||||
return;
|
||||
}
|
||||
|
||||
simulateClick(minion, fromSlot, fromScreen);
|
||||
simulateClick(minion, toSlot, toScreen);
|
||||
simulateClick(minion, fromSlot, fromScreen);
|
||||
minion.getInventory().offerOrDrop(cursor);
|
||||
}
|
||||
|
||||
private ScreenHandler getScreen(MinionFakePlayer minion, boolean screen) {
|
||||
if(screen) {
|
||||
return minion.currentScreenHandler;
|
||||
} else {
|
||||
return minion.playerScreenHandler;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean checkBounds(MinionFakePlayer minion, int slot, boolean screen) {
|
||||
return slot >= 0 && slot < getScreen(minion, screen).slots.size();
|
||||
}
|
||||
|
||||
private ItemStack getStack(MinionFakePlayer minion, int slot, boolean screen) {
|
||||
return getScreen(minion, screen).getSlot(slot).getStack();
|
||||
}
|
||||
|
||||
private boolean canExchange(MinionFakePlayer minion, int slotIndex, boolean screen, ItemStack newStack) {
|
||||
ScreenHandler screenHandler = getScreen(minion, screen);
|
||||
Slot slot = screenHandler.getSlot(slotIndex);
|
||||
if(!slot.getStack().isEmpty() && !slot.canTakeItems(minion)) {
|
||||
return false;
|
||||
}
|
||||
if(!newStack.isEmpty() && !slot.canInsert(newStack)) {
|
||||
return false;
|
||||
}
|
||||
/*else {
|
||||
if(slotIndex >= PlayerInventory.MAIN_SIZE && slotIndex < PlayerInventory.OFF_HAND_SLOT) {
|
||||
if(!minion.canEquip(newStack, PlayerInventory.EQUIPMENT_SLOTS.get(slotIndex))) {
|
||||
return false;
|
||||
}
|
||||
if(EnchantmentHelper.hasAnyEnchantmentsWith(minion.getInventory().getStack(slotIndex), EnchantmentEffectComponentTypes.PREVENT_ARMOR_CHANGE)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}*/
|
||||
return true;
|
||||
}
|
||||
|
||||
private void simulateClick(MinionFakePlayer minion, int slotIndex, boolean screen) {
|
||||
ScreenHandler screenHandler = getScreen(minion, screen);
|
||||
ItemStack previousCursor = screenHandler.getCursorStack();
|
||||
screenHandler.setCursorStack(cursor);
|
||||
screenHandler.onSlotClick(slotIndex, 0, SlotActionType.SWAP, minion);
|
||||
cursor = screenHandler.getCursorStack();
|
||||
screenHandler.setCursorStack(previousCursor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick(MinionRuntime runtime) {
|
||||
InstructionExecution.super.tick(runtime);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDone(MinionRuntime runtime) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop(MinionRuntime runtime, ValueConsumerList<MinionRuntime> valueConsumers) {
|
||||
InstructionExecution.super.stop(runtime, valueConsumers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> arguments, MinionRuntime runtime) {
|
||||
fromSlot = Math.clamp(arguments.getValue(FROM_SLOT, runtime), 0, Integer.MAX_VALUE);
|
||||
fromScreen = arguments.getValue(FROM_SCREEN, runtime);
|
||||
toSlot = Math.clamp(arguments.getValue(TO_SLOT, runtime), 0, Integer.MAX_VALUE);
|
||||
toScreen = arguments.getValue(TO_SCREEN, runtime);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(WriteView view, MinionRuntime runtime) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(ReadView view, MinionRuntime runtime) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionExecution;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
|
||||
public abstract class AbstractTurnExecution implements InstructionExecution<MinionRuntime> {
|
||||
protected float targetYaw;
|
||||
protected float targetPitch;
|
||||
|
||||
private static final float anglePerTick = 10;
|
||||
|
||||
@Override
|
||||
public void tick(MinionRuntime minion) {
|
||||
float rotateYaw = targetYaw - minion.getMinion().getYaw();
|
||||
float rotatePitch = targetPitch - minion.getMinion().getPitch();
|
||||
|
||||
minion.getMinion().getMinionActionPack().turn(Math.min(rotateYaw, anglePerTick), Math.min(rotatePitch, anglePerTick));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDone(MinionRuntime minion) {
|
||||
return Math.abs(targetYaw - minion.getMinion().getYaw()) < 0.001F && Math.abs(targetPitch - minion.getMinion().getPitch()) < 0.001F;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(WriteView view, MinionRuntime runtime) {
|
||||
view.putFloat("targetYaw", targetYaw);
|
||||
view.putFloat("targetPitch", targetPitch);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(ReadView view, MinionRuntime runtime) {
|
||||
targetYaw = view.getFloat("targetYaw", 0);
|
||||
targetPitch = view.getFloat("targetPitch", 0);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionExecution;
|
||||
import io.github.skippyall.minions.program.instruction.execution.ContinuousInstructionExecution;
|
||||
import net.minecraft.entity.MovementType;
|
||||
|
||||
public class ContinuousWalkExecution implements ContinuousInstructionExecution<MinionRuntime>, InstructionExecution.Stateless<MinionRuntime> {
|
||||
@Override
|
||||
public void tick(MinionRuntime minion) {
|
||||
minion.getMinion().move(MovementType.SELF, minion.getMinion().getHorizontalFacing().getDoubleVector().normalize().multiply(minion.getMinion().getMovementSpeed()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import io.github.skippyall.minions.gui.Displayable;
|
||||
import io.github.skippyall.minions.gui.GuiDisplay;
|
||||
import net.minecraft.util.StringIdentifiable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public enum TurnDirection implements StringIdentifiable, Displayable {
|
||||
LEFT("left", -1, 0),
|
||||
UP("up", 0, -1),
|
||||
RIGHT("right", 1, 0),
|
||||
DOWN("down", 0, 1);
|
||||
|
||||
public static final Codec<TurnDirection> CODEC = StringIdentifiable.createCodec(TurnDirection::values);
|
||||
|
||||
private static final UUID MHF_ArrowLeft = UUID.fromString("a68f0b64-8d14-4000-a95f-4b9ba14f8df9");
|
||||
private static final UUID MHF_ArrowUp = UUID.fromString("fef039ef-e6cd-4987-9c84-26a3e6134277");
|
||||
private static final UUID MHF_ArrowRight = UUID.fromString("50c8510b-5ea0-4d60-be9a-7d542d6cd156");
|
||||
private static final UUID MHF_ArrowDown = UUID.fromString("68f59b9b-5b0b-4b05-a9f2-e1d1405aa348");
|
||||
|
||||
public final String name;
|
||||
public final int xFactor;
|
||||
public final int yFactor;
|
||||
|
||||
TurnDirection(String name, int xFactor, int yFactor) {
|
||||
this.xFactor = xFactor;
|
||||
this.yFactor = yFactor;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String asString() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GuiDisplay getDisplay() {
|
||||
return switch (this) {
|
||||
case LEFT -> new GuiDisplay.HeadBased(MHF_ArrowLeft);
|
||||
case UP -> new GuiDisplay.HeadBased(MHF_ArrowUp);
|
||||
case RIGHT -> new GuiDisplay.HeadBased(MHF_ArrowRight);
|
||||
case DOWN -> new GuiDisplay.HeadBased(MHF_ArrowDown);
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.registration.ValueTypes;
|
||||
|
||||
public class TurnExecution extends AbstractTurnExecution {
|
||||
public static final Parameter<Double> ANGLE = new Parameter<>("maxAngle", ValueTypes.DOUBLE);
|
||||
public static final Parameter<TurnDirection> DIRECTION = new Parameter<>("direction", ValueTypes.TURN_DIRECTION);
|
||||
|
||||
@Override
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> arguments, MinionRuntime minion) {
|
||||
float maxAngle = arguments.getValue(ANGLE, minion).floatValue();
|
||||
TurnDirection direction = arguments.getValue(DIRECTION, minion);
|
||||
|
||||
float turnYaw = maxAngle * direction.xFactor;
|
||||
float turnPitch = maxAngle * direction.yFactor;
|
||||
|
||||
targetYaw = minion.getMinion().getYaw() + turnYaw;
|
||||
targetPitch = minion.getMinion().getPitch() + turnPitch;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import io.github.skippyall.minions.registration.ValueTypes;
|
||||
import net.minecraft.util.math.MathHelper;
|
||||
import net.minecraft.util.math.Vec2f;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
public class TurnVectorExecution extends AbstractTurnExecution {
|
||||
public static final Parameter<Double> X = new Parameter<>("x", ValueTypes.DOUBLE);
|
||||
public static final Parameter<Double> Y = new Parameter<>("y", ValueTypes.DOUBLE);
|
||||
public static final Parameter<Double> Z = new Parameter<>("z", ValueTypes.DOUBLE);
|
||||
|
||||
@Override
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> arguments, MinionRuntime runtime) {
|
||||
double x = arguments.getValue(X, runtime);
|
||||
double y = arguments.getValue(Y, runtime);
|
||||
double z = arguments.getValue(Z, runtime);
|
||||
|
||||
Vec3d vector = new Vec3d(x, y, z);
|
||||
Vec2f rotation = vectorToRotation(vector);
|
||||
targetYaw = rotation.x;
|
||||
targetPitch = rotation.y;
|
||||
}
|
||||
|
||||
//copied from Entity#lookAt (why no helper, Mojang?)
|
||||
public static Vec2f vectorToRotation(Vec3d vector) {
|
||||
double g = Math.sqrt(vector.x * vector.x + vector.z * vector.z);
|
||||
float pitch = MathHelper.wrapDegrees((float)(-(MathHelper.atan2(vector.y, g) * 180.0F / (float)Math.PI)));
|
||||
float yaw = MathHelper.wrapDegrees((float)(MathHelper.atan2(vector.z, vector.x) * 180.0F / (float)Math.PI) - 90.0F);
|
||||
|
||||
return new Vec2f(yaw, pitch);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package io.github.skippyall.minions.instruction.move;
|
||||
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionExecution;
|
||||
import io.github.skippyall.minions.program.supplier.Parameter;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierList;
|
||||
import io.github.skippyall.minions.registration.ValueTypes;
|
||||
import net.minecraft.entity.MovementType;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
|
||||
public class WalkExecution implements InstructionExecution<MinionRuntime> {
|
||||
public static final Parameter<Double> blocksToMoveParam = new Parameter<>("blocksToMove", ValueTypes.DOUBLE);
|
||||
private static final float ACCURACY = 1F / 32F;
|
||||
|
||||
private double totalBlocksToMove;
|
||||
private double blocksMoved;
|
||||
|
||||
@Override
|
||||
public void tick(MinionRuntime minion) {
|
||||
double speed = Math.min(minion.getMinion().getMovementSpeed(), totalBlocksToMove - blocksMoved);
|
||||
minion.getMinion().move(MovementType.SELF, minion.getMinion().getHorizontalFacing().getDoubleVector().normalize().multiply(speed));
|
||||
blocksMoved += speed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDone(MinionRuntime minion) {
|
||||
return totalBlocksToMove - blocksMoved < ACCURACY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readArguments(ValueSupplierList<MinionRuntime> parameters, MinionRuntime minion) {
|
||||
totalBlocksToMove = parameters.getValue(blocksToMoveParam, minion).floatValue();
|
||||
blocksMoved = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(WriteView view, MinionRuntime minion) {
|
||||
view.putDouble("totalBlocksToMove", totalBlocksToMove);
|
||||
view.putDouble("blocksMoved", blocksMoved);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(ReadView view, MinionRuntime minion) {
|
||||
totalBlocksToMove = view.getDouble("totalBlocksToMove", 0F);
|
||||
blocksMoved = view.getDouble("blocksMoved", 0F);
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package io.github.skippyall.minions.listener;
|
||||
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstructionListener;
|
||||
import net.minecraft.block.entity.BlockEntity;
|
||||
import net.minecraft.block.entity.BlockEntityType;
|
||||
import net.minecraft.registry.RegistryKey;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class BlockEntityMinionInstructionListener<E extends BlockEntity> extends BlockEntityMinionListener<E> {
|
||||
protected BlockEntityMinionInstructionListener(RegistryKey<World> worldKey, BlockPos pos, UUID minionUuid, BlockEntityType<E> type) {
|
||||
super(worldKey, pos, minionUuid, type);
|
||||
}
|
||||
|
||||
protected abstract Map<String, ConfiguredInstructionListener> getInstructionListeners();
|
||||
|
||||
@Override
|
||||
public void onMinionSpawn(MinionFakePlayer minion) {
|
||||
super.onMinionSpawn(minion);
|
||||
registerInstructionListeners();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void add(MinecraftServer server) {
|
||||
super.add(server);
|
||||
if(minion != null) {
|
||||
registerInstructionListeners();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(MinecraftServer server) {
|
||||
super.remove(server);
|
||||
if(minion != null) {
|
||||
removeInstructionListeners();
|
||||
}
|
||||
}
|
||||
|
||||
public void registerInstructionListeners() {
|
||||
for(Map.Entry<String, ConfiguredInstructionListener> listener : getInstructionListeners().entrySet()) {
|
||||
minion.getInstructionManager().getInstruction(listener.getKey()).addListener(listener.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
public void removeInstructionListeners() {
|
||||
for(Map.Entry<String, ConfiguredInstructionListener> listener : getInstructionListeners().entrySet()) {
|
||||
minion.getInstructionManager().getInstruction(listener.getKey()).removeListener(listener.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package io.github.skippyall.minions.listener;
|
||||
|
||||
import com.mojang.datafixers.util.Function3;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import io.github.skippyall.minions.minion.MinionListener;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import net.minecraft.block.entity.BlockEntity;
|
||||
import net.minecraft.block.entity.BlockEntityType;
|
||||
import net.minecraft.registry.RegistryKey;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.Uuids;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.world.World;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class BlockEntityMinionListener<E extends BlockEntity> implements MinionListener {
|
||||
protected RegistryKey<World> worldKey;
|
||||
protected BlockPos pos;
|
||||
protected UUID minionUuid;
|
||||
protected BlockEntityType<E> type;
|
||||
protected @Nullable MinionFakePlayer minion;
|
||||
|
||||
protected BlockEntityMinionListener(RegistryKey<World> worldKey, BlockPos pos, UUID minionUuid, BlockEntityType<E> type) {
|
||||
this.worldKey = worldKey;
|
||||
this.pos = pos;
|
||||
this.minionUuid = minionUuid;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMinionSpawn(MinionFakePlayer minion) {
|
||||
MinionListener.super.onMinionSpawn(minion);
|
||||
this.minion = minion;
|
||||
removeIfBeRemoved(minion.getServer());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMinionRemove(MinionFakePlayer minion) {
|
||||
MinionListener.super.onMinionRemove(minion);
|
||||
this.minion = null;
|
||||
}
|
||||
|
||||
public static <T extends BlockEntityMinionListener<?>> T getListener(World world, BlockPos pos, UUID minionUuid, Class<T> clazz) {
|
||||
if(minionUuid != null) {
|
||||
for (MinionListener listener : MinionPersistentState.get(world.getServer()).getMinionData(minionUuid).listeners()) {
|
||||
if (listener instanceof BlockEntityMinionListener<?> tl && tl.pos.equals(pos) && tl.worldKey.equals(world.getRegistryKey()) && clazz.isInstance(tl)) {
|
||||
return clazz.cast(tl);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static <L extends BlockEntityMinionListener<?>> Codec<L> getCodec(Function3<RegistryKey<World>, BlockPos, UUID, L> constructor) {
|
||||
return RecordCodecBuilder.create(instance ->
|
||||
instance.group(
|
||||
World.CODEC.fieldOf("world").forGetter(listener -> listener.worldKey),
|
||||
BlockPos.CODEC.fieldOf("pos").forGetter(listener -> listener.pos),
|
||||
Uuids.CODEC.fieldOf("minionUuid").forGetter(listener -> listener.minionUuid)
|
||||
).apply(instance, constructor));
|
||||
}
|
||||
|
||||
private BlockEntityState getBlockEntityState(MinecraftServer server) {
|
||||
World world = server.getWorld(worldKey);
|
||||
if(world == null || !world.isPosLoaded(pos)) {
|
||||
return BlockEntityState.UNLOADED;
|
||||
}
|
||||
|
||||
if(world.getBlockEntity(pos, type).isPresent()) {
|
||||
return BlockEntityState.LOADED;
|
||||
} else {
|
||||
return BlockEntityState.REMOVED;
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<E> getBlockEntity(MinecraftServer server) {
|
||||
World world = server.getWorld(worldKey);
|
||||
if(world != null && world.isPosLoaded(pos)) {
|
||||
return world.getBlockEntity(pos, type);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public boolean removeIfBeRemoved(MinecraftServer server) {
|
||||
if(getBlockEntityState(server) == BlockEntityState.REMOVED) {
|
||||
remove(server);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
protected void add(MinecraftServer server) {
|
||||
MinionPersistentState.get(server).getMinionData(minionUuid).listeners().addListener(this);
|
||||
MinionPersistentState.get(server).markDirty();
|
||||
this.minion = (MinionFakePlayer) server.getPlayerManager().getPlayer(minionUuid);
|
||||
}
|
||||
|
||||
public void remove(MinecraftServer server) {
|
||||
MinionPersistentState.get(server).getMinionData(minionUuid).listeners().removeListener(this);
|
||||
MinionPersistentState.get(server).markDirty();
|
||||
}
|
||||
|
||||
public enum BlockEntityState {
|
||||
LOADED,
|
||||
REMOVED,
|
||||
UNLOADED
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
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);
|
||||
}
|
||||
|
||||
public boolean hasListener(T listener) {
|
||||
return listeners.contains(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Iterator<T> iterator() {
|
||||
return listeners.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return super.equals(obj);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package io.github.skippyall.minions.listener;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import net.minecraft.registry.Registry;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
import net.minecraft.util.Identifier;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
|
||||
public class SerializableListenerManager<T extends SerializableListenerManager.SerializableListener> extends ListenerManager<T> {
|
||||
private final Registry<Codec<? extends T>> registry;
|
||||
|
||||
public SerializableListenerManager(Registry<Codec<? extends T>> registry) {
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
private SerializableListenerManager(Registry<Codec<? extends T>> registry, Set<T> listeners) {
|
||||
super(listeners);
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
public static <T extends SerializableListener> Codec<SerializableListenerManager<T>> getCodec(Registry<Codec<? extends T>> registry) {
|
||||
return registry.getCodec().<T>dispatch(
|
||||
listener -> listener.getCodecId().map(registry::get).orElse(Codec.unit(null)),
|
||||
codec -> codec.fieldOf("data")
|
||||
).listOf().xmap(
|
||||
list -> new SerializableListenerManager<>(registry, new CopyOnWriteArraySet<>(list)),
|
||||
manager -> {
|
||||
List<T> serializableListeners = new ArrayList<>();
|
||||
for(T listener : manager.listeners) {
|
||||
if(listener.getCodecId().isPresent()) {
|
||||
serializableListeners.add(listener);
|
||||
}
|
||||
}
|
||||
return serializableListeners;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public void save(WriteView view) {
|
||||
WriteView.ListView listView = view.getList("listeners");
|
||||
for (T listener : listeners) {
|
||||
if(listener.getCodecId().isPresent()) {
|
||||
WriteView listenerView = listView.add();
|
||||
Codec<? extends T> codec = registry.get(listener.getCodecId().get());
|
||||
listenerView.put("id", Identifier.CODEC, listener.getCodecId().get());
|
||||
//noinspection unchecked
|
||||
listenerView.put("data", (Codec<T>) codec, listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void load(ReadView view) {
|
||||
ReadView.ListReadView listView = view.getListReadView("listeners");
|
||||
for (ReadView listenerView : listView) {
|
||||
Optional<Identifier> id = listenerView.read("id", Identifier.CODEC);
|
||||
if(id.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Codec<? extends T> codec = registry.get(id.get());
|
||||
|
||||
Optional<? extends T> listener = listenerView.read("data", codec);
|
||||
|
||||
if(listener.isPresent()) {
|
||||
listeners.add(listener.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface SerializableListener {
|
||||
default Optional<Identifier> getCodecId() {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,63 @@
|
||||
package io.github.skippyall.minions.minion;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import net.minecraft.util.Identifier;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public class MinionConfig {
|
||||
public static final Codec<MinionConfig> CODEC = Codec.<Option<?>, Object>dispatchedMap(
|
||||
MinionRegistries.MINION_CONFIG_OPTIONS.getCodec(),
|
||||
Option::codec
|
||||
).xmap(MinionConfig::new, config -> config.values);
|
||||
|
||||
private final Map<Option<?>, Object> values;
|
||||
|
||||
public MinionConfig() {
|
||||
values = new HashMap<>();
|
||||
}
|
||||
|
||||
private MinionConfig(Map<Option<?>, Object> values) {
|
||||
this.values = new HashMap<>(values);
|
||||
}
|
||||
|
||||
public <T> T getOption(Option<T> option) {
|
||||
if(values.containsKey(option)) {
|
||||
//noinspection unchecked
|
||||
return (T) values.get(option);
|
||||
} else {
|
||||
return option.defaultValue();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof MinionConfig that)) return false;
|
||||
return Objects.equals(values, that.values);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(values);
|
||||
}
|
||||
|
||||
public static Option<Boolean> booleanOption(Identifier key, boolean defaultValue) {
|
||||
return new Option<>(key, defaultValue, Codec.BOOL);
|
||||
}
|
||||
|
||||
public record Option<T>(Identifier key, T defaultValue, Codec<T> codec) {
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof Option<?> option)) return false;
|
||||
return Objects.equals(key, option.key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
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.registration.MinionRegistries;
|
||||
import io.github.skippyall.minions.listener.SerializableListenerManager;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.Uuids;
|
||||
import net.minecraft.util.dynamic.Codecs;
|
||||
|
||||
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(
|
||||
Uuids.CODEC.fieldOf("uuid").forGetter(MinionData::uuid),
|
||||
Codec.STRING.fieldOf("name").forGetter(MinionData::name),
|
||||
Codecs.GAME_PROFILE_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(() -> new SerializableListenerManager<>(MinionRegistries.MINION_LISTENER_CODECS)),
|
||||
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<>(MinionRegistries.MINION_LISTENER_CODECS),
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,62 +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.GenericContainerScreenHandler;
|
||||
import net.minecraft.screen.ScreenHandlerType;
|
||||
import net.minecraft.screen.SimpleNamedScreenHandlerFactory;
|
||||
import net.minecraft.screen.slot.Slot;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
public class MinionInventory {
|
||||
public static void openInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
|
||||
openServerSideInventory(player, minion);
|
||||
}
|
||||
|
||||
public static void openServerSideInventory(ServerPlayerEntity player, MinionFakePlayer minion) {
|
||||
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_3X3, player, false);
|
||||
gui.setTitle(Text.literal("Minion"));
|
||||
gui.setSlot(4, new GuiElementBuilder()
|
||||
.setItem(Items.REDSTONE)
|
||||
.setName(Text.literal("Programming"))
|
||||
.setCallback((i, clickType, clickType1) -> {
|
||||
openProgrammingInventory(player, minion);
|
||||
})
|
||||
);
|
||||
gui.setSlot(3, new GuiElementBuilder()
|
||||
.setItem(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE)
|
||||
.setName(Text.literal("Modules and Detectors"))
|
||||
.setCallback((i, clickType, clickType1) -> {
|
||||
openModuleInventory(player, minion);
|
||||
})
|
||||
);
|
||||
gui.setSlot(5, new GuiElementBuilder()
|
||||
.setItem(Items.CHEST)
|
||||
.setName(Text.literal("Inventory"))
|
||||
.setCallback((i, clickType, clickType1) -> {
|
||||
openMinionInventory(player, minion);
|
||||
})
|
||||
);
|
||||
gui.open();
|
||||
}
|
||||
|
||||
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) {
|
||||
SimpleGui gui = new SimpleGui(ScreenHandlerType.GENERIC_9X5, player, false);
|
||||
gui.setTitle(Text.literal("Minion"));
|
||||
for (int i = 0; i < minion.getInventory().size(); i++) {
|
||||
gui.setSlotRedirect(i, new Slot(minion.getInventory(), i, 0, 0));
|
||||
}
|
||||
gui.open();
|
||||
}
|
||||
}
|
||||
@@ -2,49 +2,105 @@ 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.fakeplayer.MinionFakePlayer;
|
||||
import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
|
||||
import net.minecraft.client.item.TooltipContext;
|
||||
import net.minecraft.enchantment.Enchantments;
|
||||
import net.minecraft.item.*;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import io.github.skippyall.minions.gui.MinionLookGui;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.registration.MinionComponentTypes;
|
||||
import net.minecraft.component.DataComponentTypes;
|
||||
import net.minecraft.component.type.TooltipDisplayComponent;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
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.server.MinecraftServer;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.text.PlainTextContent;
|
||||
import net.minecraft.text.TextContent;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.ActionResult;
|
||||
import net.minecraft.util.Hand;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.math.Vec2f;
|
||||
import net.minecraft.world.World;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xyz.nucleoid.packettweaker.PacketContext;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class MinionItem extends Item implements PolymerItem {
|
||||
private boolean canProgram;
|
||||
public MinionItem(boolean canProgram) {
|
||||
super(new FabricItemSettings());
|
||||
public MinionItem(Settings settings) {
|
||||
super(settings);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Item getPolymerItem(ItemStack itemStack, @Nullable ServerPlayerEntity player) {
|
||||
public @Nullable Identifier 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, TooltipContext flag, ServerPlayerEntity player) {
|
||||
ItemStack out = PolymerItemUtils.createItemStack(stack, flag, player);
|
||||
out.addEnchantment(Enchantments.MENDING, 1);
|
||||
public ItemStack getPolymerItemStack(ItemStack stack, TooltipType tooltipType, PacketContext player) {
|
||||
ItemStack out = PolymerItemUtils.createItemStack(stack, tooltipType, player);
|
||||
out.set(DataComponentTypes.ENCHANTMENT_GLINT_OVERRIDE, true);
|
||||
return out;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void appendTooltip(ItemStack stack, TooltipContext context, TooltipDisplayComponent component, Consumer<Text> tooltip, TooltipType type) {
|
||||
MinionData data = null /*getData(stack)*/;
|
||||
if(data != null) {
|
||||
tooltip.accept(Text.translatable("minions.minion_item.tooltip", data.name()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActionResult use(World world, PlayerEntity user, Hand hand) {
|
||||
if(user instanceof ServerPlayerEntity serverPlayer) {
|
||||
ItemStack stack = user.getStackInHand(hand);
|
||||
MinionLookGui.open(serverPlayer, stack);
|
||||
return ActionResult.SUCCESS;
|
||||
}
|
||||
|
||||
return ActionResult.SUCCESS_SERVER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActionResult useOnBlock(ItemUsageContext context) {
|
||||
String contents = context.getStack().getName().getLiteralString();
|
||||
String name;
|
||||
if(contents != null) {
|
||||
name = contents;
|
||||
} else {
|
||||
name = "Minion";
|
||||
}
|
||||
if(!context.getWorld().isClient) {
|
||||
MinionFakePlayer.createMinion(name, (ServerWorld) context.getWorld(), (ServerPlayerEntity) context.getPlayer(), canProgram, context.getBlockPos().toCenterPos().add(0,0.5,0), 0, 0);
|
||||
MinionData data = getDataOrDefault(context.getWorld().getServer(), context.getStack());
|
||||
MinionFakePlayer.spawnMinion(data, (ServerWorld) context.getWorld(), context.getBlockPos().toCenterPos().add(0,0.5,0), new Vec2f(0, 0));
|
||||
}
|
||||
context.getStack().decrement(1);
|
||||
return ActionResult.SUCCESS;
|
||||
}
|
||||
|
||||
public static void setData(MinecraftServer server, MinionData data, ItemStack item) {
|
||||
item.set(MinionComponentTypes.MINION_DATA, data.uuid());
|
||||
MinionPersistentState.get(server).updateMinionData(data);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static MinionData getData(MinecraftServer server, ItemStack item) {
|
||||
if(item.contains(MinionComponentTypes.MINION_DATA)) {
|
||||
return MinionPersistentState.get(server).getMinionData(item.get(MinionComponentTypes.MINION_DATA));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static MinionData getDataOrDefault(MinecraftServer server, ItemStack item) {
|
||||
MinionData data = getData(server, item);
|
||||
if(data == null) {
|
||||
data = MinionData.createDefault(server);
|
||||
setData(server, data, item);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
public static boolean containsData(ItemStack item) {
|
||||
return item.contains(MinionComponentTypes.MINION_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package io.github.skippyall.minions.minion;
|
||||
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.listener.SerializableListenerManager;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface MinionListener extends SerializableListenerManager.SerializableListener {
|
||||
default void onMinionSpawn(MinionFakePlayer minion) {}
|
||||
|
||||
default void onMinionRemove(MinionFakePlayer minion) {}
|
||||
|
||||
default void onInstructionsUpdate(MinionFakePlayer minion) {}
|
||||
|
||||
default void onInstructionRename(MinionFakePlayer minion, ConfiguredInstruction<?> instruction, String oldName, String newName) {}
|
||||
|
||||
interface Delegating extends MinionListener {
|
||||
@Nullable MinionListener getBacking();
|
||||
|
||||
@Override
|
||||
default void onMinionSpawn(MinionFakePlayer minion) {
|
||||
if(getBacking() != null) {
|
||||
getBacking().onMinionSpawn(minion);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
default void onMinionRemove(MinionFakePlayer minion) {
|
||||
if(getBacking() != null) {
|
||||
getBacking().onMinionRemove(minion);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
default void onInstructionsUpdate(MinionFakePlayer minion) {
|
||||
if(getBacking() != null) {
|
||||
getBacking().onInstructionsUpdate(minion);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
default void onInstructionRename(MinionFakePlayer minion, ConfiguredInstruction<?> instruction, String oldName, String newName) {
|
||||
if(getBacking() != null) {
|
||||
getBacking().onInstructionRename(minion, instruction, oldName, newName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package io.github.skippyall.minions.minion;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.world.PersistentState;
|
||||
import net.minecraft.world.PersistentStateType;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public class MinionPersistentState extends PersistentState {
|
||||
public static final Codec<MinionPersistentState> CODEC = MinionData.CODEC.listOf().xmap(MinionPersistentState::new, MinionPersistentState::getMinionDataList);
|
||||
|
||||
public static PersistentStateType<MinionPersistentState> TYPE = new PersistentStateType<>("minion", MinionPersistentState::new, MinionPersistentState.CODEC, null);
|
||||
|
||||
private final Map<UUID, MinionData> minionData = new HashMap<>();
|
||||
|
||||
public MinionPersistentState() {
|
||||
|
||||
}
|
||||
|
||||
public MinionPersistentState(List<MinionData> dataList) {
|
||||
for (MinionData data : dataList) {
|
||||
minionData.put(data.uuid(), data);
|
||||
}
|
||||
}
|
||||
|
||||
public MinionData getMinionData(UUID uuid) {
|
||||
return minionData.get(uuid);
|
||||
}
|
||||
|
||||
public Map<UUID, MinionData> getMinionData() {
|
||||
return minionData;
|
||||
}
|
||||
|
||||
public List<MinionData> getMinionDataList() {
|
||||
return List.copyOf(minionData.values());
|
||||
}
|
||||
|
||||
public void updateMinionData(MinionData data) {
|
||||
minionData.put(data.uuid(), data);
|
||||
markDirty();
|
||||
}
|
||||
|
||||
public boolean isMinion(UUID uuid) {
|
||||
return minionData.containsKey(uuid);
|
||||
}
|
||||
|
||||
public boolean isMinionNameTaken(String name) {
|
||||
return getMinionWithName(name).isPresent();
|
||||
}
|
||||
|
||||
public Optional<MinionData> getMinionWithName(String name) {
|
||||
return minionData.values().stream()
|
||||
.filter(data -> data.name().equals(name))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public static MinionPersistentState get(MinecraftServer server) {
|
||||
return server.getWorld(World.OVERWORLD).getPersistentStateManager().getOrCreate(TYPE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package io.github.skippyall.minions.minion;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.authlib.properties.PropertyMap;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import io.github.skippyall.minions.MinionsConfig;
|
||||
import io.github.skippyall.minions.gui.input.Result;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.StringHelper;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.skippyall.minions.Minions.LOGGER;
|
||||
|
||||
public class MinionProfileUtils {
|
||||
public static String getPrefix() {
|
||||
return MinionsConfig.get().minion.minionPrefix;
|
||||
}
|
||||
|
||||
public static GameProfile makeNewMinionProfile(UUID uuidMinion, String username, PropertyMap skin) {
|
||||
if(uuidMinion == null) {
|
||||
uuidMinion = UUID.randomUUID();
|
||||
}
|
||||
|
||||
GameProfile newProfile = new GameProfile(uuidMinion, username);
|
||||
if (skin != null) {
|
||||
newProfile.getProperties().putAll(skin);
|
||||
}
|
||||
LOGGER.info("Minion Profile: {}", newProfile);
|
||||
return newProfile;
|
||||
}
|
||||
|
||||
public static Result<String, Text> checkMinionNameWithoutPrefix(MinecraftServer server, String name) {
|
||||
for(char c : name.toCharArray()) {
|
||||
if(!StringReader.isAllowedInUnquotedString(c)) {
|
||||
return new Result.Error<>(Text.translatable("minions.generic.name.invalid_char"));
|
||||
}
|
||||
}
|
||||
|
||||
if((getPrefix() + name).length() > 16) {
|
||||
return new Result.Error<>(Text.translatable("minions.generic.name.too_long"));
|
||||
}
|
||||
|
||||
if(!StringHelper.isValidPlayerName(getPrefix() + name)) {
|
||||
return new Result.Error<>(Text.translatable("minions.generic.name.invalid"));
|
||||
}
|
||||
|
||||
if(MinionPersistentState.get(server).isMinionNameTaken(getPrefix() + name)) {
|
||||
return new Result.Error<>(Text.translatable("minions.generic.name.taken"));
|
||||
}
|
||||
|
||||
return new Result.Success<>(name);
|
||||
}
|
||||
|
||||
public static String newDefaultMinionName(MinecraftServer server) {
|
||||
int i = 0;
|
||||
while (MinionPersistentState.get(server).isMinionNameTaken("+Minion" + i)) {
|
||||
i++;
|
||||
}
|
||||
return "+Minion" + i;
|
||||
}
|
||||
|
||||
public static boolean isMinion(MinecraftServer server, UUID uuid) {
|
||||
return MinionPersistentState.get(server).isMinion(uuid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package io.github.skippyall.minions.minion;
|
||||
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstructionListener;
|
||||
import io.github.skippyall.minions.registration.MinionRegistries;
|
||||
import io.github.skippyall.minions.Minions;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.MinionFakePlayer;
|
||||
import io.github.skippyall.minions.program.InstructionRuntime;
|
||||
import io.github.skippyall.minions.program.supplier.ValueSupplierType;
|
||||
import io.github.skippyall.minions.program.instruction.ConfiguredInstruction;
|
||||
import io.github.skippyall.minions.program.instruction.InstructionType;
|
||||
import io.github.skippyall.minions.program.consumer.ValueConsumerType;
|
||||
import net.minecraft.registry.Registry;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class MinionRuntime implements InstructionRuntime<MinionRuntime> {
|
||||
private final MinionFakePlayer minion;
|
||||
private final Map<String, ConfiguredInstruction<MinionRuntime>> configuredInstructions = new HashMap<>();
|
||||
private final Map<Integer, ConfiguredInstruction<MinionRuntime>> webSocketInstructions = new ConcurrentHashMap<>();
|
||||
|
||||
public MinionRuntime(MinionFakePlayer minion) {
|
||||
this.minion = minion;
|
||||
}
|
||||
|
||||
public MinionFakePlayer getMinion() {
|
||||
return minion;
|
||||
}
|
||||
|
||||
public void tick() {
|
||||
for (ConfiguredInstruction<MinionRuntime> instruction : configuredInstructions.values()) {
|
||||
instruction.tick(this);
|
||||
}
|
||||
|
||||
for(ConfiguredInstruction<MinionRuntime> instruction : webSocketInstructions.values()) {
|
||||
instruction.tick(this);
|
||||
}
|
||||
}
|
||||
|
||||
public void disableInstructionType(InstructionType<MinionRuntime> instructionType) {
|
||||
updatePausedStatus(instructionType);
|
||||
}
|
||||
|
||||
public void enableInstructionType(InstructionType<MinionRuntime> instructionType) {
|
||||
updatePausedStatus(instructionType);
|
||||
}
|
||||
|
||||
public void updatePausedStatus(InstructionType<MinionRuntime> instructionType) {
|
||||
for(ConfiguredInstruction<MinionRuntime> instruction : configuredInstructions.values()) {
|
||||
if(instruction.getInstruction() == instructionType) {
|
||||
instruction.updatePauseStatus(this);
|
||||
}
|
||||
}
|
||||
for(ConfiguredInstruction<MinionRuntime> instruction : webSocketInstructions.values()) {
|
||||
if(instruction.getInstruction() == instructionType) {
|
||||
instruction.updatePauseStatus(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInstructionEnabled(InstructionType<MinionRuntime> type) {
|
||||
return minion.getModuleInventory().hasInstruction(type);
|
||||
}
|
||||
|
||||
public Set<String> getInstructionNames() {
|
||||
return configuredInstructions.keySet();
|
||||
}
|
||||
|
||||
public ConfiguredInstruction<MinionRuntime> createInstruction(String name, InstructionType<MinionRuntime> instructionType) {
|
||||
if(configuredInstructions.containsKey(name)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ConfiguredInstruction<MinionRuntime> instruction = new ConfiguredInstruction<>(instructionType);
|
||||
configuredInstructions.put(name, instruction);
|
||||
minion.forEachMinionListener(listener -> listener.onInstructionsUpdate(minion));
|
||||
return instruction;
|
||||
}
|
||||
|
||||
public void removeInstruction(String name) {
|
||||
ConfiguredInstruction<MinionRuntime> instruction = getInstruction(name);
|
||||
instruction.stop(this);
|
||||
configuredInstructions.remove(name);
|
||||
|
||||
instruction.onInstructionRemove();
|
||||
minion.forEachMinionListener(listener -> listener.onInstructionsUpdate(minion));
|
||||
}
|
||||
|
||||
public ConfiguredInstruction<MinionRuntime> getInstruction(String name) {
|
||||
return configuredInstructions.get(name);
|
||||
}
|
||||
|
||||
public boolean hasInstruction(String name) {
|
||||
return configuredInstructions.containsKey(name);
|
||||
}
|
||||
|
||||
public void setInstructionName(String oldName, String newName) {
|
||||
if(!configuredInstructions.containsKey(newName) && configuredInstructions.containsKey(oldName)) {
|
||||
ConfiguredInstruction<MinionRuntime> instruction = configuredInstructions.get(oldName);
|
||||
configuredInstructions.remove(oldName);
|
||||
configuredInstructions.put(newName, instruction);
|
||||
|
||||
|
||||
minion.forEachMinionListener(minionListener -> {
|
||||
minionListener.onInstructionRename(minion, instruction, oldName, newName);
|
||||
minionListener.onInstructionsUpdate(minion);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void addWebSocketInstruction(int id, ConfiguredInstruction<MinionRuntime> instruction) {
|
||||
webSocketInstructions.put(id, instruction);
|
||||
instruction.addListener(new ConfiguredInstructionListener() {
|
||||
@Override
|
||||
public void onStop(ConfiguredInstruction<?> instruction) {
|
||||
webSocketInstructions.remove(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void save(WriteView view) {
|
||||
WriteView.ListView list = view.getList("configuredInstructions");
|
||||
for (Map.Entry<String, ConfiguredInstruction<MinionRuntime>> instruction : configuredInstructions.entrySet()) {
|
||||
WriteView inner = list.add();
|
||||
inner.putString("name", instruction.getKey());
|
||||
instruction.getValue().save(inner, this);
|
||||
}
|
||||
}
|
||||
|
||||
public void load(ReadView view) {
|
||||
ReadView.ListReadView list = view.getListReadView("configuredInstructions");
|
||||
for (ReadView inner : list) {
|
||||
Optional<String> name = inner.getOptionalString("name");
|
||||
if(name.isEmpty()) {
|
||||
Minions.LOGGER.error("Tried deserializing configured instruction without a name of minion \"{}\":", minion.getGameProfile().getName());
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
ConfiguredInstruction<MinionRuntime> instruction = ConfiguredInstruction.load(inner, this);
|
||||
configuredInstructions.put(name.get(), instruction);
|
||||
} catch (Exception e) {
|
||||
Minions.LOGGER.error("Could not deserialize configured instruction \"{}\" of minion \"{}\":", name.get(), minion.getGameProfile().getName(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Registry<ValueSupplierType<MinionRuntime>> getArgumentTypeRegistry() {
|
||||
return MinionRegistries.VALUE_SUPPLIER_TYPES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Registry<InstructionType<MinionRuntime>> getInstructionTypeRegistry() {
|
||||
return MinionRegistries.INSTRUCTION_TYPES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Registry<ValueConsumerType<MinionRuntime>> getValueConsumerTypeRegistry() {
|
||||
return MinionRegistries.VALUE_CONSUMER_TYPES;
|
||||
}
|
||||
}
|
||||
@@ -1,42 +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.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, new Identifier(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) {
|
||||
Inventories.readNbt(nbt, stacks);
|
||||
}
|
||||
|
||||
public void writeNbt(NbtCompound nbt) {
|
||||
Inventories.writeNbt(nbt, stacks);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
//code from https://github.com/gnembon/fabric-carpet
|
||||
package io.github.skippyall.minions.minion.fakeplayer;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
|
||||
+70
-42
@@ -1,10 +1,13 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
//partially code from https://github.com/gnembon/fabric-carpet
|
||||
package io.github.skippyall.minions.minion.fakeplayer;
|
||||
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import io.github.skippyall.minions.mixins.EntityAccessor;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.command.argument.EntityAnchorArgumentType;
|
||||
import net.minecraft.entity.Entity;
|
||||
@@ -31,12 +34,12 @@ import net.minecraft.util.math.Vec3d;
|
||||
|
||||
public class EntityPlayerActionPack
|
||||
{
|
||||
private final ServerPlayerEntity player;
|
||||
private final MinionFakePlayer player;
|
||||
|
||||
private final Map<ActionType, Action> actions = new EnumMap<>(ActionType.class);
|
||||
|
||||
private BlockPos currentBlock;
|
||||
private int blockHitDelay;
|
||||
public int blockHitDelay;
|
||||
private boolean isHittingBlock;
|
||||
private float curBlockDamageMP;
|
||||
|
||||
@@ -47,7 +50,7 @@ public class EntityPlayerActionPack
|
||||
|
||||
private int itemUseCooldown;
|
||||
|
||||
public EntityPlayerActionPack(ServerPlayerEntity playerIn)
|
||||
public EntityPlayerActionPack(MinionFakePlayer playerIn)
|
||||
{
|
||||
player = playerIn;
|
||||
stopAll();
|
||||
@@ -68,6 +71,14 @@ public class EntityPlayerActionPack
|
||||
itemUseCooldown = other.itemUseCooldown;
|
||||
}
|
||||
|
||||
public Action getAction(ActionType type) {
|
||||
return actions.get(type);
|
||||
}
|
||||
|
||||
public boolean hasAction(ActionType type) {
|
||||
return actions.containsKey(type);
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack start(ActionType type, Action action)
|
||||
{
|
||||
Action previous = actions.remove(type);
|
||||
@@ -80,6 +91,12 @@ public class EntityPlayerActionPack
|
||||
return this;
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack stop(ActionType type) {
|
||||
Action previous = actions.remove(type);
|
||||
if (previous != null) type.stop(player, previous);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack setSneaking(boolean doSneak)
|
||||
{
|
||||
sneaking = doSneak;
|
||||
@@ -167,12 +184,13 @@ public class EntityPlayerActionPack
|
||||
|
||||
public EntityPlayerActionPack mount(boolean onlyRideables)
|
||||
{
|
||||
|
||||
//test what happens
|
||||
List<Entity> entities;
|
||||
if (onlyRideables)
|
||||
{
|
||||
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
|
||||
{
|
||||
@@ -198,7 +216,7 @@ public class EntityPlayerActionPack
|
||||
if (closest instanceof AbstractHorseEntity && onlyRideables)
|
||||
((AbstractHorseEntity) closest).interactMob(player, Hand.MAIN_HAND);
|
||||
else
|
||||
player.startRiding(closest,true);
|
||||
player.startRiding(closest, !onlyRideables);
|
||||
return this;
|
||||
}
|
||||
public EntityPlayerActionPack dismount()
|
||||
@@ -243,9 +261,13 @@ public class EntityPlayerActionPack
|
||||
if (strafing != 0.0F || player instanceof MinionFakePlayer) {
|
||||
player.sidewaysSpeed = strafing * vel;
|
||||
}
|
||||
|
||||
if(blockHitDelay > 0) {
|
||||
blockHitDelay--;
|
||||
}
|
||||
}
|
||||
|
||||
static HitResult getTarget(ServerPlayerEntity player)
|
||||
public static HitResult getTarget(ServerPlayerEntity player)
|
||||
{
|
||||
double reach = player.interactionManager.isCreative() ? 5 : 4.5f;
|
||||
return Tracer.rayTrace(player, 1, reach, false);
|
||||
@@ -271,14 +293,14 @@ public class EntityPlayerActionPack
|
||||
else // one slot
|
||||
{
|
||||
if (selectedSlot == -1)
|
||||
selectedSlot = inv.selectedSlot;
|
||||
selectedSlot = inv.getSelectedSlot();
|
||||
dropItemFromSlot(selectedSlot, dropAll);
|
||||
}
|
||||
}
|
||||
|
||||
public void setSlot(int slot)
|
||||
{
|
||||
player.getInventory().selectedSlot = slot-1;
|
||||
player.getInventory().setSelectedSlot(slot-1);
|
||||
player.networkHandler.sendPacket(new UpdateSelectedSlotS2CPacket(slot-1));
|
||||
}
|
||||
|
||||
@@ -287,9 +309,9 @@ public class EntityPlayerActionPack
|
||||
USE(true)
|
||||
{
|
||||
@Override
|
||||
boolean execute(ServerPlayerEntity player, Action action)
|
||||
boolean execute(MinionFakePlayer player, Action action)
|
||||
{
|
||||
EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack();
|
||||
EntityPlayerActionPack ap = player.getMinionActionPack();
|
||||
if (ap.itemUseCooldown > 0)
|
||||
{
|
||||
ap.itemUseCooldown--;
|
||||
@@ -307,16 +329,16 @@ public class EntityPlayerActionPack
|
||||
case BLOCK:
|
||||
{
|
||||
player.updateLastActionTime();
|
||||
ServerWorld world = player.getServerWorld();
|
||||
ServerWorld world = player.getWorld();
|
||||
BlockHitResult blockHit = (BlockHitResult) hit;
|
||||
BlockPos pos = blockHit.getBlockPos();
|
||||
Direction side = blockHit.getSide();
|
||||
if (pos.getY() < player.getWorld().getTopY() - (side == Direction.UP ? 1 : 0) && world.canPlayerModifyAt(player, pos))
|
||||
if (pos.getY() < player.getWorld().getTopYInclusive() - (side == Direction.UP ? 1 : 0) && world.canEntityModifyAt(player, pos))
|
||||
{
|
||||
ActionResult result = player.interactionManager.interactBlock(player, world, player.getStackInHand(hand), hand, blockHit);
|
||||
if (result.isAccepted())
|
||||
if (result instanceof ActionResult.Success success)
|
||||
{
|
||||
if (result.shouldSwingHand()) player.swingHand(hand);
|
||||
if (success.swingSource() == ActionResult.SwingSource.SERVER) player.swingHand(hand);
|
||||
ap.itemUseCooldown = 3;
|
||||
return true;
|
||||
}
|
||||
@@ -356,21 +378,21 @@ public class EntityPlayerActionPack
|
||||
}
|
||||
|
||||
@Override
|
||||
void inactiveTick(ServerPlayerEntity player, Action action)
|
||||
void inactiveTick(MinionFakePlayer player, Action action)
|
||||
{
|
||||
EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack();
|
||||
EntityPlayerActionPack ap = player.getMinionActionPack();
|
||||
ap.itemUseCooldown = 0;
|
||||
player.stopUsingItem();
|
||||
}
|
||||
},
|
||||
ATTACK(true) {
|
||||
@Override
|
||||
boolean execute(ServerPlayerEntity player, Action action) {
|
||||
boolean execute(MinionFakePlayer player, Action action) {
|
||||
HitResult hit = getTarget(player);
|
||||
switch (hit.getType()) {
|
||||
case ENTITY: {
|
||||
EntityHitResult entityHit = (EntityHitResult) hit;
|
||||
if (!action.isContinuous)
|
||||
if (!action.isContinuous || action.first)
|
||||
{
|
||||
player.attack(entityHit.getEntity());
|
||||
player.swingHand(Hand.MAIN_HAND);
|
||||
@@ -380,10 +402,9 @@ public class EntityPlayerActionPack
|
||||
return true;
|
||||
}
|
||||
case BLOCK: {
|
||||
EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack();
|
||||
EntityPlayerActionPack ap = player.getMinionActionPack();
|
||||
if (ap.blockHitDelay > 0)
|
||||
{
|
||||
ap.blockHitDelay--;
|
||||
return false;
|
||||
}
|
||||
BlockHitResult blockHit = (BlockHitResult) hit;
|
||||
@@ -399,7 +420,7 @@ public class EntityPlayerActionPack
|
||||
boolean blockBroken = false;
|
||||
if (player.interactionManager.getGameMode().isCreative())
|
||||
{
|
||||
player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.getWorld().getTopY(), -1);
|
||||
player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.getWorld().getTopYInclusive(), -1);
|
||||
ap.blockHitDelay = 5;
|
||||
blockBroken = true;
|
||||
}
|
||||
@@ -407,9 +428,9 @@ public class EntityPlayerActionPack
|
||||
{
|
||||
if (ap.currentBlock != null)
|
||||
{
|
||||
player.interactionManager.processBlockBreakingAction(ap.currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, side, player.getWorld().getTopY(), -1);
|
||||
player.interactionManager.processBlockBreakingAction(ap.currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, side, player.getWorld().getTopYInclusive(), -1);
|
||||
}
|
||||
player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.getWorld().getTopY(), -1);
|
||||
player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.getWorld().getTopYInclusive(), -1);
|
||||
boolean notAir = !state.isAir();
|
||||
if (notAir && ap.curBlockDamageMP == 0)
|
||||
{
|
||||
@@ -432,7 +453,7 @@ public class EntityPlayerActionPack
|
||||
ap.curBlockDamageMP += state.calcBlockBreakingDelta(player, player.getWorld(), pos);
|
||||
if (ap.curBlockDamageMP >= 1)
|
||||
{
|
||||
player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.STOP_DESTROY_BLOCK, side, player.getWorld().getTopY(), -1);
|
||||
player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.STOP_DESTROY_BLOCK, side, player.getWorld().getTopYInclusive(), -1);
|
||||
ap.currentBlock = null;
|
||||
ap.blockHitDelay = 5;
|
||||
blockBroken = true;
|
||||
@@ -449,19 +470,19 @@ public class EntityPlayerActionPack
|
||||
}
|
||||
|
||||
@Override
|
||||
void inactiveTick(ServerPlayerEntity player, Action action)
|
||||
void inactiveTick(MinionFakePlayer player, Action action)
|
||||
{
|
||||
EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack();
|
||||
EntityPlayerActionPack ap = player.getMinionActionPack();
|
||||
if (ap.currentBlock == null) return;
|
||||
player.getWorld().setBlockBreakingInfo(-1, ap.currentBlock, -1);
|
||||
player.interactionManager.processBlockBreakingAction(ap.currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.getWorld().getTopY(), -1);
|
||||
player.interactionManager.processBlockBreakingAction(ap.currentBlock, PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.getWorld().getTopYInclusive(), -1);
|
||||
ap.currentBlock = null;
|
||||
}
|
||||
},
|
||||
JUMP(true)
|
||||
{
|
||||
@Override
|
||||
boolean execute(ServerPlayerEntity player, Action action)
|
||||
boolean execute(MinionFakePlayer player, Action action)
|
||||
{
|
||||
if (action.limit == 1)
|
||||
{
|
||||
@@ -475,7 +496,7 @@ public class EntityPlayerActionPack
|
||||
}
|
||||
|
||||
@Override
|
||||
void inactiveTick(ServerPlayerEntity player, Action action)
|
||||
void inactiveTick(MinionFakePlayer player, Action action)
|
||||
{
|
||||
player.setJumping(false);
|
||||
}
|
||||
@@ -483,7 +504,7 @@ public class EntityPlayerActionPack
|
||||
DROP_ITEM(true)
|
||||
{
|
||||
@Override
|
||||
boolean execute(ServerPlayerEntity player, Action action)
|
||||
boolean execute(MinionFakePlayer player, Action action)
|
||||
{
|
||||
player.updateLastActionTime();
|
||||
player.dropSelectedItem(false); // dropSelectedItem
|
||||
@@ -493,7 +514,7 @@ public class EntityPlayerActionPack
|
||||
DROP_STACK(true)
|
||||
{
|
||||
@Override
|
||||
boolean execute(ServerPlayerEntity player, Action action)
|
||||
boolean execute(MinionFakePlayer player, Action action)
|
||||
{
|
||||
player.updateLastActionTime();
|
||||
player.dropSelectedItem(true); // dropSelectedItem
|
||||
@@ -503,7 +524,7 @@ public class EntityPlayerActionPack
|
||||
SWAP_HANDS(true)
|
||||
{
|
||||
@Override
|
||||
boolean execute(ServerPlayerEntity player, Action action)
|
||||
boolean execute(MinionFakePlayer player, Action action)
|
||||
{
|
||||
player.updateLastActionTime();
|
||||
ItemStack itemStack_1 = player.getStackInHand(Hand.OFF_HAND);
|
||||
@@ -520,10 +541,10 @@ public class EntityPlayerActionPack
|
||||
this.preventSpectator = preventSpectator;
|
||||
}
|
||||
|
||||
void start(ServerPlayerEntity player, Action action) {}
|
||||
abstract boolean execute(ServerPlayerEntity player, Action action);
|
||||
void inactiveTick(ServerPlayerEntity player, Action action) {}
|
||||
void stop(ServerPlayerEntity player, Action action)
|
||||
void start(MinionFakePlayer player, Action action) {}
|
||||
abstract boolean execute(MinionFakePlayer player, Action action);
|
||||
void inactiveTick(MinionFakePlayer player, Action action) {}
|
||||
void stop(MinionFakePlayer player, Action action)
|
||||
{
|
||||
inactiveTick(player, action);
|
||||
}
|
||||
@@ -538,8 +559,9 @@ public class EntityPlayerActionPack
|
||||
private int count;
|
||||
private int next;
|
||||
private final boolean isContinuous;
|
||||
boolean first = true;
|
||||
|
||||
private Action(int limit, int interval, int offset, boolean continuous)
|
||||
private Action(int limit, int interval, int offset, boolean continuous, boolean first)
|
||||
{
|
||||
this.limit = limit;
|
||||
this.interval = interval;
|
||||
@@ -550,22 +572,27 @@ public class EntityPlayerActionPack
|
||||
|
||||
public static Action once()
|
||||
{
|
||||
return new Action(1, 1, 0, false);
|
||||
return new Action(1, 1, 0, false, false);
|
||||
}
|
||||
|
||||
public static Action startContinuous()
|
||||
{
|
||||
return new Action(-1, 1, 0, true, true);
|
||||
}
|
||||
|
||||
public static Action continuous()
|
||||
{
|
||||
return new Action(-1, 1, 0, true);
|
||||
return new Action(-1, 1, 0, true, false);
|
||||
}
|
||||
|
||||
public static Action interval(int interval)
|
||||
{
|
||||
return new Action(-1, interval, 0, false);
|
||||
return new Action(-1, interval, 0, false, false);
|
||||
}
|
||||
|
||||
public static Action interval(int interval, int offset)
|
||||
{
|
||||
return new Action(-1, interval, offset, false);
|
||||
return new Action(-1, interval, offset, false, false);
|
||||
}
|
||||
|
||||
Boolean tick(EntityPlayerActionPack actionPack, ActionType type)
|
||||
@@ -596,6 +623,7 @@ public class EntityPlayerActionPack
|
||||
return cancel;
|
||||
}
|
||||
next = interval;
|
||||
first = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
+4
-5
@@ -1,10 +1,11 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
//code from https://github.com/gnembon/fabric-carpet
|
||||
package io.github.skippyall.minions.minion.fakeplayer;
|
||||
|
||||
import io.netty.channel.embedded.EmbeddedChannel;
|
||||
import net.minecraft.network.ClientConnection;
|
||||
import net.minecraft.network.NetworkSide;
|
||||
import net.minecraft.network.state.NetworkState;
|
||||
import net.minecraft.network.listener.PacketListener;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
public class FakeClientConnection extends ClientConnection {
|
||||
public FakeClientConnection(NetworkSide p)
|
||||
@@ -22,7 +23,6 @@ public class FakeClientConnection extends ClientConnection {
|
||||
|
||||
@Override
|
||||
public void handleDisconnection() {
|
||||
getPacketListener().onDisconnected(getDisconnectReason()==null ? Text.literal("Disconnected"): getDisconnectReason());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -31,7 +31,6 @@ public class FakeClientConnection extends ClientConnection {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPacketListener(PacketListener packetListener) {
|
||||
|
||||
public <T extends PacketListener> void transitionInbound(NetworkState<T> state, T packetListener) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
//partially code from https://github.com/gnembon/fabric-carpet
|
||||
package io.github.skippyall.minions.minion.fakeplayer;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.authlib.properties.PropertyMap;
|
||||
import io.github.skippyall.minions.registration.MinionConfigOptions;
|
||||
import io.github.skippyall.minions.registration.MinionItems;
|
||||
import io.github.skippyall.minions.minion.MinionListener;
|
||||
import io.github.skippyall.minions.minion.MinionData;
|
||||
import io.github.skippyall.minions.gui.MinionGui;
|
||||
import io.github.skippyall.minions.minion.MinionRuntime;
|
||||
import io.github.skippyall.minions.minion.MinionItem;
|
||||
import io.github.skippyall.minions.minion.MinionPersistentState;
|
||||
import io.github.skippyall.minions.minion.MinionProfileUtils;
|
||||
import io.github.skippyall.minions.module.ModuleInventory;
|
||||
import io.github.skippyall.minions.registration.SpecialAbilities;
|
||||
import io.github.skippyall.minions.listener.SerializableListenerManager;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EquipmentSlot;
|
||||
import net.minecraft.entity.ItemEntity;
|
||||
import net.minecraft.entity.attribute.EntityAttributes;
|
||||
import net.minecraft.entity.damage.DamageSource;
|
||||
import net.minecraft.entity.player.HungerManager;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.network.DisconnectionInfo;
|
||||
import net.minecraft.network.NetworkSide;
|
||||
import net.minecraft.network.packet.c2s.common.SyncedClientOptions;
|
||||
import net.minecraft.network.packet.c2s.play.ClientStatusC2SPacket;
|
||||
import net.minecraft.network.packet.s2c.play.EntityPositionSyncS2CPacket;
|
||||
import net.minecraft.network.packet.s2c.play.EntitySetHeadYawS2CPacket;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.ServerTask;
|
||||
import net.minecraft.server.network.ConnectedClientData;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.storage.ReadView;
|
||||
import net.minecraft.storage.WriteView;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.text.TranslatableTextContent;
|
||||
import net.minecraft.util.ActionResult;
|
||||
import net.minecraft.util.Hand;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Vec2f;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.world.GameMode;
|
||||
import net.minecraft.world.TeleportTarget;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class MinionFakePlayer extends ServerPlayerEntity {
|
||||
public Runnable fixStartingPosition = () -> {};
|
||||
|
||||
private EntityPlayerActionPack actionPack;
|
||||
|
||||
private final ModuleInventory moduleInventory = new ModuleInventory(this);
|
||||
private final MinionRuntime instructionManager = new MinionRuntime(this);
|
||||
|
||||
public static void spawnMinion(MinionData data, ServerWorld level, @Nullable Vec3d pos, @Nullable Vec2f rot) {
|
||||
spawnMinion(data, level, pos, rot, false);
|
||||
}
|
||||
|
||||
public static void spawnMinion(MinionData data, ServerWorld level, @Nullable Vec3d pos, @Nullable Vec2f rot, boolean force) {
|
||||
if(!data.isSpawned() || force) {
|
||||
MinecraftServer server = level.getServer();
|
||||
|
||||
PropertyMap skin = data.skin().orElse(null);
|
||||
|
||||
GameProfile profile = MinionProfileUtils.makeNewMinionProfile(data.uuid(), data.name(), skin);
|
||||
server.send(server.createTask(() -> doSpawn(data, profile, server, level, pos, rot)));
|
||||
}
|
||||
}
|
||||
|
||||
private static void doSpawn(MinionData data, GameProfile profile, MinecraftServer server, ServerWorld level, @Nullable Vec3d pos, @Nullable Vec2f rot) {
|
||||
MinionFakePlayer instance = new MinionFakePlayer(server, level, profile, SyncedClientOptions.createDefault());
|
||||
MinionPersistentState.get(server).updateMinionData(data.withSpawned(true));
|
||||
|
||||
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());
|
||||
if(pos != null && rot != null) {
|
||||
instance.teleport(level, pos.x, pos.y, pos.z, Set.of(), rot.x, rot.y, true);
|
||||
}
|
||||
instance.setVelocity(0,0,0);
|
||||
instance.setHealth(20.0F);
|
||||
instance.unsetRemoved();
|
||||
instance.getAttributeInstance(EntityAttributes.STEP_HEIGHT).setBaseValue(0.6F);
|
||||
instance.interactionManager.changeGameMode(GameMode.SURVIVAL);
|
||||
server.getPlayerManager().sendToDimension(new EntitySetHeadYawS2CPacket(instance, (byte) (instance.headYaw * 256 / 360)), level.getRegistryKey());
|
||||
server.getPlayerManager().sendToDimension(EntityPositionSyncS2CPacket.create(instance), level.getRegistryKey());
|
||||
instance.getWorld().getChunkManager().updatePosition(instance);
|
||||
instance.dataTracker.set(PLAYER_MODEL_PARTS, (byte) 0x7f); // show all model layers (incl. capes)
|
||||
instance.getAbilities().flying = false;
|
||||
|
||||
instance.listeners().forEach(listener -> listener.onMinionSpawn(instance));
|
||||
}
|
||||
|
||||
public static MinionFakePlayer respawnFake(MinecraftServer server, ServerWorld level, GameProfile profile, SyncedClientOptions cli)
|
||||
{
|
||||
return new MinionFakePlayer(server, level, profile, cli);
|
||||
}
|
||||
|
||||
private MinionFakePlayer(MinecraftServer server, ServerWorld worldIn, GameProfile profile, SyncedClientOptions cli)
|
||||
{
|
||||
super(server, worldIn, profile, cli);
|
||||
actionPack = new EntityPlayerActionPack(this);
|
||||
}
|
||||
|
||||
public ModuleInventory getModuleInventory() {
|
||||
return moduleInventory;
|
||||
}
|
||||
|
||||
public EntityPlayerActionPack getMinionActionPack() {
|
||||
return actionPack;
|
||||
}
|
||||
|
||||
public MinionRuntime getInstructionManager() {
|
||||
return instructionManager;
|
||||
}
|
||||
|
||||
public MinionData getData() {
|
||||
return MinionPersistentState.get(getServer()).getMinionData(getUuid());
|
||||
}
|
||||
|
||||
public SerializableListenerManager<MinionListener> listeners() {
|
||||
return getData().listeners();
|
||||
}
|
||||
|
||||
public void addMinionListener(MinionListener listener) {
|
||||
listeners().addListener(listener);
|
||||
}
|
||||
|
||||
public void removeMinionListener(MinionListener listener) {
|
||||
listeners().removeListener(listener);
|
||||
}
|
||||
|
||||
public void forEachMinionListener(Consumer<MinionListener> listenerConsumer) {
|
||||
listeners().forEach(listenerConsumer);
|
||||
}
|
||||
|
||||
public boolean canSpawnMobs() {
|
||||
return moduleInventory.hasAbility(SpecialAbilities.MOB_SPAWNING) || getData().config().getOption(MinionConfigOptions.spawnAndDespawnMobs);
|
||||
}
|
||||
|
||||
public boolean canDespawnMobs() {
|
||||
return canSpawnMobs();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActionResult interact(PlayerEntity player, Hand hand) {
|
||||
if(player instanceof ServerPlayerEntity spe) {
|
||||
MinionGui.openInventory(spe, this);
|
||||
}
|
||||
return ActionResult.CONSUME;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActionResult interactAt(PlayerEntity player, Vec3d hitPos, Hand hand) {
|
||||
return interact(player, hand);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEquipStack(final EquipmentSlot slot, final ItemStack previous, final ItemStack stack)
|
||||
{
|
||||
if (!isUsingItem()) super.onEquipStack(slot, previous, stack);
|
||||
}
|
||||
|
||||
public void kill(Text reason)
|
||||
{
|
||||
listeners().forEach(listener -> listener.onMinionRemove(this));
|
||||
|
||||
shakeOff();
|
||||
|
||||
if (reason.getContent() instanceof TranslatableTextContent text && text.getKey().equals("multiplayer.disconnect.duplicate_login")) {
|
||||
this.networkHandler.onDisconnected(new DisconnectionInfo(reason));
|
||||
} else {
|
||||
this.getServer().send(new ServerTask(this.getServer().getTicks(), () -> {
|
||||
this.networkHandler.onDisconnected(new DisconnectionInfo(reason));
|
||||
}));
|
||||
}
|
||||
|
||||
MinionPersistentState.get(getServer()).updateMinionData(getData().withSpawned(false));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick()
|
||||
{
|
||||
actionPack.onUpdate();
|
||||
if (this.getServer().getTicks() % 10 == 0)
|
||||
{
|
||||
this.networkHandler.syncWithPlayerPosition();
|
||||
this.getWorld().getChunkManager().updatePosition(this);
|
||||
}
|
||||
try
|
||||
{
|
||||
super.tick();
|
||||
this.playerTick();
|
||||
instructionManager.tick();
|
||||
}
|
||||
catch (NullPointerException ignored)
|
||||
{
|
||||
// happens with that paper port thingy - not sure what that would fix, but hey
|
||||
// the game not gonna crash violently.
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void shakeOff()
|
||||
{
|
||||
if (getVehicle() instanceof PlayerEntity) stopRiding();
|
||||
for (Entity passenger : getPassengersDeep())
|
||||
{
|
||||
if (passenger instanceof PlayerEntity) passenger.stopRiding();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeath(DamageSource cause)
|
||||
{
|
||||
shakeOff();
|
||||
super.onDeath(cause);
|
||||
setHealth(20);
|
||||
this.hungerManager = new HungerManager();
|
||||
kill(this.getDamageTracker().getDeathMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIp()
|
||||
{
|
||||
return "127.0.0.1";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean allowsServerListing() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void fall(double y, boolean onGround, BlockState state, BlockPos pos) {
|
||||
handleFall(0.0, y, 0.0, onGround);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerPlayerEntity teleportTo(TeleportTarget target)
|
||||
{
|
||||
super.teleportTo(target);
|
||||
if (notInAnyWorld) {
|
||||
ClientStatusC2SPacket p = new ClientStatusC2SPacket(ClientStatusC2SPacket.Mode.PERFORM_RESPAWN);
|
||||
networkHandler.onClientStatus(p);
|
||||
}
|
||||
|
||||
// If above branch was taken, *this* has been removed and replaced, the new instance has been set
|
||||
// on 'our' connection (which is now theirs, but we still have a ref).
|
||||
if (networkHandler.player.isInTeleportationState()) {
|
||||
networkHandler.player.onTeleportationDone();
|
||||
}
|
||||
return networkHandler.player;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drop(ServerWorld world, DamageSource damageSource) {
|
||||
super.drop(world, damageSource);
|
||||
ItemEntity entity = dropStack(world, toItemStack(getServer()));
|
||||
if (entity != null) {
|
||||
entity.setNeverDespawn();
|
||||
}
|
||||
}
|
||||
|
||||
private ItemStack toItemStack(MinecraftServer server) {
|
||||
ItemStack stack = new ItemStack(MinionItems.MINION_ITEM);
|
||||
MinionItem.setData(server, getData(), stack);
|
||||
return stack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeCustomData(WriteView view) {
|
||||
super.writeCustomData(view);
|
||||
moduleInventory.writeData(view.get("modules"));
|
||||
instructionManager.save(view.get("instructionManager"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readCustomData(ReadView view) {
|
||||
super.readCustomData(view);
|
||||
moduleInventory.readData(view.getReadView("modules"));
|
||||
instructionManager.load(view.getReadView("instructionManager"));
|
||||
}
|
||||
}
|
||||
+7
-5
@@ -1,5 +1,7 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
//code from https://github.com/gnembon/fabric-carpet
|
||||
package io.github.skippyall.minions.minion.fakeplayer;
|
||||
|
||||
import net.minecraft.entity.player.PlayerPosition;
|
||||
import net.minecraft.network.ClientConnection;
|
||||
import net.minecraft.network.packet.Packet;
|
||||
import net.minecraft.network.packet.s2c.play.PositionFlag;
|
||||
@@ -33,12 +35,12 @@ public class NetHandlerPlayServerFake extends ServerPlayNetworkHandler
|
||||
}
|
||||
|
||||
@Override
|
||||
public void requestTeleport(double d, double e, double f, float g, float h, Set<PositionFlag> set)
|
||||
public void requestTeleport(PlayerPosition pos, Set<PositionFlag> set)
|
||||
{
|
||||
super.requestTeleport(d, e, f, g, h, set);
|
||||
if (player.getServerWorld().getPlayerByUuid(player.getUuid()) != null) {
|
||||
super.requestTeleport(pos, set);
|
||||
if (player.getWorld().getPlayerByUuid(player.getUuid()) != null) {
|
||||
syncWithPlayerPosition();
|
||||
player.getServerWorld().getChunkManager().updatePosition(player);
|
||||
player.getWorld().getChunkManager().updatePosition(player);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
package io.github.skippyall.minions.fakeplayer;
|
||||
//code from https://github.com/gnembon/fabric-carpet
|
||||
package io.github.skippyall.minions.minion.fakeplayer;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
@@ -0,0 +1,107 @@
|
||||
package io.github.skippyall.minions.minion.skin;
|
||||
|
||||
import com.mojang.authlib.properties.Property;
|
||||
import com.mojang.authlib.properties.PropertyMap;
|
||||
import io.github.skippyall.minions.Minions;
|
||||
import net.minecraft.dialog.AfterAction;
|
||||
import net.minecraft.dialog.DialogActionButtonData;
|
||||
import net.minecraft.dialog.DialogButtonData;
|
||||
import net.minecraft.dialog.DialogCommonData;
|
||||
import net.minecraft.dialog.action.DynamicCustomDialogAction;
|
||||
import net.minecraft.dialog.input.TextInputControl;
|
||||
import net.minecraft.dialog.type.Dialog;
|
||||
import net.minecraft.dialog.type.DialogInput;
|
||||
import net.minecraft.dialog.type.NoticeDialog;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.registry.RegistryKey;
|
||||
import net.minecraft.registry.RegistryKeys;
|
||||
import net.minecraft.registry.entry.RegistryEntry;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Identifier;
|
||||
|
||||
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 static final RegistryKey<Dialog> DIALOG = RegistryKey.of(RegistryKeys.DIALOG, Identifier.of(Minions.MOD_ID, "base_64_input"));
|
||||
public static final Identifier CUSTOM_DIALOG_ACTION = Identifier.of(Minions.MOD_ID, "base_64_submit");
|
||||
|
||||
private static long dialogIdCounter = 0;
|
||||
private static Map<Long, CompletableFuture<Optional<PropertyMap>>> futures = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<PropertyMap>> openSkinMenu(ServerPlayerEntity player) {
|
||||
dialogIdCounter++;
|
||||
player.openDialog(getDialog());
|
||||
CompletableFuture<Optional<PropertyMap>> future = new CompletableFuture<>();
|
||||
futures.put(dialogIdCounter, future);
|
||||
return future;
|
||||
}
|
||||
|
||||
public static void onCustomDialogAction(Optional<NbtElement> element) {
|
||||
if(element.isPresent() && element.get() instanceof NbtCompound compound) {
|
||||
Optional<Long> id = compound.getLong("dialog_id");
|
||||
Optional<String> base64 = compound.getString("base_64");
|
||||
if(id.isPresent() && base64.isPresent() && !base64.get().isBlank()) {
|
||||
if(futures.containsKey(id.get())) {
|
||||
PropertyMap map = new PropertyMap();
|
||||
map.put("textures", new Property("textures", base64.get().strip()));
|
||||
|
||||
futures.get(id.get()).complete(Optional.of(map));
|
||||
futures.remove(id.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static RegistryEntry<Dialog> getDialog() {
|
||||
NbtCompound additionalData = new NbtCompound();
|
||||
additionalData.putLong("dialog_id", dialogIdCounter);
|
||||
return RegistryEntry.of(
|
||||
new NoticeDialog(
|
||||
new DialogCommonData(
|
||||
Text.translatable("minions.gui.look.skin.base64.title"),
|
||||
Optional.empty(),
|
||||
true,
|
||||
false,
|
||||
AfterAction.CLOSE,
|
||||
List.of(),
|
||||
List.of(
|
||||
new DialogInput("base_64", new TextInputControl(
|
||||
200,
|
||||
Text.empty(),
|
||||
false,
|
||||
"",
|
||||
2000,
|
||||
Optional.empty()
|
||||
))
|
||||
)
|
||||
),
|
||||
new DialogActionButtonData(
|
||||
new DialogButtonData(
|
||||
Text.translatable("gui.ok"),
|
||||
150
|
||||
),
|
||||
Optional.of(
|
||||
new DynamicCustomDialogAction(
|
||||
CUSTOM_DIALOG_ACTION,
|
||||
Optional.of(
|
||||
additionalData
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Text getDisplayName() {
|
||||
return Text.translatable("minions.gui.look.skin.base64");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package io.github.skippyall.minions.minion.skin;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.authlib.properties.PropertyMap;
|
||||
import io.github.skippyall.minions.gui.input.TextInput;
|
||||
import net.minecraft.block.entity.SkullBlockEntity;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class NameSkinProvider implements SkinProvider {
|
||||
@Override
|
||||
public CompletableFuture<Optional<PropertyMap>> openSkinMenu(ServerPlayerEntity player) {
|
||||
return TextInput.inputString(player, Text.translatable("minions.gui.look.skin.name.title"), "")
|
||||
.thenCompose(SkullBlockEntity::fetchProfileByName)
|
||||
.thenApply(gameProfile -> gameProfile.map(GameProfile::getProperties));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Text getDisplayName() {
|
||||
return Text.translatable("minions.gui.look.skin.name");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package io.github.skippyall.minions.minion.skin;
|
||||
|
||||
import com.mojang.authlib.properties.PropertyMap;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public interface SkinProvider {
|
||||
CompletableFuture<Optional<PropertyMap>> openSkinMenu(ServerPlayerEntity player);
|
||||
|
||||
Text getDisplayName();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package io.github.skippyall.minions.minion.skin;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.authlib.properties.PropertyMap;
|
||||
import io.github.skippyall.minions.gui.input.TextInput;
|
||||
import net.minecraft.block.entity.SkullBlockEntity;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class UUIDSkinProvider implements SkinProvider {
|
||||
@Override
|
||||
public CompletableFuture<Optional<PropertyMap>> openSkinMenu(ServerPlayerEntity player) {
|
||||
return TextInput.inputString(player, Text.translatable("minions.gui.look.skin.uuid.title"), "")
|
||||
.thenCompose(uuidString -> SkullBlockEntity.fetchProfileByUuid(UUID.fromString(uuidString)))
|
||||
.thenApply(gameProfile -> gameProfile.map(GameProfile::getProperties));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Text getDisplayName() {
|
||||
return Text.translatable("minions.gui.look.skin.uuid");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package io.github.skippyall.minions.mixinhelper;
|
||||
|
||||
import net.minecraft.entity.Entity;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class EntityViewMixinHelper {
|
||||
public static final ThreadLocal<Predicate<Entity>> ADDITIONAL_PREDICATE = ThreadLocal.withInitial(() -> entity -> true);
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package io.github.skippyall.minions.mixinhelper.antimobcap;
|
||||
|
||||
public interface ChunkLevelManager$DistanceFromNearestPlayerTrackerAccessor {
|
||||
void minions$markAsMinionless();
|
||||
void minions$markAsTarget();
|
||||
int minions$getTickedChunkCount();
|
||||
|
||||
boolean minions$isRealPlayerInChunk(long chunkPos);
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package io.github.skippyall.minions.mixinhelper.antimobcap;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.ObjectSet;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ChunkLevelManager;
|
||||
|
||||
public interface ChunkLevelManagerAccessor {
|
||||
ObjectSet<ServerPlayerEntity> minions$getPlayers(long chunkpos);
|
||||
|
||||
ChunkLevelManager.DistanceFromNearestPlayerTracker minions$getMinionless();
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package io.github.skippyall.minions.mixins;
|
||||
|
||||
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
|
||||
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectSet;
|
||||
import net.minecraft.server.world.ChunkLevelManager;
|
||||
import org.slf4j.Logger;
|
||||
import org.spongepowered.asm.mixin.Final;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Shadow;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
|
||||
@Mixin(value = ChunkLevelManager.class)
|
||||
public class ChunkTicketManagerFixMixin {
|
||||
@Shadow
|
||||
@Final
|
||||
private static Logger LOGGER;
|
||||
|
||||
@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) {
|
||||
if (instance != null) {
|
||||
return original.call(instance, o);
|
||||
}
|
||||
|
||||
LOGGER.error("Prevented NPE in handleChunkLeave");
|
||||
|
||||
return false;//Unused
|
||||
}
|
||||
|
||||
@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) {
|
||||
if (instance != null) {
|
||||
return original.call(instance);
|
||||
}
|
||||
|
||||
LOGGER.error("Prevented NPE in handleChunkLeave");
|
||||
|
||||
return true;//Unused
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//code from https://github.com/gnembon/fabric-carpet
|
||||
package io.github.skippyall.minions.mixins;
|
||||
|
||||
import io.github.skippyall.minions.fakeplayer.ClientConnectionInterface;
|
||||
import io.github.skippyall.minions.minion.fakeplayer.ClientConnectionInterface;
|
||||
import io.netty.channel.Channel;
|
||||
import net.minecraft.network.ClientConnection;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user