Migrate the Carpet codebase to Mojang Mappings
This commit is contained in:
346 files changed
+8353
-8492
No files matched your search
@@ -1,14 +1,14 @@
|
||||
package carpet.script;
|
||||
|
||||
import carpet.script.value.Value;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.BlockPos;
|
||||
|
||||
public class CarpetContext extends Context
|
||||
{
|
||||
public ServerCommandSource s;
|
||||
public CommandSourceStack s;
|
||||
public final BlockPos origin;
|
||||
public CarpetContext(ScriptHost host, ServerCommandSource source, BlockPos origin)
|
||||
public CarpetContext(ScriptHost host, CommandSourceStack source, BlockPos origin)
|
||||
{
|
||||
super(host);
|
||||
s = source;
|
||||
|
||||
@@ -21,34 +21,6 @@ import carpet.settings.ParsedRule;
|
||||
import carpet.utils.CarpetProfiler;
|
||||
import carpet.utils.Messenger;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.entity.EntityType;
|
||||
import net.minecraft.entity.LivingEntity;
|
||||
import net.minecraft.entity.TntEntity;
|
||||
import net.minecraft.entity.damage.DamageSource;
|
||||
import net.minecraft.entity.passive.MerchantEntity;
|
||||
import net.minecraft.entity.projectile.ProjectileEntity;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.stat.Stat;
|
||||
import net.minecraft.stat.Stats;
|
||||
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.ChunkPos;
|
||||
import net.minecraft.util.math.Direction;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
import net.minecraft.util.registry.RegistryKey;
|
||||
import net.minecraft.village.Merchant;
|
||||
import net.minecraft.village.TradeOffer;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.explosion.Explosion;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
@@ -67,6 +39,33 @@ import java.util.function.Supplier;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.stats.Stat;
|
||||
import net.minecraft.stats.Stats;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.item.PrimedTnt;
|
||||
import net.minecraft.world.entity.npc.AbstractVillager;
|
||||
import net.minecraft.world.entity.projectile.Projectile;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.trading.Merchant;
|
||||
import net.minecraft.world.item.trading.MerchantOffer;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.Explosion;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class CarpetEventServer
|
||||
{
|
||||
@@ -101,7 +100,7 @@ public class CarpetEventServer
|
||||
* @param sender - entity command source
|
||||
* @param runtimeArgs = options
|
||||
*/
|
||||
public CallbackResult execute(ServerCommandSource sender, List<Value> runtimeArgs)
|
||||
public CallbackResult execute(CommandSourceStack sender, List<Value> runtimeArgs)
|
||||
{
|
||||
if (!this.parametrizedArgs.isEmpty())
|
||||
{
|
||||
@@ -110,7 +109,7 @@ public class CarpetEventServer
|
||||
}
|
||||
if (CarpetServer.scriptServer == null) return CallbackResult.FAIL; // already stopped
|
||||
return CarpetServer.scriptServer.events.runEventCall(
|
||||
sender.withLevel(CarpetSettings.runPermissionLevel),
|
||||
sender.withPermission(CarpetSettings.runPermissionLevel),
|
||||
host, optionalTarget, function, runtimeArgs);
|
||||
}
|
||||
|
||||
@@ -120,10 +119,10 @@ public class CarpetEventServer
|
||||
* @param optionalRecipient - optional target player argument
|
||||
* @param runtimeArgs = options
|
||||
*/
|
||||
public CallbackResult signal(ServerCommandSource sender, ServerPlayerEntity optionalRecipient, List<Value> runtimeArgs)
|
||||
public CallbackResult signal(CommandSourceStack sender, ServerPlayer optionalRecipient, List<Value> runtimeArgs)
|
||||
{
|
||||
// recipent of the call doesn't match the handlingHost
|
||||
if (optionalRecipient != null && !optionalRecipient.getEntityName().equals(optionalTarget))
|
||||
if (optionalRecipient != null && !optionalRecipient.getScoreboardName().equals(optionalTarget))
|
||||
return CallbackResult.FAIL;
|
||||
return execute(sender, runtimeArgs);
|
||||
}
|
||||
@@ -218,14 +217,14 @@ public class CarpetEventServer
|
||||
* @param argumentSupplier
|
||||
* @param cmdSourceSupplier
|
||||
*/
|
||||
public void call(Supplier<List<Value>> argumentSupplier, Supplier<ServerCommandSource> cmdSourceSupplier)
|
||||
public void call(Supplier<List<Value>> argumentSupplier, Supplier<CommandSourceStack> cmdSourceSupplier)
|
||||
{
|
||||
if (callList.size() > 0 && CarpetServer.scriptServer != null)
|
||||
{
|
||||
CarpetServer.scriptServer.events.handleEvents.runIfEnabled( () -> {
|
||||
CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet events", CarpetProfiler.TYPE.GENERAL);
|
||||
List<Value> argv = argumentSupplier.get(); // empty for onTickDone
|
||||
ServerCommandSource source;
|
||||
CommandSourceStack source;
|
||||
try
|
||||
{
|
||||
source = cmdSourceSupplier.get();
|
||||
@@ -234,7 +233,7 @@ public class CarpetEventServer
|
||||
{
|
||||
return;
|
||||
}
|
||||
String nameCheck = perPlayerDistribution ? source.getName() : null;
|
||||
String nameCheck = perPlayerDistribution ? source.getTextName() : null;
|
||||
assert argv.size() == reqArgs;
|
||||
try
|
||||
{
|
||||
@@ -261,7 +260,7 @@ public class CarpetEventServer
|
||||
}
|
||||
}
|
||||
|
||||
public int signal(ServerCommandSource sender, ServerPlayerEntity optinoalReceipient, List<Value> callArg)
|
||||
public int signal(CommandSourceStack sender, ServerPlayer optinoalReceipient, List<Value> callArg)
|
||||
{
|
||||
if (callList.isEmpty()) return 0;
|
||||
int successes = 0;
|
||||
@@ -281,7 +280,7 @@ public class CarpetEventServer
|
||||
return successes;
|
||||
}
|
||||
|
||||
public boolean addFromExternal(ServerCommandSource source, String hostName, String funName, Consumer<ScriptHost> hostOnEventHandler)
|
||||
public boolean addFromExternal(CommandSourceStack source, String hostName, String funName, Consumer<ScriptHost> hostOnEventHandler)
|
||||
{
|
||||
ScriptHost host = CarpetServer.scriptServer.getAppHostByName(hostName);
|
||||
if (host == null)
|
||||
@@ -303,7 +302,7 @@ public class CarpetEventServer
|
||||
{
|
||||
try
|
||||
{
|
||||
target = source.getPlayer().getEntityName();
|
||||
target = source.getPlayerOrException().getScoreboardName();
|
||||
}
|
||||
catch (CommandSyntaxException e)
|
||||
{
|
||||
@@ -382,8 +381,8 @@ public class CarpetEventServer
|
||||
public void onTick()
|
||||
{
|
||||
handler.call(Collections::emptyList, () ->
|
||||
CarpetServer.minecraft_server.getCommandSource().
|
||||
withWorld(CarpetServer.minecraft_server.getWorld(World.OVERWORLD))
|
||||
CarpetServer.minecraft_server.createCommandSourceStack().
|
||||
withLevel(CarpetServer.minecraft_server.getLevel(Level.OVERWORLD))
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -394,8 +393,8 @@ public class CarpetEventServer
|
||||
public void onTick()
|
||||
{
|
||||
handler.call(Collections::emptyList, () ->
|
||||
CarpetServer.minecraft_server.getCommandSource().
|
||||
withWorld(CarpetServer.minecraft_server.getWorld(World.OVERWORLD))
|
||||
CarpetServer.minecraft_server.createCommandSourceStack().
|
||||
withLevel(CarpetServer.minecraft_server.getLevel(Level.OVERWORLD))
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -406,8 +405,8 @@ public class CarpetEventServer
|
||||
public void onTick()
|
||||
{
|
||||
handler.call(Collections::emptyList, () ->
|
||||
CarpetServer.minecraft_server.getCommandSource().
|
||||
withWorld(CarpetServer.minecraft_server.getWorld(World.OVERWORLD))
|
||||
CarpetServer.minecraft_server.createCommandSourceStack().
|
||||
withLevel(CarpetServer.minecraft_server.getLevel(Level.OVERWORLD))
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -423,8 +422,8 @@ public class CarpetEventServer
|
||||
public void onTick()
|
||||
{
|
||||
handler.call(Collections::emptyList, () ->
|
||||
CarpetServer.minecraft_server.getCommandSource().
|
||||
withWorld(CarpetServer.minecraft_server.getWorld(World.NETHER))
|
||||
CarpetServer.minecraft_server.createCommandSourceStack().
|
||||
withLevel(CarpetServer.minecraft_server.getLevel(Level.NETHER))
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -439,32 +438,32 @@ public class CarpetEventServer
|
||||
public void onTick()
|
||||
{
|
||||
handler.call(Collections::emptyList, () ->
|
||||
CarpetServer.minecraft_server.getCommandSource().
|
||||
withWorld(CarpetServer.minecraft_server.getWorld(World.END))
|
||||
CarpetServer.minecraft_server.createCommandSourceStack().
|
||||
withLevel(CarpetServer.minecraft_server.getLevel(Level.END))
|
||||
);
|
||||
}
|
||||
};
|
||||
public static final Event CHUNK_GENERATED = new Event("chunk_generated", 2, true)
|
||||
{
|
||||
@Override
|
||||
public void onChunkEvent(ServerWorld world, ChunkPos chPos, boolean generated)
|
||||
public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated)
|
||||
{
|
||||
handler.call( () ->
|
||||
{
|
||||
return Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4));
|
||||
}, () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world)
|
||||
}, () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
|
||||
);
|
||||
}
|
||||
};
|
||||
public static final Event CHUNK_LOADED = new Event("chunk_loaded", 2, true)
|
||||
{
|
||||
@Override
|
||||
public void onChunkEvent(ServerWorld world, ChunkPos chPos, boolean generated)
|
||||
public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated)
|
||||
{
|
||||
handler.call( () ->
|
||||
{
|
||||
return Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4));
|
||||
}, () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world)
|
||||
}, () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -472,49 +471,49 @@ public class CarpetEventServer
|
||||
public static final Event PLAYER_JUMPS = new Event("player_jumps", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_DEPLOYS_ELYTRA = new Event("player_deploys_elytra", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_WAKES_UP = new Event("player_wakes_up", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_ESCAPES_SLEEP = new Event("player_escapes_sleep", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_RIDES = new Event("player_rides", 5, false)
|
||||
{
|
||||
@Override
|
||||
public void onMountControls(ServerPlayerEntity player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking)
|
||||
public void onMountControls(ServerPlayer player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking)
|
||||
{
|
||||
handler.call( () -> Arrays.asList(new EntityValue(player),
|
||||
new NumericValue(forwardSpeed), new NumericValue(strafeSpeed), BooleanValue.of(jumping), BooleanValue.of(sneaking)
|
||||
), player::getCommandSource);
|
||||
), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_USES_ITEM = new Event("player_uses_item", 3, false)
|
||||
{
|
||||
@Override
|
||||
public void onItemAction(ServerPlayerEntity player, Hand enumhand, ItemStack itemstack)
|
||||
public void onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack)
|
||||
{
|
||||
handler.call( () ->
|
||||
{
|
||||
@@ -522,42 +521,42 @@ public class CarpetEventServer
|
||||
return Arrays.asList(
|
||||
new EntityValue(player),
|
||||
ValueConversions.of(itemstack),
|
||||
StringValue.of(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand")
|
||||
StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
|
||||
);
|
||||
}, player::getCommandSource);
|
||||
}, player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_CLICKS_BLOCK = new Event("player_clicks_block", 3, false)
|
||||
{
|
||||
@Override
|
||||
public void onBlockAction(ServerPlayerEntity player, BlockPos blockpos, Direction facing)
|
||||
public void onBlockAction(ServerPlayer player, BlockPos blockpos, Direction facing)
|
||||
{
|
||||
handler.call( () ->
|
||||
{
|
||||
return Arrays.asList(
|
||||
new EntityValue(player),
|
||||
new BlockValue(null, player.getWorld(), blockpos),
|
||||
new BlockValue(null, player.getLevel(), blockpos),
|
||||
StringValue.of(facing.getName())
|
||||
);
|
||||
}, player::getCommandSource);
|
||||
}, player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_RIGHT_CLICKS_BLOCK = new Event("player_right_clicks_block", 6, false)
|
||||
{
|
||||
@Override
|
||||
public void onBlockHit(ServerPlayerEntity player, Hand enumhand, BlockHitResult hitRes)//ItemStack itemstack, Hand enumhand, BlockPos blockpos, Direction enumfacing, Vec3d vec3d)
|
||||
public void onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes)//ItemStack itemstack, Hand enumhand, BlockPos blockpos, Direction enumfacing, Vec3d vec3d)
|
||||
{
|
||||
handler.call( () ->
|
||||
{
|
||||
ItemStack itemstack = player.getStackInHand(enumhand);
|
||||
ItemStack itemstack = player.getItemInHand(enumhand);
|
||||
BlockPos blockpos = hitRes.getBlockPos();
|
||||
Direction enumfacing = hitRes.getSide();
|
||||
Vec3d vec3d = hitRes.getPos().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ());
|
||||
Direction enumfacing = hitRes.getDirection();
|
||||
Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ());
|
||||
return Arrays.asList(
|
||||
new EntityValue(player),
|
||||
ValueConversions.of(itemstack),
|
||||
StringValue.of(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand"),
|
||||
new BlockValue(null, player.getWorld(), blockpos),
|
||||
StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"),
|
||||
new BlockValue(null, player.getLevel(), blockpos),
|
||||
StringValue.of(enumfacing.getName()),
|
||||
ListValue.of(
|
||||
new NumericValue(vec3d.x),
|
||||
@@ -565,23 +564,23 @@ public class CarpetEventServer
|
||||
new NumericValue(vec3d.z)
|
||||
)
|
||||
);
|
||||
}, player::getCommandSource);
|
||||
}, player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_INTERACTS_WITH_BLOCK = new Event("player_interacts_with_block", 5, false)
|
||||
{
|
||||
@Override
|
||||
public void onBlockHit(ServerPlayerEntity player, Hand enumhand, BlockHitResult hitRes)
|
||||
public void onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes)
|
||||
{
|
||||
handler.call( () ->
|
||||
{
|
||||
BlockPos blockpos = hitRes.getBlockPos();
|
||||
Direction enumfacing = hitRes.getSide();
|
||||
Vec3d vec3d = hitRes.getPos().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ());
|
||||
Direction enumfacing = hitRes.getDirection();
|
||||
Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ());
|
||||
return Arrays.asList(
|
||||
new EntityValue(player),
|
||||
StringValue.of(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand"),
|
||||
new BlockValue(null, player.getWorld(), blockpos),
|
||||
StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"),
|
||||
new BlockValue(null, player.getLevel(), blockpos),
|
||||
StringValue.of(enumfacing.getName()),
|
||||
ListValue.of(
|
||||
new NumericValue(vec3d.x),
|
||||
@@ -589,167 +588,167 @@ public class CarpetEventServer
|
||||
new NumericValue(vec3d.z)
|
||||
)
|
||||
);
|
||||
}, player::getCommandSource);
|
||||
}, player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_PLACES_BLOCK = new Event("player_places_block", 4, false)
|
||||
{
|
||||
@Override
|
||||
public void onBlockPlaced(ServerPlayerEntity player, BlockPos pos, Hand enumhand, ItemStack itemstack)
|
||||
public void onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack)
|
||||
{
|
||||
handler.call( () -> Arrays.asList(
|
||||
new EntityValue(player),
|
||||
ValueConversions.of(itemstack),
|
||||
StringValue.of(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand"),
|
||||
new BlockValue(null, player.getWorld(), pos)
|
||||
), player::getCommandSource);
|
||||
StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"),
|
||||
new BlockValue(null, player.getLevel(), pos)
|
||||
), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_BREAK_BLOCK = new Event("player_breaks_block", 2, false)
|
||||
{
|
||||
@Override
|
||||
public void onBlockBroken(ServerPlayerEntity player, BlockPos pos, BlockState previousBS)
|
||||
public void onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previousBS)
|
||||
{
|
||||
handler.call(
|
||||
() -> Arrays.asList(new EntityValue(player), new BlockValue(previousBS, player.getWorld(), pos)),
|
||||
player::getCommandSource
|
||||
() -> Arrays.asList(new EntityValue(player), new BlockValue(previousBS, player.getLevel(), pos)),
|
||||
player::createCommandSourceStack
|
||||
);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_INTERACTS_WITH_ENTITY = new Event("player_interacts_with_entity", 3, false)
|
||||
{
|
||||
@Override
|
||||
public void onEntityHandAction(ServerPlayerEntity player, Entity entity, Hand enumhand)
|
||||
public void onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand)
|
||||
{
|
||||
handler.call( () -> Arrays.asList(
|
||||
new EntityValue(player), new EntityValue(entity), StringValue.of(enumhand==Hand.MAIN_HAND?"mainhand":"offhand")
|
||||
), player::getCommandSource);
|
||||
new EntityValue(player), new EntityValue(entity), StringValue.of(enumhand==InteractionHand.MAIN_HAND?"mainhand":"offhand")
|
||||
), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_TRADES = new Event("player_trades", 5, false)
|
||||
{
|
||||
@Override
|
||||
public void onTrade(ServerPlayerEntity player, Merchant merchant, TradeOffer tradeOffer)
|
||||
public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer)
|
||||
{
|
||||
handler.call( () -> Arrays.asList(
|
||||
new EntityValue(player),
|
||||
merchant instanceof MerchantEntity ? new EntityValue((MerchantEntity) merchant) : Value.NULL,
|
||||
ValueConversions.of(tradeOffer.getOriginalFirstBuyItem()),
|
||||
ValueConversions.of(tradeOffer.getSecondBuyItem()),
|
||||
ValueConversions.of(tradeOffer.getSellItem())
|
||||
), player::getCommandSource);
|
||||
merchant instanceof AbstractVillager ? new EntityValue((AbstractVillager) merchant) : Value.NULL,
|
||||
ValueConversions.of(tradeOffer.getBaseCostA()),
|
||||
ValueConversions.of(tradeOffer.getCostB()),
|
||||
ValueConversions.of(tradeOffer.getResult())
|
||||
), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_PICKS_UP_ITEM = new Event("player_picks_up_item", 2, false)
|
||||
{
|
||||
@Override
|
||||
public void onItemAction(ServerPlayerEntity player, Hand enumhand, ItemStack itemstack) {
|
||||
handler.call( () -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack)), player::getCommandSource);
|
||||
public void onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) {
|
||||
handler.call( () -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
|
||||
public static final Event PLAYER_ATTACKS_ENTITY = new Event("player_attacks_entity", 2, false)
|
||||
{
|
||||
@Override
|
||||
public void onEntityHandAction(ServerPlayerEntity player, Entity entity, Hand enumhand)
|
||||
public void onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand)
|
||||
{
|
||||
handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::getCommandSource);
|
||||
handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_STARTS_SNEAKING = new Event("player_starts_sneaking", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_STOPS_SNEAKING = new Event("player_stops_sneaking", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_STARTS_SPRINTING = new Event("player_starts_sprinting", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_STOPS_SPRINTING = new Event("player_stops_sprinting", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
|
||||
public static final Event PLAYER_RELEASED_ITEM = new Event("player_releases_item", 3, false)
|
||||
{
|
||||
@Override
|
||||
public void onItemAction(ServerPlayerEntity player, Hand enumhand, ItemStack itemstack)
|
||||
public void onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack)
|
||||
{
|
||||
// this.getStackInHand(this.getActiveHand()), this.activeItemStack)
|
||||
handler.call( () ->
|
||||
Arrays.asList(
|
||||
new EntityValue(player),
|
||||
ValueConversions.of(itemstack),
|
||||
StringValue.of(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand")
|
||||
), player::getCommandSource);
|
||||
StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
|
||||
), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_FINISHED_USING_ITEM = new Event("player_finishes_using_item", 3, false)
|
||||
{
|
||||
@Override
|
||||
public void onItemAction(ServerPlayerEntity player, Hand enumhand, ItemStack itemstack)
|
||||
public void onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack)
|
||||
{
|
||||
// this.getStackInHand(this.getActiveHand()), this.activeItemStack)
|
||||
handler.call( () ->
|
||||
Arrays.asList(
|
||||
new EntityValue(player),
|
||||
ValueConversions.of(itemstack),
|
||||
new StringValue(enumhand == Hand.MAIN_HAND ? "mainhand" : "offhand")
|
||||
), player::getCommandSource);
|
||||
new StringValue(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
|
||||
), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_DROPS_ITEM = new Event("player_drops_item", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_DROPS_STACK = new Event("player_drops_stack", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_CHOOSES_RECIPE = new Event("player_chooses_recipe", 3, false)
|
||||
{
|
||||
@Override
|
||||
public void onRecipeSelected(ServerPlayerEntity player, Identifier recipe, boolean fullStack)
|
||||
public void onRecipeSelected(ServerPlayer player, ResourceLocation recipe, boolean fullStack)
|
||||
{
|
||||
handler.call( () ->
|
||||
Arrays.asList(
|
||||
new EntityValue(player),
|
||||
StringValue.of(NBTSerializableValue.nameFromRegistryId(recipe)),
|
||||
BooleanValue.of(fullStack)
|
||||
), player::getCommandSource);
|
||||
), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_SWITCHES_SLOT = new Event("player_switches_slot", 3, false)
|
||||
{
|
||||
@Override
|
||||
public void onSlotSwitch(ServerPlayerEntity player, int from, int to)
|
||||
public void onSlotSwitch(ServerPlayer player, int from, int to)
|
||||
{
|
||||
if (from == to) return; // initial slot update
|
||||
handler.call( () ->
|
||||
@@ -757,27 +756,27 @@ public class CarpetEventServer
|
||||
new EntityValue(player),
|
||||
new NumericValue(from),
|
||||
new NumericValue(to)
|
||||
), player::getCommandSource);
|
||||
), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_SWAPS_HANDS = new Event("player_swaps_hands", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_SWINGS_HAND = new Event("player_swings_hand", 2, false)
|
||||
{
|
||||
@Override
|
||||
public void onHandAction(ServerPlayerEntity player, Hand hand)
|
||||
public void onHandAction(ServerPlayer player, InteractionHand hand)
|
||||
{
|
||||
handler.call( () -> Arrays.asList(
|
||||
new EntityValue(player),
|
||||
StringValue.of(hand == Hand.MAIN_HAND ? "mainhand" : "offhand")
|
||||
StringValue.of(hand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
|
||||
)
|
||||
, player::getCommandSource);
|
||||
, player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_TAKES_DAMAGE = new Event("player_takes_damage", 4, false)
|
||||
@@ -789,9 +788,9 @@ public class CarpetEventServer
|
||||
Arrays.asList(
|
||||
new EntityValue(target),
|
||||
new NumericValue(amount),
|
||||
StringValue.of(source.getName()),
|
||||
source.getAttacker()==null?Value.NULL:new EntityValue(source.getAttacker())
|
||||
), target::getCommandSource);
|
||||
StringValue.of(source.getMsgId()),
|
||||
source.getEntity()==null?Value.NULL:new EntityValue(source.getEntity())
|
||||
), target::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_DEALS_DAMAGE = new Event("player_deals_damage", 3, false)
|
||||
@@ -800,70 +799,70 @@ public class CarpetEventServer
|
||||
public void onDamage(Entity target, float amount, DamageSource source)
|
||||
{
|
||||
handler.call( () ->
|
||||
Arrays.asList(new EntityValue(source.getAttacker()), new NumericValue(amount), new EntityValue(target)),
|
||||
() -> source.getAttacker().getCommandSource()
|
||||
Arrays.asList(new EntityValue(source.getEntity()), new NumericValue(amount), new EntityValue(target)),
|
||||
() -> source.getEntity().createCommandSourceStack()
|
||||
);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_COLLIDES_WITH_ENTITY = new Event("player_collides_with_entity", 2, false)
|
||||
{
|
||||
@Override
|
||||
public void onEntityHandAction(ServerPlayerEntity player, Entity entity, Hand enumhand) {
|
||||
handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::getCommandSource);
|
||||
public void onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) {
|
||||
handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
|
||||
public static final Event PLAYER_DIES = new Event("player_dies", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_RESPAWNS = new Event("player_respawns", 1, false)
|
||||
{
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_CHANGES_DIMENSION = new Event("player_changes_dimension", 5, false)
|
||||
{
|
||||
@Override
|
||||
public void onDimensionChange(ServerPlayerEntity player, Vec3d from, Vec3d to, RegistryKey<World> fromDim, RegistryKey<World> dimTo)
|
||||
public void onDimensionChange(ServerPlayer player, Vec3 from, Vec3 to, ResourceKey<Level> fromDim, ResourceKey<Level> dimTo)
|
||||
{
|
||||
// eligibility already checked in mixin
|
||||
Value fromValue = ListValue.fromTriple(from.x, from.y, from.z);
|
||||
Value toValue = (to == null)?Value.NULL:ListValue.fromTriple(to.x, to.y, to.z);
|
||||
Value fromDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(fromDim.getValue()));
|
||||
Value toDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(dimTo.getValue()));
|
||||
Value fromDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(fromDim.location()));
|
||||
Value toDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(dimTo.location()));
|
||||
|
||||
handler.call( () -> Arrays.asList(new EntityValue(player), fromValue, fromDimStr, toValue, toDimStr), player::getCommandSource);
|
||||
handler.call( () -> Arrays.asList(new EntityValue(player), fromValue, fromDimStr, toValue, toDimStr), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_CONNECTS = new Event("player_connects", 1, false) {
|
||||
@Override
|
||||
public void onPlayerEvent(ServerPlayerEntity player)
|
||||
public void onPlayerEvent(ServerPlayer player)
|
||||
{
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::getCommandSource);
|
||||
handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event PLAYER_DISCONNECTS = new Event("player_disconnects", 2, false) {
|
||||
@Override
|
||||
public void onPlayerMessage(ServerPlayerEntity player, String message)
|
||||
public void onPlayerMessage(ServerPlayer player, String message)
|
||||
{
|
||||
handler.call( () -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::getCommandSource);
|
||||
handler.call( () -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event STATISTICS = new Event("statistic", 4, false)
|
||||
{
|
||||
private <T> Identifier getStatId(Stat<T> stat)
|
||||
private <T> ResourceLocation getStatId(Stat<T> stat)
|
||||
{
|
||||
return stat.getType().getRegistry().getId(stat.getValue());
|
||||
return stat.getType().getRegistry().getKey(stat.getValue());
|
||||
}
|
||||
private final Set<Identifier> skippedStats = new HashSet<Identifier>(){{
|
||||
private final Set<ResourceLocation> skippedStats = new HashSet<ResourceLocation>(){{
|
||||
add(Stats.TIME_SINCE_DEATH);
|
||||
add(Stats.TIME_SINCE_REST);
|
||||
//add(Stats.PLAY_ONE_MINUTE);
|
||||
@@ -871,35 +870,35 @@ public class CarpetEventServer
|
||||
add(Stats.TOTAL_WORLD_TIME);
|
||||
}};
|
||||
@Override
|
||||
public void onPlayerStatistic(ServerPlayerEntity player, Stat<?> stat, int amount)
|
||||
public void onPlayerStatistic(ServerPlayer player, Stat<?> stat, int amount)
|
||||
{
|
||||
Identifier id = getStatId(stat);
|
||||
ResourceLocation id = getStatId(stat);
|
||||
if (skippedStats.contains(id)) return;
|
||||
handler.call( () -> Arrays.asList(
|
||||
new EntityValue(player),
|
||||
StringValue.of(NBTSerializableValue.nameFromRegistryId(Registry.STAT_TYPE.getId(stat.getType()))),
|
||||
StringValue.of(NBTSerializableValue.nameFromRegistryId(Registry.STAT_TYPE.getKey(stat.getType()))),
|
||||
StringValue.of(NBTSerializableValue.nameFromRegistryId(id)),
|
||||
new NumericValue(amount)
|
||||
), player::getCommandSource);
|
||||
), player::createCommandSourceStack);
|
||||
}
|
||||
};
|
||||
public static final Event LIGHTNING = new Event("lightning", 2, true)
|
||||
{
|
||||
@Override
|
||||
public void onWorldEventFlag(ServerWorld world, BlockPos pos, int flag)
|
||||
public void onWorldEventFlag(ServerLevel world, BlockPos pos, int flag)
|
||||
{
|
||||
handler.call(
|
||||
() -> Arrays.asList(
|
||||
new BlockValue(null, world, pos),
|
||||
flag>0?Value.TRUE:Value.FALSE
|
||||
), () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world)
|
||||
), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
|
||||
);
|
||||
}
|
||||
};
|
||||
public static final Event CARPET_RULE_CHANGES = new Event("carpet_rule_changes", 2, true)
|
||||
{
|
||||
@Override
|
||||
public void onCarpetRuleChanges(ParsedRule<?> rule, ServerCommandSource source)
|
||||
public void onCarpetRuleChanges(ParsedRule<?> rule, CommandSourceStack source)
|
||||
{
|
||||
String identifier = rule.settingsManager.getIdentifier();
|
||||
final String namespace;
|
||||
@@ -919,10 +918,10 @@ public class CarpetEventServer
|
||||
private static LivingEntity getExplosionCausingEntity(Entity entity)
|
||||
{
|
||||
if (entity == null) return null;
|
||||
else if (entity instanceof TntEntity) return ((TntEntity)entity).getCausingEntity();
|
||||
else if (entity instanceof PrimedTnt) return ((PrimedTnt)entity).getOwner();
|
||||
else if (entity instanceof LivingEntity) return (LivingEntity)entity;
|
||||
else if (entity instanceof ProjectileEntity) {
|
||||
Entity owner = ((ProjectileEntity)entity).getOwner();
|
||||
else if (entity instanceof Projectile) {
|
||||
Entity owner = ((Projectile)entity).getOwner();
|
||||
if (owner instanceof LivingEntity) return (LivingEntity)owner;
|
||||
}
|
||||
return null;
|
||||
@@ -931,7 +930,7 @@ public class CarpetEventServer
|
||||
public static final Event EXPLOSION_OUTCOME = new Event("explosion_outcome", 8, true)
|
||||
{
|
||||
@Override
|
||||
public void onExplosion(ServerWorld world, Entity e, Supplier<LivingEntity> attacker, double x, double y, double z, float power, boolean createFire, List<BlockPos> affectedBlocks, List<Entity> affectedEntities, Explosion.DestructionType type)
|
||||
public void onExplosion(ServerLevel world, Entity e, Supplier<LivingEntity> attacker, double x, double y, double z, float power, boolean createFire, List<BlockPos> affectedBlocks, List<Entity> affectedEntities, Explosion.BlockInteraction type)
|
||||
{
|
||||
handler.call(
|
||||
() -> Arrays.asList(
|
||||
@@ -941,11 +940,11 @@ public class CarpetEventServer
|
||||
EntityValue.of(attacker!= null?attacker.get():Event.getExplosionCausingEntity(e)),
|
||||
StringValue.of(type.name().toLowerCase(Locale.ROOT)),
|
||||
BooleanValue.of(createFire),
|
||||
new ListValue(affectedBlocks.stream().filter(b -> !world.isAir(b)). map( // da heck they send air blocks
|
||||
new ListValue(affectedBlocks.stream().filter(b -> !world.isEmptyBlock(b)). map( // da heck they send air blocks
|
||||
b -> new BlockValue(world.getBlockState(b),world,b)
|
||||
).collect(Collectors.toList())),
|
||||
new ListValue(affectedEntities.stream().map(EntityValue::of).collect(Collectors.toList()))
|
||||
), () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world)
|
||||
), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -954,7 +953,7 @@ public class CarpetEventServer
|
||||
public static final Event EXPLOSION = new Event("explosion", 6, true)
|
||||
{
|
||||
@Override
|
||||
public void onExplosion(ServerWorld world, Entity e, Supplier<LivingEntity> attacker, double x, double y, double z, float power, boolean createFire, List<BlockPos> affectedBlocks, List<Entity> affectedEntities, Explosion.DestructionType type)
|
||||
public void onExplosion(ServerLevel world, Entity e, Supplier<LivingEntity> attacker, double x, double y, double z, float power, boolean createFire, List<BlockPos> affectedBlocks, List<Entity> affectedEntities, Explosion.BlockInteraction type)
|
||||
{
|
||||
handler.call(
|
||||
() -> Arrays.asList(
|
||||
@@ -964,7 +963,7 @@ public class CarpetEventServer
|
||||
EntityValue.of(attacker!= null?attacker.get():Event.getExplosionCausingEntity(e)),
|
||||
StringValue.of(type.name().toLowerCase(Locale.ROOT)),
|
||||
BooleanValue.of(createFire)
|
||||
), () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world)
|
||||
), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -972,13 +971,13 @@ public class CarpetEventServer
|
||||
@Deprecated
|
||||
public static String getEntityLoadEventName(EntityType<? extends Entity> et)
|
||||
{
|
||||
return "entity_loaded_" + ValueConversions.of(Registry.ENTITY_TYPE.getId(et)).getString();
|
||||
return "entity_loaded_" + ValueConversions.of(Registry.ENTITY_TYPE.getKey(et)).getString();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static final Map<EntityType<? extends Entity>, Event> ENTITY_LOAD= new HashMap<>()
|
||||
{{
|
||||
EntityType.get("zombie");
|
||||
EntityType.byString("zombie");
|
||||
Registry.ENTITY_TYPE.forEach(et -> {
|
||||
put(et, new Event(getEntityLoadEventName(et), 1, true, false)
|
||||
{
|
||||
@@ -987,7 +986,7 @@ public class CarpetEventServer
|
||||
{
|
||||
handler.call(
|
||||
() -> Collections.singletonList(new EntityValue(entity)),
|
||||
() -> CarpetServer.minecraft_server.getCommandSource().withWorld((ServerWorld) entity.world).withLevel(CarpetSettings.runPermissionLevel)
|
||||
() -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(CarpetSettings.runPermissionLevel)
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -996,12 +995,12 @@ public class CarpetEventServer
|
||||
|
||||
public static String getEntityHandlerEventName(EntityType<? extends Entity> et)
|
||||
{
|
||||
return "entity_handler_" + ValueConversions.of(Registry.ENTITY_TYPE.getId(et)).getString();
|
||||
return "entity_handler_" + ValueConversions.of(Registry.ENTITY_TYPE.getKey(et)).getString();
|
||||
}
|
||||
|
||||
public static final Map<EntityType<? extends Entity>, Event> ENTITY_HANDLER= new HashMap<>()
|
||||
{{
|
||||
EntityType.get("zombie");
|
||||
EntityType.byString("zombie");
|
||||
Registry.ENTITY_TYPE.forEach(et -> {
|
||||
put(et, new Event(getEntityHandlerEventName(et), 2, true, false)
|
||||
{
|
||||
@@ -1010,7 +1009,7 @@ public class CarpetEventServer
|
||||
{
|
||||
handler.call(
|
||||
() -> Arrays.asList(new EntityValue(entity), BooleanValue.of(created)),
|
||||
() -> CarpetServer.minecraft_server.getCommandSource().withWorld((ServerWorld) entity.world).withLevel(CarpetSettings.runPermissionLevel)
|
||||
() -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(CarpetSettings.runPermissionLevel)
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1092,30 +1091,30 @@ public class CarpetEventServer
|
||||
public boolean deprecated() {return false;}
|
||||
//stubs for calls just to ease calls in vanilla code so they don't need to deal with scarpet value types
|
||||
public void onTick() { }
|
||||
public void onChunkEvent(ServerWorld world, ChunkPos chPos, boolean generated) { }
|
||||
public void onPlayerEvent(ServerPlayerEntity player) { }
|
||||
public void onPlayerMessage(ServerPlayerEntity player, String message) { }
|
||||
public void onPlayerStatistic(ServerPlayerEntity player, Stat<?> stat, int amount) { }
|
||||
public void onMountControls(ServerPlayerEntity player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking) { }
|
||||
public void onItemAction(ServerPlayerEntity player, Hand enumhand, ItemStack itemstack) { }
|
||||
public void onBlockAction(ServerPlayerEntity player, BlockPos blockpos, Direction facing) { }
|
||||
public void onBlockHit(ServerPlayerEntity player, Hand enumhand, BlockHitResult hitRes) { }
|
||||
public void onBlockBroken(ServerPlayerEntity player, BlockPos pos, BlockState previousBS) { }
|
||||
public void onBlockPlaced(ServerPlayerEntity player, BlockPos pos, Hand enumhand, ItemStack itemstack) { }
|
||||
public void onEntityHandAction(ServerPlayerEntity player, Entity entity, Hand enumhand) { }
|
||||
public void onHandAction(ServerPlayerEntity player, Hand enumhand) { }
|
||||
public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) { }
|
||||
public void onPlayerEvent(ServerPlayer player) { }
|
||||
public void onPlayerMessage(ServerPlayer player, String message) { }
|
||||
public void onPlayerStatistic(ServerPlayer player, Stat<?> stat, int amount) { }
|
||||
public void onMountControls(ServerPlayer player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking) { }
|
||||
public void onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { }
|
||||
public void onBlockAction(ServerPlayer player, BlockPos blockpos, Direction facing) { }
|
||||
public void onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes) { }
|
||||
public void onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previousBS) { }
|
||||
public void onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack) { }
|
||||
public void onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) { }
|
||||
public void onHandAction(ServerPlayer player, InteractionHand enumhand) { }
|
||||
public void onEntityAction(Entity entity, boolean created) { }
|
||||
public void onDimensionChange(ServerPlayerEntity player, Vec3d from, Vec3d to, RegistryKey<World> fromDim, RegistryKey<World> dimTo) {}
|
||||
public void onDimensionChange(ServerPlayer player, Vec3 from, Vec3 to, ResourceKey<Level> fromDim, ResourceKey<Level> dimTo) {}
|
||||
public void onDamage(Entity target, float amount, DamageSource source) { }
|
||||
public void onRecipeSelected(ServerPlayerEntity player, Identifier recipe, boolean fullStack) {}
|
||||
public void onSlotSwitch(ServerPlayerEntity player, int from, int to) {}
|
||||
public void onTrade(ServerPlayerEntity player, Merchant merchant, TradeOffer tradeOffer) {}
|
||||
public void onRecipeSelected(ServerPlayer player, ResourceLocation recipe, boolean fullStack) {}
|
||||
public void onSlotSwitch(ServerPlayer player, int from, int to) {}
|
||||
public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer) {}
|
||||
|
||||
public void onExplosion(ServerWorld world, Entity e, Supplier<LivingEntity> attacker, double x, double y, double z, float power, boolean createFire, List<BlockPos> affectedBlocks, List<Entity> affectedEntities, Explosion.DestructionType type) { }
|
||||
public void onWorldEvent(ServerWorld world, BlockPos pos) { }
|
||||
public void onWorldEventFlag(ServerWorld world, BlockPos pos, int flag) { }
|
||||
public void onCarpetRuleChanges(ParsedRule<?> rule, ServerCommandSource source) { }
|
||||
public void onCustomPlayerEvent(ServerPlayerEntity player, Object ... args)
|
||||
public void onExplosion(ServerLevel world, Entity e, Supplier<LivingEntity> attacker, double x, double y, double z, float power, boolean createFire, List<BlockPos> affectedBlocks, List<Entity> affectedEntities, Explosion.BlockInteraction type) { }
|
||||
public void onWorldEvent(ServerLevel world, BlockPos pos) { }
|
||||
public void onWorldEventFlag(ServerLevel world, BlockPos pos, int flag) { }
|
||||
public void onCarpetRuleChanges(ParsedRule<?> rule, CommandSourceStack source) { }
|
||||
public void onCustomPlayerEvent(ServerPlayer player, Object ... args)
|
||||
{
|
||||
if (handler.reqArgs != (args.length+1))
|
||||
throw new InternalExpressionException("Expected "+handler.reqArgs+" arguments for "+name+", got "+(args.length+1));
|
||||
@@ -1125,13 +1124,13 @@ public class CarpetEventServer
|
||||
valArgs.add(EntityValue.of(player));
|
||||
for (Object o: args)
|
||||
{
|
||||
valArgs.add(ValueConversions.guess(player.getWorld(), o));
|
||||
valArgs.add(ValueConversions.guess(player.getLevel(), o));
|
||||
}
|
||||
return valArgs;
|
||||
}, player::getCommandSource
|
||||
}, player::createCommandSourceStack
|
||||
);
|
||||
}
|
||||
public void onCustomWorldEvent(ServerWorld world, Object ... args)
|
||||
public void onCustomWorldEvent(ServerLevel world, Object ... args)
|
||||
{
|
||||
if (handler.reqArgs != args.length)
|
||||
throw new InternalExpressionException("Expected "+handler.reqArgs+" arguments for "+name+", got "+args.length);
|
||||
@@ -1143,7 +1142,7 @@ public class CarpetEventServer
|
||||
valArgs.add(ValueConversions.guess(world, o));
|
||||
}
|
||||
return valArgs;
|
||||
}, () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world)
|
||||
}, () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1182,7 +1181,7 @@ public class CarpetEventServer
|
||||
scheduledCalls.add(new ScheduledCall(context, function, args, due));
|
||||
}
|
||||
|
||||
public void runScheduledCall(BlockPos origin, ServerCommandSource source, String hostname, CarpetScriptHost host, FunctionValue udf, List<Value> argv)
|
||||
public void runScheduledCall(BlockPos origin, CommandSourceStack source, String hostname, CarpetScriptHost host, FunctionValue udf, List<Value> argv)
|
||||
{
|
||||
if (hostname != null && !scriptServer.modules.containsKey(hostname)) // well - scheduled call app got unloaded
|
||||
return;
|
||||
@@ -1193,25 +1192,25 @@ public class CarpetEventServer
|
||||
catch (NullPointerException | InvalidCallbackException | IntegrityException ignored) { }
|
||||
}
|
||||
|
||||
public CallbackResult runEventCall(ServerCommandSource sender, String hostname, String optionalTarget, FunctionValue udf, List<Value> argv)
|
||||
public CallbackResult runEventCall(CommandSourceStack sender, String hostname, String optionalTarget, FunctionValue udf, List<Value> argv)
|
||||
{
|
||||
CarpetScriptHost appHost = scriptServer.getAppHostByName(hostname);
|
||||
// no such app
|
||||
if (appHost == null) return CallbackResult.FAIL;
|
||||
// dummy call for player apps that reside on the global copy - do not run them, but report as passes.
|
||||
if (appHost.isPerUser() && optionalTarget==null) return CallbackResult.PASS;
|
||||
ServerPlayerEntity target = null;
|
||||
ServerPlayer target = null;
|
||||
if (optionalTarget != null)
|
||||
{
|
||||
target = sender.getServer().getPlayerManager().getPlayer(optionalTarget);
|
||||
target = sender.getServer().getPlayerList().getPlayerByName(optionalTarget);
|
||||
if (target == null) return CallbackResult.FAIL;
|
||||
}
|
||||
ServerCommandSource source = sender.withLevel(CarpetSettings.runPermissionLevel);
|
||||
CommandSourceStack source = sender.withPermission(CarpetSettings.runPermissionLevel);
|
||||
CarpetScriptHost executingHost = appHost.retrieveForExecution(sender, target);
|
||||
if (executingHost == null) return CallbackResult.FAIL;
|
||||
try
|
||||
{
|
||||
executingHost.callUDF(BlockPos.ORIGIN, source.withLevel(CarpetSettings.runPermissionLevel), udf, argv);
|
||||
executingHost.callUDF(BlockPos.ZERO, source.withPermission(CarpetSettings.runPermissionLevel), udf, argv);
|
||||
return CallbackResult.SUCCESS;
|
||||
}
|
||||
catch (NullPointerException | InvalidCallbackException | IntegrityException error)
|
||||
@@ -1221,7 +1220,7 @@ public class CarpetEventServer
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addEventFromCommand(ServerCommandSource source, String event, String host, String funName)
|
||||
public boolean addEventFromCommand(CommandSourceStack source, String event, String host, String funName)
|
||||
{
|
||||
Event ev = Event.getEvent(event, CarpetServer.scriptServer);
|
||||
if (ev == null)
|
||||
@@ -1249,7 +1248,7 @@ public class CarpetEventServer
|
||||
return ev.handler.addEventCallInternal(host, function, args==null?NOARGS:args);
|
||||
}
|
||||
|
||||
public int signalEvent(String event, CarpetContext cc, ServerPlayerEntity optionalTarget, List<Value> callArgs)
|
||||
public int signalEvent(String event, CarpetContext cc, ServerPlayer optionalTarget, List<Value> callArgs)
|
||||
{
|
||||
Event ev = Event.getEvent(event, ((CarpetScriptHost)cc.host).getScriptServer());
|
||||
if (ev == null) return -1;
|
||||
@@ -1262,7 +1261,7 @@ public class CarpetEventServer
|
||||
//return !(event.globalOnly && (host.perUser || host.parent != null));
|
||||
}
|
||||
|
||||
public boolean removeEventFromCommand(ServerCommandSource source, String event, String funName)
|
||||
public boolean removeEventFromCommand(CommandSourceStack source, String event, String funName)
|
||||
{
|
||||
Event ev = Event.getEvent(event, CarpetServer.scriptServer);
|
||||
if (ev == null)
|
||||
|
||||
@@ -17,21 +17,21 @@ import carpet.script.value.BlockValue;
|
||||
import carpet.script.value.EntityValue;
|
||||
import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.Value;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
|
||||
public class CarpetExpression
|
||||
{
|
||||
private final ServerCommandSource source;
|
||||
private final CommandSourceStack source;
|
||||
private final BlockPos origin;
|
||||
private final Expression expr;
|
||||
// these are for extensions
|
||||
public Expression getExpr() {return expr;}
|
||||
public ServerCommandSource getSource() {return source;}
|
||||
public CommandSourceStack getSource() {return source;}
|
||||
public BlockPos getOrigin() {return origin;}
|
||||
|
||||
public CarpetExpression(Module module, String expression, ServerCommandSource source, BlockPos origin)
|
||||
public CarpetExpression(Module module, String expression, CommandSourceStack source, BlockPos origin)
|
||||
{
|
||||
this.origin = origin;
|
||||
this.source = source;
|
||||
@@ -60,7 +60,7 @@ public class CarpetExpression
|
||||
with("x", (c, t) -> new NumericValue(x - origin.getX()).bindTo("x")).
|
||||
with("y", (c, t) -> new NumericValue(y - origin.getY()).bindTo("y")).
|
||||
with("z", (c, t) -> new NumericValue(z - origin.getZ()).bindTo("z")).
|
||||
with("_", (c, t) -> new BlockValue(null, source.getWorld(), new BlockPos(x, y, z)).bindTo("_"));
|
||||
with("_", (c, t) -> new BlockValue(null, source.getLevel(), new BlockPos(x, y, z)).bindTo("_"));
|
||||
Entity e = source.getEntity();
|
||||
if (e==null)
|
||||
{
|
||||
|
||||
@@ -39,16 +39,16 @@ import net.fabricmc.loader.api.SemanticVersion;
|
||||
import net.fabricmc.loader.api.Version;
|
||||
import net.fabricmc.loader.api.VersionParsingException;
|
||||
import net.fabricmc.loader.api.metadata.version.VersionPredicate;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EntityType;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.text.BaseText;
|
||||
import net.minecraft.text.LiteralText;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.network.chat.BaseComponent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.math.BigInteger;
|
||||
@@ -68,26 +68,26 @@ import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.lang.Math.max;
|
||||
import static net.minecraft.server.command.CommandManager.argument;
|
||||
import static net.minecraft.server.command.CommandManager.literal;
|
||||
import static net.minecraft.commands.Commands.argument;
|
||||
import static net.minecraft.commands.Commands.literal;
|
||||
|
||||
public class CarpetScriptHost extends ScriptHost
|
||||
{
|
||||
private final CarpetScriptServer scriptServer;
|
||||
public ServerCommandSource responsibleSource;
|
||||
public CommandSourceStack responsibleSource;
|
||||
|
||||
private NbtElement globalState;
|
||||
private Tag globalState;
|
||||
private int saveTimeout;
|
||||
public boolean persistenceRequired;
|
||||
|
||||
public Map<Value, Value> appConfig;
|
||||
public Map<String, CommandArgument> appArgTypes;
|
||||
|
||||
Predicate<ServerCommandSource> commandValidator;
|
||||
Predicate<CommandSourceStack> commandValidator;
|
||||
boolean isRuleApp;
|
||||
public AppStoreManager.StoreNode storeSource;
|
||||
|
||||
private CarpetScriptHost(CarpetScriptServer server, Module code, boolean perUser, ScriptHost parent, Map<Value, Value> config, Map<String, CommandArgument> argTypes, Predicate<ServerCommandSource> commandValidator, boolean isRuleApp)
|
||||
private CarpetScriptHost(CarpetScriptServer server, Module code, boolean perUser, ScriptHost parent, Map<Value, Value> config, Map<String, CommandArgument> argTypes, Predicate<CommandSourceStack> commandValidator, boolean isRuleApp)
|
||||
{
|
||||
super(code, perUser, parent);
|
||||
this.saveTimeout = 0;
|
||||
@@ -109,7 +109,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
storeSource = null;
|
||||
}
|
||||
|
||||
public static CarpetScriptHost create(CarpetScriptServer scriptServer, Module module, boolean perPlayer, ServerCommandSource source, Predicate<ServerCommandSource> commandValidator, boolean isRuleApp, AppStoreManager.StoreNode storeSource)
|
||||
public static CarpetScriptHost create(CarpetScriptServer scriptServer, Module module, boolean perPlayer, CommandSourceStack source, Predicate<CommandSourceStack> commandValidator, boolean isRuleApp, AppStoreManager.StoreNode storeSource)
|
||||
{
|
||||
CarpetScriptHost host = new CarpetScriptHost(scriptServer, module, perPlayer, null, Collections.emptyMap(), new HashMap<>(), commandValidator, isRuleApp);
|
||||
// parse code and convert to expression
|
||||
@@ -150,13 +150,13 @@ public class CarpetScriptHost extends ScriptHost
|
||||
return host;
|
||||
}
|
||||
|
||||
private static int execute(CommandContext<ServerCommandSource> ctx, String hostName, FunctionArgument funcSpec, List<String> paramNames) throws CommandSyntaxException
|
||||
private static int execute(CommandContext<CommandSourceStack> ctx, String hostName, FunctionArgument funcSpec, List<String> paramNames) throws CommandSyntaxException
|
||||
{
|
||||
CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL);
|
||||
CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource());
|
||||
List<String> argNames = funcSpec.function.getArguments();
|
||||
if ((argNames.size()-funcSpec.args.size()) != paramNames.size())
|
||||
throw new SimpleCommandExceptionType(new LiteralText("Target function "+funcSpec.function.getPrettyString()+" as wrong number of arguments, required "+paramNames.size()+", found "+argNames.size()+" with "+funcSpec.args.size()+" provided")).create();
|
||||
throw new SimpleCommandExceptionType(new TextComponent("Target function "+funcSpec.function.getPrettyString()+" as wrong number of arguments, required "+paramNames.size()+", found "+argNames.size()+" with "+funcSpec.args.size()+" provided")).create();
|
||||
List<Value> args = new ArrayList<>(argNames.size());
|
||||
for (String s : paramNames)
|
||||
{
|
||||
@@ -171,8 +171,8 @@ public class CarpetScriptHost extends ScriptHost
|
||||
return intres;
|
||||
}
|
||||
|
||||
public LiteralArgumentBuilder<ServerCommandSource> addPathToCommand(
|
||||
LiteralArgumentBuilder<ServerCommandSource> command,
|
||||
public LiteralArgumentBuilder<CommandSourceStack> addPathToCommand(
|
||||
LiteralArgumentBuilder<CommandSourceStack> command,
|
||||
List<CommandToken> path,
|
||||
FunctionArgument functionSpec
|
||||
) throws CommandSyntaxException
|
||||
@@ -187,7 +187,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
}
|
||||
List<CommandToken> reversedPath = new ArrayList<>(path);
|
||||
Collections.reverse(reversedPath);
|
||||
ArgumentBuilder<ServerCommandSource, ?> argChain = reversedPath.get(0).getCommandNode(this).executes(c -> execute(c, hostName, functionSpec, commandArgs));
|
||||
ArgumentBuilder<CommandSourceStack, ?> argChain = reversedPath.get(0).getCommandNode(this).executes(c -> execute(c, hostName, functionSpec, commandArgs));
|
||||
for (int i = 1; i < reversedPath.size(); i++)
|
||||
{
|
||||
argChain = reversedPath.get(i).getCommandNode(this).then(argChain);
|
||||
@@ -195,13 +195,13 @@ public class CarpetScriptHost extends ScriptHost
|
||||
return command.then(argChain);
|
||||
}
|
||||
|
||||
public LiteralArgumentBuilder<ServerCommandSource> getNewCommandTree(
|
||||
List<Pair<List<CommandToken>,FunctionArgument>> entries, Predicate<ServerCommandSource> useValidator
|
||||
public LiteralArgumentBuilder<CommandSourceStack> getNewCommandTree(
|
||||
List<Pair<List<CommandToken>,FunctionArgument>> entries, Predicate<CommandSourceStack> useValidator
|
||||
) throws CommandSyntaxException
|
||||
{
|
||||
String hostName = main.getName();
|
||||
Predicate<ServerCommandSource> configValidator = getCommandConfigPermissions();
|
||||
LiteralArgumentBuilder<ServerCommandSource> command = literal(hostName).
|
||||
Predicate<CommandSourceStack> configValidator = getCommandConfigPermissions();
|
||||
LiteralArgumentBuilder<CommandSourceStack> command = literal(hostName).
|
||||
requires((player) -> CarpetServer.scriptServer.modules.containsKey(hostName) && useValidator.test(player) && configValidator.test(player));
|
||||
for (Pair<List<CommandToken>,FunctionArgument> commandData : entries)
|
||||
{
|
||||
@@ -210,7 +210,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
return command;
|
||||
}
|
||||
|
||||
public Predicate<ServerCommandSource> getCommandConfigPermissions() throws CommandSyntaxException
|
||||
public Predicate<CommandSourceStack> getCommandConfigPermissions() throws CommandSyntaxException
|
||||
{
|
||||
Value confValue = appConfig.get(StringValue.of("command_permission"));
|
||||
if (confValue == null) return s -> true;
|
||||
@@ -218,16 +218,16 @@ public class CarpetScriptHost extends ScriptHost
|
||||
{
|
||||
int level = ((NumericValue) confValue).getInt();
|
||||
if (level < 1 || level > 4) throw CommandArgument.error("Numeric permission level for custom commands should be between 1 and 4");
|
||||
return s -> s.hasPermissionLevel(level);
|
||||
return s -> s.hasPermission(level);
|
||||
}
|
||||
if (!(confValue instanceof FunctionValue))
|
||||
{
|
||||
String perm = confValue.getString().toLowerCase(Locale.ROOT);
|
||||
switch (perm)
|
||||
{
|
||||
case "ops": return s -> s.hasPermissionLevel(2);
|
||||
case "server": return s -> !(s.getEntity() instanceof ServerPlayerEntity);
|
||||
case "players": return s -> s.getEntity() instanceof ServerPlayerEntity;
|
||||
case "ops": return s -> s.hasPermission(2);
|
||||
case "server": return s -> !(s.getEntity() instanceof ServerPlayer);
|
||||
case "players": return s -> s.getEntity() instanceof ServerPlayer;
|
||||
case "all": return s -> true;
|
||||
default: throw CommandArgument.error("Unknown command permission: "+perm);
|
||||
}
|
||||
@@ -242,7 +242,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
CarpetScriptHost cHost = null;
|
||||
cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(s);
|
||||
Value response = cHost.handleCommand(s, fun, Collections.singletonList(
|
||||
(s.getEntity() instanceof ServerPlayerEntity)?new EntityValue(s.getEntity()):Value.NULL)
|
||||
(s.getEntity() instanceof ServerPlayer)?new EntityValue(s.getEntity()):Value.NULL)
|
||||
);
|
||||
boolean res = response.getBoolean();
|
||||
CarpetProfiler.end_current_section(currentSection);
|
||||
@@ -385,7 +385,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
}
|
||||
}
|
||||
|
||||
public Boolean addAppCommands(Consumer<Text> notifier)
|
||||
public Boolean addAppCommands(Consumer<Component> notifier)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -400,10 +400,10 @@ public class CarpetScriptHost extends ScriptHost
|
||||
{
|
||||
try
|
||||
{
|
||||
LiteralArgumentBuilder<ServerCommandSource> command = readCommands(commandValidator);
|
||||
LiteralArgumentBuilder<CommandSourceStack> command = readCommands(commandValidator);
|
||||
if (command != null)
|
||||
{
|
||||
scriptServer.server.getCommandManager().getDispatcher().register(command);
|
||||
scriptServer.server.getCommands().getDispatcher().register(command);
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
@@ -453,7 +453,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
}
|
||||
}
|
||||
|
||||
private Boolean addLegacyCommand(Consumer<Text> notifier)
|
||||
private Boolean addLegacyCommand(Consumer<Component> notifier)
|
||||
{
|
||||
if (main == null) return false;
|
||||
if (getFunction("__command") == null) return false;
|
||||
@@ -464,7 +464,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
return null;
|
||||
}
|
||||
|
||||
Predicate<ServerCommandSource> configValidator;
|
||||
Predicate<CommandSourceStack> configValidator;
|
||||
try
|
||||
{
|
||||
configValidator = getCommandConfigPermissions();
|
||||
@@ -475,7 +475,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
return null;
|
||||
}
|
||||
String hostName = getName();
|
||||
LiteralArgumentBuilder<ServerCommandSource> command = literal(hostName).
|
||||
LiteralArgumentBuilder<CommandSourceStack> command = literal(hostName).
|
||||
requires((player) -> scriptServer.modules.containsKey(hostName) && commandValidator.test(player) && configValidator.test(player)).
|
||||
executes( (c) ->
|
||||
{
|
||||
@@ -525,11 +525,11 @@ public class CarpetScriptHost extends ScriptHost
|
||||
})));
|
||||
}
|
||||
}
|
||||
scriptServer.server.getCommandManager().getDispatcher().register(command);
|
||||
scriptServer.server.getCommands().getDispatcher().register(command);
|
||||
return true;
|
||||
}
|
||||
|
||||
public LiteralArgumentBuilder<ServerCommandSource> readCommands(Predicate<ServerCommandSource> useValidator) throws CommandSyntaxException
|
||||
public LiteralArgumentBuilder<CommandSourceStack> readCommands(Predicate<CommandSourceStack> useValidator) throws CommandSyntaxException
|
||||
{
|
||||
Value commands = appConfig.get(StringValue.of("commands"));
|
||||
|
||||
@@ -599,7 +599,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
}
|
||||
}
|
||||
|
||||
public CarpetScriptHost retrieveForExecution(ServerCommandSource source, ServerPlayerEntity player)
|
||||
public CarpetScriptHost retrieveForExecution(CommandSourceStack source, ServerPlayer player)
|
||||
{
|
||||
CarpetScriptHost target = null;
|
||||
if (!perUser)
|
||||
@@ -608,13 +608,13 @@ public class CarpetScriptHost extends ScriptHost
|
||||
}
|
||||
else if (player != null)
|
||||
{
|
||||
target = (CarpetScriptHost) retrieveForExecution(player.getEntityName());
|
||||
target = (CarpetScriptHost) retrieveForExecution(player.getScoreboardName());
|
||||
}
|
||||
if (target != null && target.errorSnooper == null) target.setChatErrorSnooper(source);
|
||||
return target;
|
||||
}
|
||||
|
||||
public CarpetScriptHost retrieveOwnForExecution(ServerCommandSource source) throws CommandSyntaxException
|
||||
public CarpetScriptHost retrieveOwnForExecution(CommandSourceStack source) throws CommandSyntaxException
|
||||
{
|
||||
if (!perUser)
|
||||
{
|
||||
@@ -622,21 +622,21 @@ public class CarpetScriptHost extends ScriptHost
|
||||
return this;
|
||||
}
|
||||
// user based
|
||||
ServerPlayerEntity player;
|
||||
ServerPlayer player;
|
||||
try
|
||||
{
|
||||
player = source.getPlayer();
|
||||
player = source.getPlayerOrException();
|
||||
}
|
||||
catch (CommandSyntaxException ignored)
|
||||
{
|
||||
throw new SimpleCommandExceptionType(new LiteralText("Cannot run player based apps without the player context")).create();
|
||||
throw new SimpleCommandExceptionType(new TextComponent("Cannot run player based apps without the player context")).create();
|
||||
}
|
||||
CarpetScriptHost userHost = (CarpetScriptHost)retrieveForExecution(player.getEntityName());
|
||||
CarpetScriptHost userHost = (CarpetScriptHost)retrieveForExecution(player.getScoreboardName());
|
||||
if (userHost.errorSnooper == null) userHost.setChatErrorSnooper(source);
|
||||
return userHost;
|
||||
}
|
||||
|
||||
public Value handleCommandLegacy(ServerCommandSource source, String call, List<Integer> coords, String arg)
|
||||
public Value handleCommandLegacy(CommandSourceStack source, String call, List<Integer> coords, String arg)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -660,7 +660,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
return Value.NULL;
|
||||
}
|
||||
|
||||
public Value handleCommand(ServerCommandSource source, FunctionValue function, List<Value> args)
|
||||
public Value handleCommand(CommandSourceStack source, FunctionValue function, List<Value> args)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -681,7 +681,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
return Value.NULL;
|
||||
}
|
||||
|
||||
public Value callLegacy(ServerCommandSource source, String call, List<Integer> coords, String arg)
|
||||
public Value callLegacy(CommandSourceStack source, String call, List<Integer> coords, String arg)
|
||||
{
|
||||
if (CarpetServer.scriptServer.stopAll)
|
||||
throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null);
|
||||
@@ -768,7 +768,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
{
|
||||
// TODO: this is just for now - invoke would be able to invoke other hosts scripts
|
||||
assertAppIntegrity(function.getModule());
|
||||
Context context = new CarpetContext(this, source, BlockPos.ORIGIN);
|
||||
Context context = new CarpetContext(this, source, BlockPos.ZERO);
|
||||
return scriptServer.events.handleEvents.getWhileDisabled(() -> function.getExpression().evalValue(
|
||||
() -> function.lazyEval(context, Context.VOID, function.getExpression(), function.getToken(), argv),
|
||||
context,
|
||||
@@ -781,7 +781,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
}
|
||||
}
|
||||
|
||||
public Value call(ServerCommandSource source, FunctionValue function, List<Value> argv)
|
||||
public Value call(CommandSourceStack source, FunctionValue function, List<Value> argv)
|
||||
{
|
||||
if (CarpetServer.scriptServer.stopAll)
|
||||
throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null);
|
||||
@@ -799,7 +799,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
try
|
||||
{
|
||||
assertAppIntegrity(function.getModule());
|
||||
Context context = new CarpetContext(this, source, BlockPos.ORIGIN);
|
||||
Context context = new CarpetContext(this, source, BlockPos.ZERO);
|
||||
return function.getExpression().evalValue(
|
||||
() -> function.execute(context, Context.VOID, function.getExpression(), function.getToken(), argv),
|
||||
context,
|
||||
@@ -812,7 +812,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
}
|
||||
}
|
||||
|
||||
public Value callUDF(BlockPos pos, ServerCommandSource source, FunctionValue fun, List<Value> argv) throws InvalidCallbackException, IntegrityException
|
||||
public Value callUDF(BlockPos pos, CommandSourceStack source, FunctionValue fun, List<Value> argv) throws InvalidCallbackException, IntegrityException
|
||||
{
|
||||
if (CarpetServer.scriptServer.stopAll)
|
||||
return Value.NULL;
|
||||
@@ -843,12 +843,12 @@ public class CarpetScriptHost extends ScriptHost
|
||||
|
||||
public Value callNow(FunctionValue fun, List<Value> arguments)
|
||||
{
|
||||
ServerPlayerEntity player = (user==null)?null:scriptServer.server.getPlayerManager().getPlayer(user);
|
||||
ServerCommandSource source = (player != null)?player.getCommandSource():scriptServer.server.getCommandSource();
|
||||
ServerPlayer player = (user==null)?null:scriptServer.server.getPlayerList().getPlayerByName(user);
|
||||
CommandSourceStack source = (player != null)?player.createCommandSourceStack():scriptServer.server.createCommandSourceStack();
|
||||
return scriptServer.events.handleEvents.getWhileDisabled(()->{
|
||||
try
|
||||
{
|
||||
return callUDF(BlockPos.ORIGIN, source, fun, arguments);
|
||||
return callUDF(BlockPos.ZERO, source, fun, arguments);
|
||||
}
|
||||
catch (InvalidCallbackException ignored)
|
||||
{
|
||||
@@ -873,9 +873,9 @@ public class CarpetScriptHost extends ScriptHost
|
||||
{
|
||||
|
||||
String markerName = Auxiliary.MARKER_STRING + "_" + ((getName() == null) ? "" : getName());
|
||||
for (ServerWorld world : scriptServer.server.getWorlds())
|
||||
for (ServerLevel world : scriptServer.server.getAllLevels())
|
||||
{
|
||||
for (Entity e : world.getEntitiesByType(EntityType.ARMOR_STAND, (as) -> as.getScoreboardTags().contains(markerName)))
|
||||
for (Entity e : world.getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName)))
|
||||
{
|
||||
e.discard();
|
||||
}
|
||||
@@ -890,12 +890,12 @@ public class CarpetScriptHost extends ScriptHost
|
||||
Module.saveData(main, globalState);
|
||||
}
|
||||
|
||||
private NbtElement loadState()
|
||||
private Tag loadState()
|
||||
{
|
||||
return Module.getData(main);
|
||||
}
|
||||
|
||||
public NbtElement readFileTag(FileArgument fdesc)
|
||||
public Tag readFileTag(FileArgument fdesc)
|
||||
{
|
||||
if (getName() == null && !fdesc.isShared) return null;
|
||||
if (fdesc.resource != null)
|
||||
@@ -905,7 +905,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
return ((CarpetScriptHost)parent).globalState;
|
||||
}
|
||||
|
||||
public boolean writeTagFile(NbtElement tag, FileArgument fdesc)
|
||||
public boolean writeTagFile(Tag tag, FileArgument fdesc)
|
||||
{
|
||||
if (getName() == null && !fdesc.isShared) return false; // if belongs to an app, cannot be default host.
|
||||
|
||||
@@ -973,14 +973,14 @@ public class CarpetScriptHost extends ScriptHost
|
||||
}
|
||||
}
|
||||
|
||||
public void setChatErrorSnooper(ServerCommandSource source)
|
||||
public void setChatErrorSnooper(CommandSourceStack source)
|
||||
{
|
||||
responsibleSource = source;
|
||||
errorSnooper = (expr, /*Nullable*/ token, ctx, message) ->
|
||||
{
|
||||
try
|
||||
{
|
||||
source.getPlayer();
|
||||
source.getPlayerOrException();
|
||||
}
|
||||
catch (CommandSyntaxException e)
|
||||
{
|
||||
@@ -1021,7 +1021,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>Creates a {@link BaseText} using {@link Messenger} that has the locals in the {@code line} snippet with a hover over
|
||||
* <p>Creates a {@link BaseComponent} using {@link Messenger} that has the locals in the {@code line} snippet with a hover over
|
||||
* tooltip with the value of the local at that location</p>
|
||||
* @param line The line to find references to locals on
|
||||
* @param context The {@link Context} to extract the locals from
|
||||
@@ -1031,7 +1031,7 @@ public class CarpetScriptHost extends ScriptHost
|
||||
* @implNote The implementation of this method is far from perfect, and won't detect actual references to variables, but try to find the strings
|
||||
* and add the hover effect to anything that equals to any variable name, so short variable names may appear on random positions
|
||||
*/
|
||||
private static BaseText withLocals(String format, String line, Context context)
|
||||
private static BaseComponent withLocals(String format, String line, Context context)
|
||||
{
|
||||
format += " ";
|
||||
List<String> stringsToFormat = new ArrayList<>();
|
||||
|
||||
@@ -30,10 +30,10 @@ import com.mojang.brigadier.tree.CommandNode;
|
||||
|
||||
import net.fabricmc.api.EnvType;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.util.WorldSavePath;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
@@ -123,7 +123,7 @@ public class CarpetScriptServer
|
||||
unloadableModules = new HashSet<>();
|
||||
tickStart = 0L;
|
||||
stopAll = false;
|
||||
holyMoly = server.getCommandManager().getDispatcher().getRoot().getChildren().stream().map(CommandNode::getName).collect(Collectors.toSet());
|
||||
holyMoly = server.getCommands().getDispatcher().getRoot().getChildren().stream().map(CommandNode::getName).collect(Collectors.toSet());
|
||||
globalHost = CarpetScriptHost.create(this, null, false, null, p -> true, false, null);
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ public class CarpetScriptServer
|
||||
{
|
||||
for (String moduleName: listAvailableModules(false))
|
||||
{
|
||||
addScriptHost(server.getCommandSource(), moduleName, null, true, true, false, null);
|
||||
addScriptHost(server.createCommandSourceStack(), moduleName, null, true, true, false, null);
|
||||
}
|
||||
}
|
||||
CarpetEventServer.Event.START.onTick();
|
||||
@@ -148,7 +148,7 @@ public class CarpetScriptServer
|
||||
public Module getModule(String name, boolean allowLibraries)
|
||||
{
|
||||
try {
|
||||
Path folder = server.getSavePath(WorldSavePath.ROOT).resolve("scripts");
|
||||
Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts");
|
||||
if (!Files.exists(folder))
|
||||
Files.createDirectories(folder);
|
||||
Optional<Path>
|
||||
@@ -208,7 +208,7 @@ public class CarpetScriptServer
|
||||
}
|
||||
}
|
||||
try {
|
||||
Path worldScripts = server.getSavePath(WorldSavePath.ROOT).resolve("scripts");
|
||||
Path worldScripts = server.getWorldPath(LevelResource.ROOT).resolve("scripts");
|
||||
if (!Files.exists(worldScripts))
|
||||
Files.createDirectories(worldScripts);
|
||||
Files.list(worldScripts)
|
||||
@@ -237,7 +237,7 @@ public class CarpetScriptServer
|
||||
return modules.get(name);
|
||||
}
|
||||
|
||||
public boolean addScriptHost(ServerCommandSource source, String name, Predicate<ServerCommandSource> commandValidator,
|
||||
public boolean addScriptHost(CommandSourceStack source, String name, Predicate<CommandSourceStack> commandValidator,
|
||||
boolean perPlayer, boolean autoload, boolean isRuleApp, AppStoreManager.StoreNode installer)
|
||||
{
|
||||
CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet load", CarpetProfiler.TYPE.GENERAL);
|
||||
@@ -312,9 +312,9 @@ public class CarpetScriptServer
|
||||
if (newHost.isPerUser())
|
||||
{
|
||||
// that will provide player hosts right at the startup
|
||||
for (ServerPlayerEntity player : source.getServer().getPlayerManager().getPlayerList())
|
||||
for (ServerPlayer player : source.getServer().getPlayerList().getPlayers())
|
||||
{
|
||||
newHost.retrieveForExecution(player.getCommandSource(), player);
|
||||
newHost.retrieveForExecution(player.createCommandSourceStack(), player);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -335,7 +335,7 @@ public class CarpetScriptServer
|
||||
}
|
||||
|
||||
|
||||
public boolean removeScriptHost(ServerCommandSource source, String name, boolean notifySource, boolean isRuleApp)
|
||||
public boolean removeScriptHost(CommandSourceStack source, String name, boolean notifySource, boolean isRuleApp)
|
||||
{
|
||||
name = name.toLowerCase(Locale.ROOT);
|
||||
if (!modules.containsKey(name) || (!isRuleApp && !unloadableModules.contains(name)))
|
||||
@@ -353,12 +353,12 @@ public class CarpetScriptServer
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean uninstallApp(ServerCommandSource source, String name)
|
||||
public boolean uninstallApp(CommandSourceStack source, String name)
|
||||
{
|
||||
try
|
||||
{
|
||||
name = name.toLowerCase(Locale.ROOT);
|
||||
Path folder = server.getSavePath(WorldSavePath.ROOT).resolve("scripts/trash");
|
||||
Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts/trash");
|
||||
if (!Files.exists(folder)) Files.createDirectories(folder);
|
||||
if (!Files.exists(folder.getParent().resolve(name+".sc")))
|
||||
{
|
||||
@@ -401,7 +401,7 @@ public class CarpetScriptServer
|
||||
}
|
||||
}
|
||||
|
||||
public void onPlayerJoin(ServerPlayerEntity player)
|
||||
public void onPlayerJoin(ServerPlayer player)
|
||||
{
|
||||
modules.values().forEach(h ->
|
||||
{
|
||||
@@ -409,7 +409,7 @@ public class CarpetScriptServer
|
||||
{
|
||||
try
|
||||
{
|
||||
h.retrieveOwnForExecution(player.getCommandSource());
|
||||
h.retrieveOwnForExecution(player.createCommandSourceStack());
|
||||
}
|
||||
catch (CommandSyntaxException ignored)
|
||||
{
|
||||
@@ -418,7 +418,7 @@ public class CarpetScriptServer
|
||||
});
|
||||
}
|
||||
|
||||
private static record TransferData(boolean perUser, Predicate<ServerCommandSource> commandValidator, boolean isRuleApp)
|
||||
private static record TransferData(boolean perUser, Predicate<CommandSourceStack> commandValidator, boolean isRuleApp)
|
||||
{
|
||||
private TransferData(CarpetScriptHost host)
|
||||
{
|
||||
@@ -430,10 +430,10 @@ public class CarpetScriptServer
|
||||
{
|
||||
Map<String, TransferData> apps = new HashMap<>();
|
||||
modules.forEach((s, h) -> apps.put(s, new TransferData(h)));
|
||||
apps.keySet().forEach(s -> removeScriptHost(server.getCommandSource(), s, false, false));
|
||||
apps.keySet().forEach(s -> removeScriptHost(server.createCommandSourceStack(), s, false, false));
|
||||
CarpetEventServer.Event.clearAllBuiltinEvents();
|
||||
init();
|
||||
apps.forEach((s, data) -> addScriptHost(server.getCommandSource(), s,data.commandValidator, data.perUser,false, data.isRuleApp, null));
|
||||
apps.forEach((s, data) -> addScriptHost(server.createCommandSourceStack(), s,data.commandValidator, data.perUser,false, data.isRuleApp, null));
|
||||
}
|
||||
|
||||
public void reAddCommands()
|
||||
|
||||
@@ -8,16 +8,15 @@ import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.StringValue;
|
||||
import carpet.script.value.Value;
|
||||
import carpet.script.value.ValueConversions;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.damage.DamageSource;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class EntityEventsGroup
|
||||
{
|
||||
@@ -48,7 +47,7 @@ public class EntityEventsGroup
|
||||
}
|
||||
if (key.user() != null)
|
||||
{
|
||||
if (entity.getServer().getPlayerManager().getPlayer(key.user())==null)
|
||||
if (entity.getServer().getPlayerList().getPlayerByName(key.user())==null)
|
||||
{
|
||||
iterator.remove();
|
||||
continue;
|
||||
@@ -105,8 +104,8 @@ public class EntityEventsGroup
|
||||
return Arrays.asList(
|
||||
new EntityValue(entity),
|
||||
new NumericValue(amount),
|
||||
new StringValue(source.getName()),
|
||||
source.getAttacker()==null?Value.NULL:new EntityValue(source.getAttacker())
|
||||
new StringValue(source.getMsgId()),
|
||||
source.getEntity()==null?Value.NULL:new EntityValue(source.getEntity())
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -117,9 +116,9 @@ public class EntityEventsGroup
|
||||
{
|
||||
return Arrays.asList(
|
||||
new EntityValue(entity),
|
||||
ValueConversions.of((Vec3d) providedArgs[0]),
|
||||
ValueConversions.of((Vec3d) providedArgs[1]),
|
||||
ValueConversions.of((Vec3d) providedArgs[2])
|
||||
ValueConversions.of((Vec3) providedArgs[0]),
|
||||
ValueConversions.of((Vec3) providedArgs[1]),
|
||||
ValueConversions.of((Vec3) providedArgs[2])
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -143,7 +142,7 @@ public class EntityEventsGroup
|
||||
public CarpetEventServer.CallbackResult call(CarpetEventServer.Callback tickCall, Entity entity, Object ... args)
|
||||
{
|
||||
assert args.length == argcount-1;
|
||||
return tickCall.execute(entity.getCommandSource(), makeArgs(entity, args));
|
||||
return tickCall.execute(entity.createCommandSourceStack(), makeArgs(entity, args));
|
||||
}
|
||||
protected List<Value> makeArgs(Entity entity, Object ... args)
|
||||
{
|
||||
|
||||
@@ -3,11 +3,6 @@ package carpet.script.annotation;
|
||||
import carpet.logging.HUDController;
|
||||
import carpet.script.annotation.Param.AllowSingleton;
|
||||
import carpet.script.exception.InternalExpressionException;
|
||||
import net.minecraft.network.packet.s2c.play.TitleS2CPacket;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.BaseText;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -5,7 +5,8 @@ import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
import java.lang.reflect.AnnotatedType;
|
||||
import java.util.Iterator;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import carpet.script.CarpetContext;
|
||||
@@ -18,8 +19,6 @@ import carpet.script.bundled.Module;
|
||||
import carpet.script.value.BlockValue;
|
||||
import carpet.script.value.FunctionValue;
|
||||
import carpet.script.value.Value;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
import static java.lang.annotation.ElementType.PARAMETER;
|
||||
import static java.lang.annotation.ElementType.TYPE_USE;
|
||||
@@ -62,7 +61,7 @@ public interface Locator
|
||||
/**
|
||||
* <p>Represents that the annotated argument must be gotten by passing the arguments in there into a {@link Vector3Argument} locator.</p>
|
||||
*
|
||||
* <p>Must be used in either a {@link Vector3Argument} or a {@link net.minecraft.util.math.Vec3d Vec3d} parameter.</p>
|
||||
* <p>Must be used in either a {@link Vector3Argument} or a {@link net.minecraft.world.phys.Vec3 Vec3d} parameter.</p>
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RUNTIME)
|
||||
@@ -71,7 +70,7 @@ public interface Locator
|
||||
{
|
||||
/**
|
||||
* <p>Whether or not should the {@link Vector3Argument} locator accept an optional direction aside from the
|
||||
* {@link net.minecraft.util.math.Vec3d}</p> <p>This parameter can only be used in a {@link Vector3Argument} type, since else there is no way
|
||||
* {@link net.minecraft.world.phys.Vec3}</p> <p>This parameter can only be used in a {@link Vector3Argument} type, since else there is no way
|
||||
* to get the direction too.</p>
|
||||
*/
|
||||
boolean optionalDirection() default false;
|
||||
@@ -187,7 +186,7 @@ public interface Locator
|
||||
{
|
||||
this.optionalDirection = annotation.optionalDirection();
|
||||
this.optionalEntity = annotation.optionalEntity();
|
||||
this.returnVec3d = type == net.minecraft.util.math.Vec3d.class; // Because of the locator
|
||||
this.returnVec3d = type == net.minecraft.world.phys.Vec3.class; // Because of the locator
|
||||
if (returnVec3d && optionalDirection)
|
||||
throw new IllegalArgumentException("optionalDirection Locator.Vec3d cannot be used for Vec3d type, use Vector3Argument instead");
|
||||
if (!returnVec3d && type != Vector3Argument.class)
|
||||
|
||||
@@ -4,8 +4,14 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.GlobalPos;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.apache.commons.lang3.ClassUtils;
|
||||
|
||||
import carpet.script.LazyValue;
|
||||
@@ -16,13 +22,6 @@ import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.StringValue;
|
||||
import carpet.script.value.Value;
|
||||
import carpet.script.value.ValueConversions;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.dynamic.GlobalPos;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/**
|
||||
* <p>A converter from a given {@link Object} of type T into a {@link LazyValue}, used in order to convert the outputs of methods into usable Scarpet
|
||||
@@ -47,12 +46,12 @@ public final class OutputConverter<T>
|
||||
registerToValue(Long.class, NumericValue::of);
|
||||
registerToValue(String.class, StringValue::new);
|
||||
registerToValue(Entity.class, EntityValue::new);
|
||||
registerToValue(Text.class, FormattedTextValue::new);
|
||||
registerToValue(NbtElement.class, NBTSerializableValue::new);
|
||||
registerToValue(Component.class, FormattedTextValue::new);
|
||||
registerToValue(Tag.class, NBTSerializableValue::new);
|
||||
registerToValue(BlockPos.class, ValueConversions::of);
|
||||
registerToValue(Vec3d.class, ValueConversions::of);
|
||||
registerToValue(Vec3.class, ValueConversions::of);
|
||||
registerToValue(ItemStack.class, ValueConversions::of);
|
||||
registerToValue(Identifier.class, ValueConversions::of);
|
||||
registerToValue(ResourceLocation.class, ValueConversions::of);
|
||||
registerToValue(GlobalPos.class, ValueConversions::of);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,9 +20,9 @@ import carpet.script.value.FormattedTextValue;
|
||||
import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.StringValue;
|
||||
import carpet.script.value.Value;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
|
||||
import static java.lang.annotation.ElementType.PARAMETER;
|
||||
import static java.lang.annotation.ElementType.TYPE_USE;
|
||||
@@ -97,7 +97,7 @@ public interface Param
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>Defines that a parameter of type {@link String}, {@link Text}, {@link ServerPlayerEntity}, {@link Boolean} or other registered strict type
|
||||
* <p>Defines that a parameter of type {@link String}, {@link Component}, {@link ServerPlayer}, {@link Boolean} or other registered strict type
|
||||
* <b>must</b> be of its corresponding {@link Value} in order to be accepted (respectively {@link StringValue}, {@link FormattedTextValue},
|
||||
* {@link EntityValue} or {@link BooleanValue}).</p>
|
||||
*
|
||||
@@ -105,7 +105,7 @@ public interface Param
|
||||
* {@code new LiteralText(Value#getString())}, {@link EntityValue#getPlayerByValue(MinecraftServer, Value)} or {@link Value#getBoolean()}.</p>
|
||||
*
|
||||
* <p>You can define "shallow strictness" ({@link #shallow()}) if you want to allow passing both a {@link StringValue} or a
|
||||
* {@link FormattedTextValue} to a {@link Text} parameter or a {@link NumericValue} to a {@link BooleanValue}, but not any {@link Value}.</p>
|
||||
* {@link FormattedTextValue} to a {@link Component} parameter or a {@link NumericValue} to a {@link BooleanValue}, but not any {@link Value}.</p>
|
||||
*
|
||||
*/
|
||||
@Documented
|
||||
@@ -114,7 +114,7 @@ public interface Param
|
||||
public @interface Strict
|
||||
{
|
||||
/**
|
||||
* <p>Defines whether this parameter can accept types with "shallow strictness", that is, in order to get a {@link Text}, accepting either a
|
||||
* <p>Defines whether this parameter can accept types with "shallow strictness", that is, in order to get a {@link Component}, accepting either a
|
||||
* {@link StringValue} or a {@link FormattedTextValue} as the parameter, or in order to get a {@link Boolean}, accepting either a
|
||||
* {@link NumericValue} or a {@link BooleanValue}.</p>
|
||||
*
|
||||
@@ -198,9 +198,9 @@ public interface Param
|
||||
static
|
||||
{ // TODO Specify strictness in name?
|
||||
registerStrictConverter(String.class, false, new SimpleTypeConverter<>(StringValue.class, StringValue::getString, "string"));
|
||||
registerStrictConverter(Text.class, false, new SimpleTypeConverter<>(FormattedTextValue.class, FormattedTextValue::getText, "text"));
|
||||
registerStrictConverter(Text.class, true, new SimpleTypeConverter<>(StringValue.class, FormattedTextValue::getTextByValue, "text"));
|
||||
registerStrictConverter(ServerPlayerEntity.class, false, new SimpleTypeConverter<>(EntityValue.class,
|
||||
registerStrictConverter(Component.class, false, new SimpleTypeConverter<>(FormattedTextValue.class, FormattedTextValue::getText, "text"));
|
||||
registerStrictConverter(Component.class, true, new SimpleTypeConverter<>(StringValue.class, FormattedTextValue::getTextByValue, "text"));
|
||||
registerStrictConverter(ServerPlayer.class, false, new SimpleTypeConverter<>(EntityValue.class,
|
||||
v -> EntityValue.getPlayerByValue(CarpetServer.minecraft_server, v), "online player entity"));
|
||||
registerStrictConverter(Boolean.class, false, new SimpleTypeConverter<>(BooleanValue.class, BooleanValue::getBoolean, "boolean"));
|
||||
registerStrictConverter(Boolean.class, true, new SimpleTypeConverter<>(NumericValue.class, NumericValue::getBoolean, "boolean"));
|
||||
|
||||
@@ -3,7 +3,10 @@ package carpet.script.annotation;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.level.Level;
|
||||
import carpet.CarpetServer;
|
||||
import carpet.script.exception.InternalExpressionException;
|
||||
import carpet.script.value.EntityValue;
|
||||
@@ -11,10 +14,6 @@ import carpet.script.value.FormattedTextValue;
|
||||
import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.Value;
|
||||
import carpet.script.value.ValueConversions;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
/**
|
||||
* <p>A simple {@link ValueConverter} implementation that converts from a specified subclass of {@link Value} into {@code <R>} by using a given
|
||||
@@ -32,10 +31,10 @@ public final class SimpleTypeConverter<T extends Value, R> implements ValueConve
|
||||
private static final Map<Class<?>, SimpleTypeConverter<? extends Value, ?>> byResult = new HashMap<>();
|
||||
static
|
||||
{
|
||||
registerType(Value.class, ServerPlayerEntity.class, val -> EntityValue.getPlayerByValue(CarpetServer.minecraft_server, val), "online player");
|
||||
registerType(Value.class, ServerPlayer.class, val -> EntityValue.getPlayerByValue(CarpetServer.minecraft_server, val), "online player");
|
||||
registerType(EntityValue.class, Entity.class, EntityValue::getEntity, "entity");
|
||||
registerType(Value.class, World.class, val -> ValueConversions.dimFromValue(val, CarpetServer.minecraft_server), "dimension");
|
||||
registerType(Value.class, Text.class, FormattedTextValue::getTextByValue, "text");
|
||||
registerType(Value.class, Level.class, val -> ValueConversions.dimFromValue(val, CarpetServer.minecraft_server), "dimension");
|
||||
registerType(Value.class, Component.class, FormattedTextValue::getTextByValue, "text");
|
||||
registerType(Value.class, String.class, Value::getString, "string"); // Check out @Param.Strict for more specific types
|
||||
|
||||
// Primitives are also query those classes
|
||||
|
||||
@@ -41,68 +41,64 @@ import carpet.script.value.ValueConversions;
|
||||
import carpet.utils.Messenger;
|
||||
import com.google.common.collect.Lists;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.command.DataCommandStorage;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EntityType;
|
||||
import net.minecraft.entity.EquipmentSlot;
|
||||
import net.minecraft.entity.decoration.ArmorStandEntity;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.nbt.NbtHelper;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.Rotations;
|
||||
import net.minecraft.core.particles.ParticleOptions;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.NbtIo;
|
||||
import net.minecraft.nbt.NbtOps;
|
||||
import net.minecraft.nbt.NbtString;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.network.Packet;
|
||||
import net.minecraft.network.packet.s2c.play.ClearTitleS2CPacket;
|
||||
import net.minecraft.network.packet.s2c.play.OverlayMessageS2CPacket;
|
||||
import net.minecraft.network.packet.s2c.play.PlaySoundIdS2CPacket;
|
||||
import net.minecraft.network.packet.s2c.play.PlayerListHeaderS2CPacket;
|
||||
//import net.minecraft.network.packet.s2c.play.TitleS2CPacket;
|
||||
//import net.minecraft.network.packet.s2c.play.TitleS2CPacket.Action;
|
||||
import net.minecraft.network.packet.s2c.play.SubtitleS2CPacket;
|
||||
import net.minecraft.network.packet.s2c.play.TitleFadeS2CPacket;
|
||||
import net.minecraft.network.packet.s2c.play.TitleS2CPacket;
|
||||
import net.minecraft.particle.ParticleEffect;
|
||||
import net.minecraft.resource.DataPackSettings;
|
||||
import net.minecraft.resource.ReloadableResourceManagerImpl;
|
||||
import net.minecraft.resource.ResourcePackManager;
|
||||
import net.minecraft.resource.ResourcePackProfile;
|
||||
import net.minecraft.resource.ServerResourceManager;
|
||||
import net.minecraft.nbt.NbtUtils;
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.network.chat.BaseComponent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.game.ClientboundClearTitlesPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundCustomSoundPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetActionBarTextPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetSubtitleTextPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetTitleTextPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetTitlesAnimationPacket;
|
||||
import net.minecraft.resources.RegistryReadOps;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.sound.SoundCategory;
|
||||
import net.minecraft.stat.Stat;
|
||||
import net.minecraft.stat.StatType;
|
||||
import net.minecraft.text.BaseText;
|
||||
import net.minecraft.text.LiteralText;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.InvalidIdentifierException;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.util.WorldSavePath;
|
||||
import net.minecraft.util.dynamic.RegistryOps;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.ChunkPos;
|
||||
import net.minecraft.util.math.EulerAngle;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.util.registry.DynamicRegistryManager;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
import net.minecraft.util.registry.RegistryKey;
|
||||
import net.minecraft.world.SaveProperties;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.biome.source.BiomeAccess;
|
||||
import net.minecraft.world.border.WorldBorderListener;
|
||||
import net.minecraft.world.dimension.DimensionOptions;
|
||||
import net.minecraft.world.dimension.DimensionType;
|
||||
import net.minecraft.world.gen.GeneratorOptions;
|
||||
import net.minecraft.world.gen.chunk.ChunkGenerator;
|
||||
import net.minecraft.world.level.UnmodifiableLevelProperties;
|
||||
import net.minecraft.world.level.storage.LevelStorage;
|
||||
import net.minecraft.server.ServerResources;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.packs.repository.Pack;
|
||||
import net.minecraft.server.packs.repository.PackRepository;
|
||||
import net.minecraft.server.packs.resources.SimpleReloadableResourceManager;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.stats.Stat;
|
||||
import net.minecraft.stats.StatType;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.decoration.ArmorStand;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.DataPackConfig;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.biome.BiomeManager;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.border.BorderChangeListener;
|
||||
import net.minecraft.world.level.chunk.ChunkGenerator;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.dimension.LevelStem;
|
||||
import net.minecraft.world.level.levelgen.WorldGenSettings;
|
||||
import net.minecraft.world.level.storage.CommandStorage;
|
||||
import net.minecraft.world.level.storage.DerivedLevelData;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
import net.minecraft.world.level.storage.LevelStorageSource;
|
||||
import net.minecraft.world.level.storage.WorldData;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
@@ -136,7 +132,7 @@ import static java.lang.Math.min;
|
||||
|
||||
public class Auxiliary {
|
||||
public static final String MARKER_STRING = "__scarpet_marker";
|
||||
private static final Map<String, SoundCategory> mixerMap = Arrays.stream(SoundCategory.values()).collect(Collectors.toMap(SoundCategory::getName, k -> k));
|
||||
private static final Map<String, SoundSource> mixerMap = Arrays.stream(SoundSource.values()).collect(Collectors.toMap(SoundSource::getName, k -> k));
|
||||
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().registerTypeAdapter(Value.class, new ScarpetJsonDeserializer()).create();
|
||||
|
||||
@Deprecated
|
||||
@@ -158,16 +154,16 @@ public class Auxiliary {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
if (lv.size() == 0)
|
||||
{
|
||||
return ListValue.wrap(Registry.SOUND_EVENT.getIds().stream().map(ValueConversions::of));
|
||||
return ListValue.wrap(Registry.SOUND_EVENT.keySet().stream().map(ValueConversions::of));
|
||||
}
|
||||
String rawString = lv.get(0).getString();
|
||||
Identifier soundName = InputValidator.identifierOf(rawString);
|
||||
ResourceLocation soundName = InputValidator.identifierOf(rawString);
|
||||
Vector3Argument locator = Vector3Argument.findIn(lv, 1);
|
||||
if (Registry.SOUND_EVENT.get(soundName) == null)
|
||||
throw new ThrowStatement(rawString, Throwables.UNKNOWN_SOUND);
|
||||
float volume = 1.0F;
|
||||
float pitch = 1.0F;
|
||||
SoundCategory mixer = SoundCategory.MASTER;
|
||||
SoundSource mixer = SoundSource.MASTER;
|
||||
if (lv.size() > 0+locator.offset)
|
||||
{
|
||||
volume = (float) NumericValue.asNumber(lv.get(0+locator.offset)).getDouble();
|
||||
@@ -182,13 +178,13 @@ public class Auxiliary {
|
||||
}
|
||||
}
|
||||
}
|
||||
Vec3d vec = locator.vec;
|
||||
Vec3 vec = locator.vec;
|
||||
double d0 = Math.pow(volume > 1.0F ? (double)(volume * 16.0F) : 16.0D, 2.0D);
|
||||
int count = 0;
|
||||
for (ServerPlayerEntity player : cc.s.getWorld().getPlayers( (p) -> p.squaredDistanceTo(vec) < d0))
|
||||
for (ServerPlayer player : cc.s.getLevel().getPlayers( (p) -> p.distanceToSqr(vec) < d0))
|
||||
{
|
||||
count++;
|
||||
player.networkHandler.sendPacket(new PlaySoundIdS2CPacket(soundName, mixer, vec, volume, pitch));
|
||||
player.connection.send(new ClientboundCustomSoundPacket(soundName, mixer, vec, volume, pitch));
|
||||
}
|
||||
return new NumericValue(count);
|
||||
});
|
||||
@@ -196,15 +192,15 @@ public class Auxiliary {
|
||||
expression.addContextFunction("particle", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
if (lv.size() == 0) return ListValue.wrap(Registry.PARTICLE_TYPE.getIds().stream().map(ValueConversions::of));
|
||||
if (lv.size() == 0) return ListValue.wrap(Registry.PARTICLE_TYPE.keySet().stream().map(ValueConversions::of));
|
||||
MinecraftServer ms = cc.s.getServer();
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
Vector3Argument locator = Vector3Argument.findIn(lv, 1);
|
||||
String particleName = lv.get(0).getString();
|
||||
int count = 10;
|
||||
double speed = 0;
|
||||
float spread = 0.5f;
|
||||
ServerPlayerEntity player = null;
|
||||
ServerPlayer player = null;
|
||||
if (lv.size() > locator.offset)
|
||||
{
|
||||
count = (int) NumericValue.asNumber(lv.get(locator.offset)).getLong();
|
||||
@@ -216,24 +212,24 @@ public class Auxiliary {
|
||||
speed = NumericValue.asNumber(lv.get(2 + locator.offset)).getDouble();
|
||||
if (lv.size() > 3 + locator.offset) // should accept entity as well as long as it is player
|
||||
{
|
||||
player = ms.getPlayerManager().getPlayer(lv.get(3 + locator.offset).getString());
|
||||
player = ms.getPlayerList().getPlayerByName(lv.get(3 + locator.offset).getString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ParticleEffect particle = ShapeDispatcher.getParticleData(particleName);
|
||||
Vec3d vec = locator.vec;
|
||||
ParticleOptions particle = ShapeDispatcher.getParticleData(particleName);
|
||||
Vec3 vec = locator.vec;
|
||||
if (player == null)
|
||||
{
|
||||
for (PlayerEntity p : (world.getPlayers()))
|
||||
for (Player p : (world.players()))
|
||||
{
|
||||
world.spawnParticles((ServerPlayerEntity)p, particle, true, vec.x, vec.y, vec.z, count,
|
||||
world.sendParticles((ServerPlayer)p, particle, true, vec.x, vec.y, vec.z, count,
|
||||
spread, spread, spread, speed);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
world.spawnParticles(player,
|
||||
world.sendParticles(player,
|
||||
particle, true, vec.x, vec.y, vec.z, count,
|
||||
spread, spread, spread, speed);
|
||||
}
|
||||
@@ -244,13 +240,13 @@ public class Auxiliary {
|
||||
expression.addContextFunction("particle_line", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
String particleName = lv.get(0).getString();
|
||||
ParticleEffect particle = ShapeDispatcher.getParticleData(particleName);
|
||||
ParticleOptions particle = ShapeDispatcher.getParticleData(particleName);
|
||||
Vector3Argument pos1 = Vector3Argument.findIn(lv, 1);
|
||||
Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset);
|
||||
double density = 1.0;
|
||||
ServerPlayerEntity player = null;
|
||||
ServerPlayer player = null;
|
||||
if (lv.size() > pos2.offset+0 )
|
||||
{
|
||||
density = NumericValue.asNumber(lv.get(pos2.offset+0)).getDouble();
|
||||
@@ -264,18 +260,18 @@ public class Auxiliary {
|
||||
if (playerValue instanceof EntityValue)
|
||||
{
|
||||
Entity e = ((EntityValue) playerValue).getEntity();
|
||||
if (!(e instanceof ServerPlayerEntity)) throw new InternalExpressionException("'particle_line' player argument has to be a player");
|
||||
player = (ServerPlayerEntity) e;
|
||||
if (!(e instanceof ServerPlayer)) throw new InternalExpressionException("'particle_line' player argument has to be a player");
|
||||
player = (ServerPlayer) e;
|
||||
}
|
||||
else
|
||||
{
|
||||
player = cc.s.getServer().getPlayerManager().getPlayer(playerValue.getString());
|
||||
player = cc.s.getServer().getPlayerList().getPlayerByName(playerValue.getString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new NumericValue(ShapeDispatcher.drawParticleLine(
|
||||
(player == null)?world.getPlayers(): Collections.singletonList(player),
|
||||
(player == null)?world.players(): Collections.singletonList(player),
|
||||
particle, pos1.vec, pos2.vec, density
|
||||
));
|
||||
});
|
||||
@@ -283,14 +279,14 @@ public class Auxiliary {
|
||||
expression.addContextFunction("particle_box", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
String particleName = lv.get(0).getString();
|
||||
ParticleEffect particle = ShapeDispatcher.getParticleData(particleName);
|
||||
ParticleOptions particle = ShapeDispatcher.getParticleData(particleName);
|
||||
Vector3Argument pos1 = Vector3Argument.findIn(lv, 1);
|
||||
Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset);
|
||||
|
||||
double density = 1.0;
|
||||
ServerPlayerEntity player = null;
|
||||
ServerPlayer player = null;
|
||||
if (lv.size() > pos2.offset+0 )
|
||||
{
|
||||
density = NumericValue.asNumber(lv.get(pos2.offset+0)).getDouble();
|
||||
@@ -304,21 +300,21 @@ public class Auxiliary {
|
||||
if (playerValue instanceof EntityValue)
|
||||
{
|
||||
Entity e = ((EntityValue) playerValue).getEntity();
|
||||
if (!(e instanceof ServerPlayerEntity)) throw new InternalExpressionException("'particle_box' player argument has to be a player");
|
||||
player = (ServerPlayerEntity) e;
|
||||
if (!(e instanceof ServerPlayer)) throw new InternalExpressionException("'particle_box' player argument has to be a player");
|
||||
player = (ServerPlayer) e;
|
||||
}
|
||||
else
|
||||
{
|
||||
player = cc.s.getServer().getPlayerManager().getPlayer(playerValue.getString());
|
||||
player = cc.s.getServer().getPlayerList().getPlayerByName(playerValue.getString());
|
||||
}
|
||||
}
|
||||
}
|
||||
Vec3d a = pos1.vec;
|
||||
Vec3d b = pos2.vec;
|
||||
Vec3d from = new Vec3d(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z));
|
||||
Vec3d to = new Vec3d(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z));
|
||||
Vec3 a = pos1.vec;
|
||||
Vec3 b = pos2.vec;
|
||||
Vec3 from = new Vec3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z));
|
||||
Vec3 to = new Vec3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z));
|
||||
int particleCount = ShapeDispatcher.Box.particleMesh(
|
||||
player==null?world.getPlayers():Collections.singletonList(player),
|
||||
player==null?world.players():Collections.singletonList(player),
|
||||
particle, density, from, to
|
||||
);
|
||||
return new NumericValue(particleCount);
|
||||
@@ -330,9 +326,9 @@ public class Auxiliary {
|
||||
expression.addContextFunction("draw_shape", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
MinecraftServer server = world.getServer();
|
||||
Set<ServerPlayerEntity> playerTargets = new HashSet<>();
|
||||
Set<ServerPlayer> playerTargets = new HashSet<>();
|
||||
List<ShapeDispatcher.ShapeWithConfig> shapes = new ArrayList<>();
|
||||
if (lv.size() == 1) // bulk
|
||||
{
|
||||
@@ -350,7 +346,7 @@ public class Auxiliary {
|
||||
}
|
||||
|
||||
ShapeDispatcher.sendShape(
|
||||
(playerTargets.isEmpty())?cc.s.getWorld().getPlayers():playerTargets,
|
||||
(playerTargets.isEmpty())?cc.s.getLevel().players():playerTargets,
|
||||
shapes
|
||||
);
|
||||
return Value.TRUE;
|
||||
@@ -382,7 +378,7 @@ public class Auxiliary {
|
||||
throw new InternalExpressionException("'create_marker' requires a name and three coordinates, with optional direction, and optional block on its head");
|
||||
}
|
||||
|
||||
ArmorStandEntity armorstand = new ArmorStandEntity(EntityType.ARMOR_STAND, cc.s.getWorld());
|
||||
ArmorStand armorstand = new ArmorStand(EntityType.ARMOR_STAND, cc.s.getLevel());
|
||||
double yoffset;
|
||||
if (targetBlock == null && name.isEmpty())
|
||||
{
|
||||
@@ -396,14 +392,14 @@ public class Auxiliary {
|
||||
{
|
||||
if (targetBlock==null)
|
||||
{
|
||||
yoffset = -armorstand.getHeight()-0.41;
|
||||
yoffset = -armorstand.getBbHeight()-0.41;
|
||||
}
|
||||
else
|
||||
{
|
||||
yoffset = -armorstand.getHeight()+0.3;
|
||||
yoffset = -armorstand.getBbHeight()+0.3;
|
||||
}
|
||||
}
|
||||
armorstand.refreshPositionAndAngles(
|
||||
armorstand.moveTo(
|
||||
pointLocator.vec.x,
|
||||
//pointLocator.vec.y - ((!interactable && targetBlock == null)?0.41f:((targetBlock==null)?(armorstand.getHeight()+0.41):(armorstand.getHeight()-0.3))),
|
||||
pointLocator.vec.y + yoffset,
|
||||
@@ -411,21 +407,21 @@ public class Auxiliary {
|
||||
(float)pointLocator.yaw,
|
||||
(float) pointLocator.pitch
|
||||
);
|
||||
armorstand.addScoreboardTag(MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName()));
|
||||
armorstand.addScoreboardTag(MARKER_STRING);
|
||||
armorstand.addTag(MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName()));
|
||||
armorstand.addTag(MARKER_STRING);
|
||||
if (targetBlock != null)
|
||||
armorstand.equipStack(EquipmentSlot.HEAD, new ItemStack(targetBlock.getBlock().asItem()));
|
||||
armorstand.setItemSlot(EquipmentSlot.HEAD, new ItemStack(targetBlock.getBlock().asItem()));
|
||||
if (!name.isEmpty())
|
||||
{
|
||||
armorstand.setCustomName(new LiteralText(name));
|
||||
armorstand.setCustomName(new TextComponent(name));
|
||||
armorstand.setCustomNameVisible(true);
|
||||
}
|
||||
armorstand.setHeadRotation(new EulerAngle((int)pointLocator.pitch,0,0));
|
||||
armorstand.setHeadPose(new Rotations((int)pointLocator.pitch,0,0));
|
||||
armorstand.setNoGravity(true);
|
||||
armorstand.setInvisible(true);
|
||||
armorstand.setInvulnerable(true);
|
||||
armorstand.getDataTracker().set(ArmorStandEntity.ARMOR_STAND_FLAGS, (byte)(interactable?8 : 16|8));
|
||||
cc.s.getWorld().spawnEntity(armorstand);
|
||||
armorstand.getEntityData().set(ArmorStand.DATA_CLIENT_FLAGS, (byte)(interactable?8 : 16|8));
|
||||
cc.s.getLevel().addFreshEntity(armorstand);
|
||||
return new EntityValue(armorstand);
|
||||
});
|
||||
|
||||
@@ -433,7 +429,7 @@ public class Auxiliary {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
int total = 0;
|
||||
String markerName = MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName());
|
||||
for (Entity e : cc.s.getWorld().getEntitiesByType(EntityType.ARMOR_STAND, (as) -> as.getScoreboardTags().contains(markerName)))
|
||||
for (Entity e : cc.s.getLevel().getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName)))
|
||||
{
|
||||
total ++;
|
||||
e.discard(); // discard // remove();
|
||||
@@ -443,7 +439,7 @@ public class Auxiliary {
|
||||
|
||||
expression.addUnaryFunction("nbt", NBTSerializableValue::fromValue);
|
||||
|
||||
expression.addUnaryFunction("escape_nbt", v -> new StringValue(NbtString.escape(v.getString())));
|
||||
expression.addUnaryFunction("escape_nbt", v -> new StringValue(StringTag.quoteAndEscape(v.getString())));
|
||||
|
||||
expression.addUnaryFunction("parse_nbt", v -> {
|
||||
if (v instanceof NBTSerializableValue) return ((NBTSerializableValue) v).toValue();
|
||||
@@ -457,9 +453,9 @@ public class Auxiliary {
|
||||
if (numParam != 2 && numParam != 3) throw new InternalExpressionException("'tag_matches' requires 2 or 3 arguments");
|
||||
if (lv.get(1).isNull()) return Value.TRUE;
|
||||
if (lv.get(0).isNull()) return Value.FALSE;
|
||||
NbtElement source = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(0)))).getTag();
|
||||
NbtElement match = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(1)))).getTag();
|
||||
return BooleanValue.of(NbtHelper.matches(match, source, numParam == 2 || lv.get(2).getBoolean()));
|
||||
Tag source = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(0)))).getTag();
|
||||
Tag match = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(1)))).getTag();
|
||||
return BooleanValue.of(NbtUtils.compareNbt(match, source, numParam == 2 || lv.get(2).getBoolean()));
|
||||
});
|
||||
|
||||
expression.addFunction("encode_nbt", lv -> {
|
||||
@@ -467,7 +463,7 @@ public class Auxiliary {
|
||||
if (argSize==0 || argSize > 2) throw new InternalExpressionException("'encode_nbt' requires 1 or 2 parameters");
|
||||
Value v = lv.get(0);
|
||||
boolean force = (argSize > 1) && lv.get(1).getBoolean();
|
||||
NbtElement tag;
|
||||
Tag tag;
|
||||
try
|
||||
{
|
||||
tag = v.toTag(force);
|
||||
@@ -483,30 +479,30 @@ public class Auxiliary {
|
||||
expression.addContextFunction("print", -1, (c, t, lv) ->
|
||||
{
|
||||
if (lv.size() == 0 || lv.size() > 2) throw new InternalExpressionException("'print' takes one or two arguments");
|
||||
ServerCommandSource s = ((CarpetContext)c).s;
|
||||
CommandSourceStack s = ((CarpetContext)c).s;
|
||||
MinecraftServer server = s.getServer();
|
||||
Value res = lv.get(0);
|
||||
List<ServerPlayerEntity> targets = null;
|
||||
List<ServerPlayer> targets = null;
|
||||
if (lv.size() == 2)
|
||||
{
|
||||
List<Value> playerValues = (res instanceof ListValue)?((ListValue) res).getItems():Collections.singletonList(res);
|
||||
List<ServerPlayerEntity> playerTargets = new ArrayList<>();
|
||||
List<ServerPlayer> playerTargets = new ArrayList<>();
|
||||
playerValues.forEach(pv -> {
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(server, pv);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(server, pv);
|
||||
if (player == null) throw new InternalExpressionException("Cannot target player "+pv.getString()+" in print");
|
||||
playerTargets.add(player);
|
||||
});
|
||||
targets = playerTargets;
|
||||
res = lv.get(1);
|
||||
}
|
||||
Text message = FormattedTextValue.getTextByValue(res);
|
||||
Component message = FormattedTextValue.getTextByValue(res);
|
||||
if (targets == null)
|
||||
{
|
||||
s.sendFeedback(message, false);
|
||||
s.sendSuccess(message, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
targets.forEach(p -> p.getCommandSource().sendFeedback(message, false));
|
||||
targets.forEach(p -> p.createCommandSourceStack().sendSuccess(message, false));
|
||||
}
|
||||
return res; // pass through for variables
|
||||
});
|
||||
@@ -516,40 +512,40 @@ public class Auxiliary {
|
||||
Value pVal = lv.get(0);
|
||||
if (!(pVal instanceof ListValue)) pVal = ListValue.of(pVal);
|
||||
MinecraftServer server = ((CarpetContext)c).s.getServer();
|
||||
Stream<ServerPlayerEntity> targets = ((ListValue) pVal).getItems().stream().map(v ->
|
||||
Stream<ServerPlayer> targets = ((ListValue) pVal).getItems().stream().map(v ->
|
||||
{
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(server, v);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(server, v);
|
||||
if (player == null) throw new InternalExpressionException("'display_title' requires a valid online player or a list of players as first argument. "+v.getString()+" is not a player.");
|
||||
return player;
|
||||
});
|
||||
Function<Text, Packet<?>> packetGetter = null;
|
||||
Function<Component, Packet<?>> packetGetter = null;
|
||||
//TitleS2CPacket.Action action;
|
||||
String actionString = lv.get(1).getString().toLowerCase(Locale.ROOT);
|
||||
switch (actionString)
|
||||
{
|
||||
case "title":
|
||||
packetGetter = TitleS2CPacket::new;
|
||||
packetGetter = ClientboundSetTitleTextPacket::new;
|
||||
//action = Action.TITLE;
|
||||
if (lv.size() < 3)
|
||||
throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type");
|
||||
|
||||
break;
|
||||
case "subtitle":
|
||||
packetGetter = SubtitleS2CPacket::new;
|
||||
packetGetter = ClientboundSetSubtitleTextPacket::new;
|
||||
if (lv.size() < 3)
|
||||
throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type");
|
||||
|
||||
//action = Action.SUBTITLE;
|
||||
break;
|
||||
case "actionbar":
|
||||
packetGetter = OverlayMessageS2CPacket::new;
|
||||
packetGetter = ClientboundSetActionBarTextPacket::new;
|
||||
if (lv.size() < 3)
|
||||
throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type");
|
||||
|
||||
//action = Action.ACTIONBAR;
|
||||
break;
|
||||
case "clear":
|
||||
packetGetter = (x) -> new ClearTitleS2CPacket(true); // resetting default fade
|
||||
packetGetter = (x) -> new ClientboundClearTitlesPacket(true); // resetting default fade
|
||||
//action = Action.CLEAR;
|
||||
break;
|
||||
case "player_list_header":
|
||||
@@ -560,7 +556,7 @@ public class Auxiliary {
|
||||
}
|
||||
//if (action != Action.CLEAR && lv.size() < 3)
|
||||
// throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type");
|
||||
Text title;
|
||||
Component title;
|
||||
boolean soundsTrue = false;
|
||||
if (lv.size() > 2)
|
||||
{
|
||||
@@ -571,35 +567,35 @@ public class Auxiliary {
|
||||
else title = null; // Will never happen, just to make lambda happy
|
||||
if (packetGetter == null)
|
||||
{
|
||||
Map<String, BaseText> map;
|
||||
Map<String, BaseComponent> map;
|
||||
if (actionString.equals("player_list_header"))
|
||||
map = HUDController.scarpet_headers;
|
||||
else
|
||||
map = HUDController.scarpet_footers;
|
||||
|
||||
AtomicInteger total = new AtomicInteger(0);
|
||||
List<ServerPlayerEntity> targetList = targets.collect(Collectors.toList());
|
||||
List<ServerPlayer> targetList = targets.collect(Collectors.toList());
|
||||
if (!soundsTrue) // null or empty string
|
||||
targetList.forEach(target -> {
|
||||
map.remove(target.getEntityName());
|
||||
map.remove(target.getScoreboardName());
|
||||
total.getAndIncrement();
|
||||
});
|
||||
else
|
||||
targetList.forEach(target -> {
|
||||
map.put(target.getEntityName(), (BaseText) title);
|
||||
map.put(target.getScoreboardName(), (BaseComponent) title);
|
||||
total.getAndIncrement();
|
||||
});
|
||||
HUDController.update_hud(((CarpetContext)c).s.getServer(), targetList);
|
||||
return NumericValue.of(total.get());
|
||||
}
|
||||
TitleFadeS2CPacket timesPacket; // TimesPacket
|
||||
ClientboundSetTitlesAnimationPacket timesPacket; // TimesPacket
|
||||
if (lv.size() > 3)
|
||||
{
|
||||
if (lv.size() != 6) throw new InternalExpressionException("'display_title' needs all fade-in, stay and fade-out times");
|
||||
int in = NumericValue.asNumber(lv.get(3),"fade in for display_title" ).getInt();
|
||||
int stay = NumericValue.asNumber(lv.get(4),"stay for display_title" ).getInt();
|
||||
int out = NumericValue.asNumber(lv.get(5),"fade out for display_title" ).getInt();
|
||||
timesPacket = new TitleFadeS2CPacket(in, stay, out);
|
||||
timesPacket = new ClientboundSetTitlesAnimationPacket(in, stay, out);
|
||||
//timesPacket = new TitleS2CPacket(Action.TIMES, null, in, stay, out);
|
||||
}
|
||||
else timesPacket = null;
|
||||
@@ -608,8 +604,8 @@ public class Auxiliary {
|
||||
//TitleS2CPacket packet = new TitleS2CPacket(action, title);
|
||||
AtomicInteger total = new AtomicInteger(0);
|
||||
targets.forEach(p -> {
|
||||
if (timesPacket != null) p.networkHandler.sendPacket(timesPacket);
|
||||
p.networkHandler.sendPacket(packet);
|
||||
if (timesPacket != null) p.connection.send(timesPacket);
|
||||
p.connection.send(packet);
|
||||
total.getAndIncrement();
|
||||
});
|
||||
return NumericValue.of(total.get());
|
||||
@@ -624,12 +620,12 @@ public class Auxiliary {
|
||||
|
||||
expression.addContextFunction("run", 1, (c, t, lv) ->
|
||||
{
|
||||
ServerCommandSource s = ((CarpetContext)c).s;
|
||||
CommandSourceStack s = ((CarpetContext)c).s;
|
||||
try
|
||||
{
|
||||
Text[] error = {null};
|
||||
List<Text> output = new ArrayList<>();
|
||||
Value retval = new NumericValue(s.getServer().getCommandManager().execute(
|
||||
Component[] error = {null};
|
||||
List<Component> output = new ArrayList<>();
|
||||
Value retval = new NumericValue(s.getServer().getCommands().performCommand(
|
||||
new SnoopyCommandSource(s, error, output),
|
||||
lv.get(0).getString())
|
||||
);
|
||||
@@ -641,39 +637,39 @@ public class Auxiliary {
|
||||
}
|
||||
catch (Exception exc)
|
||||
{
|
||||
return ListValue.of(Value.NULL, ListValue.of(), new FormattedTextValue(new LiteralText(exc.getMessage())));
|
||||
return ListValue.of(Value.NULL, ListValue.of(), new FormattedTextValue(new TextComponent(exc.getMessage())));
|
||||
}
|
||||
});
|
||||
|
||||
expression.addContextFunction("save", 0, (c, t, lv) ->
|
||||
{
|
||||
ServerCommandSource s = ((CarpetContext)c).s;
|
||||
s.getServer().getPlayerManager().saveAllPlayerData();
|
||||
s.getServer().save(true,true,true);
|
||||
for (ServerWorld world : s.getServer().getWorlds())
|
||||
CommandSourceStack s = ((CarpetContext)c).s;
|
||||
s.getServer().getPlayerList().saveAll();
|
||||
s.getServer().saveAllChunks(true,true,true);
|
||||
for (ServerLevel world : s.getServer().getAllLevels())
|
||||
{
|
||||
world.getChunkManager().tick(() -> true, false);
|
||||
world.getChunkSource().tick(() -> true, false);
|
||||
}
|
||||
CarpetScriptServer.LOG.warn("Saved chunks");
|
||||
return Value.TRUE;
|
||||
});
|
||||
|
||||
expression.addContextFunction("tick_time", 0, (c, t, lv) ->
|
||||
new NumericValue(((CarpetContext) c).s.getServer().getTicks()));
|
||||
new NumericValue(((CarpetContext) c).s.getServer().getTickCount()));
|
||||
|
||||
expression.addContextFunction("world_time", 0, (c, t, lv) -> {
|
||||
c.host.issueDeprecation("world_time()");
|
||||
return new NumericValue(((CarpetContext) c).s.getWorld().getTime());
|
||||
return new NumericValue(((CarpetContext) c).s.getLevel().getGameTime());
|
||||
});
|
||||
|
||||
expression.addContextFunction("day_time", -1, (c, t, lv) ->
|
||||
{
|
||||
Value time = new NumericValue(((CarpetContext) c).s.getWorld().getTimeOfDay());
|
||||
Value time = new NumericValue(((CarpetContext) c).s.getLevel().getDayTime());
|
||||
if (lv.size() > 0)
|
||||
{
|
||||
long newTime = NumericValue.asNumber(lv.get(0)).getLong();
|
||||
if (newTime < 0) newTime = 0;
|
||||
((CarpetContext) c).s.getWorld().setTimeOfDay(newTime);// setTimeOfDay(newTime);
|
||||
((CarpetContext) c).s.getLevel().setDayTime(newTime);// setTimeOfDay(newTime);
|
||||
}
|
||||
return time;
|
||||
});
|
||||
@@ -687,9 +683,9 @@ public class Auxiliary {
|
||||
|
||||
expression.addContextFunction("game_tick", -1, (c, t, lv) -> {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerCommandSource s = cc.s;
|
||||
CommandSourceStack s = cc.s;
|
||||
if (CarpetServer.scriptServer == null) return Value.NULL;
|
||||
if (!s.getServer().isOnThread()) throw new InternalExpressionException("Unable to run ticks from threads");
|
||||
if (!s.getServer().isSameThread()) throw new InternalExpressionException("Unable to run ticks from threads");
|
||||
if (CarpetServer.scriptServer.tickDepth > 16) throw new InternalExpressionException("'game_tick' function caused other 'game_tick' functions to run. You should not allow that.");
|
||||
try
|
||||
{
|
||||
@@ -725,9 +721,9 @@ public class Auxiliary {
|
||||
});
|
||||
|
||||
expression.addContextFunction("seed", -1, (c, t, lv) -> {
|
||||
ServerCommandSource s = ((CarpetContext)c).s;
|
||||
CommandSourceStack s = ((CarpetContext)c).s;
|
||||
c.host.issueDeprecation("seed()");
|
||||
return new NumericValue(s.getWorld().getSeed());
|
||||
return new NumericValue(s.getLevel().getSeed());
|
||||
});
|
||||
|
||||
expression.addContextFunction("relight", -1, (c, t, lv) ->
|
||||
@@ -735,28 +731,28 @@ public class Auxiliary {
|
||||
CarpetContext cc = (CarpetContext) c;
|
||||
BlockArgument locator = BlockArgument.findIn(cc, lv, 0);
|
||||
BlockPos pos = locator.block.getPos();
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
((ThreadedAnvilChunkStorageInterface) world.getChunkManager().threadedAnvilChunkStorage).relightChunk(new ChunkPos(pos));
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
((ThreadedAnvilChunkStorageInterface) world.getChunkSource().chunkMap).relightChunk(new ChunkPos(pos));
|
||||
WorldTools.forceChunkUpdate(pos, world);
|
||||
return Value.TRUE;
|
||||
});
|
||||
|
||||
// Should this be deprecated for system_info('source_dimension')?
|
||||
expression.addContextFunction("current_dimension", 0, (c, t, lv) ->
|
||||
ValueConversions.of( ((CarpetContext)c).s.getWorld()));
|
||||
ValueConversions.of( ((CarpetContext)c).s.getLevel()));
|
||||
|
||||
expression.addContextFunction("view_distance", 0, (c, t, lv) -> {
|
||||
c.host.issueDeprecation("view_distance()");
|
||||
return new NumericValue(((CarpetContext)c).s.getServer().getPlayerManager().getViewDistance());
|
||||
return new NumericValue(((CarpetContext)c).s.getServer().getPlayerList().getViewDistance());
|
||||
});
|
||||
|
||||
// lazy due to passthrough and context changing ability
|
||||
expression.addLazyFunction("in_dimension", 2, (c, t, lv) -> {
|
||||
ServerCommandSource outerSource = ((CarpetContext)c).s;
|
||||
CommandSourceStack outerSource = ((CarpetContext)c).s;
|
||||
Value dimensionValue = lv.get(0).evalValue(c);
|
||||
World world = ValueConversions.dimFromValue(dimensionValue, outerSource.getServer());
|
||||
if (world == outerSource.getWorld()) return lv.get(1);
|
||||
ServerCommandSource innerSource = outerSource.withWorld((ServerWorld)world);
|
||||
Level world = ValueConversions.dimFromValue(dimensionValue, outerSource.getServer());
|
||||
if (world == outerSource.getLevel()) return lv.get(1);
|
||||
CommandSourceStack innerSource = outerSource.withLevel((ServerLevel)world);
|
||||
Context newCtx = c.recreate();
|
||||
((CarpetContext) newCtx).s = innerSource;
|
||||
newCtx.variables = c.variables;
|
||||
@@ -769,21 +765,21 @@ public class Auxiliary {
|
||||
{
|
||||
Map<Value, Value> plopData = new HashMap<>();
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
DynamicRegistryManager registryManager = cc.s.getWorld().getRegistryManager();
|
||||
RegistryAccess registryManager = cc.s.getLevel().registryAccess();
|
||||
plopData.put(StringValue.of("scarpet_custom"),
|
||||
ListValue.wrap(FeatureGenerator.featureMap.keySet().stream().sorted().map(StringValue::of).collect(Collectors.toList()))
|
||||
);
|
||||
plopData.put(StringValue.of("features"),
|
||||
ListValue.wrap(Registry.FEATURE.getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
ListValue.wrap(Registry.FEATURE.keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
);
|
||||
plopData.put(StringValue.of("configured_features"),
|
||||
ListValue.wrap(registryManager.get(Registry.CONFIGURED_FEATURE_KEY).getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
ListValue.wrap(registryManager.registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
);
|
||||
plopData.put(StringValue.of("structures"),
|
||||
ListValue.wrap(Registry.STRUCTURE_FEATURE.getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
ListValue.wrap(Registry.STRUCTURE_FEATURE.keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
);
|
||||
plopData.put(StringValue.of("configured_structures"),
|
||||
ListValue.wrap(registryManager.get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).getIds().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
ListValue.wrap(registryManager.registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
|
||||
);
|
||||
return MapValue.wrap(plopData);
|
||||
}
|
||||
@@ -792,14 +788,14 @@ public class Auxiliary {
|
||||
throw new InternalExpressionException("'plop' needs extra argument indicating what to plop");
|
||||
String what = lv.get(locator.offset).getString();
|
||||
Value [] result = new Value[]{Value.NULL};
|
||||
((CarpetContext)c).s.getServer().submitAndJoin( () ->
|
||||
((CarpetContext)c).s.getServer().executeBlocking( () ->
|
||||
{
|
||||
Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).s.getWorld(), locator.block.getPos());
|
||||
Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).s.getLevel(), locator.block.getPos());
|
||||
|
||||
if (res == null)
|
||||
return;
|
||||
if (what.equalsIgnoreCase("boulder")) // there might be more of those
|
||||
WorldTools.forceChunkUpdate(locator.block.getPos(), ((CarpetContext) c).s.getWorld());
|
||||
WorldTools.forceChunkUpdate(locator.block.getPos(), ((CarpetContext) c).s.getLevel());
|
||||
result[0] = BooleanValue.of(res);
|
||||
});
|
||||
return result[0];
|
||||
@@ -861,7 +857,7 @@ public class Auxiliary {
|
||||
Value retVal;
|
||||
if (fdesc.type == FileArgument.Type.NBT)
|
||||
{
|
||||
NbtElement state = ((CarpetScriptHost) c.host).readFileTag(fdesc);
|
||||
Tag state = ((CarpetScriptHost) c.host).readFileTag(fdesc);
|
||||
if (state == null) return Value.NULL;
|
||||
retVal = new NBTSerializableValue(state);
|
||||
}
|
||||
@@ -898,7 +894,7 @@ public class Auxiliary {
|
||||
NBTSerializableValue tagValue = (val instanceof NBTSerializableValue)
|
||||
? (NBTSerializableValue) val
|
||||
: new NBTSerializableValue(val.getString());
|
||||
NbtElement tag = tagValue.getTag();
|
||||
Tag tag = tagValue.getTag();
|
||||
success = ((CarpetScriptHost) c.host).writeTagFile(tag, fdesc);
|
||||
}
|
||||
else if (fdesc.type == FileArgument.Type.JSON)
|
||||
@@ -970,17 +966,17 @@ public class Auxiliary {
|
||||
expression.addContextFunction("statistic", 3, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(cc.s.getServer(), lv.get(0));
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(cc.s.getServer(), lv.get(0));
|
||||
if (player == null) return Value.NULL;
|
||||
Identifier category;
|
||||
Identifier statName;
|
||||
ResourceLocation category;
|
||||
ResourceLocation statName;
|
||||
category = InputValidator.identifierOf(lv.get(1).getString());
|
||||
statName = InputValidator.identifierOf(lv.get(2).getString());
|
||||
StatType<?> type = Registry.STAT_TYPE.get(category);
|
||||
if (type == null) return Value.NULL;
|
||||
Stat<?> stat = getStat(type, statName);
|
||||
if (stat == null) return Value.NULL;
|
||||
return new NumericValue(player.getStatHandler().getStat(stat));
|
||||
return new NumericValue(player.getStats().getValue(stat));
|
||||
});
|
||||
|
||||
//handle_event('event', function...)
|
||||
@@ -1006,7 +1002,7 @@ public class Auxiliary {
|
||||
String eventName = lv.get(0).getString();
|
||||
// no such event yet
|
||||
if (CarpetEventServer.Event.getEvent(eventName, server) == null) return Value.NULL;
|
||||
ServerPlayerEntity player = null;
|
||||
ServerPlayer player = null;
|
||||
List<Value> args = Collections.emptyList();
|
||||
if (lv.size() > 1)
|
||||
{
|
||||
@@ -1024,11 +1020,11 @@ public class Auxiliary {
|
||||
expression.addContextFunction("nbt_storage", -1, (c, t, lv) -> {
|
||||
if (lv.size() > 2) throw new InternalExpressionException("'nbt_storage' requires 0, 1 or 2 arguments.");
|
||||
CarpetContext cc = (CarpetContext) c;
|
||||
DataCommandStorage storage = cc.s.getServer().getDataCommandStorage();
|
||||
CommandStorage storage = cc.s.getServer().getCommandStorage();
|
||||
if (lv.size() == 0)
|
||||
return ListValue.wrap(storage.getIds().map(i -> new StringValue(nameFromRegistryId(i))).collect(Collectors.toList()));
|
||||
return ListValue.wrap(storage.keys().map(i -> new StringValue(nameFromRegistryId(i))).collect(Collectors.toList()));
|
||||
String key = lv.get(0).getString();
|
||||
NbtCompound old_nbt = storage.get(InputValidator.identifierOf(key));
|
||||
CompoundTag old_nbt = storage.get(InputValidator.identifierOf(key));
|
||||
if (lv.size() == 2) {
|
||||
Value nbt = lv.get(1);
|
||||
NBTSerializableValue new_nbt = (nbt instanceof NBTSerializableValue) ? (NBTSerializableValue) nbt
|
||||
@@ -1044,7 +1040,7 @@ public class Auxiliary {
|
||||
String origName = lv.get(0).getString();
|
||||
String name = InputValidator.validateSimpleString(origName, true);
|
||||
MinecraftServer server = cc.s.getServer();
|
||||
for (String dpName : server.getDataPackManager().getNames())
|
||||
for (String dpName : server.getPackRepository().getAvailableIds())
|
||||
{
|
||||
if (dpName.equalsIgnoreCase("file/"+name+".zip") ||
|
||||
dpName.equalsIgnoreCase("file/"+name))
|
||||
@@ -1054,12 +1050,12 @@ public class Auxiliary {
|
||||
Value dpdata = lv.get(1);
|
||||
if (!(dpdata instanceof MapValue))
|
||||
throw new InternalExpressionException("datapack data needs to be a valid map type");
|
||||
ResourcePackManager packManager = server.getDataPackManager();
|
||||
Path dbFloder = server.getSavePath(WorldSavePath.DATAPACKS);
|
||||
PackRepository packManager = server.getPackRepository();
|
||||
Path dbFloder = server.getWorldPath(LevelResource.DATAPACK_DIR);
|
||||
Path packFloder = dbFloder.resolve(name+".zip");
|
||||
if (Files.exists(packFloder) || Files.exists(dbFloder.resolve(name))) return Value.NULL;
|
||||
Boolean [] successful = new Boolean[]{true};
|
||||
server.submitAndJoin( () ->
|
||||
server.executeBlocking( () ->
|
||||
{
|
||||
try {
|
||||
//Files.createDirectory(packFloder);
|
||||
@@ -1067,23 +1063,23 @@ public class Auxiliary {
|
||||
Path zipRoot = zipfs.getPath("/");
|
||||
zipValueToJson(zipRoot.resolve("pack.mcmeta"), MapValue.wrap(
|
||||
Map.of(StringValue.of("pack"), MapValue.wrap(Map.of(
|
||||
StringValue.of("pack_format"), new NumericValue(SharedConstants.getGameVersion().getPackVersion()),
|
||||
StringValue.of("pack_format"), new NumericValue(SharedConstants.getCurrentVersion().getPackVersion()),
|
||||
StringValue.of("description"), StringValue.of(name),
|
||||
StringValue.of("source"), StringValue.of("scarpet")
|
||||
)))
|
||||
));
|
||||
walkTheDPMap((MapValue) dpdata, zipRoot);
|
||||
}
|
||||
packManager.scanPacks();
|
||||
ResourcePackProfile resourcePackProfile = packManager.getProfile("file/" + name + ".zip");
|
||||
if (resourcePackProfile == null || packManager.getEnabledProfiles().contains(resourcePackProfile)) {
|
||||
packManager.reload();
|
||||
Pack resourcePackProfile = packManager.getPack("file/" + name + ".zip");
|
||||
if (resourcePackProfile == null || packManager.getSelectedPacks().contains(resourcePackProfile)) {
|
||||
throw new IOException();
|
||||
}
|
||||
List<ResourcePackProfile> list = Lists.newArrayList(packManager.getEnabledProfiles());
|
||||
resourcePackProfile.getInitialPosition().insert(list, resourcePackProfile, p -> p, false);
|
||||
List<Pack> list = Lists.newArrayList(packManager.getSelectedPacks());
|
||||
resourcePackProfile.getDefaultPosition().insert(list, resourcePackProfile, p -> p, false);
|
||||
|
||||
|
||||
server.reloadResources(list.stream().map(ResourcePackProfile::getName).collect(Collectors.toList())).
|
||||
server.reloadResources(list.stream().map(Pack::getId).collect(Collectors.toList())).
|
||||
exceptionally(exc -> {
|
||||
successful[0] = false;
|
||||
return null;
|
||||
@@ -1109,44 +1105,44 @@ public class Auxiliary {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
// from minecraft.server.Main.main
|
||||
MinecraftServer server = cc.s.getServer();
|
||||
LevelStorage.Session session = ((MinecraftServerInterface)server).getCMSession();
|
||||
DataPackSettings dataPackSettings = session.getDataPackSettings();
|
||||
ResourcePackManager resourcePackManager = server.getDataPackManager();
|
||||
DataPackSettings dataPackSettings2 = MinecraftServer.loadDataPacks(resourcePackManager, dataPackSettings == null ? DataPackSettings.SAFE_MODE : dataPackSettings, false);
|
||||
ServerResourceManager serverRM = ((MinecraftServerInterface)server).getResourceManager();
|
||||
ReloadableResourceManagerImpl resourceManager = (ReloadableResourceManagerImpl) serverRM.getResourceManager();
|
||||
LevelStorageSource.LevelStorageAccess session = ((MinecraftServerInterface)server).getCMSession();
|
||||
DataPackConfig dataPackSettings = session.getDataPacks();
|
||||
PackRepository resourcePackManager = server.getPackRepository();
|
||||
DataPackConfig dataPackSettings2 = MinecraftServer.configurePackRepository(resourcePackManager, dataPackSettings == null ? DataPackConfig.DEFAULT : dataPackSettings, false);
|
||||
ServerResources serverRM = ((MinecraftServerInterface)server).getResourceManager();
|
||||
SimpleReloadableResourceManager resourceManager = (SimpleReloadableResourceManager) serverRM.getResourceManager();
|
||||
|
||||
//believe the other one will fillup based on the datapacks only.
|
||||
resourceManager.close();
|
||||
resourcePackManager.createResourcePacks().forEach(resourceManager::addPack);
|
||||
resourcePackManager.openAllSelected().forEach(resourceManager::add);
|
||||
|
||||
//not sure its needed, but doesn't seem to have a negative effect and might be used in some custom shtuff
|
||||
serverRM.loadRegistryTags();
|
||||
serverRM.updateGlobals();
|
||||
|
||||
RegistryOps<NbtElement> registryOps = RegistryOps.of(NbtOps.INSTANCE, serverRM.getResourceManager(), (DynamicRegistryManager.Impl) server.getRegistryManager());
|
||||
SaveProperties saveProperties = session.readLevelProperties(registryOps, dataPackSettings2);
|
||||
RegistryReadOps<Tag> registryOps = RegistryReadOps.create(NbtOps.INSTANCE, serverRM.getResourceManager(), (RegistryAccess.RegistryHolder) server.registryAccess());
|
||||
WorldData saveProperties = session.getDataTag(registryOps, dataPackSettings2);
|
||||
if (saveProperties == null) return Value.NULL;
|
||||
//session.backupLevelDataFile(server.getRegistryManager(), saveProperties); // no need
|
||||
|
||||
// MinecraftServer.createWorlds
|
||||
// save properties should now contain dimension settings
|
||||
GeneratorOptions generatorOptions = saveProperties.getGeneratorOptions();
|
||||
boolean bl = generatorOptions.isDebugWorld();
|
||||
long l = generatorOptions.getSeed();
|
||||
long m = BiomeAccess.hashSeed(l);
|
||||
Map<RegistryKey<World>, ServerWorld> existing_worlds = ((MinecraftServerInterface)server).getCMWorlds();
|
||||
WorldGenSettings generatorOptions = saveProperties.worldGenSettings();
|
||||
boolean bl = generatorOptions.isDebug();
|
||||
long l = generatorOptions.seed();
|
||||
long m = BiomeManager.obfuscateSeed(l);
|
||||
Map<ResourceKey<Level>, ServerLevel> existing_worlds = ((MinecraftServerInterface)server).getCMWorlds();
|
||||
List<Value> addeds = new ArrayList<>();
|
||||
for (Map.Entry<RegistryKey<DimensionOptions>, DimensionOptions> entry : generatorOptions.getDimensions().getEntries()) {
|
||||
RegistryKey<DimensionOptions> registryKey = entry.getKey();
|
||||
for (Map.Entry<ResourceKey<LevelStem>, LevelStem> entry : generatorOptions.dimensions().entrySet()) {
|
||||
ResourceKey<LevelStem> registryKey = entry.getKey();
|
||||
if (!existing_worlds.containsKey(registryKey))
|
||||
{
|
||||
addeds.add(ValueConversions.of(registryKey.getValue()));
|
||||
RegistryKey<World> registryKey2 = RegistryKey.of(Registry.WORLD_KEY, registryKey.getValue());
|
||||
DimensionType dimensionType3 = entry.getValue().getDimensionType();
|
||||
ChunkGenerator chunkGenerator3 = entry.getValue().getChunkGenerator();
|
||||
UnmodifiableLevelProperties unmodifiableLevelProperties = new UnmodifiableLevelProperties(saveProperties, ((ServerWorldInterface) server.getOverworld()).getWorldPropertiesCM());
|
||||
ServerWorld serverWorld2 = new ServerWorld(server, Util.getMainWorkerExecutor(), session, unmodifiableLevelProperties, registryKey2, dimensionType3, WorldTools.NOOP_LISTENER, chunkGenerator3, bl, m, List.of(), false);
|
||||
server.getOverworld().getWorldBorder().addListener(new WorldBorderListener.WorldBorderSyncer(serverWorld2.getWorldBorder()));
|
||||
addeds.add(ValueConversions.of(registryKey.location()));
|
||||
ResourceKey<Level> registryKey2 = ResourceKey.create(Registry.DIMENSION_REGISTRY, registryKey.location());
|
||||
DimensionType dimensionType3 = entry.getValue().type();
|
||||
ChunkGenerator chunkGenerator3 = entry.getValue().generator();
|
||||
DerivedLevelData unmodifiableLevelProperties = new DerivedLevelData(saveProperties, ((ServerWorldInterface) server.overworld()).getWorldPropertiesCM());
|
||||
ServerLevel serverWorld2 = new ServerLevel(server, Util.backgroundExecutor(), session, unmodifiableLevelProperties, registryKey2, dimensionType3, WorldTools.NOOP_LISTENER, chunkGenerator3, bl, m, List.of(), false);
|
||||
server.overworld().getWorldBorder().addListener(new BorderChangeListener.DelegateBorderChangeListener(serverWorld2.getWorldBorder()));
|
||||
existing_worlds.put(registryKey2, serverWorld2);
|
||||
}
|
||||
}
|
||||
@@ -1240,14 +1236,14 @@ public class Auxiliary {
|
||||
NBTSerializableValue tagValue = (output instanceof NBTSerializableValue)
|
||||
? (NBTSerializableValue) output
|
||||
: new NBTSerializableValue(output.getString());
|
||||
NbtElement tag = tagValue.getTag();
|
||||
Tag tag = tagValue.getTag();
|
||||
Files.createDirectories(path.getParent());
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
if (tag instanceof NbtCompound)
|
||||
NbtIo.writeCompressed((NbtCompound) tag, Files.newOutputStream(path));
|
||||
if (tag instanceof CompoundTag)
|
||||
NbtIo.writeCompressed((CompoundTag) tag, Files.newOutputStream(path));
|
||||
}
|
||||
catch (Throwable shitHappened)
|
||||
{
|
||||
@@ -1282,11 +1278,11 @@ public class Auxiliary {
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> Stat<T> getStat(StatType<T> type, Identifier id)
|
||||
private static <T> Stat<T> getStat(StatType<T> type, ResourceLocation id)
|
||||
{
|
||||
T key = type.getRegistry().get(id);
|
||||
if (key == null || !type.hasStat(key))
|
||||
if (key == null || !type.contains(key))
|
||||
return null;
|
||||
return type.getOrCreateStat(key);
|
||||
return type.get(key);
|
||||
}
|
||||
}
|
||||
@@ -15,14 +15,13 @@ import carpet.script.value.LazyListValue;
|
||||
import carpet.script.value.ListValue;
|
||||
import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.Value;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.MathHelper;
|
||||
import net.minecraft.util.math.Vec3i;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Vec3i;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.util.Mth;
|
||||
|
||||
import static java.lang.Math.abs;
|
||||
import static java.lang.Math.max;
|
||||
@@ -217,11 +216,11 @@ public class BlockIterators {
|
||||
expression.addContextFunction("neighbours", -1, (c, t, lv)->
|
||||
{
|
||||
BlockPos center = BlockArgument.findIn((CarpetContext) c, lv,0).block.getPos();
|
||||
ServerWorld world = ((CarpetContext) c).s.getWorld();
|
||||
ServerLevel world = ((CarpetContext) c).s.getLevel();
|
||||
|
||||
List<Value> neighbours = new ArrayList<>();
|
||||
neighbours.add(new BlockValue(null, world, center.up()));
|
||||
neighbours.add(new BlockValue(null, world, center.down()));
|
||||
neighbours.add(new BlockValue(null, world, center.above()));
|
||||
neighbours.add(new BlockValue(null, world, center.below()));
|
||||
neighbours.add(new BlockValue(null, world, center.north()));
|
||||
neighbours.add(new BlockValue(null, world, center.south()));
|
||||
neighbours.add(new BlockValue(null, world, center.east()));
|
||||
@@ -245,30 +244,30 @@ public class BlockIterators {
|
||||
Vector3Argument diffLocator = Vector3Argument.findIn(lv, cposLocator.offset);
|
||||
if (diffLocator.fromBlock)
|
||||
{
|
||||
sminx = MathHelper.floor(abs(diffLocator.vec.x - cx));
|
||||
sminy = MathHelper.floor(abs(diffLocator.vec.y - cx));
|
||||
sminz = MathHelper.floor(abs(diffLocator.vec.z - cx));
|
||||
sminx = Mth.floor(abs(diffLocator.vec.x - cx));
|
||||
sminy = Mth.floor(abs(diffLocator.vec.y - cx));
|
||||
sminz = Mth.floor(abs(diffLocator.vec.z - cx));
|
||||
}
|
||||
else
|
||||
{
|
||||
sminx = MathHelper.floor(abs(diffLocator.vec.x));
|
||||
sminy = MathHelper.floor(abs(diffLocator.vec.y));
|
||||
sminz = MathHelper.floor(abs(diffLocator.vec.z));
|
||||
sminx = Mth.floor(abs(diffLocator.vec.x));
|
||||
sminy = Mth.floor(abs(diffLocator.vec.y));
|
||||
sminz = Mth.floor(abs(diffLocator.vec.z));
|
||||
}
|
||||
if (lv.size() > diffLocator.offset)
|
||||
{
|
||||
Vector3Argument posDiff = Vector3Argument.findIn(lv, diffLocator.offset);
|
||||
if (posDiff.fromBlock)
|
||||
{
|
||||
smaxx = MathHelper.floor(abs(posDiff.vec.x - cx));
|
||||
smaxy = MathHelper.floor(abs(posDiff.vec.y - cx));
|
||||
smaxz = MathHelper.floor(abs(posDiff.vec.z - cx));
|
||||
smaxx = Mth.floor(abs(posDiff.vec.x - cx));
|
||||
smaxy = Mth.floor(abs(posDiff.vec.y - cx));
|
||||
smaxz = Mth.floor(abs(posDiff.vec.z - cx));
|
||||
}
|
||||
else
|
||||
{
|
||||
smaxx = MathHelper.floor(abs(posDiff.vec.x));
|
||||
smaxy = MathHelper.floor(abs(posDiff.vec.y));
|
||||
smaxz = MathHelper.floor(abs(posDiff.vec.z));
|
||||
smaxx = Mth.floor(abs(posDiff.vec.x));
|
||||
smaxy = Mth.floor(abs(posDiff.vec.y));
|
||||
smaxz = Mth.floor(abs(posDiff.vec.z));
|
||||
}
|
||||
}
|
||||
else
|
||||
|
||||
@@ -15,21 +15,6 @@ import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.Value;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EntityType;
|
||||
import net.minecraft.entity.SpawnReason;
|
||||
import net.minecraft.entity.mob.MobEntity;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.predicate.entity.EntityPredicates;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.math.Box;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
@@ -39,11 +24,25 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntitySelector;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.Mob;
|
||||
import net.minecraft.world.entity.MobSpawnType;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class Entities {
|
||||
private static ListValue getPlayersFromWorldMatching(Context c, Predicate<ServerPlayerEntity> condition) {
|
||||
private static ListValue getPlayersFromWorldMatching(Context c, Predicate<ServerPlayer> condition) {
|
||||
List<Value> ret = new ArrayList<>();
|
||||
for (ServerPlayerEntity player: ((CarpetContext) c).s.getWorld().getPlayers()) {
|
||||
for (ServerPlayer player: ((CarpetContext) c).s.getLevel().players()) {
|
||||
if (condition.test(player)) {
|
||||
ret.add(new EntityValue(player));
|
||||
}
|
||||
@@ -60,30 +59,30 @@ public class Entities {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
if (cc.host.user != null)
|
||||
{
|
||||
ServerPlayerEntity player = cc.s.getServer().getPlayerManager().getPlayer(cc.host.user);
|
||||
ServerPlayer player = cc.s.getServer().getPlayerList().getPlayerByName(cc.host.user);
|
||||
return EntityValue.of(player);
|
||||
}
|
||||
Entity callingEntity = cc.s.getEntity();
|
||||
if (callingEntity instanceof PlayerEntity) return EntityValue.of(callingEntity);
|
||||
Vec3d pos = ((CarpetContext)c).s.getPosition();
|
||||
PlayerEntity closestPlayer = ((CarpetContext)c).s.getWorld().getClosestPlayer(pos.x, pos.y, pos.z, -1.0, EntityPredicates.VALID_ENTITY);
|
||||
if (callingEntity instanceof Player) return EntityValue.of(callingEntity);
|
||||
Vec3 pos = ((CarpetContext)c).s.getPosition();
|
||||
Player closestPlayer = ((CarpetContext)c).s.getLevel().getNearestPlayer(pos.x, pos.y, pos.z, -1.0, EntitySelector.ENTITY_STILL_ALIVE);
|
||||
return EntityValue.of(closestPlayer);
|
||||
}
|
||||
String playerName = lv.get(0).getString();
|
||||
return switch (playerName) {
|
||||
case "all" -> {
|
||||
List<Value> ret = new ArrayList<>();
|
||||
for (ServerPlayerEntity player: ((CarpetContext)c).s.getServer().getPlayerManager().getPlayerList())
|
||||
for (ServerPlayer player: ((CarpetContext)c).s.getServer().getPlayerList().getPlayers())
|
||||
ret.add(new EntityValue(player));
|
||||
yield ListValue.wrap(ret);
|
||||
}
|
||||
case "*" -> getPlayersFromWorldMatching(c, p -> true);
|
||||
case "survival" -> getPlayersFromWorldMatching(c, p -> p.interactionManager.isSurvivalLike());
|
||||
case "creative" -> getPlayersFromWorldMatching(c, PlayerEntity::isCreative);
|
||||
case "spectating" -> getPlayersFromWorldMatching(c, PlayerEntity::isSpectator);
|
||||
case "survival" -> getPlayersFromWorldMatching(c, p -> p.gameMode.isSurvival()); // todo assert correct
|
||||
case "creative" -> getPlayersFromWorldMatching(c, ServerPlayer::isCreative);
|
||||
case "spectating" -> getPlayersFromWorldMatching(c, ServerPlayer::isSpectator);
|
||||
case "!spectating" -> getPlayersFromWorldMatching(c, p -> !p.isSpectator());
|
||||
default -> {
|
||||
ServerPlayerEntity player = ((CarpetContext) c).s.getServer().getPlayerManager().getPlayer(playerName);
|
||||
ServerPlayer player = ((CarpetContext) c).s.getServer().getPlayerList().getPlayerByName(playerName);
|
||||
if (player != null) {
|
||||
yield new EntityValue(player);
|
||||
}
|
||||
@@ -98,12 +97,12 @@ public class Entities {
|
||||
if (lv.size() < 2)
|
||||
throw new InternalExpressionException("'spawn' function takes mob name, and position to spawn");
|
||||
String entityString = lv.get(0).getString();
|
||||
Identifier entityId;
|
||||
ResourceLocation entityId;
|
||||
try
|
||||
{
|
||||
entityId = Identifier.fromCommandInput(new StringReader(entityString));
|
||||
EntityType<? extends Entity> type = Registry.ENTITY_TYPE.getOrEmpty(entityId).orElse(null);
|
||||
if (type == null || !type.isSummonable())
|
||||
entityId = ResourceLocation.read(new StringReader(entityString));
|
||||
EntityType<? extends Entity> type = Registry.ENTITY_TYPE.getOptional(entityId).orElse(null);
|
||||
if (type == null || !type.canSummon())
|
||||
return Value.NULL;
|
||||
}
|
||||
catch (CommandSyntaxException exception)
|
||||
@@ -114,7 +113,7 @@ public class Entities {
|
||||
Vector3Argument position = Vector3Argument.findIn(lv, 1);
|
||||
if (position.fromBlock)
|
||||
position.vec = position.vec.subtract(0, 0.5, 0);
|
||||
NbtCompound tag = new NbtCompound();
|
||||
CompoundTag tag = new CompoundTag();
|
||||
boolean hasTag = false;
|
||||
if (lv.size() > position.offset)
|
||||
{
|
||||
@@ -126,18 +125,18 @@ public class Entities {
|
||||
|
||||
}
|
||||
tag.putString("id", entityId.toString());
|
||||
Vec3d vec3d = position.vec;
|
||||
Vec3 vec3d = position.vec;
|
||||
|
||||
ServerWorld serverWorld = cc.s.getWorld();
|
||||
Entity entity_1 = EntityType.loadEntityWithPassengers(tag, serverWorld, (entity_1x) -> {
|
||||
entity_1x.refreshPositionAndAngles(vec3d.x, vec3d.y, vec3d.z, entity_1x.getYaw(), entity_1x.getPitch());
|
||||
return !serverWorld.tryLoadEntity(entity_1x) ? null : entity_1x;
|
||||
ServerLevel serverWorld = cc.s.getLevel();
|
||||
Entity entity_1 = EntityType.loadEntityRecursive(tag, serverWorld, (entity_1x) -> {
|
||||
entity_1x.moveTo(vec3d.x, vec3d.y, vec3d.z, entity_1x.getYRot(), entity_1x.getXRot());
|
||||
return !serverWorld.addWithUUID(entity_1x) ? null : entity_1x;
|
||||
});
|
||||
if (entity_1 == null) {
|
||||
return Value.NULL;
|
||||
} else {
|
||||
if (!hasTag && entity_1 instanceof MobEntity) {
|
||||
((MobEntity)entity_1).initialize(serverWorld, serverWorld.getLocalDifficulty(entity_1.getBlockPos()), SpawnReason.COMMAND, null, null);
|
||||
if (!hasTag && entity_1 instanceof Mob) {
|
||||
((Mob)entity_1).finalizeSpawn(serverWorld, serverWorld.getCurrentDifficultyAt(entity_1.blockPosition()), MobSpawnType.COMMAND, null, null);
|
||||
}
|
||||
return new EntityValue(entity_1);
|
||||
}
|
||||
@@ -147,16 +146,16 @@ public class Entities {
|
||||
{
|
||||
Value who = lv.get(0);
|
||||
if (who instanceof NumericValue)
|
||||
return EntityValue.of(((CarpetContext)c).s.getWorld().getEntityById((int)((NumericValue) who).getLong()));
|
||||
return EntityValue.of(((CarpetContext)c).s.getWorld().getEntity(UUID.fromString(who.getString())));
|
||||
return EntityValue.of(((CarpetContext)c).s.getLevel().getEntity((int)((NumericValue) who).getLong()));
|
||||
return EntityValue.of(((CarpetContext)c).s.getLevel().getEntity(UUID.fromString(who.getString())));
|
||||
});
|
||||
|
||||
expression.addContextFunction("entity_list", 1, (c, t, lv) ->
|
||||
{
|
||||
String who = lv.get(0).getString();
|
||||
ServerCommandSource source = ((CarpetContext)c).s;
|
||||
CommandSourceStack source = ((CarpetContext)c).s;
|
||||
EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, source.getServer());
|
||||
List<? extends Entity> entityList = source.getWorld().getEntitiesByType(eDesc.directType, eDesc.filteringPredicate);
|
||||
List<? extends Entity> entityList = source.getLevel().getEntities(eDesc.directType, eDesc.filteringPredicate);
|
||||
return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList()));
|
||||
});
|
||||
|
||||
@@ -167,24 +166,24 @@ public class Entities {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
Vector3Argument centerLocator = Vector3Argument.findIn(lv, 1, false, true);
|
||||
|
||||
Box centerBox;
|
||||
AABB centerBox;
|
||||
if (centerLocator.entity != null)
|
||||
{
|
||||
centerBox = centerLocator.entity.getBoundingBox();
|
||||
}
|
||||
else
|
||||
{
|
||||
Vec3d center = centerLocator.vec;
|
||||
Vec3 center = centerLocator.vec;
|
||||
if (centerLocator.fromBlock) center.add(0.5, 0.5, 0.5);
|
||||
centerBox = new Box(center, center);
|
||||
centerBox = new AABB(center, center);
|
||||
}
|
||||
Vector3Argument rangeLocator = Vector3Argument.findIn(lv, centerLocator.offset);
|
||||
if (rangeLocator.fromBlock)
|
||||
throw new InternalExpressionException("Range of 'entity_area' cannot come from a block argument");
|
||||
Vec3d range = rangeLocator.vec;
|
||||
Box area = centerBox.expand(range.x, range.y, range.z);
|
||||
Vec3 range = rangeLocator.vec;
|
||||
AABB area = centerBox.inflate(range.x, range.y, range.z);
|
||||
EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.s.getServer());
|
||||
List<? extends Entity> entityList = cc.s.getWorld().getEntitiesByType(eDesc.directType, area,eDesc.filteringPredicate);
|
||||
List<? extends Entity> entityList = cc.s.getLevel().getEntities(eDesc.directType, area,eDesc.filteringPredicate);
|
||||
return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList()));
|
||||
});
|
||||
|
||||
|
||||
@@ -23,70 +23,69 @@ import carpet.script.value.Value;
|
||||
import carpet.script.value.ValueConversions;
|
||||
import com.google.common.collect.Sets;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.command.argument.ItemStackArgument;
|
||||
import net.minecraft.entity.ItemEntity;
|
||||
import net.minecraft.entity.LivingEntity;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemGroup;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.network.packet.s2c.play.ScreenHandlerSlotUpdateS2CPacket;
|
||||
import net.minecraft.recipe.AbstractCookingRecipe;
|
||||
import net.minecraft.recipe.CuttingRecipe;
|
||||
import net.minecraft.recipe.Recipe;
|
||||
import net.minecraft.recipe.RecipeType;
|
||||
import net.minecraft.recipe.ShapedRecipe;
|
||||
import net.minecraft.recipe.ShapelessRecipe;
|
||||
import net.minecraft.recipe.SpecialCraftingRecipe;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.tag.TagManager;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.commands.arguments.item.ItemInput;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.tags.TagContainer;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.CreativeModeTab;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.AbstractCookingRecipe;
|
||||
import net.minecraft.world.item.crafting.CustomRecipe;
|
||||
import net.minecraft.world.item.crafting.Recipe;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraft.world.item.crafting.ShapedRecipe;
|
||||
import net.minecraft.world.item.crafting.ShapelessRecipe;
|
||||
import net.minecraft.world.item.crafting.SingleItemRecipe;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class Inventories {
|
||||
public static void apply(Expression expression)
|
||||
{
|
||||
expression.addUnaryFunction("stack_limit", v ->
|
||||
new NumericValue(NBTSerializableValue.parseItem(v.getString()).getItem().getMaxCount()));
|
||||
new NumericValue(NBTSerializableValue.parseItem(v.getString()).getItem().getMaxStackSize()));
|
||||
|
||||
expression.addUnaryFunction("item_category", v ->
|
||||
{
|
||||
ItemStackArgument item = NBTSerializableValue.parseItem(v.getString());
|
||||
ItemGroup ig = item.getItem().getGroup();
|
||||
return (ig==null)?Value.NULL:new StringValue(ig.getName());
|
||||
ItemInput item = NBTSerializableValue.parseItem(v.getString());
|
||||
CreativeModeTab ig = item.getItem().getItemCategory();
|
||||
return (ig==null)?Value.NULL:new StringValue(ig.getRecipeFolderName());
|
||||
});
|
||||
|
||||
expression.addContextFunction("item_list", -1, (c, t, lv) ->
|
||||
{
|
||||
if (lv.size() == 0)
|
||||
return ListValue.wrap(Registry.ITEM.getIds().stream().map(ValueConversions::of).collect(Collectors.toList()));
|
||||
return ListValue.wrap(Registry.ITEM.keySet().stream().map(ValueConversions::of).collect(Collectors.toList()));
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
TagManager tagManager = cc.s.getServer().getTagManager();
|
||||
TagContainer tagManager = cc.s.getServer().getTags();
|
||||
String tag = lv.get(0).getString();
|
||||
net.minecraft.tag.Tag<Item> itemTag = tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTag(InputValidator.identifierOf(tag));
|
||||
net.minecraft.tags.Tag<Item> itemTag = tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getTag(InputValidator.identifierOf(tag));
|
||||
if (itemTag == null) return Value.NULL;
|
||||
return ListValue.wrap(itemTag.values().stream().map(b -> ValueConversions.of(Registry.ITEM.getId(b))).collect(Collectors.toList()));
|
||||
return ListValue.wrap(itemTag.getValues().stream().map(b -> ValueConversions.of(Registry.ITEM.getKey(b))).collect(Collectors.toList()));
|
||||
});
|
||||
|
||||
expression.addContextFunction("item_tags", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
TagManager tagManager = cc.s.getServer().getTagManager();
|
||||
TagContainer tagManager = cc.s.getServer().getTags();
|
||||
if (lv.size() == 0)
|
||||
return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTagIds().stream().map(ValueConversions::of).collect(Collectors.toList()));
|
||||
return ListValue.wrap(tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getAvailableTags().stream().map(ValueConversions::of).collect(Collectors.toList()));
|
||||
Item item = NBTSerializableValue.parseItem(lv.get(0).getString()).getItem();
|
||||
if (lv.size() == 1)
|
||||
return ListValue.wrap(tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTags().entrySet().stream().filter(e -> e.getValue().contains(item)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList()));
|
||||
return ListValue.wrap(tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getAllTags().entrySet().stream().filter(e -> e.getValue().contains(item)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList()));
|
||||
String tag = lv.get(1).getString();
|
||||
net.minecraft.tag.Tag<Item> itemTag = tagManager.getOrCreateTagGroup(Registry.ITEM_KEY).getTag(InputValidator.identifierOf(tag));
|
||||
net.minecraft.tags.Tag<Item> itemTag = tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getTag(InputValidator.identifierOf(tag));
|
||||
if (itemTag == null) return Value.NULL;
|
||||
return BooleanValue.of(itemTag.contains(item));
|
||||
});
|
||||
@@ -109,7 +108,7 @@ public class Inventories {
|
||||
List<Value> recipesOutput = new ArrayList<>();
|
||||
for (Recipe<?> recipe: recipes)
|
||||
{
|
||||
ItemStack result = recipe.getOutput();
|
||||
ItemStack result = recipe.getResultItem();
|
||||
List<Value> ingredientValue = new ArrayList<>();
|
||||
recipe.getIngredients().forEach(
|
||||
ingredient ->
|
||||
@@ -147,15 +146,15 @@ public class Inventories {
|
||||
{
|
||||
recipeSpec = ListValue.of(
|
||||
new StringValue("smelting"),
|
||||
new NumericValue(((AbstractCookingRecipe) recipe).getCookTime()),
|
||||
new NumericValue(((AbstractCookingRecipe) recipe).getCookingTime()),
|
||||
new NumericValue(((AbstractCookingRecipe) recipe).getExperience())
|
||||
);
|
||||
}
|
||||
else if (recipe instanceof CuttingRecipe)
|
||||
else if (recipe instanceof SingleItemRecipe)
|
||||
{
|
||||
recipeSpec = ListValue.of(new StringValue("cutting"));
|
||||
}
|
||||
else if (recipe instanceof SpecialCraftingRecipe)
|
||||
else if (recipe instanceof CustomRecipe)
|
||||
{
|
||||
recipeSpec = ListValue.of(new StringValue("special"));
|
||||
}
|
||||
@@ -173,10 +172,10 @@ public class Inventories {
|
||||
{
|
||||
String itemStr = v.getString();
|
||||
Item item;
|
||||
Identifier id = InputValidator.identifierOf(itemStr);
|
||||
item = Registry.ITEM.getOrEmpty(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM));
|
||||
if (!item.hasRecipeRemainder()) return Value.NULL;
|
||||
return new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.ITEM.getId(item.getRecipeRemainder())));
|
||||
ResourceLocation id = InputValidator.identifierOf(itemStr);
|
||||
item = Registry.ITEM.getOptional(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM));
|
||||
if (!item.hasCraftingRemainingItem()) return Value.NULL;
|
||||
return new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.ITEM.getKey(item.getCraftingRemainingItem())));
|
||||
});
|
||||
|
||||
expression.addContextFunction("inventory_size", -1, (c, t, lv) ->
|
||||
@@ -184,7 +183,7 @@ public class Inventories {
|
||||
CarpetContext cc = (CarpetContext) c;
|
||||
NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0);
|
||||
if (inventoryLocator == null) return Value.NULL;
|
||||
return new NumericValue(inventoryLocator.inventory().size());
|
||||
return new NumericValue(inventoryLocator.inventory().getContainerSize());
|
||||
});
|
||||
|
||||
expression.addContextFunction("inventory_has_items", -1, (c, t, lv) ->
|
||||
@@ -204,14 +203,14 @@ public class Inventories {
|
||||
if (lv.size() == inventoryLocator.offset())
|
||||
{
|
||||
List<Value> fullInventory = new ArrayList<>();
|
||||
for (int i = 0, maxi = inventoryLocator.inventory().size(); i < maxi; i++)
|
||||
fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getStack(i)));
|
||||
for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++)
|
||||
fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getItem(i)));
|
||||
return ListValue.wrap(fullInventory);
|
||||
}
|
||||
int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong();
|
||||
slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory());
|
||||
if (slot == inventoryLocator.inventory().size()) return Value.NULL;
|
||||
return ValueConversions.of(inventoryLocator.inventory().getStack(slot));
|
||||
if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL;
|
||||
return ValueConversions.of(inventoryLocator.inventory().getItem(slot));
|
||||
});
|
||||
|
||||
//inventory_set(<b,e>, <n>, <count>, <item>, <nbt>)
|
||||
@@ -224,26 +223,26 @@ public class Inventories {
|
||||
throw new InternalExpressionException("'inventory_set' requires at least slot number and new stack size, and optional new item");
|
||||
int slot = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+0)).getLong();
|
||||
slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory());
|
||||
if (slot == inventoryLocator.inventory().size()) return Value.NULL;
|
||||
if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL;
|
||||
int count = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
|
||||
if (count == 0)
|
||||
{
|
||||
// clear slot
|
||||
ItemStack removedStack = inventoryLocator.inventory().removeStack(slot);
|
||||
ItemStack removedStack = inventoryLocator.inventory().removeItemNoUpdate(slot);
|
||||
syncPlayerInventory(inventoryLocator, slot);
|
||||
//Value res = ListValue.fromItemStack(removedStack); // that tuple will be read only but cheaper if noone cares
|
||||
return ValueConversions.of(removedStack);
|
||||
}
|
||||
if (lv.size() < inventoryLocator.offset()+3)
|
||||
{
|
||||
ItemStack previousStack = inventoryLocator.inventory().getStack(slot);
|
||||
ItemStack previousStack = inventoryLocator.inventory().getItem(slot);
|
||||
ItemStack newStack = previousStack.copy();
|
||||
newStack.setCount(count);
|
||||
inventoryLocator.inventory().setStack(slot, newStack);
|
||||
inventoryLocator.inventory().setItem(slot, newStack);
|
||||
syncPlayerInventory(inventoryLocator, slot);
|
||||
return ValueConversions.of(previousStack);
|
||||
}
|
||||
NbtCompound nbt = null; // skipping one argument
|
||||
CompoundTag nbt = null; // skipping one argument
|
||||
if (lv.size() > inventoryLocator.offset()+3)
|
||||
{
|
||||
Value nbtValue = lv.get(inventoryLocator.offset()+3);
|
||||
@@ -254,11 +253,11 @@ public class Inventories {
|
||||
else
|
||||
nbt = new NBTSerializableValue(nbtValue.getString()).getCompoundTag();
|
||||
}
|
||||
ItemStackArgument newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()+2).getString(), nbt);
|
||||
ItemStack previousStack = inventoryLocator.inventory().getStack(slot);
|
||||
ItemInput newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()+2).getString(), nbt);
|
||||
ItemStack previousStack = inventoryLocator.inventory().getItem(slot);
|
||||
try
|
||||
{
|
||||
inventoryLocator.inventory().setStack(slot, newitem.createStack(count, false));
|
||||
inventoryLocator.inventory().setItem(slot, newitem.createItemStack(count, false));
|
||||
syncPlayerInventory(inventoryLocator, slot);
|
||||
}
|
||||
catch (CommandSyntaxException e)
|
||||
@@ -274,7 +273,7 @@ public class Inventories {
|
||||
CarpetContext cc = (CarpetContext) c;
|
||||
NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0);
|
||||
if (inventoryLocator == null) return Value.NULL;
|
||||
ItemStackArgument itemArg = null;
|
||||
ItemInput itemArg = null;
|
||||
if (lv.size() > inventoryLocator.offset())
|
||||
{
|
||||
Value secondArg = lv.get(inventoryLocator.offset()+0);
|
||||
@@ -287,9 +286,9 @@ public class Inventories {
|
||||
startIndex = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
|
||||
}
|
||||
startIndex = NBTSerializableValue.validateSlot(startIndex, inventoryLocator.inventory());
|
||||
for (int i = startIndex, maxi = inventoryLocator.inventory().size(); i < maxi; i++)
|
||||
for (int i = startIndex, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++)
|
||||
{
|
||||
ItemStack stack = inventoryLocator.inventory().getStack(i);
|
||||
ItemStack stack = inventoryLocator.inventory().getItem(i);
|
||||
if ( (itemArg == null && stack.isEmpty()) || (itemArg != null && itemArg.getItem().equals(stack.getItem())) )
|
||||
return new NumericValue(i);
|
||||
}
|
||||
@@ -304,16 +303,16 @@ public class Inventories {
|
||||
if (inventoryLocator == null) return Value.NULL;
|
||||
if (lv.size() <= inventoryLocator.offset())
|
||||
throw new InternalExpressionException("'inventory_remove' requires at least an item to be removed");
|
||||
ItemStackArgument searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString());
|
||||
ItemInput searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString());
|
||||
int amount = 1;
|
||||
if (lv.size() > inventoryLocator.offset()+1)
|
||||
amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
|
||||
// not enough
|
||||
if (((amount == 1) && (!inventoryLocator.inventory().containsAny(Sets.newHashSet(searchItem.getItem()))))
|
||||
|| (inventoryLocator.inventory().count(searchItem.getItem()) < amount)) return Value.FALSE;
|
||||
for (int i = 0, maxi = inventoryLocator.inventory().size(); i < maxi; i++)
|
||||
if (((amount == 1) && (!inventoryLocator.inventory().hasAnyOf(Sets.newHashSet(searchItem.getItem()))))
|
||||
|| (inventoryLocator.inventory().countItem(searchItem.getItem()) < amount)) return Value.FALSE;
|
||||
for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++)
|
||||
{
|
||||
ItemStack stack = inventoryLocator.inventory().getStack(i);
|
||||
ItemStack stack = inventoryLocator.inventory().getItem(i);
|
||||
if (stack.isEmpty())
|
||||
continue;
|
||||
if (!stack.getItem().equals(searchItem.getItem()))
|
||||
@@ -322,13 +321,13 @@ public class Inventories {
|
||||
if (left > 0)
|
||||
{
|
||||
stack.setCount(left);
|
||||
inventoryLocator.inventory().setStack(i, stack);
|
||||
inventoryLocator.inventory().setItem(i, stack);
|
||||
syncPlayerInventory(inventoryLocator, i);
|
||||
return Value.TRUE;
|
||||
}
|
||||
else
|
||||
{
|
||||
inventoryLocator.inventory().removeStack(i);
|
||||
inventoryLocator.inventory().removeItemNoUpdate(i);
|
||||
syncPlayerInventory(inventoryLocator, i);
|
||||
amount -= stack.getCount();
|
||||
}
|
||||
@@ -348,51 +347,51 @@ public class Inventories {
|
||||
throw new InternalExpressionException("Slot number is required for inventory_drop");
|
||||
int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong();
|
||||
slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory());
|
||||
if (slot == inventoryLocator.inventory().size()) return Value.NULL;
|
||||
if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL;
|
||||
int amount = 0;
|
||||
if (lv.size() > inventoryLocator.offset()+1)
|
||||
amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
|
||||
if (amount < 0)
|
||||
throw new InternalExpressionException("Cannot throw negative number of items");
|
||||
ItemStack stack = inventoryLocator.inventory().getStack(slot);
|
||||
ItemStack stack = inventoryLocator.inventory().getItem(slot);
|
||||
if (stack == null || stack.isEmpty()) return Value.ZERO;
|
||||
if (amount == 0) amount = stack.getCount();
|
||||
ItemStack droppedStack = inventoryLocator.inventory().removeStack(slot, amount);
|
||||
ItemStack droppedStack = inventoryLocator.inventory().removeItem(slot, amount);
|
||||
if (droppedStack.isEmpty()) return Value.ZERO;
|
||||
Object owner = inventoryLocator.owner();
|
||||
ItemEntity item;
|
||||
if (owner instanceof PlayerEntity)
|
||||
if (owner instanceof Player)
|
||||
{
|
||||
item = ((PlayerEntity) owner).dropItem(droppedStack, false, true);
|
||||
item = ((Player) owner).drop(droppedStack, false, true);
|
||||
}
|
||||
else if (owner instanceof LivingEntity villager)
|
||||
{
|
||||
// stolen from LookTargetUtil.give((VillagerEntity)owner, droppedStack, (LivingEntity) owner);
|
||||
double double_1 = villager.getY() - 0.30000001192092896D + (double)villager.getStandingEyeHeight();
|
||||
item = new ItemEntity(villager.world, villager.getX(), double_1, villager.getZ(), droppedStack);
|
||||
Vec3d vec3d_1 = villager.getRotationVec(1.0F).normalize().multiply(0.3);// new Vec3d(0, 0.3, 0);
|
||||
item.setVelocity(vec3d_1);
|
||||
item.setToDefaultPickupDelay();
|
||||
cc.s.getWorld().spawnEntity(item);
|
||||
double double_1 = villager.getY() - 0.30000001192092896D + (double)villager.getEyeHeight();
|
||||
item = new ItemEntity(villager.level, villager.getX(), double_1, villager.getZ(), droppedStack);
|
||||
Vec3 vec3d_1 = villager.getViewVector(1.0F).normalize().scale(0.3);// new Vec3d(0, 0.3, 0);
|
||||
item.setDeltaMovement(vec3d_1);
|
||||
item.setDefaultPickUpDelay();
|
||||
cc.s.getLevel().addFreshEntity(item);
|
||||
}
|
||||
else
|
||||
{
|
||||
Vec3d point = Vec3d.ofCenter(inventoryLocator.position()); //pos+0.5v
|
||||
item = new ItemEntity(cc.s.getWorld(), point.x, point.y, point.z, droppedStack);
|
||||
item.setToDefaultPickupDelay();
|
||||
cc.s.getWorld().spawnEntity(item);
|
||||
Vec3 point = Vec3.atCenterOf(inventoryLocator.position()); //pos+0.5v
|
||||
item = new ItemEntity(cc.s.getLevel(), point.x, point.y, point.z, droppedStack);
|
||||
item.setDefaultPickUpDelay();
|
||||
cc.s.getLevel().addFreshEntity(item);
|
||||
}
|
||||
return new NumericValue(item.getStack().getCount());
|
||||
return new NumericValue(item.getItem().getCount());
|
||||
});
|
||||
|
||||
expression.addContextFunction("create_screen",-1, (c, t, lv) ->
|
||||
{
|
||||
if(lv.size() < 3) throw new InternalExpressionException("'create_screen' requires at least three arguments");
|
||||
Value playerValue = lv.get(0);
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), playerValue);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), playerValue);
|
||||
if(player == null) throw new InternalExpressionException("'create_screen' requires a valid online player as the first argument.");
|
||||
String type = lv.get(1).getString();
|
||||
Text name = FormattedTextValue.getTextByValue(lv.get(2));
|
||||
Component name = FormattedTextValue.getTextByValue(lv.get(2));
|
||||
FunctionValue function = null;
|
||||
if(lv.size() > 3)
|
||||
function = FunctionArgument.findIn(c, expression.module, lv, 3, true, false).function;
|
||||
@@ -427,12 +426,12 @@ public class Inventories {
|
||||
|
||||
private static void syncPlayerInventory(NBTSerializableValue.InventoryLocator inventory, int int_1)
|
||||
{
|
||||
if (inventory.owner() instanceof ServerPlayerEntity player && !inventory.isEnder() && !(inventory.inventory() instanceof ScreenValue.ScreenHandlerInventory))
|
||||
if (inventory.owner() instanceof ServerPlayer player && !inventory.isEnder() && !(inventory.inventory() instanceof ScreenValue.ScreenHandlerInventory))
|
||||
{
|
||||
player.networkHandler.sendPacket(new ScreenHandlerSlotUpdateS2CPacket(
|
||||
player.connection.send(new ClientboundContainerSetSlotPacket(
|
||||
-2, 0, // resolve mystery argument
|
||||
int_1,
|
||||
inventory.inventory().getStack(int_1)
|
||||
inventory.inventory().getItem(int_1)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,13 +12,12 @@ import carpet.script.value.StringValue;
|
||||
import carpet.script.value.Value;
|
||||
import carpet.utils.SpawnReporter;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
||||
import net.minecraft.entity.SpawnGroup;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.world.SpawnHelper;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.MobCategory;
|
||||
import net.minecraft.world.level.NaturalSpawner;
|
||||
|
||||
public class Monitoring {
|
||||
|
||||
@@ -42,19 +41,19 @@ public class Monitoring {
|
||||
expression.addContextFunction("get_mob_counts", -1, (c, t, lv) ->
|
||||
{
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
ServerWorld world = cc.s.getWorld();
|
||||
SpawnHelper.Info info = world.getChunkManager().getSpawnInfo();
|
||||
ServerLevel world = cc.s.getLevel();
|
||||
NaturalSpawner.SpawnState info = world.getChunkSource().getLastSpawnState();
|
||||
if (info == null) return Value.NULL;
|
||||
Object2IntMap<SpawnGroup> mobcounts = info.getGroupToCount();
|
||||
Object2IntMap<MobCategory> mobcounts = info.getMobCategoryCounts();
|
||||
int chunks = ((SpawnHelperInnerInterface)info).cmGetChunkCount();
|
||||
if (lv.size() == 0)
|
||||
{
|
||||
Map<Value, Value> retDict = new HashMap<>();
|
||||
for (SpawnGroup category: mobcounts.keySet())
|
||||
for (MobCategory category: mobcounts.keySet())
|
||||
{
|
||||
int currentCap = (int)(category.getCapacity() * chunks / SpawnReporter.MAGIC_NUMBER);
|
||||
int currentCap = (int)(category.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER);
|
||||
retDict.put(
|
||||
new StringValue(category.asString().toLowerCase(Locale.ROOT)),
|
||||
new StringValue(category.getSerializedName().toLowerCase(Locale.ROOT)),
|
||||
ListValue.of(
|
||||
new NumericValue(mobcounts.getInt(category)),
|
||||
new NumericValue(currentCap))
|
||||
@@ -63,11 +62,11 @@ public class Monitoring {
|
||||
return MapValue.wrap(retDict);
|
||||
}
|
||||
String catString = lv.get(0).getString();
|
||||
SpawnGroup cat = SpawnGroup.byName(catString.toLowerCase(Locale.ROOT));
|
||||
MobCategory cat = MobCategory.byName(catString.toLowerCase(Locale.ROOT));
|
||||
if (cat == null) throw new InternalExpressionException("Unreconized mob category: "+catString);
|
||||
return ListValue.of(
|
||||
new NumericValue(mobcounts.getInt(cat)),
|
||||
new NumericValue((int)(cat.getCapacity() * chunks / SpawnReporter.MAGIC_NUMBER))
|
||||
new NumericValue((int)(cat.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER))
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -19,28 +19,26 @@ import carpet.script.value.StringValue;
|
||||
import carpet.script.value.FormattedTextValue;
|
||||
import carpet.script.value.Value;
|
||||
import com.google.common.collect.Lists;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.boss.BossBar;
|
||||
import net.minecraft.entity.boss.BossBarManager;
|
||||
import net.minecraft.entity.boss.CommandBossBar;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.scoreboard.Scoreboard;
|
||||
import net.minecraft.scoreboard.ServerScoreboard;
|
||||
import net.minecraft.scoreboard.ScoreboardCriterion;
|
||||
import net.minecraft.scoreboard.ScoreboardObjective;
|
||||
import net.minecraft.scoreboard.ScoreboardPlayerScore;
|
||||
import net.minecraft.scoreboard.Team;
|
||||
import net.minecraft.scoreboard.AbstractTeam;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.LiteralText;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Formatting;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.InvalidIdentifierException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.ServerScoreboard;
|
||||
import net.minecraft.server.bossevents.CustomBossEvent;
|
||||
import net.minecraft.server.bossevents.CustomBossEvents;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.BossEvent;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.scores.Objective;
|
||||
import net.minecraft.world.scores.PlayerTeam;
|
||||
import net.minecraft.world.scores.Score;
|
||||
import net.minecraft.world.scores.Scoreboard;
|
||||
import net.minecraft.world.scores.Team;
|
||||
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
|
||||
|
||||
public class Scoreboards {
|
||||
private static String getScoreboardKeyFromValue(Value keyValue)
|
||||
@@ -48,13 +46,13 @@ public class Scoreboards {
|
||||
if (keyValue instanceof EntityValue)
|
||||
{
|
||||
Entity e = ((EntityValue) keyValue).getEntity();
|
||||
if (e instanceof PlayerEntity)
|
||||
if (e instanceof Player)
|
||||
{
|
||||
return e.getName().getString();
|
||||
}
|
||||
else
|
||||
{
|
||||
return e.getUuidAsString();
|
||||
return e.getStringUUID();
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -74,25 +72,25 @@ public class Scoreboards {
|
||||
if (lv.size()==0)
|
||||
return ListValue.wrap(scoreboard.getObjectiveNames().stream().map(StringValue::new).collect(Collectors.toList()));
|
||||
String objectiveName = lv.get(0).getString();
|
||||
ScoreboardObjective objective = scoreboard.getObjective(objectiveName);
|
||||
Objective objective = scoreboard.getOrCreateObjective(objectiveName);
|
||||
if (objective == null) return Value.NULL;
|
||||
if (lv.size()==1)
|
||||
return ListValue.wrap(scoreboard.getAllPlayerScores(objective).stream().map(s -> new StringValue(s.getPlayerName())).collect(Collectors.toList()));
|
||||
return ListValue.wrap(scoreboard.getPlayerScores(objective).stream().map(s -> new StringValue(s.getOwner())).collect(Collectors.toList()));
|
||||
String key = getScoreboardKeyFromValue(lv.get(1));
|
||||
if(lv.size()==2)
|
||||
{
|
||||
if(!scoreboard.playerHasObjective(key, objective)) return Value.NULL;
|
||||
return NumericValue.of(scoreboard.getPlayerScore(key,objective).getScore());
|
||||
if(!scoreboard.hasPlayerScore(key, objective)) return Value.NULL;
|
||||
return NumericValue.of(scoreboard.getOrCreatePlayerScore(key,objective).getScore());
|
||||
}
|
||||
|
||||
Value value = lv.get(2);
|
||||
if(value.isNull()) {
|
||||
ScoreboardPlayerScore score = scoreboard.getPlayerScore(key, objective);
|
||||
Score score = scoreboard.getOrCreatePlayerScore(key, objective);
|
||||
scoreboard.resetPlayerScore(key,objective);
|
||||
return NumericValue.of(score.getScore());
|
||||
}
|
||||
if (value instanceof NumericValue) {
|
||||
ScoreboardPlayerScore score = scoreboard.getPlayerScore(key, objective);
|
||||
Score score = scoreboard.getOrCreatePlayerScore(key, objective);
|
||||
score.setScore(NumericValue.asNumber(value).getInt());
|
||||
return NumericValue.of(score.getScore());
|
||||
}
|
||||
@@ -105,7 +103,7 @@ public class Scoreboards {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
Scoreboard scoreboard = cc.s.getServer().getScoreboard();
|
||||
String objectiveName = lv.get(0).getString();
|
||||
ScoreboardObjective objective = scoreboard.getObjective(objectiveName);
|
||||
Objective objective = scoreboard.getOrCreateObjective(objectiveName);
|
||||
if (objective == null) return Value.FALSE;
|
||||
if (lv.size() == 1)
|
||||
{
|
||||
@@ -113,8 +111,8 @@ public class Scoreboards {
|
||||
return Value.TRUE;
|
||||
}
|
||||
String key = getScoreboardKeyFromValue(lv.get(1));
|
||||
if (!scoreboard.playerHasObjective(key, objective)) return Value.NULL;
|
||||
ScoreboardPlayerScore scoreboardPlayerScore = scoreboard.getPlayerScore(key, objective);
|
||||
if (!scoreboard.hasPlayerScore(key, objective)) return Value.NULL;
|
||||
Score scoreboardPlayerScore = scoreboard.getOrCreatePlayerScore(key, objective);
|
||||
Value previous = new NumericValue(scoreboardPlayerScore.getScore());
|
||||
scoreboard.resetPlayerScore(key, objective);
|
||||
return previous;
|
||||
@@ -129,34 +127,34 @@ public class Scoreboards {
|
||||
Scoreboard scoreboard = cc.s.getServer().getScoreboard();
|
||||
if (lv.size() == 0 || lv.size()>2) throw new InternalExpressionException("'scoreboard_add' should have one or two parameters");
|
||||
String objectiveName = lv.get(0).getString();
|
||||
ScoreboardCriterion criterion;
|
||||
ObjectiveCriteria criterion;
|
||||
if (lv.size() == 1 )
|
||||
{
|
||||
criterion = ScoreboardCriterion.DUMMY;
|
||||
criterion = ObjectiveCriteria.DUMMY;
|
||||
}
|
||||
else
|
||||
{
|
||||
String critetionName = lv.get(1).getString();
|
||||
criterion = ScoreboardCriterion.getOrCreateStatCriterion(critetionName).orElse(null);
|
||||
criterion = ObjectiveCriteria.byName(critetionName).orElse(null);
|
||||
if (criterion==null)
|
||||
{
|
||||
throw new ThrowStatement(critetionName, Throwables.UNKNOWN_CRITERION);
|
||||
}
|
||||
}
|
||||
|
||||
ScoreboardObjective objective = scoreboard.getObjective(objectiveName);
|
||||
Objective objective = scoreboard.getOrCreateObjective(objectiveName);
|
||||
if (objective != null) {
|
||||
c.host.issueDeprecation("reading or modifying an objective's criterion with scoreboard_add");
|
||||
if(lv.size() == 1) return StringValue.of(objective.getCriterion().getName());
|
||||
if(objective.getCriterion().equals(criterion) || lv.size() == 1) return Value.NULL;
|
||||
((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriterion()).remove(objective);
|
||||
if(lv.size() == 1) return StringValue.of(objective.getCriteria().getName());
|
||||
if(objective.getCriteria().equals(criterion) || lv.size() == 1) return Value.NULL;
|
||||
((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriteria()).remove(objective);
|
||||
((ScoreboardObjective_scarpetMixin) objective).setCriterion(criterion);
|
||||
(((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective);
|
||||
scoreboard.updateObjective(objective);
|
||||
scoreboard.onObjectiveAdded(objective);
|
||||
return Value.FALSE;
|
||||
}
|
||||
|
||||
scoreboard.addObjective(objectiveName, criterion, new LiteralText(objectiveName), criterion.getDefaultRenderType());
|
||||
scoreboard.addObjective(objectiveName, criterion, new TextComponent(objectiveName), criterion.getDefaultRenderType());
|
||||
return Value.TRUE;
|
||||
});
|
||||
|
||||
@@ -165,7 +163,7 @@ public class Scoreboards {
|
||||
if(lv.size() < 2) throw new InternalExpressionException("'scoreboard_property' requires at least two parameters");
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
Scoreboard scoreboard = cc.s.getServer().getScoreboard();
|
||||
ScoreboardObjective objective = scoreboard.getObjective(lv.get(0).getString());
|
||||
Objective objective = scoreboard.getOrCreateObjective(lv.get(0).getString());
|
||||
if(objective == null) return Value.NULL;
|
||||
|
||||
boolean modify = lv.size() > 2;
|
||||
@@ -177,37 +175,37 @@ public class Scoreboards {
|
||||
switch (property) {
|
||||
case "criterion":
|
||||
if(modify) {
|
||||
ScoreboardCriterion criterion = ScoreboardCriterion.getOrCreateStatCriterion(setValue.getString()).orElse(null);
|
||||
ObjectiveCriteria criterion = ObjectiveCriteria.byName(setValue.getString()).orElse(null);
|
||||
if (criterion==null) throw new InternalExpressionException("Unknown scoreboard criterion: "+ setValue.getString());
|
||||
if(objective.getCriterion().equals(criterion) || lv.size() == 1) return Value.FALSE;
|
||||
((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriterion()).remove(objective);
|
||||
if(objective.getCriteria().equals(criterion) || lv.size() == 1) return Value.FALSE;
|
||||
((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriteria()).remove(objective);
|
||||
((ScoreboardObjective_scarpetMixin) objective).setCriterion(criterion);
|
||||
(((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective);
|
||||
scoreboard.updateObjective(objective);
|
||||
scoreboard.onObjectiveAdded(objective);
|
||||
return Value.TRUE;
|
||||
}
|
||||
return StringValue.of(objective.getCriterion().getName());
|
||||
return StringValue.of(objective.getCriteria().getName());
|
||||
case "display_name":
|
||||
if(modify) {
|
||||
Text text = FormattedTextValue.getTextByValue(setValue);
|
||||
Component text = FormattedTextValue.getTextByValue(setValue);
|
||||
objective.setDisplayName(text);
|
||||
return Value.TRUE;
|
||||
}
|
||||
return new FormattedTextValue(objective.getDisplayName());
|
||||
case "display_slot":
|
||||
if(modify) {
|
||||
int slotId = Scoreboard.getDisplaySlotId(setValue.getString());
|
||||
int slotId = Scoreboard.getDisplaySlotByName(setValue.getString());
|
||||
if(slotId == -1) throw new InternalExpressionException("Unknown scoreboard display slot: " + setValue.getString());
|
||||
if(objective.equals(scoreboard.getObjectiveForSlot(slotId))) {
|
||||
if(objective.equals(scoreboard.getDisplayObjective(slotId))) {
|
||||
return Value.FALSE;
|
||||
}
|
||||
scoreboard.setObjectiveSlot(slotId,objective);
|
||||
scoreboard.setDisplayObjective(slotId,objective);
|
||||
return Value.TRUE;
|
||||
}
|
||||
|
||||
List<Value> slots = new ArrayList<>();
|
||||
for(int i = 0; i < 19; i++) {
|
||||
if (scoreboard.getObjectiveForSlot(i) == objective) {
|
||||
if (scoreboard.getDisplayObjective(i) == objective) {
|
||||
String slotName = Scoreboard.getDisplaySlotName(i);
|
||||
slots.add(StringValue.of(slotName));
|
||||
}
|
||||
@@ -215,12 +213,12 @@ public class Scoreboards {
|
||||
return ListValue.wrap(slots);
|
||||
case "render_type":
|
||||
if(modify) {
|
||||
ScoreboardCriterion.RenderType renderType = ScoreboardCriterion.RenderType.getType(setValue.getString().toLowerCase());
|
||||
ObjectiveCriteria.RenderType renderType = ObjectiveCriteria.RenderType.byId(setValue.getString().toLowerCase());
|
||||
if(objective.getRenderType().equals(renderType)) return Value.FALSE;
|
||||
objective.setRenderType(renderType);
|
||||
return Value.TRUE;
|
||||
}
|
||||
return StringValue.of(objective.getRenderType().getName());
|
||||
return StringValue.of(objective.getRenderType().getId());
|
||||
default:
|
||||
throw new InternalExpressionException("scoreboard property '" + property + "' is not a valid property");
|
||||
}
|
||||
@@ -231,18 +229,18 @@ public class Scoreboards {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
Scoreboard scoreboard = cc.s.getServer().getScoreboard();
|
||||
String location = lv.get(0).getString();
|
||||
int slot = Scoreboard.getDisplaySlotId(location);
|
||||
int slot = Scoreboard.getDisplaySlotByName(location);
|
||||
if (slot < 0) throw new InternalExpressionException("Invalid objective slot: "+location);
|
||||
Value target = lv.get(1);
|
||||
if (target instanceof NullValue)
|
||||
{
|
||||
scoreboard.setObjectiveSlot(slot, null);
|
||||
scoreboard.setDisplayObjective(slot, null);
|
||||
return new NumericValue(slot);
|
||||
}
|
||||
String objectiveString = target.getString();
|
||||
ScoreboardObjective objective = scoreboard.getObjective(objectiveString);
|
||||
Objective objective = scoreboard.getOrCreateObjective(objectiveString);
|
||||
if (objective == null) return Value.NULL;
|
||||
scoreboard.setObjectiveSlot(slot, objective);
|
||||
scoreboard.setDisplayObjective(slot, objective);
|
||||
return new NumericValue(slot);
|
||||
});
|
||||
|
||||
@@ -254,9 +252,9 @@ public class Scoreboards {
|
||||
if(lv.size() == 0)
|
||||
return ListValue.wrap(scoreboard.getTeamNames().stream().map(StringValue::of).collect(Collectors.toList()));
|
||||
if (lv.size() != 1) return Value.NULL;
|
||||
Team team = scoreboard.getTeam(lv.get(0).getString());
|
||||
PlayerTeam team = scoreboard.getPlayerTeam(lv.get(0).getString());
|
||||
if(team == null) return Value.NULL;
|
||||
return ListValue.wrap(team.getPlayerList().stream().map(StringValue::of).collect(Collectors.toList()));
|
||||
return ListValue.wrap(team.getPlayers().stream().map(StringValue::of).collect(Collectors.toList()));
|
||||
});
|
||||
|
||||
|
||||
@@ -270,18 +268,18 @@ public class Scoreboards {
|
||||
|
||||
if(lv.size() == 1)
|
||||
{
|
||||
if (scoreboard.getTeam(teamName) != null) return Value.NULL;
|
||||
scoreboard.addTeam(teamName);
|
||||
if (scoreboard.getPlayerTeam(teamName) != null) return Value.NULL;
|
||||
scoreboard.addPlayerTeam(teamName);
|
||||
return new StringValue(teamName);
|
||||
}
|
||||
if(lv.size() != 2) return Value.NULL;
|
||||
Value playerVal = lv.get(1);
|
||||
String player = EntityValue.getPlayerNameByValue(playerVal);
|
||||
if(player == null) return Value.NULL;
|
||||
Team team = scoreboard.getTeam(teamName);
|
||||
PlayerTeam team = scoreboard.getPlayerTeam(teamName);
|
||||
if(team == null) return Value.NULL;
|
||||
if(team.isEqual(scoreboard.getPlayerTeam(player))) return Value.FALSE;
|
||||
scoreboard.addPlayerToTeam(player,scoreboard.getTeam(teamName));
|
||||
if(team.isAlliedTo(scoreboard.getPlayersTeam(player))) return Value.FALSE;
|
||||
scoreboard.addPlayerToTeam(player,scoreboard.getPlayerTeam(teamName));
|
||||
return Value.TRUE;
|
||||
});
|
||||
|
||||
@@ -291,8 +289,8 @@ public class Scoreboards {
|
||||
ServerScoreboard scoreboard = cc.s.getServer().getScoreboard();
|
||||
Value teamVal = lv.get(0);
|
||||
String team = teamVal.getString();
|
||||
if(scoreboard.getTeam(team) == null) return Value.NULL;
|
||||
scoreboard.removeTeam(scoreboard.getTeam(team));
|
||||
if(scoreboard.getPlayerTeam(team) == null) return Value.NULL;
|
||||
scoreboard.removePlayerTeam(scoreboard.getPlayerTeam(team));
|
||||
return Value.TRUE;
|
||||
});
|
||||
|
||||
@@ -304,7 +302,7 @@ public class Scoreboards {
|
||||
Value playerVal = lv.get(0);
|
||||
String player = EntityValue.getPlayerNameByValue(playerVal);
|
||||
if(player == null) return Value.NULL;
|
||||
return BooleanValue.of(scoreboard.clearPlayerTeam(player));
|
||||
return BooleanValue.of(scoreboard.removePlayerFromTeam(player));
|
||||
});
|
||||
|
||||
expression.addContextFunction("team_property", -1, (c, t, lv) ->
|
||||
@@ -325,7 +323,7 @@ public class Scoreboards {
|
||||
settingVal = lv.get(2);
|
||||
}
|
||||
|
||||
Team team = scoreboard.getTeam(teamVal.getString());
|
||||
PlayerTeam team = scoreboard.getPlayerTeam(teamVal.getString());
|
||||
if(team == null) return Value.NULL;
|
||||
|
||||
if(!(propertyVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the second argument");
|
||||
@@ -334,64 +332,64 @@ public class Scoreboards {
|
||||
case "collisionRule":
|
||||
if(!modifying) return new StringValue(team.getCollisionRule().name);
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString());
|
||||
AbstractTeam.CollisionRule collisionRule = AbstractTeam.CollisionRule.getRule(settingVal.getString());
|
||||
Team.CollisionRule collisionRule = Team.CollisionRule.byName(settingVal.getString());
|
||||
if(collisionRule == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString());
|
||||
team.setCollisionRule(collisionRule);
|
||||
break;
|
||||
case "color":
|
||||
if(!modifying) return new StringValue(((Team_scarpetMixin) team).getColor().getName());
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString());
|
||||
Formatting color = Formatting.byName(settingVal.getString().toUpperCase());
|
||||
ChatFormatting color = ChatFormatting.getByName(settingVal.getString().toUpperCase());
|
||||
if(color == null || !color.isColor()) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString());
|
||||
team.setColor(color);
|
||||
break;
|
||||
case "deathMessageVisibility":
|
||||
if(!modifying) return new StringValue(team.getDeathMessageVisibilityRule().name);
|
||||
if(!modifying) return new StringValue(team.getDeathMessageVisibility().name);
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString());
|
||||
AbstractTeam.VisibilityRule deathMessageVisibility = AbstractTeam.VisibilityRule.getRule(settingVal.getString());
|
||||
Team.Visibility deathMessageVisibility = Team.Visibility.byName(settingVal.getString());
|
||||
if(deathMessageVisibility == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString());
|
||||
team.setDeathMessageVisibilityRule(deathMessageVisibility);
|
||||
team.setDeathMessageVisibility(deathMessageVisibility);
|
||||
break;
|
||||
case "displayName":
|
||||
if(!modifying) return new FormattedTextValue(team.getDisplayName());
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string or formatted text as the third argument for the property " + propertyVal.getString());
|
||||
Text displayName;
|
||||
Component displayName;
|
||||
displayName = FormattedTextValue.getTextByValue(settingVal);
|
||||
team.setDisplayName(displayName);
|
||||
break;
|
||||
case "friendlyFire":
|
||||
if(!modifying) return BooleanValue.of(team.isFriendlyFireAllowed());
|
||||
if(!modifying) return BooleanValue.of(team.isAllowFriendlyFire());
|
||||
if(!(settingVal instanceof NumericValue)) throw new InternalExpressionException("'team_property' requires a boolean as the third argument for the property " + propertyVal.getString());
|
||||
boolean friendlyFire = settingVal.getBoolean();
|
||||
team.setFriendlyFireAllowed(friendlyFire);
|
||||
team.setAllowFriendlyFire(friendlyFire);
|
||||
break;
|
||||
case "nametagVisibility":
|
||||
if(!modifying) return new StringValue(team.getNameTagVisibilityRule().name);
|
||||
if(!modifying) return new StringValue(team.getNameTagVisibility().name);
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString());
|
||||
AbstractTeam.VisibilityRule nametagVisibility = AbstractTeam.VisibilityRule.getRule(settingVal.getString());
|
||||
Team.Visibility nametagVisibility = Team.Visibility.byName(settingVal.getString());
|
||||
if(nametagVisibility == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString());
|
||||
team.setNameTagVisibilityRule(nametagVisibility);
|
||||
team.setNameTagVisibility(nametagVisibility);
|
||||
|
||||
break;
|
||||
case "prefix":
|
||||
if(!modifying) return new FormattedTextValue(team.getPrefix());
|
||||
if(!modifying) return new FormattedTextValue(team.getPlayerPrefix());
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property ' requires a string or formatted text as the third argument for the property " + propertyVal.getString());
|
||||
Text prefix;
|
||||
Component prefix;
|
||||
prefix = FormattedTextValue.getTextByValue(settingVal);
|
||||
team.setPrefix(prefix);
|
||||
team.setPlayerPrefix(prefix);
|
||||
break;
|
||||
case "seeFriendlyInvisibles":
|
||||
if(!modifying) return BooleanValue.of(team.shouldShowFriendlyInvisibles());
|
||||
if(!modifying) return BooleanValue.of(team.canSeeFriendlyInvisibles());
|
||||
if(!(settingVal instanceof NumericValue)) throw new InternalExpressionException("'team_property' requires a boolean as the third argument for the property " + propertyVal.getString());
|
||||
boolean seeFriendlyInvisibles = settingVal.getBoolean();
|
||||
team.setShowFriendlyInvisibles(seeFriendlyInvisibles);
|
||||
team.setSeeFriendlyInvisibles(seeFriendlyInvisibles);
|
||||
break;
|
||||
case "suffix":
|
||||
if(!modifying) return new FormattedTextValue(team.getSuffix());
|
||||
if(!modifying) return new FormattedTextValue(team.getPlayerSuffix());
|
||||
if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string or formatted text as the third argument for the property " + propertyVal.getString());
|
||||
Text suffix;
|
||||
Component suffix;
|
||||
suffix = FormattedTextValue.getTextByValue(settingVal);
|
||||
team.setSuffix(suffix);
|
||||
team.setPlayerSuffix(suffix);
|
||||
break;
|
||||
default:
|
||||
throw new InternalExpressionException("team property '" + propertyVal.getString() + "' is not a valid property");
|
||||
@@ -401,24 +399,24 @@ public class Scoreboards {
|
||||
|
||||
expression.addContextFunction("bossbar", -1, (c, t, lv) ->
|
||||
{
|
||||
BossBarManager bossBarManager = ((CarpetContext)c).s.getServer().getBossBarManager();
|
||||
CustomBossEvents bossBarManager = ((CarpetContext)c).s.getServer().getCustomBossEvents();
|
||||
if(lv.size() > 3) throw new InternalExpressionException("'bossbar' accepts max three arguments");
|
||||
|
||||
if(lv.size() == 0) return ListValue.wrap(bossBarManager.getAll().stream().map(CommandBossBar::getId).map(Identifier::toString).map(StringValue::of).collect(Collectors.toList()));
|
||||
if(lv.size() == 0) return ListValue.wrap(bossBarManager.getEvents().stream().map(CustomBossEvent::getTextId).map(ResourceLocation::toString).map(StringValue::of).collect(Collectors.toList()));
|
||||
|
||||
String id = lv.get(0).getString();
|
||||
Identifier identifier;
|
||||
ResourceLocation identifier;
|
||||
identifier = InputValidator.identifierOf(id);
|
||||
|
||||
if(lv.size() == 1)
|
||||
{
|
||||
if(bossBarManager.get(identifier) != null) return Value.FALSE;
|
||||
return StringValue.of(bossBarManager.add(identifier,new LiteralText(id)).getId().toString());
|
||||
return StringValue.of(bossBarManager.create(identifier,new TextComponent(id)).getTextId().toString());
|
||||
}
|
||||
|
||||
String property = lv.get(1).getString();
|
||||
|
||||
CommandBossBar bossBar = bossBarManager.get(identifier);
|
||||
CustomBossEvent bossBar = bossBarManager.get(identifier);
|
||||
if(bossBar == null) return Value.NULL;
|
||||
|
||||
Value propertyValue = (lv.size() == 3)?lv.get(2):null;
|
||||
@@ -426,20 +424,20 @@ public class Scoreboards {
|
||||
switch (property) {
|
||||
case "color":
|
||||
if(propertyValue == null) {
|
||||
BossBar.Color color = (bossBar).getColor();
|
||||
BossEvent.BossBarColor color = (bossBar).getColor();
|
||||
if(color == null) return Value.NULL;
|
||||
return StringValue.of(color.getName());
|
||||
}
|
||||
|
||||
BossBar.Color color = BossBar.Color.byName(propertyValue.getString());
|
||||
BossEvent.BossBarColor color = BossEvent.BossBarColor.byName(propertyValue.getString());
|
||||
if(color == null) return Value.NULL;
|
||||
bossBar.setColor(BossBar.Color.byName(propertyValue.getString()));
|
||||
bossBar.setColor(BossEvent.BossBarColor.byName(propertyValue.getString()));
|
||||
return Value.TRUE;
|
||||
case "max":
|
||||
if(propertyValue == null) return NumericValue.of(bossBar.getMaxValue());
|
||||
if(propertyValue == null) return NumericValue.of(bossBar.getMax());
|
||||
|
||||
if(!(propertyValue instanceof NumericValue)) throw new InternalExpressionException("'bossbar' requires a number as the value for the property " + property);
|
||||
bossBar.setMaxValue(((NumericValue) propertyValue).getInt());
|
||||
bossBar.setMax(((NumericValue) propertyValue).getInt());
|
||||
return Value.TRUE;
|
||||
case "name":
|
||||
if(propertyValue == null) return new FormattedTextValue(bossBar.getName());
|
||||
@@ -451,13 +449,13 @@ public class Scoreboards {
|
||||
|
||||
if(propertyValue instanceof ListValue) {
|
||||
((ListValue) propertyValue).getItems().forEach((v)->{
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext)c).s.getServer(),propertyValue);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext)c).s.getServer(),propertyValue);
|
||||
if(player != null) bossBar.addPlayer(player);
|
||||
});
|
||||
return Value.TRUE;
|
||||
}
|
||||
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue);
|
||||
if(player != null) {
|
||||
bossBar.addPlayer(player);
|
||||
return Value.TRUE;
|
||||
@@ -467,27 +465,27 @@ public class Scoreboards {
|
||||
if (propertyValue == null) return ListValue.wrap(bossBar.getPlayers().stream().map(EntityValue::new).collect(Collectors.toList()));
|
||||
if(propertyValue instanceof ListValue)
|
||||
{
|
||||
bossBar.clearPlayers();
|
||||
bossBar.removeAllPlayers();
|
||||
((ListValue) propertyValue).getItems().forEach((v) -> {
|
||||
ServerPlayerEntity p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), v);
|
||||
ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), v);
|
||||
if (p != null) bossBar.addPlayer(p);
|
||||
});
|
||||
return Value.TRUE;
|
||||
}
|
||||
|
||||
|
||||
ServerPlayerEntity p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue);
|
||||
bossBar.clearPlayers();
|
||||
ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue);
|
||||
bossBar.removeAllPlayers();
|
||||
if (p != null) {
|
||||
bossBar.addPlayer(p);
|
||||
return Value.TRUE;
|
||||
}
|
||||
return Value.FALSE;
|
||||
case "style":
|
||||
if(propertyValue == null) return StringValue.of(bossBar.getStyle().getName());
|
||||
BossBar.Style style = BossBar.Style.byName(propertyValue.getString());
|
||||
if(propertyValue == null) return StringValue.of(bossBar.getOverlay().getName());
|
||||
BossEvent.BossBarOverlay style = BossEvent.BossBarOverlay.byName(propertyValue.getString());
|
||||
if(style == null) throw new InternalExpressionException("'" + propertyValue.getString() + "' is not a valid value for property " + property);
|
||||
bossBar.setStyle(style);
|
||||
bossBar.setOverlay(style);
|
||||
return Value.TRUE;
|
||||
case "value":
|
||||
if(propertyValue == null) return NumericValue.of(bossBar.getValue());
|
||||
|
||||
@@ -16,7 +16,7 @@ public class Threading
|
||||
{
|
||||
//"overidden" native call to cancel if on main thread
|
||||
expression.addContextFunction("task_join", 1, (c, t, lv) -> {
|
||||
if (((CarpetContext)c).s.getServer().isOnThread())
|
||||
if (((CarpetContext)c).s.getServer().isSameThread())
|
||||
throw new InternalExpressionException("'task_join' cannot be called from main thread to avoid deadlocks");
|
||||
Value v = lv.get(0);
|
||||
if (!(v instanceof ThreadValue))
|
||||
@@ -28,12 +28,12 @@ public class Threading
|
||||
expression.addLazyFunctionWithDelegation("task_dock", 1, false,true, (c, t, expr, tok, lv) -> {
|
||||
CarpetContext cc = (CarpetContext)c;
|
||||
MinecraftServer server = cc.s.getServer();
|
||||
if (server.isOnThread()) return lv.get(0); // pass through for on thread tasks
|
||||
if (server.isSameThread()) return lv.get(0); // pass through for on thread tasks
|
||||
Value[] result = new Value[]{Value.NULL};
|
||||
RuntimeException[] internal = new RuntimeException[]{null};
|
||||
try
|
||||
{
|
||||
((CarpetContext) c).s.getServer().submitAndJoin(() ->
|
||||
((CarpetContext) c).s.getServer().executeBlocking(() ->
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -8,11 +8,10 @@ import carpet.script.value.NullValue;
|
||||
import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.StringValue;
|
||||
import carpet.script.value.Value;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import net.minecraft.core.BlockPos;
|
||||
|
||||
public class BlockArgument extends Argument
|
||||
{
|
||||
@@ -77,7 +76,7 @@ public class BlockArgument extends Argument
|
||||
return new BlockArgument(
|
||||
new BlockValue(
|
||||
null,
|
||||
c.s.getWorld(),
|
||||
c.s.getLevel(),
|
||||
new BlockPos(c.origin.getX() + xpos, c.origin.getY() + ypos, c.origin.getZ() + zpos)
|
||||
),
|
||||
1 + offset);
|
||||
@@ -88,7 +87,7 @@ public class BlockArgument extends Argument
|
||||
return new BlockArgument(
|
||||
new BlockValue(
|
||||
null,
|
||||
c.s.getWorld(),
|
||||
c.s.getLevel(),
|
||||
new BlockPos(c.origin.getX() + xpos, c.origin.getY() + ypos, c.origin.getZ() + zpos)
|
||||
),
|
||||
3 + offset
|
||||
@@ -127,7 +126,7 @@ public class BlockArgument extends Argument
|
||||
return new BlockArgument(
|
||||
new BlockValue(
|
||||
null,
|
||||
c.s.getWorld(),
|
||||
c.s.getLevel(),
|
||||
new BlockPos(c.origin.getX() + xpos, c.origin.getY() + ypos, c.origin.getZ() + zpos)
|
||||
),
|
||||
1+offset);
|
||||
@@ -138,7 +137,7 @@ public class BlockArgument extends Argument
|
||||
return new BlockArgument(
|
||||
new BlockValue(
|
||||
null,
|
||||
c.s.getWorld(),
|
||||
c.s.getLevel(),
|
||||
new BlockPos(c.origin.getX() + xpos, c.origin.getY() + ypos, c.origin.getZ() + zpos)
|
||||
),
|
||||
3+offset
|
||||
|
||||
@@ -13,13 +13,13 @@ import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.ReportedException;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.NbtAccounter;
|
||||
import net.minecraft.nbt.NbtIo;
|
||||
import net.minecraft.nbt.NbtTagSizeTracker;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.nbt.NbtTypes;
|
||||
import net.minecraft.util.WorldSavePath;
|
||||
import net.minecraft.util.crash.CrashException;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.nbt.TagTypes;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
@@ -172,7 +172,7 @@ public class FileArgument
|
||||
{
|
||||
if (CarpetServer.minecraft_server == null)
|
||||
throw new InternalExpressionException("Accessing world files without server running");
|
||||
return CarpetServer.minecraft_server.getSavePath(WorldSavePath.ROOT).resolve("scripts/"+suffix);
|
||||
return CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/"+suffix);
|
||||
}
|
||||
|
||||
private Path toPath(Module module)
|
||||
@@ -330,7 +330,7 @@ public class FileArgument
|
||||
return true;
|
||||
}
|
||||
|
||||
public NbtElement getNbtData(Module module) // aka getData
|
||||
public Tag getNbtData(Module module) // aka getData
|
||||
{
|
||||
try { synchronized (writeIOSync) {
|
||||
Path dataFile = toPath(module);
|
||||
@@ -344,7 +344,7 @@ public class FileArgument
|
||||
|
||||
//copied private method from net.minecraft.nbt.NbtIo.read()
|
||||
// to read non-compound tags - these won't be compressed
|
||||
public static NbtElement readTag(Path path)
|
||||
public static Tag readTag(Path path)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -374,7 +374,7 @@ public class FileArgument
|
||||
else
|
||||
{
|
||||
dataInput_1.readUTF();
|
||||
return NbtTypes.byId(byte_1).read(dataInput_1, 0, NbtTagSizeTracker.EMPTY);
|
||||
return TagTypes.getType(byte_1).load(dataInput_1, 0, NbtAccounter.UNLIMITED);
|
||||
}
|
||||
}
|
||||
catch (IOException secondIO)
|
||||
@@ -386,13 +386,13 @@ public class FileArgument
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (CrashException e)
|
||||
catch (ReportedException e)
|
||||
{
|
||||
throw new ThrowStatement("Error when reading NBT file "+path.toString(), Throwables.NBT_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean saveNbtData(Module module, NbtElement tag) // aka saveData
|
||||
public boolean saveNbtData(Module module, Tag tag) // aka saveData
|
||||
{
|
||||
try { synchronized (writeIOSync) {
|
||||
Path dataFile = toPath(module);
|
||||
@@ -407,7 +407,7 @@ public class FileArgument
|
||||
}
|
||||
|
||||
//copied private method from net.minecraft.nbt.NbtIo.write() and client method safe_write
|
||||
public static boolean writeTagDisk(NbtElement tag_1, Path path, boolean zipped)
|
||||
public static boolean writeTagDisk(Tag tag_1, Path path, boolean zipped)
|
||||
{
|
||||
Path original = path;
|
||||
try
|
||||
@@ -418,16 +418,16 @@ public class FileArgument
|
||||
Files.deleteIfExists(path);
|
||||
}
|
||||
|
||||
if (tag_1 instanceof NbtCompound)
|
||||
if (tag_1 instanceof CompoundTag)
|
||||
{
|
||||
NbtIo.writeCompressed((NbtCompound) tag_1, Files.newOutputStream(path));
|
||||
NbtIo.writeCompressed((CompoundTag) tag_1, Files.newOutputStream(path));
|
||||
}
|
||||
else
|
||||
{
|
||||
try (DataOutputStream dataOutputStream_1 = new DataOutputStream(Files.newOutputStream(path)))
|
||||
{
|
||||
dataOutputStream_1.writeByte(tag_1.getType());
|
||||
if (tag_1.getType() != 0)
|
||||
dataOutputStream_1.writeByte(tag_1.getId());
|
||||
if (tag_1.getId() != 0)
|
||||
{
|
||||
dataOutputStream_1.writeUTF("");
|
||||
tag_1.write(dataOutputStream_1);
|
||||
|
||||
@@ -6,28 +6,27 @@ import carpet.script.value.EntityValue;
|
||||
import carpet.script.value.ListValue;
|
||||
import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.Value;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public class Vector3Argument extends Argument
|
||||
{
|
||||
public Vec3d vec;
|
||||
public Vec3 vec;
|
||||
public final double yaw;
|
||||
public final double pitch;
|
||||
public boolean fromBlock = false;
|
||||
public Entity entity = null;
|
||||
private Vector3Argument(Vec3d v, int o)
|
||||
private Vector3Argument(Vec3 v, int o)
|
||||
{
|
||||
super(o);
|
||||
this.vec = v;
|
||||
this.yaw = 0.0D;
|
||||
this.pitch = 0.0D;
|
||||
}
|
||||
private Vector3Argument(Vec3d v, int o, double y, double p)
|
||||
private Vector3Argument(Vec3 v, int o, double y, double p)
|
||||
{
|
||||
super(o);
|
||||
this.vec = v;
|
||||
@@ -63,17 +62,17 @@ public class Vector3Argument extends Argument
|
||||
Value v1 = params.next();
|
||||
if (v1 instanceof BlockValue)
|
||||
{
|
||||
return (new Vector3Argument(Vec3d.ofCenter(((BlockValue) v1).getPos()), 1+offset)).fromBlock();
|
||||
return (new Vector3Argument(Vec3.atCenterOf(((BlockValue) v1).getPos()), 1+offset)).fromBlock();
|
||||
}
|
||||
if (optionalEntity && v1 instanceof EntityValue)
|
||||
{
|
||||
Entity e = ((EntityValue) v1).getEntity();
|
||||
return new Vector3Argument(e.getPos(), 1+offset).withEntity(e);
|
||||
return new Vector3Argument(e.position(), 1+offset).withEntity(e);
|
||||
}
|
||||
if (v1 instanceof ListValue)
|
||||
{
|
||||
List<Value> args = ((ListValue) v1).getItems();
|
||||
Vec3d pos = new Vec3d(
|
||||
Vec3 pos = new Vec3(
|
||||
NumericValue.asNumber(args.get(0)).getDouble(),
|
||||
NumericValue.asNumber(args.get(1)).getDouble(),
|
||||
NumericValue.asNumber(args.get(2)).getDouble());
|
||||
@@ -86,7 +85,7 @@ public class Vector3Argument extends Argument
|
||||
}
|
||||
return new Vector3Argument(pos,offset+1, yaw, pitch);
|
||||
}
|
||||
Vec3d pos = new Vec3d(
|
||||
Vec3 pos = new Vec3(
|
||||
NumericValue.asNumber(v1).getDouble(),
|
||||
NumericValue.asNumber(params.next()).getDouble(),
|
||||
NumericValue.asNumber(params.next()).getDouble());
|
||||
|
||||
@@ -2,11 +2,10 @@ package carpet.script.bundled;
|
||||
|
||||
import carpet.CarpetServer;
|
||||
import carpet.script.argument.FileArgument;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.util.WorldSavePath;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
|
||||
public abstract class Module
|
||||
{
|
||||
@@ -14,7 +13,7 @@ public abstract class Module
|
||||
public abstract String getCode();
|
||||
public abstract boolean isLibrary();
|
||||
|
||||
public static NbtElement getData(Module module)
|
||||
public static Tag getData(Module module)
|
||||
{
|
||||
Path dataFile = resolveResource(module);
|
||||
if (dataFile == null) return null;
|
||||
@@ -22,7 +21,7 @@ public abstract class Module
|
||||
synchronized (FileArgument.writeIOSync) { return FileArgument.readTag(dataFile); }
|
||||
}
|
||||
|
||||
public static void saveData(Module module, NbtElement globalState)
|
||||
public static void saveData(Module module, Tag globalState)
|
||||
{
|
||||
Path dataFile = resolveResource(module);
|
||||
if (dataFile == null) return;
|
||||
@@ -33,7 +32,7 @@ public abstract class Module
|
||||
private static Path resolveResource(Module module)
|
||||
{
|
||||
if (module == null || module.getName() == null) return null; // commandline app
|
||||
return CarpetServer.minecraft_server.getSavePath(WorldSavePath.ROOT).resolve("scripts/"+module.getName()+".data.nbt");
|
||||
return CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/"+module.getName()+".data.nbt");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -37,56 +37,6 @@ import com.mojang.brigadier.suggestion.Suggestions;
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import com.mojang.brigadier.tree.ArgumentCommandNode;
|
||||
import com.mojang.brigadier.tree.CommandNode;
|
||||
import net.minecraft.advancement.Advancement;
|
||||
import net.minecraft.command.CommandSource;
|
||||
import net.minecraft.command.argument.AngleArgumentType;
|
||||
import net.minecraft.command.argument.BlockPosArgumentType;
|
||||
import net.minecraft.command.argument.BlockPredicateArgumentType;
|
||||
import net.minecraft.command.argument.BlockStateArgument;
|
||||
import net.minecraft.command.argument.BlockStateArgumentType;
|
||||
import net.minecraft.command.argument.ColorArgumentType;
|
||||
import net.minecraft.command.argument.ColumnPosArgumentType;
|
||||
import net.minecraft.command.argument.DimensionArgumentType;
|
||||
import net.minecraft.command.argument.EntityAnchorArgumentType;
|
||||
import net.minecraft.command.argument.EntityArgumentType;
|
||||
import net.minecraft.command.argument.EntitySummonArgumentType;
|
||||
import net.minecraft.command.argument.GameProfileArgumentType;
|
||||
import net.minecraft.command.argument.IdentifierArgumentType;
|
||||
import net.minecraft.command.argument.EnchantmentArgumentType;
|
||||
import net.minecraft.command.argument.ItemSlotArgumentType;
|
||||
import net.minecraft.command.argument.ItemStackArgumentType;
|
||||
import net.minecraft.command.argument.MessageArgumentType;
|
||||
import net.minecraft.command.argument.StatusEffectArgumentType;
|
||||
import net.minecraft.command.argument.NbtCompoundArgumentType;
|
||||
import net.minecraft.command.argument.NbtPathArgumentType;
|
||||
import net.minecraft.command.argument.NbtElementArgumentType;
|
||||
import net.minecraft.command.argument.NumberRangeArgumentType;
|
||||
import net.minecraft.command.argument.ScoreboardObjectiveArgumentType;
|
||||
import net.minecraft.command.argument.ScoreboardCriterionArgumentType;
|
||||
import net.minecraft.command.argument.ParticleEffectArgumentType;
|
||||
import net.minecraft.command.argument.RotationArgumentType;
|
||||
import net.minecraft.command.argument.ScoreHolderArgumentType;
|
||||
import net.minecraft.command.argument.ScoreboardSlotArgumentType;
|
||||
import net.minecraft.command.argument.SwizzleArgumentType;
|
||||
import net.minecraft.command.argument.TeamArgumentType;
|
||||
import net.minecraft.command.argument.TimeArgumentType;
|
||||
import net.minecraft.command.argument.UuidArgumentType;
|
||||
import net.minecraft.command.argument.Vec2ArgumentType;
|
||||
import net.minecraft.command.argument.Vec3ArgumentType;
|
||||
import net.minecraft.command.suggestion.SuggestionProviders;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.predicate.NumberRange;
|
||||
import net.minecraft.scoreboard.Scoreboard;
|
||||
import net.minecraft.server.command.BossBarCommand;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.text.LiteralText;
|
||||
import net.minecraft.util.Formatting;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Direction;
|
||||
import net.minecraft.util.math.Vec2f;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
@@ -100,14 +50,60 @@ import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.advancements.Advancement;
|
||||
import net.minecraft.advancements.critereon.MinMaxBounds;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.arguments.AngleArgument;
|
||||
import net.minecraft.commands.arguments.ColorArgument;
|
||||
import net.minecraft.commands.arguments.CompoundTagArgument;
|
||||
import net.minecraft.commands.arguments.DimensionArgument;
|
||||
import net.minecraft.commands.arguments.EntityAnchorArgument;
|
||||
import net.minecraft.commands.arguments.EntitySummonArgument;
|
||||
import net.minecraft.commands.arguments.GameProfileArgument;
|
||||
import net.minecraft.commands.arguments.ItemEnchantmentArgument;
|
||||
import net.minecraft.commands.arguments.MessageArgument;
|
||||
import net.minecraft.commands.arguments.MobEffectArgument;
|
||||
import net.minecraft.commands.arguments.NbtPathArgument;
|
||||
import net.minecraft.commands.arguments.NbtTagArgument;
|
||||
import net.minecraft.commands.arguments.ObjectiveArgument;
|
||||
import net.minecraft.commands.arguments.ObjectiveCriteriaArgument;
|
||||
import net.minecraft.commands.arguments.ParticleArgument;
|
||||
import net.minecraft.commands.arguments.RangeArgument;
|
||||
import net.minecraft.commands.arguments.ResourceLocationArgument;
|
||||
import net.minecraft.commands.arguments.ScoreHolderArgument;
|
||||
import net.minecraft.commands.arguments.ScoreboardSlotArgument;
|
||||
import net.minecraft.commands.arguments.TeamArgument;
|
||||
import net.minecraft.commands.arguments.TimeArgument;
|
||||
import net.minecraft.commands.arguments.UuidArgument;
|
||||
import net.minecraft.commands.arguments.blocks.BlockInput;
|
||||
import net.minecraft.commands.arguments.blocks.BlockPredicateArgument;
|
||||
import net.minecraft.commands.arguments.blocks.BlockStateArgument;
|
||||
import net.minecraft.commands.arguments.coordinates.ColumnPosArgument;
|
||||
import net.minecraft.commands.arguments.coordinates.RotationArgument;
|
||||
import net.minecraft.commands.arguments.coordinates.SwizzleArgument;
|
||||
import net.minecraft.commands.arguments.coordinates.Vec2Argument;
|
||||
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
|
||||
import net.minecraft.commands.arguments.item.ItemArgument;
|
||||
import net.minecraft.commands.synchronization.SuggestionProviders;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.commands.BossBarCommands;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.phys.Vec2;
|
||||
import net.minecraft.world.scores.Scoreboard;
|
||||
|
||||
import static net.minecraft.server.command.CommandManager.argument;
|
||||
import static net.minecraft.commands.Commands.argument;
|
||||
|
||||
public abstract class CommandArgument
|
||||
{
|
||||
public static CommandSyntaxException error(String text)
|
||||
{
|
||||
return new SimpleCommandExceptionType(new LiteralText(text)).create();
|
||||
return new SimpleCommandExceptionType(new TextComponent(text)).create();
|
||||
}
|
||||
|
||||
private static final List<? extends CommandArgument> baseTypes = Lists.newArrayList(
|
||||
@@ -120,107 +116,107 @@ public abstract class CommandArgument
|
||||
new FloatArgument(),
|
||||
new IntArgument(),
|
||||
new WordArgument(), new GreedyStringArgument(),
|
||||
new VanillaUnconfigurableArgument( "yaw", AngleArgumentType::angle, // angle
|
||||
(c, p) -> new NumericValue(AngleArgumentType.getAngle(c, p)), true
|
||||
new VanillaUnconfigurableArgument( "yaw", AngleArgument::angle, // angle
|
||||
(c, p) -> new NumericValue(AngleArgument.getAngle(c, p)), true
|
||||
),
|
||||
new BlockPosArgument(),
|
||||
new VanillaUnconfigurableArgument( "block", BlockStateArgumentType::blockState,
|
||||
new VanillaUnconfigurableArgument( "block", BlockStateArgument::block,
|
||||
(c, p) -> {
|
||||
BlockStateArgument result = BlockStateArgumentType.getBlockState(c, p);
|
||||
return new BlockValue(result.getBlockState(), null, null, ((BlockStateArgumentInterface)result).getCMTag() );
|
||||
BlockInput result = BlockStateArgument.getBlock(c, p);
|
||||
return new BlockValue(result.getState(), null, null, ((BlockStateArgumentInterface)result).getCMTag() );
|
||||
},
|
||||
false
|
||||
),
|
||||
new VanillaUnconfigurableArgument( "blockpredicate", BlockPredicateArgumentType::blockPredicate,
|
||||
(c, p) -> ValueConversions.ofBlockPredicate(c.getSource().getServer().getTagManager(), BlockPredicateArgumentType.getBlockPredicate(c, p)), false
|
||||
new VanillaUnconfigurableArgument( "blockpredicate", BlockPredicateArgument::blockPredicate,
|
||||
(c, p) -> ValueConversions.ofBlockPredicate(c.getSource().getServer().getTags(), BlockPredicateArgument.getBlockPredicate(c, p)), false
|
||||
),
|
||||
new VanillaUnconfigurableArgument("teamcolor", ColorArgumentType::color,
|
||||
new VanillaUnconfigurableArgument("teamcolor", ColorArgument::color,
|
||||
(c, p) -> {
|
||||
Formatting format = ColorArgumentType.getColor(c, p);
|
||||
return ListValue.of(StringValue.of(format.getName()), ValueConversions.ofRGB(format.getColorValue()));
|
||||
ChatFormatting format = ColorArgument.getColor(c, p);
|
||||
return ListValue.of(StringValue.of(format.getName()), ValueConversions.ofRGB(format.getColor()));
|
||||
},
|
||||
false
|
||||
),
|
||||
new VanillaUnconfigurableArgument("columnpos", ColumnPosArgumentType::columnPos,
|
||||
(c, p) -> ValueConversions.of(ColumnPosArgumentType.getColumnPos(c, p)), false
|
||||
new VanillaUnconfigurableArgument("columnpos", ColumnPosArgument::columnPos,
|
||||
(c, p) -> ValueConversions.of(ColumnPosArgument.getColumnPos(c, p)), false
|
||||
),
|
||||
// component // raw json
|
||||
new VanillaUnconfigurableArgument("dimension", DimensionArgumentType::dimension,
|
||||
(c, p) -> ValueConversions.of(DimensionArgumentType.getDimensionArgument(c, p)), false
|
||||
new VanillaUnconfigurableArgument("dimension", DimensionArgument::dimension,
|
||||
(c, p) -> ValueConversions.of(DimensionArgument.getDimension(c, p)), false
|
||||
),
|
||||
new EntityArgument(),
|
||||
new VanillaUnconfigurableArgument("anchor", EntityAnchorArgumentType::entityAnchor,
|
||||
(c, p) -> StringValue.of(EntityAnchorArgumentType.getEntityAnchor(c, p).name()), false
|
||||
new VanillaUnconfigurableArgument("anchor", EntityAnchorArgument::anchor,
|
||||
(c, p) -> StringValue.of(EntityAnchorArgument.getAnchor(c, p).name()), false
|
||||
),
|
||||
new VanillaUnconfigurableArgument("entitytype", EntitySummonArgumentType::entitySummon,
|
||||
(c, p) -> ValueConversions.of(EntitySummonArgumentType.getEntitySummon(c, p)), SuggestionProviders.SUMMONABLE_ENTITIES
|
||||
new VanillaUnconfigurableArgument("entitytype", EntitySummonArgument::id,
|
||||
(c, p) -> ValueConversions.of(EntitySummonArgument.getSummonableEntity(c, p)), SuggestionProviders.SUMMONABLE_ENTITIES
|
||||
),
|
||||
new VanillaUnconfigurableArgument("floatrange", NumberRangeArgumentType::floatRange,
|
||||
(c, p) -> ValueConversions.of(c.getArgument(p, NumberRange.FloatRange.class)), true
|
||||
new VanillaUnconfigurableArgument("floatrange", RangeArgument::floatRange,
|
||||
(c, p) -> ValueConversions.of(c.getArgument(p, MinMaxBounds.Doubles.class)), true
|
||||
),
|
||||
// function??
|
||||
|
||||
new PlayerProfileArgument(),
|
||||
new VanillaUnconfigurableArgument("intrange", NumberRangeArgumentType::intRange,
|
||||
(c, p) -> ValueConversions.of(NumberRangeArgumentType.IntRangeArgumentType.getRangeArgument(c, p)), true
|
||||
new VanillaUnconfigurableArgument("intrange", RangeArgument::intRange,
|
||||
(c, p) -> ValueConversions.of(RangeArgument.Ints.getRange(c, p)), true
|
||||
),
|
||||
new VanillaUnconfigurableArgument("enchantment", EnchantmentArgumentType::enchantment,
|
||||
(c, p) -> ValueConversions.of(Registry.ENCHANTMENT.getId(EnchantmentArgumentType.getEnchantment(c, p))), false
|
||||
new VanillaUnconfigurableArgument("enchantment", ItemEnchantmentArgument::enchantment,
|
||||
(c, p) -> ValueConversions.of(Registry.ENCHANTMENT.getKey(ItemEnchantmentArgument.getEnchantment(c, p))), false
|
||||
),
|
||||
// item_predicate ?? //same as item but accepts tags, not sure right now
|
||||
new SlotArgument(),
|
||||
new VanillaUnconfigurableArgument("item", ItemStackArgumentType::itemStack,
|
||||
(c, p) -> ValueConversions.of(ItemStackArgumentType.getItemStackArgument(c, p).createStack(1, false)), false
|
||||
new VanillaUnconfigurableArgument("item", ItemArgument::item,
|
||||
(c, p) -> ValueConversions.of(ItemArgument.getItem(c, p).createItemStack(1, false)), false
|
||||
),
|
||||
new VanillaUnconfigurableArgument("message", MessageArgumentType::message,
|
||||
(c, p) -> new FormattedTextValue(MessageArgumentType.getMessage(c, p)), true
|
||||
new VanillaUnconfigurableArgument("message", MessageArgument::message,
|
||||
(c, p) -> new FormattedTextValue(MessageArgument.getMessage(c, p)), true
|
||||
),
|
||||
new VanillaUnconfigurableArgument("effect", StatusEffectArgumentType::statusEffect,
|
||||
(c, p) -> ValueConversions.of(Registry.STATUS_EFFECT.getId(StatusEffectArgumentType.getStatusEffect(c, p))),false
|
||||
new VanillaUnconfigurableArgument("effect", MobEffectArgument::effect,
|
||||
(c, p) -> ValueConversions.of(Registry.MOB_EFFECT.getKey(MobEffectArgument.getEffect(c, p))),false
|
||||
),
|
||||
new TagArgument(), // for nbt_compound_tag and nbt_tag
|
||||
new VanillaUnconfigurableArgument("path", NbtPathArgumentType::nbtPath,
|
||||
(c, p) -> StringValue.of(NbtPathArgumentType.getNbtPath(c, p).toString()), true
|
||||
new VanillaUnconfigurableArgument("path", NbtPathArgument::nbtPath,
|
||||
(c, p) -> StringValue.of(NbtPathArgument.getPath(c, p).toString()), true
|
||||
),
|
||||
new VanillaUnconfigurableArgument("objective", ScoreboardObjectiveArgumentType::scoreboardObjective,
|
||||
(c, p) -> ValueConversions.of(ScoreboardObjectiveArgumentType.getObjective(c, p)), false
|
||||
new VanillaUnconfigurableArgument("objective", ObjectiveArgument::objective,
|
||||
(c, p) -> ValueConversions.of(ObjectiveArgument.getObjective(c, p)), false
|
||||
),
|
||||
new VanillaUnconfigurableArgument("criterion", ScoreboardCriterionArgumentType::scoreboardCriterion,
|
||||
(c, p) -> StringValue.of(ScoreboardCriterionArgumentType.getCriterion(c, p).getName()), false
|
||||
new VanillaUnconfigurableArgument("criterion", ObjectiveCriteriaArgument::criteria,
|
||||
(c, p) -> StringValue.of(ObjectiveCriteriaArgument.getCriteria(c, p).getName()), false
|
||||
),
|
||||
// operation // not sure if we need it, you have scarpet for that
|
||||
new VanillaUnconfigurableArgument("particle", ParticleEffectArgumentType::particleEffect,
|
||||
(c, p) -> ValueConversions.of(ParticleEffectArgumentType.getParticle(c, p)), false
|
||||
new VanillaUnconfigurableArgument("particle", ParticleArgument::particle,
|
||||
(c, p) -> ValueConversions.of(ParticleArgument.getParticle(c, p)), false
|
||||
),
|
||||
|
||||
// resource / identifier section
|
||||
|
||||
new VanillaUnconfigurableArgument("recipe", IdentifierArgumentType::identifier,
|
||||
(c, p) -> ValueConversions.of( IdentifierArgumentType.getRecipeArgument(c, p).getId()), SuggestionProviders.ALL_RECIPES
|
||||
new VanillaUnconfigurableArgument("recipe", ResourceLocationArgument::id,
|
||||
(c, p) -> ValueConversions.of( ResourceLocationArgument.getRecipe(c, p).getId()), SuggestionProviders.ALL_RECIPES
|
||||
),
|
||||
new VanillaUnconfigurableArgument("advancement", IdentifierArgumentType::identifier,
|
||||
(c, p) -> ValueConversions.of( IdentifierArgumentType.getAdvancementArgument(c, p).getId()), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getAdvancementLoader().getAdvancements().stream().map(Advancement::getId), builder)
|
||||
new VanillaUnconfigurableArgument("advancement", ResourceLocationArgument::id,
|
||||
(c, p) -> ValueConversions.of( ResourceLocationArgument.getAdvancement(c, p).getId()), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getAdvancements().getAllAdvancements().stream().map(Advancement::getId), builder)
|
||||
),
|
||||
new VanillaUnconfigurableArgument("lootcondition", IdentifierArgumentType::identifier,
|
||||
(c, p) -> ValueConversions.of( Registry.LOOT_CONDITION_TYPE.getId(IdentifierArgumentType.getPredicateArgument(c, p).getType())), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getPredicateManager().getIds(), builder)
|
||||
new VanillaUnconfigurableArgument("lootcondition", ResourceLocationArgument::id,
|
||||
(c, p) -> ValueConversions.of( Registry.LOOT_CONDITION_TYPE.getKey(ResourceLocationArgument.getPredicate(c, p).getType())), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getPredicateManager().getKeys(), builder)
|
||||
),
|
||||
new VanillaUnconfigurableArgument("loottable", IdentifierArgumentType::identifier,
|
||||
(c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getLootManager().getTableIds(), builder)
|
||||
new VanillaUnconfigurableArgument("loottable", ResourceLocationArgument::id,
|
||||
(c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getLootTables().getIds(), builder)
|
||||
),
|
||||
new VanillaUnconfigurableArgument("attribute", IdentifierArgumentType::identifier,
|
||||
(c, p) -> ValueConversions.of( Registry.ATTRIBUTE.getId(IdentifierArgumentType.getAttributeArgument(c, p))), (ctx, builder) -> CommandSource.suggestIdentifiers(Registry.ATTRIBUTE.getIds(), builder)
|
||||
new VanillaUnconfigurableArgument("attribute", ResourceLocationArgument::id,
|
||||
(c, p) -> ValueConversions.of( Registry.ATTRIBUTE.getKey(ResourceLocationArgument.getAttribute(c, p))), (ctx, builder) -> SharedSuggestionProvider.suggestResource(Registry.ATTRIBUTE.keySet(), builder)
|
||||
),
|
||||
new VanillaUnconfigurableArgument("boss", IdentifierArgumentType::identifier,
|
||||
(c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), BossBarCommand.SUGGESTION_PROVIDER
|
||||
new VanillaUnconfigurableArgument("boss", ResourceLocationArgument::id,
|
||||
(c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), BossBarCommands.SUGGEST_BOSS_BAR
|
||||
),
|
||||
new VanillaUnconfigurableArgument("biome", IdentifierArgumentType::identifier,
|
||||
(c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), SuggestionProviders.ALL_BIOMES
|
||||
new VanillaUnconfigurableArgument("biome", ResourceLocationArgument::id,
|
||||
(c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), SuggestionProviders.AVAILABLE_BIOMES
|
||||
),
|
||||
new VanillaUnconfigurableArgument("sound", IdentifierArgumentType::identifier,
|
||||
(c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), SuggestionProviders.AVAILABLE_SOUNDS
|
||||
new VanillaUnconfigurableArgument("sound", ResourceLocationArgument::id,
|
||||
(c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), SuggestionProviders.AVAILABLE_SOUNDS
|
||||
),
|
||||
new VanillaUnconfigurableArgument("storekey", IdentifierArgumentType::identifier,
|
||||
(c, p) -> ValueConversions.of( IdentifierArgumentType.getIdentifier(c, p)), (ctx, builder) -> CommandSource.suggestIdentifiers(ctx.getSource().getServer().getDataCommandStorage().getIds(), builder)
|
||||
new VanillaUnconfigurableArgument("storekey", ResourceLocationArgument::id,
|
||||
(c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getCommandStorage().keys(), builder)
|
||||
),
|
||||
|
||||
// default
|
||||
@@ -229,32 +225,32 @@ public abstract class CommandArgument
|
||||
// end resource / identifier // I would be great if you guys have suggestions for that.
|
||||
|
||||
new VanillaUnconfigurableArgument("rotation",
|
||||
RotationArgumentType::rotation,
|
||||
RotationArgument::rotation,
|
||||
(c, p) -> {
|
||||
Vec2f rot = RotationArgumentType.getRotation(c, p).toAbsoluteRotation(c.getSource());
|
||||
Vec2 rot = RotationArgument.getRotation(c, p).getRotation(c.getSource());
|
||||
return ListValue.of(new NumericValue(rot.x), new NumericValue(rot.y));
|
||||
},
|
||||
true
|
||||
),
|
||||
new ScoreholderArgument(),
|
||||
new VanillaUnconfigurableArgument("scoreboardslot", ScoreboardSlotArgumentType::scoreboardSlot,
|
||||
(c, p) -> StringValue.of(Scoreboard.getDisplaySlotName(ScoreboardSlotArgumentType.getScoreboardSlot(c, p))), false
|
||||
new VanillaUnconfigurableArgument("scoreboardslot", ScoreboardSlotArgument::displaySlot,
|
||||
(c, p) -> StringValue.of(Scoreboard.getDisplaySlotName(ScoreboardSlotArgument.getDisplaySlot(c, p))), false
|
||||
),
|
||||
new VanillaUnconfigurableArgument("swizzle", SwizzleArgumentType::swizzle,
|
||||
(c, p) -> StringValue.of(SwizzleArgumentType.getSwizzle(c, p).stream().map(Direction.Axis::asString).collect(Collectors.joining())), true
|
||||
new VanillaUnconfigurableArgument("swizzle", SwizzleArgument::swizzle,
|
||||
(c, p) -> StringValue.of(SwizzleArgument.getSwizzle(c, p).stream().map(Direction.Axis::getSerializedName).collect(Collectors.joining())), true
|
||||
),
|
||||
new VanillaUnconfigurableArgument("team", TeamArgumentType::team,
|
||||
(c, p) -> StringValue.of(TeamArgumentType.getTeam(c, p).getName()), false
|
||||
new VanillaUnconfigurableArgument("team", TeamArgument::team,
|
||||
(c, p) -> StringValue.of(TeamArgument.getTeam(c, p).getName()), false
|
||||
),
|
||||
new VanillaUnconfigurableArgument("time", TimeArgumentType::time,
|
||||
new VanillaUnconfigurableArgument("time", TimeArgument::time,
|
||||
(c, p) -> new NumericValue(IntegerArgumentType.getInteger(c, p)), false
|
||||
),
|
||||
new VanillaUnconfigurableArgument("uuid", UuidArgumentType::uuid,
|
||||
(c, p) -> StringValue.of(UuidArgumentType.getUuid(c, p).toString()), false
|
||||
new VanillaUnconfigurableArgument("uuid", UuidArgument::uuid,
|
||||
(c, p) -> StringValue.of(UuidArgument.getUuid(c, p).toString()), false
|
||||
),
|
||||
new VanillaUnconfigurableArgument("surfacelocation", Vec2ArgumentType::vec2, // vec2
|
||||
new VanillaUnconfigurableArgument("surfacelocation", Vec2Argument::vec2, // vec2
|
||||
(c, p) -> {
|
||||
Vec2f res = Vec2ArgumentType.getVec2(c, p);
|
||||
Vec2 res = Vec2Argument.getVec2(c, p);
|
||||
return ListValue.of(NumericValue.of(res.x), NumericValue.of(res.y));
|
||||
},
|
||||
false
|
||||
@@ -281,7 +277,7 @@ public abstract class CommandArgument
|
||||
return DEFAULT;
|
||||
}
|
||||
|
||||
public static RequiredArgumentBuilder<ServerCommandSource, ?> argumentNode(String param, CarpetScriptHost host) throws CommandSyntaxException
|
||||
public static RequiredArgumentBuilder<CommandSourceStack, ?> argumentNode(String param, CarpetScriptHost host) throws CommandSyntaxException
|
||||
{
|
||||
CommandArgument arg = getTypeForArgument(param, host);
|
||||
if (arg.suggestionProvider != null) return argument(param, arg.getArgumentType()).suggests(arg.suggestionProvider);
|
||||
@@ -297,7 +293,7 @@ public abstract class CommandArgument
|
||||
protected Collection<String> examples;
|
||||
protected boolean needsMatching;
|
||||
protected boolean caseSensitive = true;
|
||||
protected SuggestionProvider<ServerCommandSource> suggestionProvider;
|
||||
protected SuggestionProvider<CommandSourceStack> suggestionProvider;
|
||||
protected FunctionArgument customSuggester;
|
||||
|
||||
|
||||
@@ -314,12 +310,12 @@ public abstract class CommandArgument
|
||||
protected abstract ArgumentType<?> getArgumentType() throws CommandSyntaxException;
|
||||
|
||||
|
||||
public static Value getValue(CommandContext<ServerCommandSource> context, String param, CarpetScriptHost host) throws CommandSyntaxException
|
||||
public static Value getValue(CommandContext<CommandSourceStack> context, String param, CarpetScriptHost host) throws CommandSyntaxException
|
||||
{
|
||||
return getTypeForArgument(param, host).getValueFromContext(context, param);
|
||||
}
|
||||
|
||||
protected abstract Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException;
|
||||
protected abstract Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException;
|
||||
|
||||
public String getTypeSuffix()
|
||||
{
|
||||
@@ -359,7 +355,7 @@ public abstract class CommandArgument
|
||||
}
|
||||
|
||||
public CompletableFuture<Suggestions> suggest(
|
||||
CommandContext<ServerCommandSource> context,
|
||||
CommandContext<CommandSourceStack> context,
|
||||
SuggestionsBuilder suggestionsBuilder,
|
||||
CarpetScriptHost host
|
||||
) throws CommandSyntaxException
|
||||
@@ -370,20 +366,20 @@ public abstract class CommandArgument
|
||||
return suggestionsBuilder.buildFuture();
|
||||
}
|
||||
|
||||
protected List<String> suggestFor(CommandContext<ServerCommandSource> context, String prefix, CarpetScriptHost host) throws CommandSyntaxException
|
||||
protected List<String> suggestFor(CommandContext<CommandSourceStack> context, String prefix, CarpetScriptHost host) throws CommandSyntaxException
|
||||
{
|
||||
return getOptions(context, host).stream().filter(s -> optionMatchesPrefix(prefix, s)).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
protected Collection<String> getOptions(CommandContext<ServerCommandSource> context, CarpetScriptHost host) throws CommandSyntaxException
|
||||
protected Collection<String> getOptions(CommandContext<CommandSourceStack> context, CarpetScriptHost host) throws CommandSyntaxException
|
||||
{
|
||||
if (customSuggester != null)
|
||||
{
|
||||
CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL);
|
||||
Map<Value, Value> params = new HashMap<>();
|
||||
for(ParsedCommandNode<ServerCommandSource> pnode : context.getNodes())
|
||||
for(ParsedCommandNode<CommandSourceStack> pnode : context.getNodes())
|
||||
{
|
||||
CommandNode<ServerCommandSource> node = pnode.getNode();
|
||||
CommandNode<CommandSourceStack> node = pnode.getNode();
|
||||
if (node instanceof ArgumentCommandNode)
|
||||
{
|
||||
params.put(StringValue.of(node.getName()), CommandArgument.getValue(context, node.getName(), host));
|
||||
@@ -437,13 +433,13 @@ public abstract class CommandArgument
|
||||
}
|
||||
|
||||
@Override
|
||||
public Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
public Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
String choseValue = StringArgumentType.getString(context, param);
|
||||
if (!caseSensitive) choseValue = choseValue.toLowerCase(Locale.ROOT);
|
||||
if (!validOptions.isEmpty() && !validOptions.contains(choseValue))
|
||||
{
|
||||
throw new SimpleCommandExceptionType(new LiteralText("Incorrect value for "+param+": "+choseValue+" for custom type "+suffix)).create();
|
||||
throw new SimpleCommandExceptionType(new TextComponent("Incorrect value for "+param+": "+choseValue+" for custom type "+suffix)).create();
|
||||
}
|
||||
return StringValue.of(choseValue);
|
||||
}
|
||||
@@ -463,7 +459,7 @@ public abstract class CommandArgument
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Collection<String> getOptions(CommandContext<ServerCommandSource> context, CarpetScriptHost host) throws CommandSyntaxException
|
||||
protected Collection<String> getOptions(CommandContext<CommandSourceStack> context, CarpetScriptHost host) throws CommandSyntaxException
|
||||
{
|
||||
return validOptions.isEmpty()?super.getOptions(context, host):validOptions;
|
||||
}
|
||||
@@ -496,21 +492,21 @@ public abstract class CommandArgument
|
||||
|
||||
private BlockPosArgument()
|
||||
{
|
||||
super("pos", BlockPosArgumentType.blockPos().getExamples(), false);
|
||||
super("pos", net.minecraft.commands.arguments.coordinates.BlockPosArgument.blockPos().getExamples(), false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArgumentType<?> getArgumentType()
|
||||
{
|
||||
return BlockPosArgumentType.blockPos();
|
||||
return net.minecraft.commands.arguments.coordinates.BlockPosArgument.blockPos();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
public Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
BlockPos pos = mustBeLoaded
|
||||
? BlockPosArgumentType.getLoadedBlockPos(context, param)
|
||||
: BlockPosArgumentType.getBlockPos(context, param);
|
||||
? net.minecraft.commands.arguments.coordinates.BlockPosArgument.getLoadedBlockPos(context, param)
|
||||
: net.minecraft.commands.arguments.coordinates.BlockPosArgument.getSpawnablePos(context, param);
|
||||
return ValueConversions.of(pos);
|
||||
}
|
||||
|
||||
@@ -534,19 +530,19 @@ public abstract class CommandArgument
|
||||
|
||||
private LocationArgument()
|
||||
{
|
||||
super("location", Vec3ArgumentType.vec3().getExamples(), false);
|
||||
super("location", Vec3Argument.vec3().getExamples(), false);
|
||||
blockCentered = true;
|
||||
}
|
||||
@Override
|
||||
protected ArgumentType<?> getArgumentType()
|
||||
{
|
||||
return Vec3ArgumentType.vec3(blockCentered);
|
||||
return Vec3Argument.vec3(blockCentered);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
protected Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
return ValueConversions.of(Vec3ArgumentType.getVec3(context, param));
|
||||
return ValueConversions.of(Vec3Argument.getVec3(context, param));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -570,7 +566,7 @@ public abstract class CommandArgument
|
||||
|
||||
private EntityArgument()
|
||||
{
|
||||
super("entities", EntityArgumentType.entities().getExamples(), false);
|
||||
super("entities", net.minecraft.commands.arguments.EntityArgument.entities().getExamples(), false);
|
||||
onlyFans = false;
|
||||
single = false;
|
||||
}
|
||||
@@ -579,22 +575,22 @@ public abstract class CommandArgument
|
||||
{
|
||||
if (onlyFans)
|
||||
{
|
||||
return single?EntityArgumentType.player():EntityArgumentType.players();
|
||||
return single?net.minecraft.commands.arguments.EntityArgument.player():net.minecraft.commands.arguments.EntityArgument.players();
|
||||
}
|
||||
else
|
||||
{
|
||||
return single?EntityArgumentType.entity():EntityArgumentType.entities();
|
||||
return single?net.minecraft.commands.arguments.EntityArgument.entity():net.minecraft.commands.arguments.EntityArgument.entities();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
protected Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
Collection<? extends Entity> founds = EntityArgumentType.getOptionalEntities(context, param);
|
||||
Collection<? extends Entity> founds = net.minecraft.commands.arguments.EntityArgument.getOptionalEntities(context, param);
|
||||
if (!single) return ListValue.wrap(founds.stream().map(EntityValue::new).collect(Collectors.toList()));
|
||||
if (founds.size() == 0) return Value.NULL;
|
||||
if (founds.size() == 1) return new EntityValue(founds.iterator().next());
|
||||
throw new SimpleCommandExceptionType(new LiteralText("Multiple entities returned while only one was requested"+" for custom type "+suffix)).create();
|
||||
throw new SimpleCommandExceptionType(new TextComponent("Multiple entities returned while only one was requested"+" for custom type "+suffix)).create();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -618,24 +614,24 @@ public abstract class CommandArgument
|
||||
|
||||
private PlayerProfileArgument()
|
||||
{
|
||||
super("players", GameProfileArgumentType.gameProfile().getExamples(), false);
|
||||
super("players", GameProfileArgument.gameProfile().getExamples(), false);
|
||||
single = false;
|
||||
}
|
||||
@Override
|
||||
protected ArgumentType<?> getArgumentType()
|
||||
{
|
||||
return GameProfileArgumentType.gameProfile();
|
||||
return GameProfileArgument.gameProfile();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
protected Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
Collection<GameProfile> profiles = GameProfileArgumentType.getProfileArgument(context, param);
|
||||
Collection<GameProfile> profiles = GameProfileArgument.getGameProfiles(context, param);
|
||||
if (!single) return ListValue.wrap(profiles.stream().map(p -> StringValue.of(p.getName())).collect(Collectors.toList()));
|
||||
int size = profiles.size();
|
||||
if (size == 0) return Value.NULL;
|
||||
if (size == 1) return StringValue.of(profiles.iterator().next().getName());
|
||||
throw new SimpleCommandExceptionType(new LiteralText("Multiple game profiles returned while only one was requested"+" for custom type "+suffix)).create();
|
||||
throw new SimpleCommandExceptionType(new TextComponent("Multiple game profiles returned while only one was requested"+" for custom type "+suffix)).create();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -658,25 +654,25 @@ public abstract class CommandArgument
|
||||
|
||||
private ScoreholderArgument()
|
||||
{
|
||||
super("scoreholder", ScoreHolderArgumentType.scoreHolder().getExamples(), false);
|
||||
super("scoreholder", ScoreHolderArgument.scoreHolder().getExamples(), false);
|
||||
single = false;
|
||||
suggestionProvider = ScoreHolderArgumentType.SUGGESTION_PROVIDER;
|
||||
suggestionProvider = ScoreHolderArgument.SUGGEST_SCORE_HOLDERS;
|
||||
}
|
||||
@Override
|
||||
protected ArgumentType<?> getArgumentType()
|
||||
{
|
||||
return single?ScoreHolderArgumentType.scoreHolder():ScoreHolderArgumentType.scoreHolders();
|
||||
return single?ScoreHolderArgument.scoreHolder():ScoreHolderArgument.scoreHolders();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
protected Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
Collection<String> holders = ScoreHolderArgumentType.getScoreHolders(context, param);
|
||||
Collection<String> holders = ScoreHolderArgument.getNames(context, param);
|
||||
if (!single) return ListValue.wrap(holders.stream().map(StringValue::of).collect(Collectors.toList()));
|
||||
int size = holders.size();
|
||||
if (size == 0) return Value.NULL;
|
||||
if (size == 1) return StringValue.of(holders.iterator().next());
|
||||
throw new SimpleCommandExceptionType(new LiteralText("Multiple score holders returned while only one was requested"+" for custom type "+suffix)).create();
|
||||
throw new SimpleCommandExceptionType(new TextComponent("Multiple score holders returned while only one was requested"+" for custom type "+suffix)).create();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -698,22 +694,22 @@ public abstract class CommandArgument
|
||||
boolean mapRequired;
|
||||
private TagArgument()
|
||||
{
|
||||
super("tag", NbtCompoundArgumentType.nbtCompound().getExamples(), false);
|
||||
super("tag", CompoundTagArgument.compoundTag().getExamples(), false);
|
||||
mapRequired = true;
|
||||
}
|
||||
@Override
|
||||
protected ArgumentType<?> getArgumentType()
|
||||
{
|
||||
return mapRequired?NbtCompoundArgumentType.nbtCompound(): NbtElementArgumentType.nbtElement();
|
||||
return mapRequired?CompoundTagArgument.compoundTag(): NbtTagArgument.nbtTag();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
protected Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
if (mapRequired)
|
||||
return new NBTSerializableValue(NbtCompoundArgumentType.getNbtCompound(context, param));
|
||||
return new NBTSerializableValue(CompoundTagArgument.getCompoundTag(context, param));
|
||||
else
|
||||
return new NBTSerializableValue(NbtElementArgumentType.getNbtElement(context, param));
|
||||
return new NBTSerializableValue(NbtTagArgument.getNbtTag(context, param));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -732,7 +728,7 @@ public abstract class CommandArgument
|
||||
|
||||
private static class CustomIdentifierArgument extends CommandArgument
|
||||
{
|
||||
Set<Identifier> validOptions = Collections.emptySet();
|
||||
Set<ResourceLocation> validOptions = Collections.emptySet();
|
||||
|
||||
protected CustomIdentifierArgument()
|
||||
{
|
||||
@@ -742,16 +738,16 @@ public abstract class CommandArgument
|
||||
@Override
|
||||
protected ArgumentType<?> getArgumentType()
|
||||
{
|
||||
return IdentifierArgumentType.identifier();
|
||||
return ResourceLocationArgument.id();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
protected Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
Identifier choseValue = IdentifierArgumentType.getIdentifier(context, param);
|
||||
ResourceLocation choseValue = ResourceLocationArgument.getId(context, param);
|
||||
if (!validOptions.isEmpty() && !validOptions.contains(choseValue))
|
||||
{
|
||||
throw new SimpleCommandExceptionType(new LiteralText("Incorrect value for "+param+": "+choseValue+" for custom type "+suffix)).create();
|
||||
throw new SimpleCommandExceptionType(new TextComponent("Incorrect value for "+param+": "+choseValue+" for custom type "+suffix)).create();
|
||||
}
|
||||
return ValueConversions.of(choseValue);
|
||||
}
|
||||
@@ -770,7 +766,7 @@ public abstract class CommandArgument
|
||||
{
|
||||
Value optionsValue = config.get("options");
|
||||
if (!(optionsValue instanceof ListValue)) throw error("Custom sting type requires options passed as a list"+" for custom type "+suffix);
|
||||
validOptions = ((ListValue) optionsValue).getItems().stream().map(v -> new Identifier(v.getString())).collect(Collectors.toSet());
|
||||
validOptions = ((ListValue) optionsValue).getItems().stream().map(v -> new ResourceLocation(v.getString())).collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -799,7 +795,7 @@ public abstract class CommandArgument
|
||||
}
|
||||
|
||||
@Override
|
||||
public Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
public Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
return new NumericValue(DoubleArgumentType.getDouble(context, param));
|
||||
}
|
||||
@@ -850,7 +846,7 @@ public abstract class CommandArgument
|
||||
}
|
||||
|
||||
@Override
|
||||
public Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
public Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
return new NumericValue(LongArgumentType.getLong(context, param));
|
||||
}
|
||||
@@ -926,22 +922,22 @@ public abstract class CommandArgument
|
||||
|
||||
protected SlotArgument()
|
||||
{
|
||||
super("slot", ItemSlotArgumentType.itemSlot().getExamples(), false);
|
||||
super("slot", net.minecraft.commands.arguments.SlotArgument.slot().getExamples(), false);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ArgumentType<?> getArgumentType() throws CommandSyntaxException
|
||||
{
|
||||
return ItemSlotArgumentType.itemSlot();
|
||||
return net.minecraft.commands.arguments.SlotArgument.slot();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
protected Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
int slot = ItemSlotArgumentType.getItemSlot(context, param);
|
||||
int slot = net.minecraft.commands.arguments.SlotArgument.getSlot(context, param);
|
||||
if (restrict != null && !RESTRICTED_CONTAINERS.get(restrict).numericalIds().contains(slot))
|
||||
{
|
||||
throw new SimpleCommandExceptionType(new LiteralText("Incorrect slot restricted to "+restrict+" for custom type "+suffix)).create();
|
||||
throw new SimpleCommandExceptionType(new TextComponent("Incorrect slot restricted to "+restrict+" for custom type "+suffix)).create();
|
||||
}
|
||||
return ValueConversions.ofVanillaSlotResult(slot);
|
||||
}
|
||||
@@ -960,7 +956,7 @@ public abstract class CommandArgument
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Collection<String> getOptions(CommandContext<ServerCommandSource> context, CarpetScriptHost host) throws CommandSyntaxException
|
||||
protected Collection<String> getOptions(CommandContext<CommandSourceStack> context, CarpetScriptHost host) throws CommandSyntaxException
|
||||
{
|
||||
return restrict==null?super.getOptions(context, host):RESTRICTED_CONTAINERS.get(restrict).commandIds();
|
||||
}
|
||||
@@ -975,7 +971,7 @@ public abstract class CommandArgument
|
||||
@FunctionalInterface
|
||||
private interface ValueExtractor
|
||||
{
|
||||
Value apply(CommandContext<ServerCommandSource> ctx, String param) throws CommandSyntaxException;
|
||||
Value apply(CommandContext<CommandSourceStack> ctx, String param) throws CommandSyntaxException;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
@@ -1013,7 +1009,7 @@ public abstract class CommandArgument
|
||||
String suffix,
|
||||
ArgumentProvider argumentTypeSupplier,
|
||||
ValueExtractor valueExtractor,
|
||||
SuggestionProvider<ServerCommandSource> suggester
|
||||
SuggestionProvider<CommandSourceStack> suggester
|
||||
)
|
||||
{
|
||||
super(suffix, Collections.emptyList(), false);
|
||||
@@ -1030,7 +1026,7 @@ public abstract class CommandArgument
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
|
||||
protected Value getValueFromContext(CommandContext<CommandSourceStack> context, String param) throws CommandSyntaxException
|
||||
{
|
||||
return valueExtractor.apply(context, param);
|
||||
}
|
||||
|
||||
@@ -5,15 +5,14 @@ import carpet.script.value.FunctionValue;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.brigadier.builder.ArgumentBuilder;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
|
||||
import static net.minecraft.server.command.CommandManager.literal;
|
||||
import static net.minecraft.commands.Commands.literal;
|
||||
|
||||
public class CommandToken implements Comparable<CommandToken>
|
||||
{
|
||||
@@ -71,7 +70,7 @@ public class CommandToken implements Comparable<CommandToken>
|
||||
}
|
||||
|
||||
|
||||
public ArgumentBuilder<ServerCommandSource, ?> getCommandNode(CarpetScriptHost host) throws CommandSyntaxException
|
||||
public ArgumentBuilder<CommandSourceStack, ?> getCommandNode(CarpetScriptHost host) throws CommandSyntaxException
|
||||
{
|
||||
if (isArgument)
|
||||
return CommandArgument.argumentNode(surface, host);
|
||||
|
||||
@@ -2,9 +2,8 @@ package carpet.script.exception;
|
||||
|
||||
import carpet.script.value.FunctionValue;
|
||||
import carpet.utils.Messenger;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
|
||||
public class CarpetExpressionException extends RuntimeException implements ResolvedException
|
||||
{
|
||||
@@ -15,7 +14,7 @@ public class CarpetExpressionException extends RuntimeException implements Resol
|
||||
super(message);
|
||||
this.stack = stack;
|
||||
}
|
||||
public void printStack(ServerCommandSource source)
|
||||
public void printStack(CommandSourceStack source)
|
||||
{
|
||||
if (stack != null && !stack.isEmpty())
|
||||
{
|
||||
|
||||
@@ -15,10 +15,9 @@ import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.minecraft.command.CommandException;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.util.WorldSavePath;
|
||||
|
||||
import net.minecraft.commands.CommandRuntimeException;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
@@ -58,7 +57,7 @@ public class AppStoreManager
|
||||
|
||||
public static class ScarpetAppStoreValidator extends Validator<String>
|
||||
{
|
||||
@Override public String validate(ServerCommandSource source, ParsedRule<String> currentRule, String newValue, String string)
|
||||
@Override public String validate(CommandSourceStack source, ParsedRule<String> currentRule, String newValue, String string)
|
||||
{
|
||||
APP_STORE_ROOT.sealed = false;
|
||||
APP_STORE_ROOT.children = new HashMap<>();
|
||||
@@ -251,13 +250,13 @@ public class AppStoreManager
|
||||
* @return {@code 1} if we succesfully saved the script, {@code 0} otherwise
|
||||
*/
|
||||
|
||||
public static int downloadScript(ServerCommandSource source, String path)
|
||||
public static int downloadScript(CommandSourceStack source, String path)
|
||||
{
|
||||
AppInfo nodeInfo = getFileNode(path);
|
||||
return downloadScript(source, path, nodeInfo, false);
|
||||
}
|
||||
|
||||
private static int downloadScript(ServerCommandSource source, String path, AppInfo nodeInfo, boolean useTrash)
|
||||
private static int downloadScript(CommandSourceStack source, String path, AppInfo nodeInfo, boolean useTrash)
|
||||
{
|
||||
String code;
|
||||
try
|
||||
@@ -266,7 +265,7 @@ public class AppStoreManager
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
throw new CommandException(Messenger.c("rb Failed to obtain app file content: "+e.getMessage()));
|
||||
throw new CommandRuntimeException(Messenger.c("rb Failed to obtain app file content: "+e.getMessage()));
|
||||
}
|
||||
if (!saveScriptToFile(source, path, nodeInfo.name(), code, false, useTrash)) return 0;
|
||||
boolean success = CarpetServer.scriptServer.addScriptHost(source, nodeInfo.name().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.source());
|
||||
@@ -297,21 +296,21 @@ public class AppStoreManager
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
throw new CommandException(Messenger.c("rb '"+ appPath + "' is not a valid path to a scarpet app: "+e.getMessage()));
|
||||
throw new CommandRuntimeException(Messenger.c("rb '"+ appPath + "' is not a valid path to a scarpet app: "+e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static boolean saveScriptToFile(ServerCommandSource source, String path, String appFileName, String code, boolean globalSavePath, boolean useTrash)
|
||||
public static boolean saveScriptToFile(CommandSourceStack source, String path, String appFileName, String code, boolean globalSavePath, boolean useTrash)
|
||||
{
|
||||
Path scriptLocation;
|
||||
if (globalSavePath && !source.getServer().isDedicated()) // never happens, this is always called with globalSavePath being false
|
||||
if (globalSavePath && !source.getServer().isDedicatedServer()) // never happens, this is always called with globalSavePath being false
|
||||
{ //cos config folder only is in clients
|
||||
scriptLocation = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts/appstore").toAbsolutePath().resolve(path);
|
||||
}
|
||||
else
|
||||
{
|
||||
scriptLocation = source.getServer().getSavePath(WorldSavePath.ROOT).resolve("scripts").toAbsolutePath().resolve(appFileName);
|
||||
scriptLocation = source.getServer().getWorldPath(LevelResource.ROOT).resolve("scripts").toAbsolutePath().resolve(appFileName);
|
||||
}
|
||||
try
|
||||
{
|
||||
@@ -463,7 +462,7 @@ public class AppStoreManager
|
||||
{
|
||||
downloadScript(carpetScriptHost.responsibleSource, target, new AppInfo(target, contentUrl, getNewStoreNode(storeSource, source, contentUrl)), true);
|
||||
}
|
||||
catch (CommandException e)
|
||||
catch (CommandRuntimeException e)
|
||||
{
|
||||
throw new InternalExpressionException("Error when installing app dependencies: " + e.toString());
|
||||
}
|
||||
|
||||
@@ -7,39 +7,37 @@ import carpet.script.value.NumericValue;
|
||||
import carpet.script.value.StringValue;
|
||||
import carpet.script.value.Value;
|
||||
import carpet.script.value.ValueConversions;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
import net.minecraft.world.biome.Biome;
|
||||
import net.minecraft.world.gen.feature.ConfiguredFeature;
|
||||
import net.minecraft.world.gen.feature.ConfiguredStructureFeature;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiFunction;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
|
||||
|
||||
public class BiomeInfo
|
||||
{
|
||||
public final static Map<String, BiFunction<ServerWorld, Biome, Value>> biomeFeatures = new HashMap<String, BiFunction<ServerWorld, Biome, Value>>(){{
|
||||
public final static Map<String, BiFunction<ServerLevel, Biome, Value>> biomeFeatures = new HashMap<String, BiFunction<ServerLevel, Biome, Value>>(){{
|
||||
//put("top_material", (w, b) -> new BlockValue( b.getGenerationSettings(). getSurfaceConfig().getTopMaterial(), null, null));
|
||||
//put("under_material", (w, b) -> new BlockValue( b.getGenerationSettings().getSurfaceConfig().getUnderMaterial(), null, null));
|
||||
put("category", (w, b) -> StringValue.of(b.getCategory().getName()));
|
||||
put("temperature", (w, b) -> NumericValue.of(b.getTemperature()));
|
||||
put("fog_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getFogColor()));
|
||||
put("foliage_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getFoliageColor().orElse(4764952))); // client Biome.getDefaultFoliageColor
|
||||
put("sky_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getSkyColor()));
|
||||
put("water_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getWaterColor()));
|
||||
put("water_fog_color", (w, b) -> ValueConversions.ofRGB(b.getEffects().getWaterFogColor()));
|
||||
put("category", (w, b) -> StringValue.of(b.getBiomeCategory().getName()));
|
||||
put("temperature", (w, b) -> NumericValue.of(b.getBaseTemperature()));
|
||||
put("fog_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getFogColor()));
|
||||
put("foliage_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getFoliageColorOverride().orElse(4764952))); // client Biome.getDefaultFoliageColor
|
||||
put("sky_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getSkyColor()));
|
||||
put("water_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getWaterColor()));
|
||||
put("water_fog_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getWaterFogColor()));
|
||||
put("humidity", (w, b) -> NumericValue.of(b.getDownfall()));
|
||||
put("precipitation", (w, b) -> StringValue.of(b.getPrecipitation().getName()));
|
||||
//put("depth", (w, b) -> NumericValue.of(b.getDepth()));
|
||||
//put("scale", (w, b) -> NumericValue.of(b.getScale()));
|
||||
put("features", (w, b) -> {
|
||||
|
||||
Registry<ConfiguredFeature<?,?>> registry = w.getRegistryManager().get(Registry.CONFIGURED_FEATURE_KEY);
|
||||
Registry<ConfiguredFeature<?,?>> registry = w.registryAccess().registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY);
|
||||
return ListValue.wrap(
|
||||
b.getGenerationSettings().getFeatures().stream().map(step ->
|
||||
b.getGenerationSettings().features().stream().map(step ->
|
||||
ListValue.wrap(step.stream().map(cfp ->
|
||||
ValueConversions.of(registry.getId(((PlacedFeatureInterface)cfp.get()).getRawFeature()))
|
||||
ValueConversions.of(registry.getKey(((PlacedFeatureInterface)cfp.get()).getRawFeature()))
|
||||
))
|
||||
)
|
||||
);
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
package carpet.script.utils;
|
||||
|
||||
import net.minecraft.entity.EquipmentSlot;
|
||||
import net.minecraft.entity.LivingEntity;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.inventory.Inventory;
|
||||
import net.minecraft.item.ItemStack;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import net.minecraft.world.Container;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
|
||||
public class EquipmentInventory implements Inventory
|
||||
public class EquipmentInventory implements Container
|
||||
{
|
||||
private static final List<EquipmentSlot> slotToSlot = Arrays.asList(
|
||||
EquipmentSlot.MAINHAND,
|
||||
@@ -24,7 +23,7 @@ public class EquipmentInventory implements Inventory
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size()
|
||||
public int getContainerSize()
|
||||
{
|
||||
return 6;
|
||||
}
|
||||
@@ -33,12 +32,12 @@ public class EquipmentInventory implements Inventory
|
||||
public boolean isEmpty()
|
||||
{
|
||||
for (EquipmentSlot slot: slotToSlot)
|
||||
if (!mob.getEquippedStack(slot).isEmpty()) return false;
|
||||
if (!mob.getItemBySlot(slot).isEmpty()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getStack(int slot)
|
||||
public ItemStack getItem(int slot)
|
||||
{
|
||||
EquipmentSlot slotSlot;
|
||||
try
|
||||
@@ -50,11 +49,11 @@ public class EquipmentInventory implements Inventory
|
||||
//going out of the index should be really exceptional
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
return mob.getEquippedStack(slotSlot);
|
||||
return mob.getItemBySlot(slotSlot);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack removeStack(int slot, int amount)
|
||||
public ItemStack removeItem(int slot, int amount)
|
||||
{
|
||||
EquipmentSlot slotSlot;
|
||||
try
|
||||
@@ -66,11 +65,11 @@ public class EquipmentInventory implements Inventory
|
||||
//going out of the index should be really exceptional
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
return mob.getEquippedStack(slotSlot).split(amount);
|
||||
return mob.getItemBySlot(slotSlot).split(amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack removeStack(int slot)
|
||||
public ItemStack removeItemNoUpdate(int slot)
|
||||
{
|
||||
EquipmentSlot slotSlot;
|
||||
try
|
||||
@@ -82,13 +81,13 @@ public class EquipmentInventory implements Inventory
|
||||
//going out of the index should be really exceptional
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
ItemStack previous = mob.getEquippedStack(slotSlot);
|
||||
mob.equipStack(slotSlot, ItemStack.EMPTY);
|
||||
ItemStack previous = mob.getItemBySlot(slotSlot);
|
||||
mob.setItemSlot(slotSlot, ItemStack.EMPTY);
|
||||
return previous;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setStack(int slot, ItemStack stack)
|
||||
public void setItem(int slot, ItemStack stack)
|
||||
{
|
||||
EquipmentSlot slotSlot;
|
||||
try
|
||||
@@ -100,25 +99,25 @@ public class EquipmentInventory implements Inventory
|
||||
//going out of the index should be really exceptional
|
||||
return;
|
||||
}
|
||||
mob.equipStack(slotSlot, stack);
|
||||
mob.setItemSlot(slotSlot, stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markDirty()
|
||||
public void setChanged()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canPlayerUse(PlayerEntity player)
|
||||
public boolean stillValid(Player player)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear()
|
||||
public void clearContent()
|
||||
{
|
||||
for (EquipmentSlot slot: slotToSlot)
|
||||
mob.equipStack(slot, ItemStack.EMPTY);
|
||||
mob.setItemSlot(slot, ItemStack.EMPTY);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
package carpet.script.utils;
|
||||
|
||||
import carpet.script.exception.InternalExpressionException;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.InvalidIdentifierException;
|
||||
import org.lwjgl.system.CallbackI;
|
||||
|
||||
import java.util.Locale;
|
||||
import net.minecraft.ResourceLocationException;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
public class InputValidator {
|
||||
public static String validateSimpleString(String input, boolean strict)
|
||||
@@ -16,13 +16,13 @@ public class InputValidator {
|
||||
return simplified;
|
||||
}
|
||||
|
||||
public static Identifier identifierOf(String string)
|
||||
public static ResourceLocation identifierOf(String string)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new Identifier(string);
|
||||
return new ResourceLocation(string);
|
||||
}
|
||||
catch (InvalidIdentifierException iie)
|
||||
catch (ResourceLocationException iie)
|
||||
{
|
||||
throw new InternalExpressionException("Incorrect identifier format '"+string+"': "+iie.getMessage());
|
||||
}
|
||||
|
||||
@@ -18,31 +18,30 @@ import carpet.script.value.Value;
|
||||
import com.google.common.collect.Sets;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.command.argument.ParticleEffectArgumentType;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.nbt.NbtByte;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.nbt.NbtDouble;
|
||||
import net.minecraft.nbt.NbtFloat;
|
||||
import net.minecraft.nbt.NbtInt;
|
||||
import net.minecraft.nbt.NbtList;
|
||||
import net.minecraft.nbt.NbtString;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.particle.ParticleEffect;
|
||||
import net.minecraft.commands.arguments.ParticleArgument;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.particles.ParticleOptions;
|
||||
import net.minecraft.nbt.ByteTag;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.DoubleTag;
|
||||
import net.minecraft.nbt.FloatTag;
|
||||
import net.minecraft.nbt.IntTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.text.LiteralText;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Direction;
|
||||
import net.minecraft.util.math.MathHelper;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.util.registry.RegistryKey;
|
||||
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
@@ -60,13 +59,13 @@ import static java.util.Map.entry;
|
||||
|
||||
public class ShapeDispatcher
|
||||
{
|
||||
private static final Map<String, ParticleEffect> particleCache = new HashMap<>();
|
||||
private static final Map<String, ParticleOptions> particleCache = new HashMap<>();
|
||||
public static record ShapeWithConfig(ExpiringShape shape, Map<String, Value> config) {}
|
||||
|
||||
public static ShapeWithConfig fromFunctionArgs(
|
||||
MinecraftServer server, ServerWorld world,
|
||||
MinecraftServer server, ServerLevel world,
|
||||
List<Value> lv,
|
||||
Set<ServerPlayerEntity> playerSet
|
||||
Set<ServerPlayer> playerSet
|
||||
)
|
||||
{
|
||||
if (lv.size() < 3) throw new InternalExpressionException("'draw_shape' takes at least three parameters, shape name, duration, and its params");
|
||||
@@ -93,7 +92,7 @@ public class ShapeDispatcher
|
||||
for (int i=2; i < lv.size(); i++) paramList.add(lv.get(i));
|
||||
params = ShapeDispatcher.parseParams(paramList);
|
||||
}
|
||||
params.putIfAbsent("dim", new StringValue(world.getRegistryKey().getValue().toString()));
|
||||
params.putIfAbsent("dim", new StringValue(world.dimension().location().toString()));
|
||||
params.putIfAbsent("duration", duration);
|
||||
|
||||
if (params.containsKey("player"))
|
||||
@@ -106,7 +105,7 @@ public class ShapeDispatcher
|
||||
playerVals = Collections.singletonList(players);
|
||||
for (Value pVal : playerVals)
|
||||
{
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(server, pVal);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(server, pVal);
|
||||
if (player == null)
|
||||
throw new InternalExpressionException("'player' parameter needs to represent an existing player, not "+pVal.getString());
|
||||
playerSet.add(player);
|
||||
@@ -116,11 +115,11 @@ public class ShapeDispatcher
|
||||
return new ShapeWithConfig(ShapeDispatcher.create(server, shapeType, params), params);
|
||||
}
|
||||
|
||||
public static void sendShape(Collection<ServerPlayerEntity> players, List<ShapeWithConfig> shapes)
|
||||
public static void sendShape(Collection<ServerPlayer> players, List<ShapeWithConfig> shapes)
|
||||
{
|
||||
List<ServerPlayerEntity> clientPlayers = new ArrayList<>();
|
||||
List<ServerPlayerEntity> alternativePlayers = new ArrayList<>();
|
||||
for (ServerPlayerEntity player : players)
|
||||
List<ServerPlayer> clientPlayers = new ArrayList<>();
|
||||
List<ServerPlayer> alternativePlayers = new ArrayList<>();
|
||||
for (ServerPlayer player : players)
|
||||
{
|
||||
if (ServerNetworkHandler.isValidCarpetPlayer(player))
|
||||
{
|
||||
@@ -134,7 +133,7 @@ public class ShapeDispatcher
|
||||
if (!clientPlayers.isEmpty())
|
||||
{
|
||||
|
||||
NbtList tag = new NbtList();
|
||||
ListTag tag = new ListTag();
|
||||
int tagcount = 0;
|
||||
for (ShapeWithConfig s : shapes)
|
||||
{
|
||||
@@ -142,30 +141,30 @@ public class ShapeDispatcher
|
||||
if (tagcount++>1000)
|
||||
{
|
||||
tagcount = 0;
|
||||
NbtElement finalTag = tag;
|
||||
Tag finalTag = tag;
|
||||
clientPlayers.forEach( p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag));
|
||||
tag = new NbtList();
|
||||
tag = new ListTag();
|
||||
}
|
||||
}
|
||||
NbtElement finalTag = tag;
|
||||
Tag finalTag = tag;
|
||||
if (tag.size() > 0) clientPlayers.forEach( p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag));
|
||||
}
|
||||
if (!alternativePlayers.isEmpty())
|
||||
{
|
||||
List<Consumer<ServerPlayerEntity>> alternatives = new ArrayList<>();
|
||||
List<Consumer<ServerPlayer>> alternatives = new ArrayList<>();
|
||||
shapes.forEach(s -> alternatives.add(s.shape().alternative()));
|
||||
alternativePlayers.forEach(p -> alternatives.forEach( a -> a.accept(p)));
|
||||
}
|
||||
}
|
||||
|
||||
public static ParticleEffect getParticleData(String name)
|
||||
public static ParticleOptions getParticleData(String name)
|
||||
{
|
||||
ParticleEffect particle = particleCache.get(name);
|
||||
ParticleOptions particle = particleCache.get(name);
|
||||
if (particle != null)
|
||||
return particle;
|
||||
try
|
||||
{
|
||||
particle = ParticleEffectArgumentType.readParameters(new StringReader(name));
|
||||
particle = ParticleArgument.readParticle(new StringReader(name));
|
||||
}
|
||||
catch (CommandSyntaxException e)
|
||||
{
|
||||
@@ -205,10 +204,10 @@ public class ShapeDispatcher
|
||||
}
|
||||
|
||||
// client
|
||||
public static ExpiringShape fromTag(NbtCompound tag)
|
||||
public static ExpiringShape fromTag(CompoundTag tag)
|
||||
{
|
||||
Map<String, Value> options = new HashMap<>();
|
||||
for (String key : tag.getKeys())
|
||||
for (String key : tag.getAllKeys())
|
||||
{
|
||||
Param decoder = Param.of.get(key);
|
||||
if (decoder==null)
|
||||
@@ -222,7 +221,7 @@ public class ShapeDispatcher
|
||||
Value shapeValue = options.get("shape");
|
||||
if (shapeValue == null)
|
||||
{
|
||||
CarpetSettings.LOG.info("Shape id missing in "+ String.join(", ", tag.getKeys()));
|
||||
CarpetSettings.LOG.info("Shape id missing in "+ String.join(", ", tag.getAllKeys()));
|
||||
return null;
|
||||
}
|
||||
Function<Map<String, Value>,ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString());
|
||||
@@ -271,16 +270,16 @@ public class ShapeDispatcher
|
||||
protected String snapTo;
|
||||
protected boolean snapX, snapY, snapZ;
|
||||
protected boolean discreteX, discreteY, discreteZ;
|
||||
protected RegistryKey<World> shapeDimension;
|
||||
protected ResourceKey<Level> shapeDimension;
|
||||
|
||||
|
||||
protected ExpiringShape() { }
|
||||
|
||||
public static NbtCompound toTag(Map<String, Value> params)
|
||||
public static CompoundTag toTag(Map<String, Value> params)
|
||||
{
|
||||
NbtCompound tag = new NbtCompound();
|
||||
CompoundTag tag = new CompoundTag();
|
||||
params.forEach((k, v) -> {
|
||||
NbtElement valTag = Param.of.get(k).toTag(v);
|
||||
Tag valTag = Param.of.get(k).toTag(v);
|
||||
if (valTag != null) tag.put(k, valTag);
|
||||
});
|
||||
return tag;
|
||||
@@ -325,7 +324,7 @@ public class ShapeDispatcher
|
||||
|
||||
key = 0;
|
||||
followEntity = -1;
|
||||
shapeDimension = RegistryKey.of(Registry.WORLD_KEY, new Identifier(options.get("dim").getString()));
|
||||
shapeDimension = ResourceKey.create(Registry.DIMENSION_REGISTRY, new ResourceLocation(options.get("dim").getString()));
|
||||
if (options.containsKey("follow"))
|
||||
{
|
||||
followEntity = NumericValue.asNumber(options.getOrDefault("follow", optional.get("follow"))).getInt();
|
||||
@@ -339,33 +338,33 @@ public class ShapeDispatcher
|
||||
}
|
||||
}
|
||||
public int getExpiry() { return duration; }
|
||||
public Vec3d toAbsolute(Entity e, Vec3d vec, float partialTick)
|
||||
public Vec3 toAbsolute(Entity e, Vec3 vec, float partialTick)
|
||||
{
|
||||
return vec.add(
|
||||
snapX?(discreteX ?MathHelper.floor(e.getX()):MathHelper.lerp(partialTick, e.prevX, e.getX())):0.0,
|
||||
snapY?(discreteY ?MathHelper.floor(e.getY()):MathHelper.lerp(partialTick, e.prevY, e.getY())):0.0,
|
||||
snapZ?(discreteZ ?MathHelper.floor(e.getZ()):MathHelper.lerp(partialTick, e.prevZ, e.getZ())):0.0
|
||||
snapX?(discreteX ?Mth.floor(e.getX()):Mth.lerp(partialTick, e.xo, e.getX())):0.0,
|
||||
snapY?(discreteY ?Mth.floor(e.getY()):Mth.lerp(partialTick, e.yo, e.getY())):0.0,
|
||||
snapZ?(discreteZ ?Mth.floor(e.getZ()):Mth.lerp(partialTick, e.zo, e.getZ())):0.0
|
||||
);
|
||||
}
|
||||
public Vec3d relativiseRender(World world, Vec3d vec, float partialTick)
|
||||
public Vec3 relativiseRender(Level world, Vec3 vec, float partialTick)
|
||||
{
|
||||
if (followEntity < 0) return vec;
|
||||
Entity e = world.getEntityById(followEntity);
|
||||
Entity e = world.getEntity(followEntity);
|
||||
if (e == null) return vec;
|
||||
return toAbsolute(e, vec, partialTick);
|
||||
}
|
||||
|
||||
public Vec3d vecFromValue(Value value)
|
||||
public Vec3 vecFromValue(Value value)
|
||||
{
|
||||
if (!(value instanceof ListValue)) throw new InternalExpressionException("decoded value of "+value.getPrettyString()+" is not a triple");
|
||||
List<Value> elements = ((ListValue) value).getItems();
|
||||
return new Vec3d(
|
||||
return new Vec3(
|
||||
NumericValue.asNumber( elements.get(0)).getDouble(),
|
||||
NumericValue.asNumber( elements.get(1)).getDouble(),
|
||||
NumericValue.asNumber( elements.get(2)).getDouble()
|
||||
);
|
||||
}
|
||||
protected ParticleEffect replacementParticle()
|
||||
protected ParticleOptions replacementParticle()
|
||||
{
|
||||
String particleName = fa ==0 ?
|
||||
String.format(Locale.ROOT , "dust %.1f %.1f %.1f 1.0", r, g, b):
|
||||
@@ -374,7 +373,7 @@ public class ShapeDispatcher
|
||||
}
|
||||
|
||||
|
||||
public abstract Consumer<ServerPlayerEntity> alternative();
|
||||
public abstract Consumer<ServerPlayer> alternative();
|
||||
public long key()
|
||||
{
|
||||
if (key!=0) return key;
|
||||
@@ -398,7 +397,7 @@ public class ShapeDispatcher
|
||||
private static final double xdif = new Random().nextDouble();
|
||||
private static final double ydif = new Random().nextDouble();
|
||||
private static final double zdif = new Random().nextDouble();
|
||||
int vec3dhash(Vec3d vec)
|
||||
int vec3dhash(Vec3 vec)
|
||||
{
|
||||
return vec.add(xdif, ydif, zdif).hashCode();
|
||||
}
|
||||
@@ -443,7 +442,7 @@ public class ShapeDispatcher
|
||||
protected Set<String> optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); }
|
||||
public DisplayedText() { }
|
||||
|
||||
Vec3d pos;
|
||||
Vec3 pos;
|
||||
String text;
|
||||
int textcolor;
|
||||
int textbck;
|
||||
@@ -457,7 +456,7 @@ public class ShapeDispatcher
|
||||
float indent;
|
||||
int align;
|
||||
float height;
|
||||
Text value;
|
||||
Component value;
|
||||
boolean doublesided;
|
||||
|
||||
@Override
|
||||
@@ -520,7 +519,7 @@ public class ShapeDispatcher
|
||||
|
||||
|
||||
@Override
|
||||
public Consumer<ServerPlayerEntity> alternative()
|
||||
public Consumer<ServerPlayer> alternative()
|
||||
{
|
||||
return s -> {};
|
||||
}
|
||||
@@ -558,8 +557,8 @@ public class ShapeDispatcher
|
||||
protected Set<String> optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); }
|
||||
public Box() { }
|
||||
|
||||
Vec3d from;
|
||||
Vec3d to;
|
||||
Vec3 from;
|
||||
Vec3 to;
|
||||
|
||||
@Override
|
||||
protected void init(Map<String, Value> options)
|
||||
@@ -570,20 +569,20 @@ public class ShapeDispatcher
|
||||
}
|
||||
|
||||
@Override
|
||||
public Consumer<ServerPlayerEntity> alternative()
|
||||
public Consumer<ServerPlayer> alternative()
|
||||
{
|
||||
ParticleEffect particle = replacementParticle();
|
||||
ParticleOptions particle = replacementParticle();
|
||||
double density = Math.max(2.0, from.distanceTo(to) /50/ (a+0.1)) ;
|
||||
return p ->
|
||||
{
|
||||
if (p.world.getRegistryKey() == shapeDimension)
|
||||
if (p.level.dimension() == shapeDimension)
|
||||
{
|
||||
particleMesh(
|
||||
Collections.singletonList(p),
|
||||
particle,
|
||||
density,
|
||||
relativiseRender(p.world, from, 0),
|
||||
relativiseRender(p.world, to, 0)
|
||||
relativiseRender(p.level, from, 0),
|
||||
relativiseRender(p.level, to, 0)
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -599,8 +598,8 @@ public class ShapeDispatcher
|
||||
return hash;
|
||||
}
|
||||
|
||||
public static int particleMesh(List<ServerPlayerEntity> playerList, ParticleEffect particle, double density,
|
||||
Vec3d from, Vec3d to)
|
||||
public static int particleMesh(List<ServerPlayer> playerList, ParticleOptions particle, double density,
|
||||
Vec3 from, Vec3 to)
|
||||
{
|
||||
double x1 = from.x;
|
||||
double y1 = from.y;
|
||||
@@ -609,20 +608,20 @@ public class ShapeDispatcher
|
||||
double y2 = to.y;
|
||||
double z2 = to.z;
|
||||
return
|
||||
drawParticleLine(playerList, particle, new Vec3d(x1, y1, z1), new Vec3d(x1, y2, z1), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3d(x1, y2, z1), new Vec3d(x2, y2, z1), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3d(x2, y2, z1), new Vec3d(x2, y1, z1), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3d(x2, y1, z1), new Vec3d(x1, y1, z1), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3(x1, y1, z1), new Vec3(x1, y2, z1), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3(x1, y2, z1), new Vec3(x2, y2, z1), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3(x2, y2, z1), new Vec3(x2, y1, z1), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3(x2, y1, z1), new Vec3(x1, y1, z1), density)+
|
||||
|
||||
drawParticleLine(playerList, particle, new Vec3d(x1, y1, z2), new Vec3d(x1, y2, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3d(x1, y2, z2), new Vec3d(x2, y2, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3d(x2, y2, z2), new Vec3d(x2, y1, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3d(x2, y1, z2), new Vec3d(x1, y1, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3(x1, y1, z2), new Vec3(x1, y2, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3(x1, y2, z2), new Vec3(x2, y2, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3(x2, y2, z2), new Vec3(x2, y1, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3(x2, y1, z2), new Vec3(x1, y1, z2), density)+
|
||||
|
||||
drawParticleLine(playerList, particle, new Vec3d(x1, y1, z1), new Vec3d(x1, y1, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3d(x1, y2, z1), new Vec3d(x1, y2, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3d(x2, y2, z1), new Vec3d(x2, y2, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3d(x2, y1, z1), new Vec3d(x2, y1, z2), density);
|
||||
drawParticleLine(playerList, particle, new Vec3(x1, y1, z1), new Vec3(x1, y1, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3(x1, y2, z1), new Vec3(x1, y2, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3(x2, y2, z1), new Vec3(x2, y2, z2), density)+
|
||||
drawParticleLine(playerList, particle, new Vec3(x2, y1, z1), new Vec3(x2, y1, z2), density);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -640,8 +639,8 @@ public class ShapeDispatcher
|
||||
super();
|
||||
}
|
||||
|
||||
Vec3d from;
|
||||
Vec3d to;
|
||||
Vec3 from;
|
||||
Vec3 to;
|
||||
|
||||
@Override
|
||||
protected void init(Map<String, Value> options)
|
||||
@@ -652,17 +651,17 @@ public class ShapeDispatcher
|
||||
}
|
||||
|
||||
@Override
|
||||
public Consumer<ServerPlayerEntity> alternative()
|
||||
public Consumer<ServerPlayer> alternative()
|
||||
{
|
||||
ParticleEffect particle = replacementParticle();
|
||||
ParticleOptions particle = replacementParticle();
|
||||
double density = Math.max(2.0, from.distanceTo(to) /50) / (a+0.1);
|
||||
return p ->
|
||||
{
|
||||
if (p.world.getRegistryKey() == shapeDimension) drawParticleLine(
|
||||
if (p.level.dimension() == shapeDimension) drawParticleLine(
|
||||
Collections.singletonList(p),
|
||||
particle,
|
||||
relativiseRender(p.world, from, 0),
|
||||
relativiseRender(p.world, to, 0),
|
||||
relativiseRender(p.level, from, 0),
|
||||
relativiseRender(p.level, to, 0),
|
||||
density
|
||||
);
|
||||
};
|
||||
@@ -693,7 +692,7 @@ public class ShapeDispatcher
|
||||
super();
|
||||
}
|
||||
|
||||
Vec3d center;
|
||||
Vec3 center;
|
||||
float radius;
|
||||
int level;
|
||||
int subdivisions;
|
||||
@@ -713,14 +712,14 @@ public class ShapeDispatcher
|
||||
}
|
||||
|
||||
@Override
|
||||
public Consumer<ServerPlayerEntity> alternative() { return p ->
|
||||
public Consumer<ServerPlayer> alternative() { return p ->
|
||||
{
|
||||
ParticleEffect particle = replacementParticle();
|
||||
ParticleOptions particle = replacementParticle();
|
||||
int partno = Math.min(1000,20*subdivisions);
|
||||
Random rand = p.world.getRandom();
|
||||
ServerWorld world = p.getWorld();
|
||||
Random rand = p.level.getRandom();
|
||||
ServerLevel world = p.getLevel();
|
||||
|
||||
Vec3d ccenter = relativiseRender(world, center, 0 );
|
||||
Vec3 ccenter = relativiseRender(world, center, 0 );
|
||||
|
||||
double ccx = ccenter.x;
|
||||
double ccy = ccenter.y;
|
||||
@@ -731,10 +730,10 @@ public class ShapeDispatcher
|
||||
float theta = (float)Math.asin(rand.nextDouble()*2.0-1.0);
|
||||
float phi = (float)(2*Math.PI*rand.nextDouble());
|
||||
|
||||
double x = radius * MathHelper.cos(theta) * MathHelper.cos(phi);
|
||||
double y = radius * MathHelper.cos(theta) * MathHelper.sin(phi);
|
||||
double z = radius * MathHelper.sin(theta);
|
||||
world.spawnParticles(p, particle, true,
|
||||
double x = radius * Mth.cos(theta) * Mth.cos(phi);
|
||||
double y = radius * Mth.cos(theta) * Mth.sin(phi);
|
||||
double z = radius * Mth.sin(theta);
|
||||
world.sendParticles(p, particle, true,
|
||||
x+ccx, y+ccy, z+ccz, 1,
|
||||
0.0, 0.0, 0.0, 0.0);
|
||||
}
|
||||
@@ -764,7 +763,7 @@ public class ShapeDispatcher
|
||||
@Override
|
||||
protected Set<String> optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); }
|
||||
|
||||
Vec3d center;
|
||||
Vec3 center;
|
||||
float height;
|
||||
float radius;
|
||||
int level;
|
||||
@@ -786,19 +785,19 @@ public class ShapeDispatcher
|
||||
subdivisions = Math.max(10, (int)(10*Math.sqrt(radius)));
|
||||
}
|
||||
height = NumericValue.asNumber(options.getOrDefault("height", optional.get("height"))).getFloat();
|
||||
axis = Direction.Axis.fromName(options.getOrDefault("axis", optional.get("axis")).getString());
|
||||
axis = Direction.Axis.byName(options.getOrDefault("axis", optional.get("axis")).getString());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Consumer<ServerPlayerEntity> alternative() { return p ->
|
||||
public Consumer<ServerPlayer> alternative() { return p ->
|
||||
{
|
||||
ParticleEffect particle = replacementParticle();
|
||||
ParticleOptions particle = replacementParticle();
|
||||
int partno = (int)Math.min(1000,Math.sqrt(20*subdivisions*(1+height)));
|
||||
Random rand = p.world.getRandom();
|
||||
ServerWorld world = p.getWorld();
|
||||
Random rand = p.level.getRandom();
|
||||
ServerLevel world = p.getLevel();
|
||||
|
||||
Vec3d ccenter = relativiseRender(world, center, 0 );
|
||||
Vec3 ccenter = relativiseRender(world, center, 0 );
|
||||
|
||||
double ccx = ccenter.x;
|
||||
double ccy = ccenter.y;
|
||||
@@ -810,10 +809,10 @@ public class ShapeDispatcher
|
||||
{
|
||||
float d = rand.nextFloat()*height;
|
||||
float phi = (float)(2*Math.PI*rand.nextDouble());
|
||||
double x = radius * MathHelper.cos(phi);
|
||||
double x = radius * Mth.cos(phi);
|
||||
double y = d;
|
||||
double z = radius * MathHelper.sin(phi);
|
||||
world.spawnParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
|
||||
double z = radius * Mth.sin(phi);
|
||||
world.sendParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
|
||||
}
|
||||
}
|
||||
else if (axis== Direction.Axis.X)
|
||||
@@ -823,9 +822,9 @@ public class ShapeDispatcher
|
||||
float d = rand.nextFloat()*height;
|
||||
float phi = (float)(2*Math.PI*rand.nextDouble());
|
||||
double x = d;
|
||||
double y = radius * MathHelper.cos(phi);
|
||||
double z = radius * MathHelper.sin(phi);
|
||||
world.spawnParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
|
||||
double y = radius * Mth.cos(phi);
|
||||
double z = radius * Mth.sin(phi);
|
||||
world.sendParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
|
||||
}
|
||||
}
|
||||
else // Z
|
||||
@@ -834,10 +833,10 @@ public class ShapeDispatcher
|
||||
{
|
||||
float d = rand.nextFloat()*height;
|
||||
float phi = (float)(2*Math.PI*rand.nextDouble());
|
||||
double x = radius * MathHelper.sin(phi);
|
||||
double y = radius * MathHelper.cos(phi);
|
||||
double x = radius * Mth.sin(phi);
|
||||
double y = radius * Mth.cos(phi);
|
||||
double z = d;
|
||||
world.spawnParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
|
||||
world.sendParticles(p, particle, true, x+ccx, y+ccy, z+ccz, 1, 0.0, 0.0, 0.0, 0.0);
|
||||
}
|
||||
}
|
||||
};}
|
||||
@@ -900,9 +899,9 @@ public class ShapeDispatcher
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public abstract NbtElement toTag(Value value); //validates value, returning null if not necessary to keep it and serialize
|
||||
public abstract Tag toTag(Value value); //validates value, returning null if not necessary to keep it and serialize
|
||||
public abstract Value validate(Map<String, Value> options, MinecraftServer server, Value value); // makes sure the value is proper
|
||||
public abstract Value decode(NbtElement tag);
|
||||
public abstract Value decode(Tag tag);
|
||||
}
|
||||
|
||||
public abstract static class StringParam extends Param
|
||||
@@ -910,9 +909,9 @@ public class ShapeDispatcher
|
||||
protected StringParam(String id) { super(id); }
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(Value value) { return NbtString.of(value.getString()); }
|
||||
public Tag toTag(Value value) { return StringTag.valueOf(value.getString()); }
|
||||
@Override
|
||||
public Value decode(NbtElement tag) { return new StringValue(tag.asString()); }
|
||||
public Value decode(Tag tag) { return new StringValue(tag.getAsString()); }
|
||||
}
|
||||
public static class TextParam extends StringParam
|
||||
{
|
||||
@@ -937,22 +936,22 @@ public class ShapeDispatcher
|
||||
public Value validate(Map<String, Value> options, MinecraftServer server, Value value)
|
||||
{
|
||||
if (!(value instanceof FormattedTextValue))
|
||||
value = new FormattedTextValue(new LiteralText(value.getString()));
|
||||
value = new FormattedTextValue(new TextComponent(value.getString()));
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(Value value)
|
||||
public Tag toTag(Value value)
|
||||
{
|
||||
if (!(value instanceof FormattedTextValue))
|
||||
value = new FormattedTextValue(new LiteralText(value.getString()));
|
||||
return NbtString.of(((FormattedTextValue)value).serialize());
|
||||
value = new FormattedTextValue(new TextComponent(value.getString()));
|
||||
return StringTag.valueOf(((FormattedTextValue)value).serialize());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Value decode(NbtElement tag)
|
||||
public Value decode(Tag tag)
|
||||
{
|
||||
return FormattedTextValue.deserialize(tag.asString());
|
||||
return FormattedTextValue.deserialize(tag.getAsString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1015,24 +1014,24 @@ public class ShapeDispatcher
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(Value value)
|
||||
public Tag toTag(Value value)
|
||||
{
|
||||
return NbtByte.of(value.getBoolean());
|
||||
return ByteTag.valueOf(value.getBoolean());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Value decode(NbtElement tag)
|
||||
public Value decode(Tag tag)
|
||||
{
|
||||
return BooleanValue.of(((NbtByte) tag).byteValue() > 0);
|
||||
return BooleanValue.of(((ByteTag) tag).getAsByte() > 0);
|
||||
}
|
||||
}
|
||||
public static class FloatParam extends NumericParam
|
||||
{
|
||||
protected FloatParam(String id) { super(id); }
|
||||
@Override
|
||||
public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); }
|
||||
public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getAsFloat()); }
|
||||
@Override
|
||||
public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); }
|
||||
public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); }
|
||||
}
|
||||
|
||||
public static abstract class PositiveParam extends NumericParam
|
||||
@@ -1049,27 +1048,27 @@ public class ShapeDispatcher
|
||||
{
|
||||
protected PositiveFloatParam(String id) { super(id); }
|
||||
@Override
|
||||
public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); }
|
||||
public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getAsFloat()); }
|
||||
@Override
|
||||
public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); }
|
||||
public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); }
|
||||
|
||||
}
|
||||
public static class PositiveIntParam extends PositiveParam
|
||||
{
|
||||
protected PositiveIntParam(String id) { super(id); }
|
||||
@Override
|
||||
public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); }
|
||||
public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); }
|
||||
@Override
|
||||
public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); }
|
||||
public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); }
|
||||
|
||||
}
|
||||
public static class NonNegativeIntParam extends NumericParam
|
||||
{
|
||||
protected NonNegativeIntParam(String id) { super(id); }
|
||||
@Override
|
||||
public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); }
|
||||
public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); }
|
||||
@Override
|
||||
public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); }
|
||||
public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); }
|
||||
@Override public Value validate(Map<String, Value> options, MinecraftServer server, Value value)
|
||||
{
|
||||
Value ret = super.validate(options, server, value);
|
||||
@@ -1081,9 +1080,9 @@ public class ShapeDispatcher
|
||||
{
|
||||
protected NonNegativeFloatParam(String id) { super(id); }
|
||||
@Override
|
||||
public Value decode(NbtElement tag) { return new NumericValue(((NbtFloat)tag).floatValue()); }
|
||||
public Value decode(Tag tag) { return new NumericValue(((FloatTag)tag).getAsFloat()); }
|
||||
@Override
|
||||
public NbtElement toTag(Value value) { return NbtFloat.of(NumericValue.asNumber(value, id).getFloat()); }
|
||||
public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); }
|
||||
@Override public Value validate(Map<String, Value> options, MinecraftServer server, Value value)
|
||||
{
|
||||
Value ret = super.validate(options, server, value);
|
||||
@@ -1149,9 +1148,9 @@ public class ShapeDispatcher
|
||||
}
|
||||
|
||||
@Override
|
||||
public Value decode(NbtElement tag)
|
||||
public Value decode(Tag tag)
|
||||
{
|
||||
NbtList ctag = (NbtList)tag;
|
||||
ListTag ctag = (ListTag)tag;
|
||||
return ListValue.of(
|
||||
new NumericValue(ctag.getDouble(0)),
|
||||
new NumericValue(ctag.getDouble(1)),
|
||||
@@ -1159,13 +1158,13 @@ public class ShapeDispatcher
|
||||
);
|
||||
}
|
||||
@Override
|
||||
public NbtElement toTag(Value value)
|
||||
public Tag toTag(Value value)
|
||||
{
|
||||
List<Value> lv = ((ListValue)value).getItems();
|
||||
NbtList tag = new NbtList();
|
||||
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(0), "x").getDouble()));
|
||||
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(1), "y").getDouble()));
|
||||
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(2), "z").getDouble()));
|
||||
ListTag tag = new ListTag();
|
||||
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(0), "x").getDouble()));
|
||||
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(1), "y").getDouble()));
|
||||
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(2), "z").getDouble()));
|
||||
return tag;
|
||||
}
|
||||
}
|
||||
@@ -1188,13 +1187,13 @@ public class ShapeDispatcher
|
||||
}
|
||||
|
||||
@Override
|
||||
public Value decode(NbtElement tag)
|
||||
public Value decode(Tag tag)
|
||||
{
|
||||
NbtList ltag = (NbtList)tag;
|
||||
ListTag ltag = (ListTag)tag;
|
||||
List<Value> points = new ArrayList<>();
|
||||
for (int i=0, ll = ltag.size(); i<ll; i++)
|
||||
{
|
||||
NbtList ptag = ltag.getList(i);
|
||||
ListTag ptag = ltag.getList(i);
|
||||
points.add(ListValue.of(
|
||||
new NumericValue(ptag.getDouble(0)),
|
||||
new NumericValue(ptag.getDouble(1)),
|
||||
@@ -1204,17 +1203,17 @@ public class ShapeDispatcher
|
||||
return ListValue.wrap(points);
|
||||
}
|
||||
@Override
|
||||
public NbtElement toTag(Value pointsValue)
|
||||
public Tag toTag(Value pointsValue)
|
||||
{
|
||||
List<Value> lv = ((ListValue)pointsValue).getItems();
|
||||
NbtList ltag = new NbtList();
|
||||
ListTag ltag = new ListTag();
|
||||
for (Value value : lv)
|
||||
{
|
||||
List<Value> coords = ((ListValue)value).getItems();
|
||||
NbtList tag = new NbtList();
|
||||
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(0), "x").getDouble()));
|
||||
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(1), "y").getDouble()));
|
||||
tag.add(NbtDouble.of(NumericValue.asNumber(lv.get(2), "z").getDouble()));
|
||||
ListTag tag = new ListTag();
|
||||
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(0), "x").getDouble()));
|
||||
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(1), "y").getDouble()));
|
||||
tag.add(DoubleTag.valueOf(NumericValue.asNumber(lv.get(2), "z").getDouble()));
|
||||
ltag.add(tag);
|
||||
}
|
||||
return ltag;
|
||||
@@ -1230,9 +1229,9 @@ public class ShapeDispatcher
|
||||
}
|
||||
|
||||
@Override
|
||||
public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); }
|
||||
public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); }
|
||||
@Override
|
||||
public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); }
|
||||
public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); }
|
||||
}
|
||||
|
||||
public static class EntityParam extends Param
|
||||
@@ -1241,47 +1240,47 @@ public class ShapeDispatcher
|
||||
protected EntityParam(String id) { super(id); }
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(Value value)
|
||||
public Tag toTag(Value value)
|
||||
{
|
||||
return NbtInt.of(NumericValue.asNumber(value, id).getInt());
|
||||
return IntTag.valueOf(NumericValue.asNumber(value, id).getInt());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Value validate(Map<String, Value> options, MinecraftServer server, Value value)
|
||||
{
|
||||
if (value instanceof EntityValue) return new NumericValue(((EntityValue) value).getEntity().getId());
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(server, value);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(server, value);
|
||||
if (player == null)
|
||||
throw new InternalExpressionException(id+" parameter needs to represent an entity or player");
|
||||
return new NumericValue(player.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); }
|
||||
public Value decode(Tag tag) { return new NumericValue(((IntTag)tag).getAsInt()); }
|
||||
}
|
||||
|
||||
private static boolean isStraight(Vec3d from, Vec3d to, double density)
|
||||
private static boolean isStraight(Vec3 from, Vec3 to, double density)
|
||||
{
|
||||
if ( (from.x == to.x && from.y == to.y) || (from.x == to.x && from.z == to.z) || (from.y == to.y && from.z == to.z))
|
||||
return from.distanceTo(to) / density > 20;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static int drawOptimizedParticleLine(List<ServerPlayerEntity> playerList, ParticleEffect particle, Vec3d from, Vec3d to, double density)
|
||||
private static int drawOptimizedParticleLine(List<ServerPlayer> playerList, ParticleOptions particle, Vec3 from, Vec3 to, double density)
|
||||
{
|
||||
double distance = from.distanceTo(to);
|
||||
int particles = (int)(distance/density);
|
||||
Vec3d towards = to.subtract(from);
|
||||
Vec3 towards = to.subtract(from);
|
||||
int parts = 0;
|
||||
for (ServerPlayerEntity player : playerList)
|
||||
for (ServerPlayer player : playerList)
|
||||
{
|
||||
ServerWorld world = player.getWorld();
|
||||
world.spawnParticles(player, particle, true,
|
||||
ServerLevel world = player.getLevel();
|
||||
world.sendParticles(player, particle, true,
|
||||
(towards.x)/2+from.x, (towards.y)/2+from.y, (towards.z)/2+from.z, particles/3,
|
||||
towards.x/6, towards.y/6, towards.z/6, 0.0);
|
||||
world.spawnParticles(player, particle, true,
|
||||
world.sendParticles(player, particle, true,
|
||||
from.x, from.y, from.z,1,0.0,0.0,0.0,0.0);
|
||||
world.spawnParticles(player, particle, true,
|
||||
world.sendParticles(player, particle, true,
|
||||
to.x, to.y, to.z,1,0.0,0.0,0.0,0.0);
|
||||
parts += particles/3+2;
|
||||
}
|
||||
@@ -1290,13 +1289,13 @@ public class ShapeDispatcher
|
||||
{
|
||||
int center = (divider*2)/3;
|
||||
int dev = 2*divider;
|
||||
for (ServerPlayerEntity player : playerList)
|
||||
for (ServerPlayer player : playerList)
|
||||
{
|
||||
ServerWorld world = player.getWorld();
|
||||
world.spawnParticles(player, particle, true,
|
||||
ServerLevel world = player.getLevel();
|
||||
world.sendParticles(player, particle, true,
|
||||
(towards.x)/center+from.x, (towards.y)/center+from.y, (towards.z)/center+from.z, particles/divider,
|
||||
towards.x/dev, towards.y/dev, towards.z/dev, 0.0);
|
||||
world.spawnParticles(player, particle, true,
|
||||
world.sendParticles(player, particle, true,
|
||||
(towards.x)*(1.0-1.0/center)+from.x, (towards.y)*(1.0-1.0/center)+from.y, (towards.z)*(1.0-1.0/center)+from.z, particles/divider,
|
||||
towards.x/dev, towards.y/dev, towards.z/dev, 0.0);
|
||||
}
|
||||
@@ -1306,22 +1305,22 @@ public class ShapeDispatcher
|
||||
return parts;
|
||||
}
|
||||
|
||||
public static int drawParticleLine(List<ServerPlayerEntity> players, ParticleEffect particle, Vec3d from, Vec3d to, double density)
|
||||
public static int drawParticleLine(List<ServerPlayer> players, ParticleOptions particle, Vec3 from, Vec3 to, double density)
|
||||
{
|
||||
double distance = from.squaredDistanceTo(to);
|
||||
double distance = from.distanceToSqr(to);
|
||||
if (distance == 0) return 0;
|
||||
int pcount = 0;
|
||||
if (distance < 100)
|
||||
{
|
||||
Random rand = players.get(0).world.random;
|
||||
Random rand = players.get(0).level.random;
|
||||
int particles = (int)(distance/density)+1;
|
||||
Vec3d towards = to.subtract(from);
|
||||
Vec3 towards = to.subtract(from);
|
||||
for (int i = 0; i < particles; i++)
|
||||
{
|
||||
Vec3d at = from.add(towards.multiply( rand.nextDouble()));
|
||||
for (ServerPlayerEntity player : players)
|
||||
Vec3 at = from.add(towards.scale( rand.nextDouble()));
|
||||
for (ServerPlayer player : players)
|
||||
{
|
||||
player.getWorld().spawnParticles(player, particle, true,
|
||||
player.getLevel().sendParticles(player, particle, true,
|
||||
at.x, at.y, at.z, 1,
|
||||
0.0, 0.0, 0.0, 0.0);
|
||||
pcount ++;
|
||||
@@ -1331,15 +1330,15 @@ public class ShapeDispatcher
|
||||
}
|
||||
|
||||
if (isStraight(from, to, density)) return drawOptimizedParticleLine(players, particle, from, to, density);
|
||||
Vec3d incvec = to.subtract(from).multiply(2*density/Math.sqrt(distance));
|
||||
Vec3 incvec = to.subtract(from).scale(2*density/Math.sqrt(distance));
|
||||
|
||||
for (Vec3d delta = new Vec3d(0.0,0.0,0.0);
|
||||
delta.lengthSquared()<distance;
|
||||
delta = delta.add(incvec.multiply(Sys.randomizer.nextFloat())))
|
||||
for (Vec3 delta = new Vec3(0.0,0.0,0.0);
|
||||
delta.lengthSqr()<distance;
|
||||
delta = delta.add(incvec.scale(Sys.randomizer.nextFloat())))
|
||||
{
|
||||
for (ServerPlayerEntity player : players)
|
||||
for (ServerPlayer player : players)
|
||||
{
|
||||
player.getWorld().spawnParticles(player, particle, true,
|
||||
player.getLevel().sendParticles(player, particle, true,
|
||||
delta.x+from.x, delta.y+from.y, delta.z+from.z, 1,
|
||||
0.0, 0.0, 0.0, 0.0);
|
||||
pcount ++;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,83 +2,83 @@ package carpet.script.utils;
|
||||
|
||||
import carpet.CarpetSettings;
|
||||
import com.mojang.brigadier.ResultConsumer;
|
||||
import net.minecraft.command.argument.EntityAnchorArgumentType;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.commands.CommandSource;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.arguments.EntityAnchorArgument;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.command.CommandOutput;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.math.MathHelper;
|
||||
import net.minecraft.util.math.Vec2f;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.world.dimension.DimensionType;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.phys.Vec2;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.BinaryOperator;
|
||||
|
||||
public class SnoopyCommandSource extends ServerCommandSource
|
||||
public class SnoopyCommandSource extends CommandSourceStack
|
||||
{
|
||||
private final CommandOutput output;
|
||||
private final Vec3d position;
|
||||
private final ServerWorld world;
|
||||
private final CommandSource output;
|
||||
private final Vec3 position;
|
||||
private final ServerLevel world;
|
||||
private final int level;
|
||||
private final String simpleName;
|
||||
private final Text name;
|
||||
private final Component name;
|
||||
private final MinecraftServer server;
|
||||
// skipping silent since snooper is never silent
|
||||
private final Entity entity;
|
||||
private final ResultConsumer<ServerCommandSource> resultConsumer;
|
||||
private final EntityAnchorArgumentType.EntityAnchor entityAnchor;
|
||||
private final Vec2f rotation;
|
||||
private final ResultConsumer<CommandSourceStack> resultConsumer;
|
||||
private final EntityAnchorArgument.Anchor entityAnchor;
|
||||
private final Vec2 rotation;
|
||||
// good stuff
|
||||
private final Text[] error;
|
||||
private final List<Text> chatOutput;
|
||||
private final Component[] error;
|
||||
private final List<Component> chatOutput;
|
||||
|
||||
public SnoopyCommandSource(ServerCommandSource original, Text[] error, List<Text> chatOutput)
|
||||
public SnoopyCommandSource(CommandSourceStack original, Component[] error, List<Component> chatOutput)
|
||||
{
|
||||
super(CommandOutput.DUMMY, original.getPosition(), original.getRotation(), original.getWorld(), CarpetSettings.runPermissionLevel,
|
||||
original.getName(), original.getDisplayName(), original.getServer(), original.getEntity(), false,
|
||||
(ctx, succ, res) -> { }, EntityAnchorArgumentType.EntityAnchor.FEET);
|
||||
this.output = CommandOutput.DUMMY;
|
||||
super(CommandSource.NULL, original.getPosition(), original.getRotation(), original.getLevel(), CarpetSettings.runPermissionLevel,
|
||||
original.getTextName(), original.getDisplayName(), original.getServer(), original.getEntity(), false,
|
||||
(ctx, succ, res) -> { }, EntityAnchorArgument.Anchor.FEET);
|
||||
this.output = CommandSource.NULL;
|
||||
this.position = original.getPosition();
|
||||
this.world = original.getWorld();
|
||||
this.world = original.getLevel();
|
||||
this.level = CarpetSettings.runPermissionLevel;
|
||||
this.simpleName = original.getName();
|
||||
this.simpleName = original.getTextName();
|
||||
this.name = original.getDisplayName();
|
||||
this.server = original.getServer();
|
||||
this.entity = original.getEntity();
|
||||
this.resultConsumer = (ctx, succ, res) -> { };
|
||||
this.entityAnchor = original.getEntityAnchor();
|
||||
this.entityAnchor = original.getAnchor();
|
||||
this.rotation = original.getRotation();
|
||||
this.error = error;
|
||||
this.chatOutput = chatOutput;
|
||||
}
|
||||
|
||||
public SnoopyCommandSource(ServerPlayerEntity player, Text[] error, List<Text> output) {
|
||||
super(player, player.getPos(), player.getRotationClient(),
|
||||
player.world instanceof ServerWorld ? (ServerWorld) player.world : null,
|
||||
player.server.getPermissionLevel(player.getGameProfile()), player.getName().getString(), player.getDisplayName(),
|
||||
player.world.getServer(), player);
|
||||
public SnoopyCommandSource(ServerPlayer player, Component[] error, List<Component> output) {
|
||||
super(player, player.position(), player.getRotationVector(),
|
||||
player.level instanceof ServerLevel ? (ServerLevel) player.level : null,
|
||||
player.server.getProfilePermissions(player.getGameProfile()), player.getName().getString(), player.getDisplayName(),
|
||||
player.level.getServer(), player);
|
||||
this.output = player;
|
||||
this.position = player.getPos();
|
||||
this.world = player.world instanceof ServerWorld ? (ServerWorld) player.world : null;
|
||||
this.level = player.server.getPermissionLevel(player.getGameProfile());
|
||||
this.position = player.position();
|
||||
this.world = player.level instanceof ServerLevel ? (ServerLevel) player.level : null;
|
||||
this.level = player.server.getProfilePermissions(player.getGameProfile());
|
||||
this.simpleName = player.getName().getString();
|
||||
this.name = player.getDisplayName();
|
||||
this.server = player.world.getServer();
|
||||
this.server = player.level.getServer();
|
||||
this.entity = player;
|
||||
this.resultConsumer = (ctx, succ, res) -> { };
|
||||
this.entityAnchor = EntityAnchorArgumentType.EntityAnchor.FEET;
|
||||
this.rotation = player.getRotationClient(); // not a client call really
|
||||
this.entityAnchor = EntityAnchorArgument.Anchor.FEET;
|
||||
this.rotation = player.getRotationVector(); // not a client call really
|
||||
this.error = error;
|
||||
this.chatOutput = output;
|
||||
}
|
||||
|
||||
private SnoopyCommandSource(CommandOutput output, Vec3d pos, Vec2f rot, ServerWorld world, int level, String simpleName, Text name, MinecraftServer server, @Nullable Entity entity, ResultConsumer<ServerCommandSource> consumer, EntityAnchorArgumentType.EntityAnchor entityAnchor,
|
||||
Text[] error, List<Text> chatOutput
|
||||
private SnoopyCommandSource(CommandSource output, Vec3 pos, Vec2 rot, ServerLevel world, int level, String simpleName, Component name, MinecraftServer server, @Nullable Entity entity, ResultConsumer<CommandSourceStack> consumer, EntityAnchorArgument.Anchor entityAnchor,
|
||||
Component[] error, List<Component> chatOutput
|
||||
) {
|
||||
super(output, pos, rot, world, level,
|
||||
simpleName, name, server, entity, false,
|
||||
@@ -99,34 +99,34 @@ public class SnoopyCommandSource extends ServerCommandSource
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerCommandSource withEntity(Entity entity)
|
||||
public CommandSourceStack withEntity(Entity entity)
|
||||
{
|
||||
return new SnoopyCommandSource(output, position, rotation, world, level, entity.getName().getString(), entity.getDisplayName(), server, entity, resultConsumer, entityAnchor, error, chatOutput);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerCommandSource withPosition(Vec3d position)
|
||||
public CommandSourceStack withPosition(Vec3 position)
|
||||
{
|
||||
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, error, chatOutput);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerCommandSource withRotation(Vec2f rotation)
|
||||
public CommandSourceStack withRotation(Vec2 rotation)
|
||||
{
|
||||
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, error, chatOutput);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerCommandSource withConsumer(ResultConsumer<ServerCommandSource> consumer)
|
||||
public CommandSourceStack withCallback(ResultConsumer<CommandSourceStack> consumer)
|
||||
{
|
||||
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, error, chatOutput);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerCommandSource mergeConsumers(ResultConsumer<ServerCommandSource> consumer, BinaryOperator<ResultConsumer<ServerCommandSource>> binaryOperator)
|
||||
public CommandSourceStack withCallback(ResultConsumer<CommandSourceStack> consumer, BinaryOperator<ResultConsumer<CommandSourceStack>> binaryOperator)
|
||||
{
|
||||
ResultConsumer<ServerCommandSource> resultConsumer = binaryOperator.apply(this.resultConsumer, consumer);
|
||||
return this.withConsumer(resultConsumer);
|
||||
ResultConsumer<CommandSourceStack> resultConsumer = binaryOperator.apply(this.resultConsumer, consumer);
|
||||
return this.withCallback(resultConsumer);
|
||||
}
|
||||
|
||||
//@Override // only used in fuctions and we really don't care to track these actually, besides the basic output
|
||||
@@ -134,51 +134,51 @@ public class SnoopyCommandSource extends ServerCommandSource
|
||||
//public ServerCommandSource withSilent() { return this; }
|
||||
|
||||
@Override
|
||||
public ServerCommandSource withLevel(int level)
|
||||
public CommandSourceStack withPermission(int level)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerCommandSource withMaxLevel(int level)
|
||||
public CommandSourceStack withMaximumPermission(int level)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerCommandSource withEntityAnchor(EntityAnchorArgumentType.EntityAnchor anchor)
|
||||
public CommandSourceStack withAnchor(EntityAnchorArgument.Anchor anchor)
|
||||
{
|
||||
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, anchor, error, chatOutput);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerCommandSource withWorld(ServerWorld world)
|
||||
public CommandSourceStack withLevel(ServerLevel world)
|
||||
{
|
||||
double d = DimensionType.getCoordinateScaleFactor(this.world.getDimension(), world.getDimension());
|
||||
Vec3d position = new Vec3d(this.position.x * d, this.position.y, this.position.z * d);
|
||||
double d = DimensionType.getTeleportationScale(this.world.dimensionType(), world.dimensionType());
|
||||
Vec3 position = new Vec3(this.position.x * d, this.position.y, this.position.z * d);
|
||||
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, error, chatOutput);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerCommandSource withLookingAt(Vec3d position)
|
||||
public CommandSourceStack facing(Vec3 position)
|
||||
{
|
||||
Vec3d vec3d = this.entityAnchor.positionAt(this);
|
||||
Vec3 vec3d = this.entityAnchor.apply(this);
|
||||
double d = position.x - vec3d.x;
|
||||
double e = position.y - vec3d.y;
|
||||
double f = position.z - vec3d.z;
|
||||
double g = (double) Math.sqrt(d * d + f * f);
|
||||
float h = MathHelper.wrapDegrees((float)(-(MathHelper.atan2(e, g) * 57.2957763671875D)));
|
||||
float i = MathHelper.wrapDegrees((float)(MathHelper.atan2(f, d) * 57.2957763671875D) - 90.0F);
|
||||
return this.withRotation(new Vec2f(h, i));
|
||||
float h = Mth.wrapDegrees((float)(-(Mth.atan2(e, g) * 57.2957763671875D)));
|
||||
float i = Mth.wrapDegrees((float)(Mth.atan2(f, d) * 57.2957763671875D) - 90.0F);
|
||||
return this.withRotation(new Vec2(h, i));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendError(Text message)
|
||||
public void sendFailure(Component message)
|
||||
{
|
||||
error[0] = message;
|
||||
}
|
||||
@Override
|
||||
public void sendFeedback(Text message, boolean broadcastToOps)
|
||||
public void sendSuccess(Component message, boolean broadcastToOps)
|
||||
{
|
||||
chatOutput.add(message);
|
||||
}
|
||||
|
||||
@@ -18,12 +18,11 @@ import com.sun.management.OperatingSystemMXBean;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.fabricmc.loader.api.ModContainer;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.util.WorldSavePath;
|
||||
import net.minecraft.util.math.Vec2f;
|
||||
import net.minecraft.world.GameRules;
|
||||
import net.minecraft.world.WorldProperties;
|
||||
import net.minecraft.world.border.WorldBorder;
|
||||
|
||||
import net.minecraft.world.level.GameRules;
|
||||
import net.minecraft.world.level.border.WorldBorder;
|
||||
import net.minecraft.world.level.storage.LevelData;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
import net.minecraft.world.phys.Vec2;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
@@ -47,65 +46,65 @@ public class SystemInfo {
|
||||
put("app_scope", c -> StringValue.of((c.host).isPerUser()?"player":"global"));
|
||||
put("app_players", c -> ListValue.wrap(c.host.getUserList().stream().map(StringValue::new).collect(Collectors.toList())));
|
||||
|
||||
put("world_name", c -> new StringValue(c.s.getServer().getSaveProperties().getLevelName()));
|
||||
put("world_seed", c -> new NumericValue(c.s.getWorld().getSeed()));
|
||||
put("server_motd", c -> StringValue.of(c.s.getServer().getServerMotd()));
|
||||
put("world_path", c -> StringValue.of(c.s.getServer().getSavePath(WorldSavePath.ROOT).toString()));
|
||||
put("world_name", c -> new StringValue(c.s.getServer().getWorldData().getLevelName()));
|
||||
put("world_seed", c -> new NumericValue(c.s.getLevel().getSeed()));
|
||||
put("server_motd", c -> StringValue.of(c.s.getServer().getMotd()));
|
||||
put("world_path", c -> StringValue.of(c.s.getServer().getWorldPath(LevelResource.ROOT).toString()));
|
||||
put("world_folder", c -> {
|
||||
Path serverPath = c.s.getServer().getSavePath(WorldSavePath.ROOT);
|
||||
Path serverPath = c.s.getServer().getWorldPath(LevelResource.ROOT);
|
||||
int nodeCount = serverPath.getNameCount();
|
||||
if (nodeCount < 2) return Value.NULL;
|
||||
String tlf = serverPath.getName(nodeCount-2).toString();
|
||||
return StringValue.of(tlf);
|
||||
});
|
||||
put("world_dimensions", c -> ListValue.wrap(c.s.getServer().getWorldRegistryKeys().stream().map(k -> ValueConversions.of(k.getValue())).collect(Collectors.toList())));
|
||||
put("world_dimensions", c -> ListValue.wrap(c.s.getServer().levelKeys().stream().map(k -> ValueConversions.of(k.location())).collect(Collectors.toList())));
|
||||
put("world_spawn_point", c -> {
|
||||
WorldProperties prop = c.s.getServer().getOverworld().getLevelProperties();
|
||||
return ListValue.of(NumericValue.of(prop.getSpawnX()), NumericValue.of(prop.getSpawnY()), NumericValue.of(prop.getSpawnZ()));
|
||||
LevelData prop = c.s.getServer().overworld().getLevelData();
|
||||
return ListValue.of(NumericValue.of(prop.getXSpawn()), NumericValue.of(prop.getYSpawn()), NumericValue.of(prop.getZSpawn()));
|
||||
});
|
||||
|
||||
put("world_bottom", c-> new NumericValue(c.s.getWorld().getBottomY()));
|
||||
put("world_bottom", c-> new NumericValue(c.s.getLevel().getMinBuildHeight()));
|
||||
|
||||
put("world_top", c-> new NumericValue(c.s.getWorld().getTopY()));
|
||||
put("world_top", c-> new NumericValue(c.s.getLevel().getMaxBuildHeight()));
|
||||
|
||||
put("world_center", c-> {
|
||||
WorldBorder worldBorder = c.s.getWorld().getWorldBorder();
|
||||
WorldBorder worldBorder = c.s.getLevel().getWorldBorder();
|
||||
return ListValue.fromTriple(worldBorder.getCenterX(), 0, worldBorder.getCenterZ());
|
||||
});
|
||||
|
||||
put("world_size", c -> new NumericValue(c.s.getWorld().getWorldBorder().getSize() / 2));
|
||||
put("world_size", c -> new NumericValue(c.s.getLevel().getWorldBorder().getSize() / 2));
|
||||
|
||||
put("world_max_size", c-> new NumericValue( c.s.getWorld().getWorldBorder().getMaxRadius()));
|
||||
put("world_max_size", c-> new NumericValue( c.s.getLevel().getWorldBorder().getAbsoluteMaxSize()));
|
||||
|
||||
put("world_time", c -> new NumericValue(c.s.getWorld().getTime()));
|
||||
put("world_time", c -> new NumericValue(c.s.getLevel().getGameTime()));
|
||||
|
||||
put("game_difficulty", c -> StringValue.of(c.s.getServer().getSaveProperties().getDifficulty().getName()));
|
||||
put("game_hardcore", c -> BooleanValue.of(c.s.getServer().getSaveProperties().isHardcore()));
|
||||
put("game_storage_format", c -> StringValue.of(c.s.getServer().getSaveProperties().getFormatName(c.s.getServer().getSaveProperties().getVersion())));
|
||||
put("game_default_gamemode", c -> StringValue.of(c.s.getServer().getDefaultGameMode().getName()));
|
||||
put("game_max_players", c -> new NumericValue(c.s.getServer().getMaxPlayerCount()));
|
||||
put("game_view_distance", c -> new NumericValue(c.s.getServer().getPlayerManager().getViewDistance()));
|
||||
put("game_difficulty", c -> StringValue.of(c.s.getServer().getWorldData().getDifficulty().getKey()));
|
||||
put("game_hardcore", c -> BooleanValue.of(c.s.getServer().getWorldData().isHardcore()));
|
||||
put("game_storage_format", c -> StringValue.of(c.s.getServer().getWorldData().getStorageVersionName(c.s.getServer().getWorldData().getVersion())));
|
||||
put("game_default_gamemode", c -> StringValue.of(c.s.getServer().getDefaultGameType().getName()));
|
||||
put("game_max_players", c -> new NumericValue(c.s.getServer().getMaxPlayers()));
|
||||
put("game_view_distance", c -> new NumericValue(c.s.getServer().getPlayerList().getViewDistance()));
|
||||
put("game_mod_name", c -> StringValue.of(c.s.getServer().getServerModName()));
|
||||
put("game_version", c -> StringValue.of(c.s.getServer().getVersion()));
|
||||
put("game_target", c -> StringValue.of(SharedConstants.getGameVersion().getReleaseTarget()));
|
||||
put("game_version", c -> StringValue.of(c.s.getServer().getServerVersion()));
|
||||
put("game_target", c -> StringValue.of(SharedConstants.getCurrentVersion().getReleaseTarget()));
|
||||
put("game_protocol", c -> NumericValue.of(SharedConstants.getProtocolVersion()));
|
||||
put("game_major_target", c -> {
|
||||
String [] vers = SharedConstants.getGameVersion().getReleaseTarget().split("\\.");
|
||||
String [] vers = SharedConstants.getCurrentVersion().getReleaseTarget().split("\\.");
|
||||
return NumericValue.of((vers.length > 1)?Integer.parseInt(vers[1]):0);
|
||||
});
|
||||
put("game_minor_target", c -> {
|
||||
String [] vers = SharedConstants.getGameVersion().getReleaseTarget().split("\\.");
|
||||
String [] vers = SharedConstants.getCurrentVersion().getReleaseTarget().split("\\.");
|
||||
return NumericValue.of((vers.length > 2)?Integer.parseInt(vers[2]):0);
|
||||
});
|
||||
put("game_stable", c -> BooleanValue.of(SharedConstants.getGameVersion().isStable()));
|
||||
put("game_data_version", c->NumericValue.of(SharedConstants.getGameVersion().getWorldVersion()));
|
||||
put("game_pack_version", c->NumericValue.of(SharedConstants.getGameVersion().getPackVersion()));
|
||||
put("game_stable", c -> BooleanValue.of(SharedConstants.getCurrentVersion().isStable()));
|
||||
put("game_data_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getWorldVersion()));
|
||||
put("game_pack_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getPackVersion()));
|
||||
|
||||
put("server_ip", c -> StringValue.of(c.s.getServer().getServerIp()));
|
||||
put("server_ip", c -> StringValue.of(c.s.getServer().getLocalIp()));
|
||||
put("server_whitelisted", c -> BooleanValue.of(c.s.getServer().isEnforceWhitelist()));
|
||||
put("server_whitelist", c -> {
|
||||
MapValue whitelist = new MapValue(Collections.emptyList());
|
||||
for (String s: c.s.getServer().getPlayerManager().getWhitelistedNames())
|
||||
for (String s: c.s.getServer().getPlayerList().getWhiteListNames())
|
||||
{
|
||||
whitelist.append(StringValue.of(s));
|
||||
}
|
||||
@@ -113,7 +112,7 @@ public class SystemInfo {
|
||||
});
|
||||
put("server_banned_players", c -> {
|
||||
MapValue whitelist = new MapValue(Collections.emptyList());
|
||||
for (String s: c.s.getServer().getPlayerManager().getUserBanList().getNames())
|
||||
for (String s: c.s.getServer().getPlayerList().getBans().getUserList())
|
||||
{
|
||||
whitelist.append(StringValue.of(s));
|
||||
}
|
||||
@@ -121,7 +120,7 @@ public class SystemInfo {
|
||||
});
|
||||
put("server_banned_ips", c -> {
|
||||
MapValue whitelist = new MapValue(Collections.emptyList());
|
||||
for (String s: c.s.getServer().getPlayerManager().getIpBanList().getNames())
|
||||
for (String s: c.s.getServer().getPlayerList().getIpBans().getUserList())
|
||||
{
|
||||
whitelist.append(StringValue.of(s));
|
||||
}
|
||||
@@ -137,9 +136,9 @@ public class SystemInfo {
|
||||
put("server_last_tick_times", c -> {
|
||||
//assuming we are in the tick world section
|
||||
// might be off one tick when run in the off tasks or asynchronously.
|
||||
int currentReportedTick = c.s.getServer().getTicks()-1;
|
||||
int currentReportedTick = c.s.getServer().getTickCount()-1;
|
||||
List<Value> ticks = new ArrayList<>(100);
|
||||
final long[] tickArray = c.s.getServer().lastTickLengths;
|
||||
final long[] tickArray = c.s.getServer().tickTimes;
|
||||
for (int i=currentReportedTick+100; i > currentReportedTick; i--)
|
||||
{
|
||||
ticks.add(new NumericValue(((double)tickArray[i % 100])/1000000.0));
|
||||
@@ -191,11 +190,11 @@ public class SystemInfo {
|
||||
});
|
||||
put("world_gamerules", c->{
|
||||
Map<Value, Value> rules = new HashMap<>();
|
||||
final GameRules gameRules = c.s.getWorld().getGameRules();
|
||||
GameRules.accept(new GameRules.Visitor() {
|
||||
final GameRules gameRules = c.s.getLevel().getGameRules();
|
||||
GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() {
|
||||
@Override
|
||||
public <T extends GameRules.Rule<T>> void visit(GameRules.Key<T> key, GameRules.Type<T> type) {
|
||||
rules.put(StringValue.of(key.getName()), StringValue.of(gameRules.get(key).toString()));
|
||||
public <T extends GameRules.Value<T>> void visit(GameRules.Key<T> key, GameRules.Type<T> type) {
|
||||
rules.put(StringValue.of(key.getId()), StringValue.of(gameRules.getRule(key).toString()));
|
||||
}
|
||||
});
|
||||
return MapValue.wrap(rules);
|
||||
@@ -203,9 +202,9 @@ public class SystemInfo {
|
||||
|
||||
put("source_entity", c -> EntityValue.of(c.s.getEntity()));
|
||||
put("source_position", c -> ValueConversions.of(c.s.getPosition()));
|
||||
put("source_dimension", c -> ValueConversions.of(c.s.getWorld()));
|
||||
put("source_dimension", c -> ValueConversions.of(c.s.getLevel()));
|
||||
put("source_rotation", c -> {
|
||||
Vec2f rotation = c.s.getRotation();
|
||||
Vec2 rotation = c.s.getRotation();
|
||||
return ListValue.of(new NumericValue(rotation.x), new NumericValue(rotation.y));
|
||||
});
|
||||
|
||||
|
||||
@@ -3,35 +3,34 @@ package carpet.script.utils;
|
||||
import carpet.fakes.MinecraftServerInterface;
|
||||
import net.fabricmc.api.EnvType;
|
||||
import net.fabricmc.api.Environment;
|
||||
import net.minecraft.network.packet.s2c.play.ChunkDataS2CPacket;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.MappedRegistry;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.WorldGenerationProgressListener;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.ChunkPos;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
import net.minecraft.util.registry.RegistryKey;
|
||||
import net.minecraft.util.registry.SimpleRegistry;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.biome.source.BiomeAccess;
|
||||
import net.minecraft.world.biome.source.MultiNoiseBiomeSource;
|
||||
import net.minecraft.world.border.WorldBorderListener;
|
||||
import net.minecraft.world.chunk.ChunkStatus;
|
||||
import net.minecraft.world.chunk.WorldChunk;
|
||||
import net.minecraft.world.dimension.DimensionOptions;
|
||||
import net.minecraft.world.dimension.DimensionType;
|
||||
import net.minecraft.world.gen.GeneratorOptions;
|
||||
import net.minecraft.world.gen.Spawner;
|
||||
import net.minecraft.world.gen.chunk.ChunkGenerator;
|
||||
import net.minecraft.world.gen.chunk.ChunkGeneratorSettings;
|
||||
import net.minecraft.world.gen.chunk.NoiseChunkGenerator;
|
||||
import net.minecraft.world.level.ServerWorldProperties;
|
||||
import net.minecraft.world.level.UnmodifiableLevelProperties;
|
||||
import net.minecraft.world.storage.RegionFile;
|
||||
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.level.progress.ChunkProgressListener;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.CustomSpawner;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.biome.BiomeManager;
|
||||
import net.minecraft.world.level.biome.MultiNoiseBiomeSource;
|
||||
import net.minecraft.world.level.border.BorderChangeListener;
|
||||
import net.minecraft.world.level.chunk.ChunkGenerator;
|
||||
import net.minecraft.world.level.chunk.ChunkStatus;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.minecraft.world.level.chunk.storage.RegionFile;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.dimension.LevelStem;
|
||||
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import net.minecraft.world.level.levelgen.WorldGenSettings;
|
||||
import net.minecraft.world.level.storage.DerivedLevelData;
|
||||
import net.minecraft.world.level.storage.ServerLevelData;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
@@ -43,7 +42,7 @@ import java.util.Set;
|
||||
public class WorldTools
|
||||
{
|
||||
|
||||
public static boolean canHasChunk(ServerWorld world, ChunkPos chpos, Map<String, RegionFile> regionCache, boolean deepcheck)
|
||||
public static boolean canHasChunk(ServerLevel world, ChunkPos chpos, Map<String, RegionFile> regionCache, boolean deepcheck)
|
||||
{
|
||||
if (world.getChunk(chpos.x, chpos.z, ChunkStatus.STRUCTURE_STARTS, false) != null)
|
||||
return true;
|
||||
@@ -54,7 +53,7 @@ public class WorldTools
|
||||
if (region == null) return false;
|
||||
return region.hasChunk(chpos);
|
||||
}
|
||||
Path regionPath = new File(((MinecraftServerInterface )world.getServer()).getCMSession().getWorldDirectory(world.getRegistryKey()).toFile(), "region").toPath();
|
||||
Path regionPath = new File(((MinecraftServerInterface )world.getServer()).getCMSession().getDimensionPath(world.dimension()).toFile(), "region").toPath();
|
||||
Path regionFilePath = regionPath.resolve(currentRegionName);
|
||||
File regionFile = regionFilePath.toFile();
|
||||
if (!regionFile.exists())
|
||||
@@ -75,37 +74,37 @@ public class WorldTools
|
||||
|
||||
public static boolean createWorld(MinecraftServer server, String worldKey, Long seed)
|
||||
{
|
||||
Identifier worldId = new Identifier(worldKey);
|
||||
ServerWorld overWorld = server.getOverworld();
|
||||
ResourceLocation worldId = new ResourceLocation(worldKey);
|
||||
ServerLevel overWorld = server.overworld();
|
||||
|
||||
Set<RegistryKey<World>> worldKeys = server.getWorldRegistryKeys();
|
||||
for (RegistryKey<World> worldRegistryKey : worldKeys)
|
||||
Set<ResourceKey<Level>> worldKeys = server.levelKeys();
|
||||
for (ResourceKey<Level> worldRegistryKey : worldKeys)
|
||||
{
|
||||
if (worldRegistryKey.getValue().equals(worldId))
|
||||
if (worldRegistryKey.location().equals(worldId))
|
||||
{
|
||||
// world with this id already exists
|
||||
return false;
|
||||
}
|
||||
}
|
||||
ServerWorldProperties serverWorldProperties = server.getSaveProperties().getMainWorldProperties();
|
||||
GeneratorOptions generatorOptions = server.getSaveProperties().getGeneratorOptions();
|
||||
boolean bl = generatorOptions.isDebugWorld();
|
||||
long l = generatorOptions.getSeed();
|
||||
long m = BiomeAccess.hashSeed(l);
|
||||
List<Spawner> list = List.of();
|
||||
SimpleRegistry<DimensionOptions> simpleRegistry = generatorOptions.getDimensions();
|
||||
DimensionOptions dimensionOptions = simpleRegistry.get(DimensionOptions.OVERWORLD);
|
||||
ServerLevelData serverWorldProperties = server.getWorldData().overworldData();
|
||||
WorldGenSettings generatorOptions = server.getWorldData().worldGenSettings();
|
||||
boolean bl = generatorOptions.isDebug();
|
||||
long l = generatorOptions.seed();
|
||||
long m = BiomeManager.obfuscateSeed(l);
|
||||
List<CustomSpawner> list = List.of();
|
||||
MappedRegistry<LevelStem> simpleRegistry = generatorOptions.dimensions();
|
||||
LevelStem dimensionOptions = simpleRegistry.get(LevelStem.OVERWORLD);
|
||||
ChunkGenerator chunkGenerator2;
|
||||
DimensionType dimensionType2;
|
||||
if (dimensionOptions == null) {
|
||||
dimensionType2 = server.getRegistryManager().getMutable(Registry.DIMENSION_TYPE_KEY).getOrThrow(DimensionType.OVERWORLD_REGISTRY_KEY);
|
||||
chunkGenerator2 = GeneratorOptions.createOverworldGenerator(server.getRegistryManager(), (new Random()).nextLong());
|
||||
dimensionType2 = server.registryAccess().ownedRegistryOrThrow(Registry.DIMENSION_TYPE_REGISTRY).getOrThrow(DimensionType.OVERWORLD_LOCATION);
|
||||
chunkGenerator2 = WorldGenSettings.makeDefaultOverworld(server.registryAccess(), (new Random()).nextLong());
|
||||
} else {
|
||||
dimensionType2 = dimensionOptions.getDimensionType();
|
||||
chunkGenerator2 = dimensionOptions.getChunkGenerator();
|
||||
dimensionType2 = dimensionOptions.type();
|
||||
chunkGenerator2 = dimensionOptions.generator();
|
||||
}
|
||||
|
||||
RegistryKey<World> customWorld = RegistryKey.of(Registry.WORLD_KEY, worldId);
|
||||
ResourceKey<Level> customWorld = ResourceKey.create(Registry.DIMENSION_REGISTRY, worldId);
|
||||
|
||||
//chunkGenerator2 = GeneratorOptions.createOverworldGenerator(server.getRegistryManager().get(Registry.BIOME_KEY), server.getRegistryManager().get(Registry.NOISE_SETTINGS_WORLDGEN), (seed==null)?l:seed);
|
||||
|
||||
@@ -114,15 +113,15 @@ public class WorldTools
|
||||
// return server.getRegistryManager().get(Registry.CHUNK_GENERATOR_SETTINGS_KEY).getOrThrow(ChunkGeneratorSettings.OVERWORLD);
|
||||
//});
|
||||
|
||||
chunkGenerator2 = new NoiseChunkGenerator(server.getRegistryManager().get(Registry.NOISE_WORLDGEN), MultiNoiseBiomeSource.Preset.OVERWORLD.getBiomeSource(server.getRegistryManager().get(Registry.BIOME_KEY)), seed, () -> {
|
||||
return server.getRegistryManager().get(Registry.CHUNK_GENERATOR_SETTINGS_KEY).getOrThrow(ChunkGeneratorSettings.OVERWORLD);
|
||||
chunkGenerator2 = new NoiseBasedChunkGenerator(server.registryAccess().registryOrThrow(Registry.NOISE_REGISTRY), MultiNoiseBiomeSource.Preset.OVERWORLD.biomeSource(server.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY)), seed, () -> {
|
||||
return server.registryAccess().registryOrThrow(Registry.NOISE_GENERATOR_SETTINGS_REGISTRY).getOrThrow(NoiseGeneratorSettings.OVERWORLD);
|
||||
});
|
||||
|
||||
ServerWorld serverWorld = new ServerWorld(
|
||||
ServerLevel serverWorld = new ServerLevel(
|
||||
server,
|
||||
Util.getMainWorkerExecutor(),
|
||||
Util.backgroundExecutor(),
|
||||
((MinecraftServerInterface) server).getCMSession(),
|
||||
new UnmodifiableLevelProperties(server.getSaveProperties(), serverWorldProperties),
|
||||
new DerivedLevelData(server.getWorldData(), serverWorldProperties),
|
||||
customWorld,
|
||||
dimensionType2,
|
||||
NOOP_LISTENER,
|
||||
@@ -131,37 +130,37 @@ public class WorldTools
|
||||
(seed==null)?l:seed,
|
||||
list,
|
||||
false);
|
||||
overWorld.getWorldBorder().addListener(new WorldBorderListener.WorldBorderSyncer(serverWorld.getWorldBorder()));
|
||||
overWorld.getWorldBorder().addListener(new BorderChangeListener.DelegateBorderChangeListener(serverWorld.getWorldBorder()));
|
||||
((MinecraftServerInterface) server).getCMWorlds().put(customWorld, serverWorld);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void forceChunkUpdate(BlockPos pos, ServerWorld world)
|
||||
public static void forceChunkUpdate(BlockPos pos, ServerLevel world)
|
||||
{
|
||||
WorldChunk worldChunk = world.getChunkManager().getWorldChunk(pos.getX()>>4, pos.getZ()>>4, false);
|
||||
LevelChunk worldChunk = world.getChunkSource().getChunk(pos.getX()>>4, pos.getZ()>>4, false);
|
||||
if (worldChunk != null)
|
||||
{
|
||||
int vd = world.getServer().getPlayerManager().getViewDistance() * 16;
|
||||
int vd = world.getServer().getPlayerList().getViewDistance() * 16;
|
||||
int vvd = vd * vd;
|
||||
List<ServerPlayerEntity> nearbyPlayers = world.getPlayers(p -> pos.getSquaredDistance(p.getX(), pos.getY(), p.getZ(), true) < vvd);
|
||||
List<ServerPlayer> nearbyPlayers = world.getPlayers(p -> pos.distSqr(p.getX(), pos.getY(), p.getZ(), true) < vvd);
|
||||
if (!nearbyPlayers.isEmpty())
|
||||
{
|
||||
ChunkDataS2CPacket packet = new ChunkDataS2CPacket(worldChunk, world.getLightingProvider(), null, null, false); // false seems to update neighbours as well.
|
||||
ClientboundLevelChunkWithLightPacket packet = new ClientboundLevelChunkWithLightPacket(worldChunk, world.getLightEngine(), null, null, false); // false seems to update neighbours as well.
|
||||
ChunkPos chpos = new ChunkPos(pos);
|
||||
nearbyPlayers.forEach(p -> p.networkHandler.sendPacket(packet));
|
||||
nearbyPlayers.forEach(p -> p.connection.send(packet));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class NoopWorldGenerationProgressListener implements WorldGenerationProgressListener
|
||||
private static class NoopWorldGenerationProgressListener implements ChunkProgressListener
|
||||
{
|
||||
@Override public void start(ChunkPos spawnPos) { }
|
||||
@Override public void setChunkStatus(ChunkPos pos, ChunkStatus status) { }
|
||||
@Override public void updateSpawnPos(ChunkPos spawnPos) { }
|
||||
@Override public void onStatusChange(ChunkPos pos, ChunkStatus status) { }
|
||||
@Environment(EnvType.CLIENT)
|
||||
@Override public void start() { }
|
||||
@Override public void stop() { }
|
||||
}
|
||||
|
||||
public static final WorldGenerationProgressListener NOOP_LISTENER = new NoopWorldGenerationProgressListener();
|
||||
public static final ChunkProgressListener NOOP_LISTENER = new NoopWorldGenerationProgressListener();
|
||||
}
|
||||
@@ -7,27 +7,6 @@ import carpet.script.exception.Throwables;
|
||||
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.block.entity.BlockEntity;
|
||||
import net.minecraft.command.argument.BlockArgumentParser;
|
||||
import net.minecraft.block.Blocks;
|
||||
import net.minecraft.item.ItemPlacementContext;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.nbt.NbtString;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.state.property.Property;
|
||||
import net.minecraft.util.dynamic.GlobalPos;
|
||||
import net.minecraft.util.Hand;
|
||||
import net.minecraft.util.hit.BlockHitResult;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Direction;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.chunk.WorldChunk;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
@@ -35,22 +14,42 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.commands.arguments.blocks.BlockStateParser;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.GlobalPos;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.context.BlockPlaceContext;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
import static carpet.script.value.NBTSerializableValue.nameFromRegistryId;
|
||||
|
||||
public class BlockValue extends Value
|
||||
{
|
||||
public static final BlockValue AIR = new BlockValue(Blocks.AIR.getDefaultState(), null, BlockPos.ORIGIN);
|
||||
public static final BlockValue AIR = new BlockValue(Blocks.AIR.defaultBlockState(), null, BlockPos.ZERO);
|
||||
public static final BlockValue NULL = new BlockValue(null, null, null);
|
||||
private BlockState blockState;
|
||||
private final BlockPos pos;
|
||||
private final ServerWorld world;
|
||||
private NbtCompound data;
|
||||
private final ServerLevel world;
|
||||
private CompoundTag data;
|
||||
|
||||
public static BlockValue fromCoords(CarpetContext c, int x, int y, int z)
|
||||
{
|
||||
BlockPos pos = locateBlockPos(c, x,y,z);
|
||||
return new BlockValue(null, c.s.getWorld(), pos);
|
||||
return new BlockValue(null, c.s.getLevel(), pos);
|
||||
}
|
||||
|
||||
private static final Map<String, BlockValue> bvCache= new HashMap<>();
|
||||
@@ -60,13 +59,13 @@ public class BlockValue extends Value
|
||||
{
|
||||
BlockValue bv = bvCache.get(str);
|
||||
if (bv != null) return bv;
|
||||
BlockArgumentParser blockstateparser = (new BlockArgumentParser(new StringReader(str), false)).parse(true);
|
||||
if (blockstateparser.getBlockState() != null)
|
||||
BlockStateParser blockstateparser = (new BlockStateParser(new StringReader(str), false)).parse(true);
|
||||
if (blockstateparser.getState() != null)
|
||||
{
|
||||
NbtCompound bd = blockstateparser.getNbtData();
|
||||
CompoundTag bd = blockstateparser.getNbt();
|
||||
if (bd == null)
|
||||
bd = new NbtCompound();
|
||||
bv = new BlockValue(blockstateparser.getBlockState(), null, null, bd );
|
||||
bd = new CompoundTag();
|
||||
bv = new BlockValue(blockstateparser.getState(), null, null, bd );
|
||||
if (bvCache.size()>10000)
|
||||
bvCache.clear();
|
||||
bvCache.put(str, bv);
|
||||
@@ -98,16 +97,16 @@ public class BlockValue extends Value
|
||||
throw new InternalExpressionException("Attempted to fetch block state without world or stored block state");
|
||||
}
|
||||
|
||||
public static BlockEntity getBlockEntity(ServerWorld world, BlockPos pos)
|
||||
public static BlockEntity getBlockEntity(ServerLevel world, BlockPos pos)
|
||||
{
|
||||
if (world.getServer().isOnThread())
|
||||
if (world.getServer().isSameThread())
|
||||
return world.getBlockEntity(pos);
|
||||
else
|
||||
return world.getWorldChunk(pos).getBlockEntity(pos, WorldChunk.CreationType.IMMEDIATE);
|
||||
return world.getChunkAt(pos).getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE);
|
||||
}
|
||||
|
||||
|
||||
public NbtCompound getData()
|
||||
public CompoundTag getData()
|
||||
{
|
||||
if (data != null)
|
||||
{
|
||||
@@ -120,17 +119,17 @@ public class BlockValue extends Value
|
||||
BlockEntity be = getBlockEntity(world, pos);
|
||||
if (be == null)
|
||||
{
|
||||
data = new NbtCompound();
|
||||
data = new CompoundTag();
|
||||
return null;
|
||||
}
|
||||
data = be.createNbt();
|
||||
data = be.saveWithoutMetadata();
|
||||
return data;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public BlockValue(BlockState state, ServerWorld world, BlockPos position)
|
||||
public BlockValue(BlockState state, ServerLevel world, BlockPos position)
|
||||
{
|
||||
this.world = world;
|
||||
blockState = state;
|
||||
@@ -138,7 +137,7 @@ public class BlockValue extends Value
|
||||
data = null;
|
||||
}
|
||||
|
||||
public BlockValue(BlockState state, ServerWorld world, BlockPos position, NbtCompound nbt)
|
||||
public BlockValue(BlockState state, ServerLevel world, BlockPos position, CompoundTag nbt)
|
||||
{
|
||||
this.world = world;
|
||||
blockState = state;
|
||||
@@ -150,7 +149,7 @@ public class BlockValue extends Value
|
||||
@Override
|
||||
public String getString()
|
||||
{
|
||||
return nameFromRegistryId(Registry.BLOCK.getId(getBlockState().getBlock()));
|
||||
return nameFromRegistryId(Registry.BLOCK.getKey(getBlockState().getBlock()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -175,7 +174,7 @@ public class BlockValue extends Value
|
||||
public int hashCode()
|
||||
{
|
||||
if (world != null && pos != null )
|
||||
return GlobalPos.create(world.getRegistryKey() , pos).hashCode(); //getDimension().getType()
|
||||
return GlobalPos.of(world.dimension() , pos).hashCode(); //getDimension().getType()
|
||||
return ("b"+getString()).hashCode();
|
||||
}
|
||||
|
||||
@@ -184,29 +183,29 @@ public class BlockValue extends Value
|
||||
return pos;
|
||||
}
|
||||
|
||||
public ServerWorld getWorld() { return world;}
|
||||
public ServerLevel getWorld() { return world;}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this);
|
||||
// follows falling block convertion
|
||||
NbtCompound tag = new NbtCompound();
|
||||
NbtCompound state = new NbtCompound();
|
||||
CompoundTag tag = new CompoundTag();
|
||||
CompoundTag state = new CompoundTag();
|
||||
BlockState s = getBlockState();
|
||||
state.put("Name", NbtString.of(Registry.BLOCK.getId(s.getBlock()).toString()));
|
||||
state.put("Name", StringTag.valueOf(Registry.BLOCK.getKey(s.getBlock()).toString()));
|
||||
Collection<Property<?>> properties = s.getProperties();
|
||||
if (!properties.isEmpty())
|
||||
{
|
||||
NbtCompound props = new NbtCompound();
|
||||
CompoundTag props = new CompoundTag();
|
||||
for (Property<?> p: properties)
|
||||
{
|
||||
props.put(p.getName(), NbtString.of(s.get(p).toString().toLowerCase(Locale.ROOT)));
|
||||
props.put(p.getName(), StringTag.valueOf(s.getValue(p).toString().toLowerCase(Locale.ROOT)));
|
||||
}
|
||||
state.put("Properties", props);
|
||||
}
|
||||
tag.put("BlockState", state);
|
||||
NbtCompound dataTag = getData();
|
||||
CompoundTag dataTag = getData();
|
||||
if (dataTag != null)
|
||||
{
|
||||
tag.put("TileEntityData", dataTag);
|
||||
@@ -241,7 +240,7 @@ public class BlockValue extends Value
|
||||
WESTUP("west-up", 1.0, 0.6, 0.5, Direction.WEST);
|
||||
|
||||
public final String name;
|
||||
public final Vec3d hitOffset;
|
||||
public final Vec3 hitOffset;
|
||||
public final Direction facing;
|
||||
|
||||
private static final Map<String, SpecificDirection> DIRECTION_MAP = Arrays.stream(values()).collect(Collectors.toMap(SpecificDirection::getName, d -> d));
|
||||
@@ -250,7 +249,7 @@ public class BlockValue extends Value
|
||||
SpecificDirection(String name, double hitx, double hity, double hitz, Direction blockFacing)
|
||||
{
|
||||
this.name = name;
|
||||
this.hitOffset = new Vec3d(hitx, hity, hitz);
|
||||
this.hitOffset = new Vec3(hitx, hity, hitz);
|
||||
this.facing = blockFacing;
|
||||
}
|
||||
private String getName()
|
||||
@@ -259,40 +258,40 @@ public class BlockValue extends Value
|
||||
}
|
||||
}
|
||||
|
||||
public static class PlacementContext extends ItemPlacementContext {
|
||||
public static class PlacementContext extends BlockPlaceContext {
|
||||
private final Direction facing;
|
||||
private final boolean sneakPlace;
|
||||
|
||||
public static PlacementContext from(World world, BlockPos pos, String direction, boolean sneakPlace, ItemStack itemStack)
|
||||
public static PlacementContext from(Level world, BlockPos pos, String direction, boolean sneakPlace, ItemStack itemStack)
|
||||
{
|
||||
SpecificDirection dir = SpecificDirection.DIRECTION_MAP.get(direction);
|
||||
if (dir == null)
|
||||
throw new InternalExpressionException("unknown block placement direction: "+direction);
|
||||
BlockHitResult hitres = new BlockHitResult(Vec3d.of(pos).add(dir.hitOffset), dir.facing, pos, false);
|
||||
BlockHitResult hitres = new BlockHitResult(Vec3.atLowerCornerOf(pos).add(dir.hitOffset), dir.facing, pos, false);
|
||||
return new PlacementContext(world, dir.facing, sneakPlace, itemStack, hitres);
|
||||
}
|
||||
private PlacementContext(World world_1, Direction direction_1, boolean sneakPlace, ItemStack itemStack_1, BlockHitResult hitres) {
|
||||
super(world_1, null, Hand.MAIN_HAND, itemStack_1, hitres);
|
||||
private PlacementContext(Level world_1, Direction direction_1, boolean sneakPlace, ItemStack itemStack_1, BlockHitResult hitres) {
|
||||
super(world_1, null, InteractionHand.MAIN_HAND, itemStack_1, hitres);
|
||||
this.facing = direction_1;
|
||||
this.sneakPlace = sneakPlace;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockPos getBlockPos() {
|
||||
boolean prevcanReplaceExisting = canReplaceExisting;
|
||||
canReplaceExisting = true;
|
||||
BlockPos ret = super.getBlockPos();
|
||||
canReplaceExisting = prevcanReplaceExisting;
|
||||
public BlockPos getClickedPos() {
|
||||
boolean prevcanReplaceExisting = replaceClicked;
|
||||
replaceClicked = true;
|
||||
BlockPos ret = super.getClickedPos();
|
||||
replaceClicked = prevcanReplaceExisting;
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Direction getPlayerLookDirection() {
|
||||
public Direction getNearestLookingDirection() {
|
||||
return facing.getOpposite();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Direction[] getPlacementDirections() {
|
||||
public Direction[] getNearestLookingDirections() {
|
||||
switch(this.facing) {
|
||||
case DOWN:
|
||||
default:
|
||||
@@ -311,18 +310,18 @@ public class BlockValue extends Value
|
||||
}
|
||||
|
||||
@Override
|
||||
public Direction getPlayerFacing() {
|
||||
public Direction getHorizontalDirection() {
|
||||
return this.facing.getAxis() == Direction.Axis.Y ? Direction.NORTH : this.facing;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldCancelInteraction() {
|
||||
public boolean isSecondaryUseActive() {
|
||||
return sneakPlace;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getPlayerYaw() {
|
||||
return (float)(this.facing.getHorizontal() * 90);
|
||||
public float getRotation() {
|
||||
return (float)(this.facing.get2DDataValue() * 90);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@ package carpet.script.value;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import net.minecraft.nbt.NbtByte;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.nbt.ByteTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
public class BooleanValue extends NumericValue
|
||||
{
|
||||
@@ -47,8 +47,8 @@ public class BooleanValue extends NumericValue
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force) {
|
||||
return NbtByte.of(boolValue);
|
||||
public Tag toTag(boolean force) {
|
||||
return ByteTag.valueOf(boolValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,36 +1,36 @@
|
||||
package carpet.script.value;
|
||||
|
||||
import net.minecraft.nbt.NbtString;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.text.BaseText;
|
||||
import net.minecraft.text.LiteralText;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.network.chat.BaseComponent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
|
||||
public class FormattedTextValue extends StringValue
|
||||
{
|
||||
Text text;
|
||||
public FormattedTextValue(Text text)
|
||||
Component text;
|
||||
public FormattedTextValue(Component text)
|
||||
{
|
||||
super(null);
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public static Value combine(Value left, Value right) {
|
||||
BaseText text;
|
||||
BaseComponent text;
|
||||
if (left instanceof FormattedTextValue)
|
||||
{
|
||||
text = (BaseText) ((FormattedTextValue) left).getText().shallowCopy();
|
||||
text = (BaseComponent) ((FormattedTextValue) left).getText().copy();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (left instanceof NullValue)
|
||||
return right;
|
||||
text = new LiteralText(left.getString());
|
||||
text = new TextComponent(left.getString());
|
||||
}
|
||||
|
||||
if (right instanceof FormattedTextValue)
|
||||
{
|
||||
text.append(((FormattedTextValue) right).getText().shallowCopy());
|
||||
text.append(((FormattedTextValue) right).getText().copy());
|
||||
return new FormattedTextValue(text);
|
||||
}
|
||||
else
|
||||
@@ -42,7 +42,7 @@ public class FormattedTextValue extends StringValue
|
||||
}
|
||||
}
|
||||
|
||||
public static Value of(Text text) {
|
||||
public static Value of(Component text) {
|
||||
if (text == null) return Value.NULL;
|
||||
return new FormattedTextValue(text);
|
||||
}
|
||||
@@ -69,16 +69,16 @@ public class FormattedTextValue extends StringValue
|
||||
return "text";
|
||||
}
|
||||
|
||||
public Text getText()
|
||||
public Component getText()
|
||||
{
|
||||
return text;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this);
|
||||
return NbtString.of(Text.Serializer.toJson(text));
|
||||
return StringTag.valueOf(Component.Serializer.toJson(text));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -88,16 +88,16 @@ public class FormattedTextValue extends StringValue
|
||||
|
||||
public String serialize()
|
||||
{
|
||||
return Text.Serializer.toJson(text);
|
||||
return Component.Serializer.toJson(text);
|
||||
}
|
||||
|
||||
public static FormattedTextValue deserialize(String serialized)
|
||||
{
|
||||
return new FormattedTextValue(Text.Serializer.fromJson(serialized));
|
||||
return new FormattedTextValue(Component.Serializer.fromJson(serialized));
|
||||
}
|
||||
|
||||
public static Text getTextByValue(Value value) {
|
||||
return (value instanceof FormattedTextValue) ? ((FormattedTextValue) value).getText() : new LiteralText(value.getString());
|
||||
public static Component getTextByValue(Value value) {
|
||||
return (value instanceof FormattedTextValue) ? ((FormattedTextValue) value).getText() : new TextComponent(value.getString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package carpet.script.value;
|
||||
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
public abstract class FrameworkValue extends Value
|
||||
{
|
||||
@@ -29,7 +29,7 @@ public abstract class FrameworkValue extends Value
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
throw new UnsupportedOperationException("Scarpet language component cannot be serialized to the tag");
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package carpet.script.value;
|
||||
|
||||
import carpet.script.exception.InternalExpressionException;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
public class FunctionAnnotationValue extends Value
|
||||
{
|
||||
@@ -37,7 +37,7 @@ public class FunctionAnnotationValue extends Value
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
throw new UnsupportedOperationException("Global value cannot be serialized to the tag");
|
||||
}
|
||||
|
||||
@@ -12,15 +12,14 @@ import carpet.script.exception.ContinueStatement;
|
||||
import carpet.script.exception.ExpressionException;
|
||||
import carpet.script.exception.InternalExpressionException;
|
||||
import carpet.script.exception.ReturnStatement;
|
||||
import net.minecraft.nbt.NbtString;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
public class FunctionValue extends Value implements Fluff.ILazyFunction
|
||||
{
|
||||
@@ -281,10 +280,10 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
|
||||
public String getVarArgs() {return varArgs; }
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this);
|
||||
return NbtString.of(getString());
|
||||
return StringTag.valueOf(getString());
|
||||
}
|
||||
|
||||
public void assertArgsOk(List<?> list, Consumer<Boolean> feedback)
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
package carpet.script.value;
|
||||
|
||||
import carpet.script.exception.InternalExpressionException;
|
||||
import net.minecraft.nbt.NbtString;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
public abstract class LazyListValue extends AbstractListValue implements Iterator<Value>
|
||||
{
|
||||
@@ -204,9 +203,9 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this);
|
||||
return NbtString.of(getString());
|
||||
return StringTag.valueOf(getString());
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,6 @@ import carpet.script.LazyValue;
|
||||
import carpet.script.exception.InternalExpressionException;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import net.minecraft.nbt.AbstractNbtNumber;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.nbt.NbtDouble;
|
||||
import net.minecraft.nbt.NbtInt;
|
||||
import net.minecraft.nbt.NbtList;
|
||||
import net.minecraft.nbt.NbtLong;
|
||||
import net.minecraft.nbt.NbtString;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
@@ -23,6 +14,14 @@ import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.StreamSupport;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.DoubleTag;
|
||||
import net.minecraft.nbt.IntTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.nbt.LongTag;
|
||||
import net.minecraft.nbt.NumericTag;
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
import static java.lang.Math.abs;
|
||||
|
||||
@@ -484,31 +483,31 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
|
||||
LIST,
|
||||
MAP,
|
||||
STRING;
|
||||
private static TagTypeCompat getType(NbtElement tag)
|
||||
private static TagTypeCompat getType(Tag tag)
|
||||
{
|
||||
if (tag instanceof NbtInt) return INT;
|
||||
if (tag instanceof NbtLong) return LONG;
|
||||
if (tag instanceof NbtDouble) return DBL;
|
||||
if (tag instanceof NbtList) return LIST;
|
||||
if (tag instanceof NbtCompound) return MAP;
|
||||
if (tag instanceof IntTag) return INT;
|
||||
if (tag instanceof LongTag) return LONG;
|
||||
if (tag instanceof DoubleTag) return DBL;
|
||||
if (tag instanceof ListTag) return LIST;
|
||||
if (tag instanceof CompoundTag) return MAP;
|
||||
return STRING;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
int argSize = items.size();
|
||||
if (argSize == 0) return new NbtList();
|
||||
NbtList tag = new NbtList();
|
||||
if (argSize == 0) return new ListTag();
|
||||
ListTag tag = new ListTag();
|
||||
if (argSize ==1)
|
||||
{
|
||||
tag.add(items.get(0).toTag(force));
|
||||
return tag;
|
||||
}
|
||||
// figuring out the types
|
||||
List<NbtElement> tags= new ArrayList<>();
|
||||
List<Tag> tags= new ArrayList<>();
|
||||
items.forEach(v -> tags.add(v.toTag(force)));
|
||||
Set<TagTypeCompat> cases = EnumSet.noneOf(TagTypeCompat.class);
|
||||
tags.forEach(t -> cases.add(TagTypeCompat.getType(t)));
|
||||
@@ -522,17 +521,17 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
|
||||
|| cases.contains(TagTypeCompat.STRING)) // incompatible types
|
||||
{
|
||||
if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this);
|
||||
tags.forEach(t -> tag.add(NbtString.of(t.asString())));
|
||||
tags.forEach(t -> tag.add(StringTag.valueOf(t.getAsString())));
|
||||
return tag;
|
||||
}
|
||||
// only numbers / mixed types
|
||||
if (cases.contains(TagTypeCompat.DBL))
|
||||
{
|
||||
tags.forEach(t -> tag.add(NbtDouble.of(((AbstractNbtNumber)t).doubleValue())));
|
||||
tags.forEach(t -> tag.add(DoubleTag.valueOf(((NumericTag)t).getAsDouble())));
|
||||
}
|
||||
else
|
||||
{
|
||||
tags.forEach(t -> tag.add(NbtLong.of(((AbstractNbtNumber)t).longValue())));
|
||||
tags.forEach(t -> tag.add(LongTag.valueOf(((NumericTag)t).getAsLong())));
|
||||
}
|
||||
return tag;
|
||||
}
|
||||
|
||||
@@ -3,9 +3,6 @@ package carpet.script.value;
|
||||
import carpet.script.exception.InternalExpressionException;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
@@ -14,6 +11,8 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
public class MapValue extends AbstractListValue implements ContainerValueInterface
|
||||
{
|
||||
@@ -260,9 +259,9 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
NbtCompound tag = new NbtCompound() ;
|
||||
CompoundTag tag = new CompoundTag() ;
|
||||
map.forEach( (k, v) ->
|
||||
{
|
||||
if (!force && !(k instanceof StringValue)) throw new NBTSerializableValue.IncompatibleTypeException(k);
|
||||
|
||||
@@ -8,38 +8,6 @@ import carpet.script.exception.Throwables;
|
||||
import carpet.script.utils.EquipmentInventory;
|
||||
import com.mojang.brigadier.StringReader;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.block.ChestBlock;
|
||||
import net.minecraft.block.InventoryProvider;
|
||||
import net.minecraft.block.entity.BlockEntity;
|
||||
import net.minecraft.block.entity.ChestBlockEntity;
|
||||
import net.minecraft.command.argument.ItemStackArgument;
|
||||
import net.minecraft.command.argument.ItemStringReader;
|
||||
import net.minecraft.command.argument.NbtPathArgumentType;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.InventoryOwner;
|
||||
import net.minecraft.entity.LivingEntity;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.inventory.Inventory;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.AbstractNbtList;
|
||||
import net.minecraft.nbt.AbstractNbtNumber;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.nbt.NbtEnd;
|
||||
import net.minecraft.nbt.NbtInt;
|
||||
import net.minecraft.nbt.NbtList;
|
||||
import net.minecraft.nbt.NbtLong;
|
||||
import net.minecraft.nbt.StringNbtReader;
|
||||
import net.minecraft.nbt.NbtString;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.predicate.entity.EntityPredicates;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
import net.minecraft.util.Identifier;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Box;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
@@ -50,12 +18,43 @@ import java.util.function.Supplier;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.commands.arguments.NbtPathArgument;
|
||||
import net.minecraft.commands.arguments.item.ItemInput;
|
||||
import net.minecraft.commands.arguments.item.ItemParser;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.nbt.CollectionTag;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.EndTag;
|
||||
import net.minecraft.nbt.IntTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.nbt.LongTag;
|
||||
import net.minecraft.nbt.NumericTag;
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.nbt.TagParser;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.Container;
|
||||
import net.minecraft.world.WorldlyContainerHolder;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntitySelector;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.npc.InventoryCarrier;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.ChestBlock;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.ChestBlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
|
||||
public class NBTSerializableValue extends Value implements ContainerValueInterface
|
||||
{
|
||||
private String nbtString = null;
|
||||
private NbtElement nbtTag = null;
|
||||
private Supplier<NbtElement> nbtSupplier = null;
|
||||
private Tag nbtTag = null;
|
||||
private Supplier<Tag> nbtSupplier = null;
|
||||
private boolean owned = false;
|
||||
|
||||
private NBTSerializableValue() {}
|
||||
@@ -66,7 +65,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
{
|
||||
try
|
||||
{
|
||||
return (new StringNbtReader(new StringReader(nbtString))).parseElement();
|
||||
return (new TagParser(new StringReader(nbtString))).readValue();
|
||||
}
|
||||
catch (CommandSyntaxException e)
|
||||
{
|
||||
@@ -76,35 +75,35 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
owned = true;
|
||||
}
|
||||
|
||||
public NBTSerializableValue(NbtElement tag)
|
||||
public NBTSerializableValue(Tag tag)
|
||||
{
|
||||
nbtTag = tag;
|
||||
owned = true;
|
||||
}
|
||||
|
||||
public static Value of(NbtElement tag)
|
||||
public static Value of(Tag tag)
|
||||
{
|
||||
if (tag == null) return Value.NULL;
|
||||
return new NBTSerializableValue(tag);
|
||||
}
|
||||
|
||||
public NBTSerializableValue(Supplier<NbtElement> tagSupplier)
|
||||
public NBTSerializableValue(Supplier<Tag> tagSupplier)
|
||||
{
|
||||
nbtSupplier = tagSupplier;
|
||||
}
|
||||
|
||||
public static Value fromStack(ItemStack stack)
|
||||
{
|
||||
if (stack.hasNbt())
|
||||
if (stack.hasTag())
|
||||
{
|
||||
NBTSerializableValue value = new NBTSerializableValue();
|
||||
value.nbtSupplier = stack::getNbt;
|
||||
value.nbtSupplier = stack::getTag;
|
||||
return value;
|
||||
}
|
||||
return Value.NULL;
|
||||
}
|
||||
|
||||
public static String nameFromRegistryId(Identifier id)
|
||||
public static String nameFromRegistryId(ResourceLocation id)
|
||||
{
|
||||
if (id == null) // should be Value.NULL
|
||||
return "";
|
||||
@@ -115,10 +114,10 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
|
||||
public static NBTSerializableValue parseString(String nbtString, boolean fail)
|
||||
{
|
||||
NbtElement tag;
|
||||
Tag tag;
|
||||
try
|
||||
{
|
||||
tag = (new StringNbtReader(new StringReader(nbtString))).parseElement();
|
||||
tag = (new TagParser(new StringReader(nbtString))).readValue();
|
||||
}
|
||||
catch (CommandSyntaxException e)
|
||||
{
|
||||
@@ -157,33 +156,33 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
}
|
||||
|
||||
// stolen from HopperBlockEntity, adjusted for threaded operation
|
||||
public static Inventory getInventoryAt(ServerWorld world, BlockPos blockPos)
|
||||
public static Container getInventoryAt(ServerLevel world, BlockPos blockPos)
|
||||
{
|
||||
Inventory inventory = null;
|
||||
Container inventory = null;
|
||||
BlockState blockState = world.getBlockState(blockPos);
|
||||
Block block = blockState.getBlock();
|
||||
if (block instanceof InventoryProvider) {
|
||||
inventory = ((InventoryProvider)block).getInventory(blockState, world, blockPos);
|
||||
if (block instanceof WorldlyContainerHolder) {
|
||||
inventory = ((WorldlyContainerHolder)block).getContainer(blockState, world, blockPos);
|
||||
} else if (blockState.hasBlockEntity()) {
|
||||
BlockEntity blockEntity = BlockValue.getBlockEntity(world, blockPos);
|
||||
if (blockEntity instanceof Inventory) {
|
||||
inventory = (Inventory)blockEntity;
|
||||
if (blockEntity instanceof Container) {
|
||||
inventory = (Container)blockEntity;
|
||||
if (inventory instanceof ChestBlockEntity && block instanceof ChestBlock) {
|
||||
inventory = ChestBlock.getInventory((ChestBlock)block, blockState, world, blockPos, true);
|
||||
inventory = ChestBlock.getContainer((ChestBlock)block, blockState, world, blockPos, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (inventory == null) {
|
||||
List<Entity> list = world.getOtherEntities(
|
||||
null,
|
||||
new Box(
|
||||
List<Entity> list = world.getEntities(
|
||||
(Entity)null, //TODO check this matches the correct method
|
||||
new AABB(
|
||||
blockPos.getX() - 0.5D, blockPos.getY() - 0.5D, blockPos.getZ() - 0.5D,
|
||||
blockPos.getX() + 0.5D, blockPos.getY() + 0.5D, blockPos.getZ() + 0.5D),
|
||||
EntityPredicates.VALID_INVENTORIES
|
||||
EntitySelector.CONTAINER_ENTITY_SELECTOR
|
||||
);
|
||||
if (!list.isEmpty()) {
|
||||
inventory = (Inventory)list.get(world.random.nextInt(list.size()));
|
||||
inventory = (Container)list.get(world.random.nextInt(list.size()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,9 +205,9 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
if (strVal.equals("enderchest"))
|
||||
{
|
||||
Value v2 = params.get(1 + offset);
|
||||
ServerPlayerEntity player = EntityValue.getPlayerByValue(c.s.getServer(), v2);
|
||||
ServerPlayer player = EntityValue.getPlayerByValue(c.s.getServer(), v2);
|
||||
if (player == null) throw new InternalExpressionException("enderchest inventory requires player argument");
|
||||
return new InventoryLocator(player, player.getBlockPos(), player.getEnderChestInventory(), offset + 2, true);
|
||||
return new InventoryLocator(player, player.blockPosition(), player.getEnderChestInventory(), offset + 2, true);
|
||||
}
|
||||
if (strVal.equals("equipment"))
|
||||
{
|
||||
@@ -216,15 +215,15 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
if (!(v2 instanceof EntityValue)) throw new InternalExpressionException("Equipment inventory requires a living entity argument");
|
||||
Entity e = ((EntityValue) v2).getEntity();
|
||||
if (!(e instanceof LivingEntity)) throw new InternalExpressionException("Equipment inventory requires a living entity argument");
|
||||
return new InventoryLocator(e, e.getBlockPos(), new EquipmentInventory((LivingEntity) e), offset + 2);
|
||||
return new InventoryLocator(e, e.blockPosition(), new EquipmentInventory((LivingEntity) e), offset + 2);
|
||||
}
|
||||
boolean isEnder = strVal.startsWith("enderchest_");
|
||||
if (isEnder) strVal = strVal.substring(11); // len("enderchest_")
|
||||
ServerPlayerEntity player = c.s.getServer().getPlayerManager().getPlayer(strVal);
|
||||
ServerPlayer player = c.s.getServer().getPlayerList().getPlayerByName(strVal);
|
||||
if (player == null) throw new InternalExpressionException("String description of an inventory should either denote a player or player's enderchest");
|
||||
return new InventoryLocator(
|
||||
player,
|
||||
player.getBlockPos(),
|
||||
player.blockPosition(),
|
||||
isEnder ? player.getEnderChestInventory() : player.getInventory(),
|
||||
offset + 1,
|
||||
isEnder
|
||||
@@ -232,24 +231,24 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
}
|
||||
if (v1 instanceof EntityValue)
|
||||
{
|
||||
Inventory inv = null;
|
||||
Container inv = null;
|
||||
Entity e = ((EntityValue) v1).getEntity();
|
||||
if (e instanceof PlayerEntity pe) inv = pe.getInventory();
|
||||
else if (e instanceof Inventory) inv = (Inventory) e;
|
||||
else if (e instanceof InventoryOwner io) inv = io.getInventory();
|
||||
if (e instanceof Player pe) inv = pe.getInventory();
|
||||
else if (e instanceof Container) inv = (Container) e;
|
||||
else if (e instanceof InventoryCarrier io) inv = io.getInventory();
|
||||
else if (e instanceof InventoryBearerInterface ibi) inv = ibi.getCMInventory(); // horse only
|
||||
else if (e instanceof LivingEntity le) return new InventoryLocator(e, e.getBlockPos(), new EquipmentInventory(le), offset+1);
|
||||
else if (e instanceof LivingEntity le) return new InventoryLocator(e, e.blockPosition(), new EquipmentInventory(le), offset+1);
|
||||
if (inv == null)
|
||||
return null;
|
||||
|
||||
return new InventoryLocator(e, e.getBlockPos(), inv, offset+1);
|
||||
return new InventoryLocator(e, e.blockPosition(), inv, offset+1);
|
||||
}
|
||||
if (v1 instanceof BlockValue)
|
||||
{
|
||||
BlockPos pos = ((BlockValue) v1).getPos();
|
||||
if (pos == null)
|
||||
throw new InternalExpressionException("Block to access inventory needs to be positioned in the world");
|
||||
Inventory inv = getInventoryAt(c.s.getWorld(), pos);
|
||||
Container inv = getInventoryAt(c.s.getLevel(), pos);
|
||||
if (inv == null)
|
||||
return null;
|
||||
return new InventoryLocator(pos, pos, inv, offset+1);
|
||||
@@ -261,7 +260,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
NumericValue.asNumber(args.get(0)).getDouble(),
|
||||
NumericValue.asNumber(args.get(1)).getDouble(),
|
||||
NumericValue.asNumber(args.get(2)).getDouble());
|
||||
Inventory inv = getInventoryAt(c.s.getWorld(), pos);
|
||||
Container inv = getInventoryAt(c.s.getLevel(), pos);
|
||||
if (inv == null)
|
||||
return null;
|
||||
return new InventoryLocator(pos, pos, inv, offset+1);
|
||||
@@ -269,13 +268,13 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
if (v1 instanceof ScreenValue screenValue)
|
||||
{
|
||||
if(!screenValue.isOpen()) return null;
|
||||
return new InventoryLocator(screenValue.getPlayer(), screenValue.getPlayer().getBlockPos(), screenValue.getInventory(), offset+1);
|
||||
return new InventoryLocator(screenValue.getPlayer(), screenValue.getPlayer().blockPosition(), screenValue.getInventory(), offset+1);
|
||||
}
|
||||
BlockPos pos = new BlockPos(
|
||||
NumericValue.asNumber(v1).getDouble(),
|
||||
NumericValue.asNumber(params.get(1 + offset)).getDouble(),
|
||||
NumericValue.asNumber(params.get(2 + offset)).getDouble());
|
||||
Inventory inv = getInventoryAt(c.s.getWorld(), pos);
|
||||
Container inv = getInventoryAt(c.s.getLevel(), pos);
|
||||
if (inv == null)
|
||||
return null;
|
||||
return new InventoryLocator(pos, pos, inv, offset + 3);
|
||||
@@ -286,33 +285,33 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
}
|
||||
}
|
||||
|
||||
private static final Map<String,ItemStackArgument> itemCache = new HashMap<>();
|
||||
private static final Map<String,ItemInput> itemCache = new HashMap<>();
|
||||
|
||||
public static ItemStackArgument parseItem(String itemString)
|
||||
public static ItemInput parseItem(String itemString)
|
||||
{
|
||||
return parseItem(itemString, null);
|
||||
}
|
||||
|
||||
public static ItemStackArgument parseItem(String itemString, NbtCompound customTag)
|
||||
public static ItemInput parseItem(String itemString, CompoundTag customTag)
|
||||
{
|
||||
try
|
||||
{
|
||||
ItemStackArgument res = itemCache.get(itemString);
|
||||
ItemInput res = itemCache.get(itemString);
|
||||
if (res != null)
|
||||
if (customTag == null)
|
||||
return res;
|
||||
else
|
||||
return new ItemStackArgument(res.getItem(), customTag);
|
||||
return new ItemInput(res.getItem(), customTag);
|
||||
|
||||
ItemStringReader parser = (new ItemStringReader(new StringReader(itemString), false)).consume();
|
||||
res = new ItemStackArgument(parser.getItem(), parser.getNbt());
|
||||
ItemParser parser = (new ItemParser(new StringReader(itemString), false)).parse();
|
||||
res = new ItemInput(parser.getItem(), parser.getNbt());
|
||||
itemCache.put(itemString, res);
|
||||
if (itemCache.size()>64000)
|
||||
itemCache.clear();
|
||||
if (customTag == null)
|
||||
return res;
|
||||
else
|
||||
return new ItemStackArgument(res.getItem(), customTag);
|
||||
return new ItemInput(res.getItem(), customTag);
|
||||
}
|
||||
catch (CommandSyntaxException e)
|
||||
{
|
||||
@@ -320,59 +319,59 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
}
|
||||
}
|
||||
|
||||
public static int validateSlot(int slot, Inventory inv)
|
||||
public static int validateSlot(int slot, Container inv)
|
||||
{
|
||||
int invSize = inv.size();
|
||||
int invSize = inv.getContainerSize();
|
||||
if (slot < 0)
|
||||
slot = invSize + slot;
|
||||
if (slot < 0 || slot >= invSize)
|
||||
return inv.size(); // outside of inventory
|
||||
return inv.getContainerSize(); // outside of inventory
|
||||
return slot;
|
||||
}
|
||||
|
||||
private static Value decodeSimpleTag(NbtElement t)
|
||||
private static Value decodeSimpleTag(Tag t)
|
||||
{
|
||||
if (t instanceof AbstractNbtNumber)
|
||||
if (t instanceof NumericTag)
|
||||
{
|
||||
if (t instanceof NbtLong || t instanceof NbtInt) // short and byte will never exceed float's precision, even int won't
|
||||
if (t instanceof LongTag || t instanceof IntTag) // short and byte will never exceed float's precision, even int won't
|
||||
{
|
||||
return NumericValue.of(((AbstractNbtNumber) t).longValue());
|
||||
return NumericValue.of(((NumericTag) t).getAsLong());
|
||||
}
|
||||
return NumericValue.of(((AbstractNbtNumber) t).numberValue());
|
||||
return NumericValue.of(((NumericTag) t).getAsNumber());
|
||||
}
|
||||
if (t instanceof NbtString)
|
||||
return StringValue.of(t.asString());
|
||||
if (t instanceof NbtEnd)
|
||||
if (t instanceof StringTag)
|
||||
return StringValue.of(t.getAsString());
|
||||
if (t instanceof EndTag)
|
||||
return Value.NULL;
|
||||
|
||||
throw new InternalExpressionException("How did we get here: Unknown nbt element class: "+t.getNbtType().getCrashReportName());
|
||||
throw new InternalExpressionException("How did we get here: Unknown nbt element class: "+t.getType().getName());
|
||||
|
||||
}
|
||||
|
||||
private static Value decodeTag(NbtElement t)
|
||||
private static Value decodeTag(Tag t)
|
||||
{
|
||||
if (t instanceof NbtCompound || t instanceof AbstractNbtList)
|
||||
if (t instanceof CompoundTag || t instanceof CollectionTag)
|
||||
return new NBTSerializableValue(() -> t);
|
||||
return decodeSimpleTag(t);
|
||||
}
|
||||
|
||||
private static Value decodeTagDeep(NbtElement t)
|
||||
private static Value decodeTagDeep(Tag t)
|
||||
{
|
||||
if (t instanceof NbtCompound)
|
||||
if (t instanceof CompoundTag)
|
||||
{
|
||||
Map<Value, Value> pairs = new HashMap<>();
|
||||
NbtCompound ctag = (NbtCompound)t;
|
||||
for (String key: ctag.getKeys())
|
||||
CompoundTag ctag = (CompoundTag)t;
|
||||
for (String key: ctag.getAllKeys())
|
||||
{
|
||||
pairs.put(new StringValue(key), decodeTagDeep(ctag.get(key)));
|
||||
}
|
||||
return MapValue.wrap(pairs);
|
||||
}
|
||||
if (t instanceof AbstractNbtList)
|
||||
if (t instanceof CollectionTag)
|
||||
{
|
||||
List<Value> elems = new ArrayList<>();
|
||||
AbstractNbtList<? extends NbtElement> ltag = (AbstractNbtList<? extends NbtElement>)t;
|
||||
for (NbtElement elem: ltag)
|
||||
CollectionTag<? extends Tag> ltag = (CollectionTag<? extends Tag>)t;
|
||||
for (Tag elem: ltag)
|
||||
{
|
||||
elems.add(decodeTagDeep(elem));
|
||||
}
|
||||
@@ -395,7 +394,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
return NBTSerializableValue.parseString(v.getString(), true);
|
||||
}
|
||||
|
||||
public NbtElement getTag()
|
||||
public Tag getTag()
|
||||
{
|
||||
if (nbtTag == null)
|
||||
nbtTag = nbtSupplier.get();
|
||||
@@ -421,24 +420,24 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
@Override
|
||||
public boolean getBoolean()
|
||||
{
|
||||
NbtElement tag = getTag();
|
||||
if (tag instanceof NbtCompound)
|
||||
return !((NbtCompound) tag).isEmpty();
|
||||
if (tag instanceof AbstractNbtList)
|
||||
return !((AbstractNbtList<?>) tag).isEmpty();
|
||||
if (tag instanceof AbstractNbtNumber)
|
||||
return ((AbstractNbtNumber) tag).doubleValue()!=0.0;
|
||||
if (tag instanceof NbtString)
|
||||
return !tag.asString().isEmpty();
|
||||
Tag tag = getTag();
|
||||
if (tag instanceof CompoundTag)
|
||||
return !((CompoundTag) tag).isEmpty();
|
||||
if (tag instanceof CollectionTag)
|
||||
return !((CollectionTag<?>) tag).isEmpty();
|
||||
if (tag instanceof NumericTag)
|
||||
return ((NumericTag) tag).getAsDouble()!=0.0;
|
||||
if (tag instanceof StringTag)
|
||||
return !tag.getAsString().isEmpty();
|
||||
return true;
|
||||
}
|
||||
|
||||
public NbtCompound getCompoundTag()
|
||||
public CompoundTag getCompoundTag()
|
||||
{
|
||||
try
|
||||
{
|
||||
ensureOwnership();
|
||||
return (NbtCompound) getTag();
|
||||
return (CompoundTag) getTag();
|
||||
}
|
||||
catch (ClassCastException e)
|
||||
{
|
||||
@@ -457,8 +456,8 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
{
|
||||
/// WIP
|
||||
ensureOwnership();
|
||||
NbtPathArgumentType.NbtPath path = cachePath(where.getString());
|
||||
NbtElement tagToInsert = value instanceof NBTSerializableValue ?
|
||||
NbtPathArgument.NbtPath path = cachePath(where.getString());
|
||||
Tag tagToInsert = value instanceof NBTSerializableValue ?
|
||||
((NBTSerializableValue) value).getTag() :
|
||||
new NBTSerializableValue(value.getString()).getTag();
|
||||
boolean modifiedTag;
|
||||
@@ -488,17 +487,17 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
|
||||
|
||||
|
||||
private boolean modify_insert(int index, NbtPathArgumentType.NbtPath nbtPath, NbtElement newElement)
|
||||
private boolean modify_insert(int index, NbtPathArgument.NbtPath nbtPath, Tag newElement)
|
||||
{
|
||||
return modify_insert(index, nbtPath, newElement, this.getTag());
|
||||
}
|
||||
|
||||
private boolean modify_insert(int index, NbtPathArgumentType.NbtPath nbtPath, NbtElement newElement, NbtElement currentTag)
|
||||
private boolean modify_insert(int index, NbtPathArgument.NbtPath nbtPath, Tag newElement, Tag currentTag)
|
||||
{
|
||||
Collection<NbtElement> targets;
|
||||
Collection<Tag> targets;
|
||||
try
|
||||
{
|
||||
targets = nbtPath.getOrInit(currentTag, NbtList::new);
|
||||
targets = nbtPath.getOrCreate(currentTag, ListTag::new);
|
||||
}
|
||||
catch (CommandSyntaxException e)
|
||||
{
|
||||
@@ -506,16 +505,16 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
}
|
||||
|
||||
boolean modified = false;
|
||||
for (NbtElement target : targets)
|
||||
for (Tag target : targets)
|
||||
{
|
||||
if (!(target instanceof AbstractNbtList))
|
||||
if (!(target instanceof CollectionTag))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
AbstractNbtList<?> targetList = (AbstractNbtList) target;
|
||||
if (!targetList.addElement(index < 0 ? targetList.size() + index + 1 : index, newElement.copy()))
|
||||
CollectionTag<?> targetList = (CollectionTag) target;
|
||||
if (!targetList.addTag(index < 0 ? targetList.size() + index + 1 : index, newElement.copy()))
|
||||
return false;
|
||||
modified = true;
|
||||
}
|
||||
@@ -527,22 +526,22 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
}
|
||||
|
||||
|
||||
private boolean modify_merge(NbtPathArgumentType.NbtPath nbtPath, NbtElement replacement) //nbtPathArgumentType$NbtPath_1, list_1)
|
||||
private boolean modify_merge(NbtPathArgument.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1)
|
||||
{
|
||||
if (!(replacement instanceof NbtCompound))
|
||||
if (!(replacement instanceof CompoundTag))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
NbtElement ownTag = getTag();
|
||||
Tag ownTag = getTag();
|
||||
try
|
||||
{
|
||||
for (NbtElement target : nbtPath.getOrInit(ownTag, NbtCompound::new))
|
||||
for (Tag target : nbtPath.getOrCreate(ownTag, CompoundTag::new))
|
||||
{
|
||||
if (!(target instanceof NbtCompound))
|
||||
if (!(target instanceof CompoundTag))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
((NbtCompound) target).copyFrom((NbtCompound) replacement);
|
||||
((CompoundTag) target).merge((CompoundTag) replacement);
|
||||
}
|
||||
}
|
||||
catch (CommandSyntaxException ignored)
|
||||
@@ -552,9 +551,9 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean modify_replace(NbtPathArgumentType.NbtPath nbtPath, NbtElement replacement) //nbtPathArgumentType$NbtPath_1, list_1)
|
||||
private boolean modify_replace(NbtPathArgument.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1)
|
||||
{
|
||||
NbtElement tag = getTag();
|
||||
Tag tag = getTag();
|
||||
String pathText = nbtPath.toString();
|
||||
if (pathText.endsWith("]")) // workaround for array replacement or item in the array replacement
|
||||
{
|
||||
@@ -581,12 +580,12 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
return false;
|
||||
}
|
||||
}
|
||||
NbtPathArgumentType.NbtPath newPath = cachePath(pathText.substring(0, pathText.length()-arrAccess.length()));
|
||||
NbtPathArgument.NbtPath newPath = cachePath(pathText.substring(0, pathText.length()-arrAccess.length()));
|
||||
return modify_insert(pos,newPath,replacement, tag);
|
||||
}
|
||||
try
|
||||
{
|
||||
nbtPath.put(tag, () -> replacement);
|
||||
nbtPath.set(tag, () -> replacement);
|
||||
}
|
||||
catch (CommandSyntaxException e)
|
||||
{
|
||||
@@ -599,10 +598,10 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
public Value get(Value value)
|
||||
{
|
||||
String valString = value.getString();
|
||||
NbtPathArgumentType.NbtPath path = cachePath(valString);
|
||||
NbtPathArgument.NbtPath path = cachePath(valString);
|
||||
try
|
||||
{
|
||||
List<NbtElement> tags = path.get(getTag());
|
||||
List<Tag> tags = path.get(getTag());
|
||||
if (tags.size()==0)
|
||||
return Value.NULL;
|
||||
if (tags.size()==1 && !valString.endsWith("[]"))
|
||||
@@ -616,7 +615,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
@Override
|
||||
public boolean has(Value where)
|
||||
{
|
||||
return cachePath(where.getString()).count(getTag()) > 0;
|
||||
return cachePath(where.getString()).countMatching(getTag()) > 0;
|
||||
}
|
||||
|
||||
private void ensureOwnership()
|
||||
@@ -638,7 +637,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
@Override
|
||||
public boolean delete(Value where)
|
||||
{
|
||||
NbtPathArgumentType.NbtPath path = cachePath(where.getString());
|
||||
NbtPathArgument.NbtPath path = cachePath(where.getString());
|
||||
ensureOwnership();
|
||||
int removed = path.remove(getTag());
|
||||
if (removed > 0)
|
||||
@@ -649,23 +648,23 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
return false;
|
||||
}
|
||||
|
||||
public static record InventoryLocator(Object owner, BlockPos position, Inventory inventory, int offset, boolean isEnder)
|
||||
public static record InventoryLocator(Object owner, BlockPos position, Container inventory, int offset, boolean isEnder)
|
||||
{
|
||||
InventoryLocator(Object owner, BlockPos pos, Inventory i, int o)
|
||||
InventoryLocator(Object owner, BlockPos pos, Container i, int o)
|
||||
{
|
||||
this(owner, pos, i, o, false);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, NbtPathArgumentType.NbtPath> pathCache = new HashMap<>();
|
||||
private static NbtPathArgumentType.NbtPath cachePath(String arg)
|
||||
private static Map<String, NbtPathArgument.NbtPath> pathCache = new HashMap<>();
|
||||
private static NbtPathArgument.NbtPath cachePath(String arg)
|
||||
{
|
||||
NbtPathArgumentType.NbtPath res = pathCache.get(arg);
|
||||
NbtPathArgument.NbtPath res = pathCache.get(arg);
|
||||
if (res != null)
|
||||
return res;
|
||||
try
|
||||
{
|
||||
res = NbtPathArgumentType.nbtPath().parse(new StringReader(arg));
|
||||
res = NbtPathArgument.nbtPath().parse(new StringReader(arg));
|
||||
}
|
||||
catch (CommandSyntaxException exc)
|
||||
{
|
||||
@@ -685,7 +684,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
|
||||
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this);
|
||||
ensureOwnership();
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
package carpet.script.value;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonNull;
|
||||
import net.minecraft.nbt.NbtString;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
|
||||
public class NullValue extends NumericValue // TODO check nonsingleton code
|
||||
{
|
||||
@@ -80,10 +79,10 @@ public class NullValue extends NumericValue // TODO check nonsingleton code
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this);
|
||||
return NbtString.of("null");
|
||||
return StringTag.valueOf("null");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -3,16 +3,16 @@ package carpet.script.value;
|
||||
import carpet.script.exception.InternalExpressionException;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import net.minecraft.nbt.NbtDouble;
|
||||
import net.minecraft.nbt.NbtInt;
|
||||
import net.minecraft.nbt.NbtLong;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.MathContext;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.Locale;
|
||||
import net.minecraft.nbt.DoubleTag;
|
||||
import net.minecraft.nbt.IntTag;
|
||||
import net.minecraft.nbt.LongTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
import static java.lang.Math.abs;
|
||||
import static java.lang.Math.signum;
|
||||
@@ -268,24 +268,24 @@ public class NumericValue extends Value
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
if (longValue != null)
|
||||
{
|
||||
if (abs(longValue) < Integer.MAX_VALUE-2)
|
||||
return NbtInt.of((int)(long)longValue);
|
||||
return NbtLong.of(longValue);
|
||||
return IntTag.valueOf((int)(long)longValue);
|
||||
return LongTag.valueOf(longValue);
|
||||
}
|
||||
long lv = getLong();
|
||||
if (value == (double)lv)
|
||||
{
|
||||
if (abs(value) < Integer.MAX_VALUE-2)
|
||||
return NbtInt.of((int)lv);
|
||||
return NbtLong.of(getLong());
|
||||
return IntTag.valueOf((int)lv);
|
||||
return LongTag.valueOf(getLong());
|
||||
}
|
||||
else
|
||||
{
|
||||
return NbtDouble.of(value);
|
||||
return DoubleTag.valueOf(value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,63 +13,62 @@ import carpet.script.exception.InternalExpressionException;
|
||||
import carpet.script.exception.InvalidCallbackException;
|
||||
import carpet.script.exception.ThrowStatement;
|
||||
import carpet.script.exception.Throwables;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.entity.player.PlayerInventory;
|
||||
import net.minecraft.inventory.Inventory;
|
||||
import net.minecraft.inventory.SimpleInventory;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NbtCompound;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.nbt.NbtList;
|
||||
import net.minecraft.recipe.Recipe;
|
||||
import net.minecraft.screen.AbstractFurnaceScreenHandler;
|
||||
import net.minecraft.screen.AnvilScreenHandler;
|
||||
import net.minecraft.screen.ArrayPropertyDelegate;
|
||||
import net.minecraft.screen.BeaconScreenHandler;
|
||||
import net.minecraft.screen.BlastFurnaceScreenHandler;
|
||||
import net.minecraft.screen.BrewingStandScreenHandler;
|
||||
import net.minecraft.screen.CartographyTableScreenHandler;
|
||||
import net.minecraft.screen.CraftingScreenHandler;
|
||||
import net.minecraft.screen.EnchantmentScreenHandler;
|
||||
import net.minecraft.screen.FurnaceScreenHandler;
|
||||
import net.minecraft.screen.GenericContainerScreenHandler;
|
||||
import net.minecraft.screen.GrindstoneScreenHandler;
|
||||
import net.minecraft.screen.HopperScreenHandler;
|
||||
import net.minecraft.screen.LecternScreenHandler;
|
||||
import net.minecraft.screen.LoomScreenHandler;
|
||||
import net.minecraft.screen.MerchantScreenHandler;
|
||||
import net.minecraft.screen.NamedScreenHandlerFactory;
|
||||
import net.minecraft.screen.Property;
|
||||
import net.minecraft.screen.ScreenHandler;
|
||||
import net.minecraft.screen.ScreenHandlerListener;
|
||||
import net.minecraft.screen.ShulkerBoxScreenHandler;
|
||||
import net.minecraft.screen.SimpleNamedScreenHandlerFactory;
|
||||
import net.minecraft.screen.SmithingScreenHandler;
|
||||
import net.minecraft.screen.SmokerScreenHandler;
|
||||
import net.minecraft.screen.StonecutterScreenHandler;
|
||||
import net.minecraft.screen.slot.Slot;
|
||||
import net.minecraft.screen.slot.SlotActionType;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.OptionalInt;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.Container;
|
||||
import net.minecraft.world.MenuProvider;
|
||||
import net.minecraft.world.SimpleContainer;
|
||||
import net.minecraft.world.SimpleMenuProvider;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.inventory.AbstractContainerMenu;
|
||||
import net.minecraft.world.inventory.AbstractFurnaceMenu;
|
||||
import net.minecraft.world.inventory.AnvilMenu;
|
||||
import net.minecraft.world.inventory.BeaconMenu;
|
||||
import net.minecraft.world.inventory.BlastFurnaceMenu;
|
||||
import net.minecraft.world.inventory.BrewingStandMenu;
|
||||
import net.minecraft.world.inventory.CartographyTableMenu;
|
||||
import net.minecraft.world.inventory.ChestMenu;
|
||||
import net.minecraft.world.inventory.ClickType;
|
||||
import net.minecraft.world.inventory.ContainerListener;
|
||||
import net.minecraft.world.inventory.CraftingMenu;
|
||||
import net.minecraft.world.inventory.DataSlot;
|
||||
import net.minecraft.world.inventory.EnchantmentMenu;
|
||||
import net.minecraft.world.inventory.FurnaceMenu;
|
||||
import net.minecraft.world.inventory.GrindstoneMenu;
|
||||
import net.minecraft.world.inventory.HopperMenu;
|
||||
import net.minecraft.world.inventory.LecternMenu;
|
||||
import net.minecraft.world.inventory.LoomMenu;
|
||||
import net.minecraft.world.inventory.MerchantMenu;
|
||||
import net.minecraft.world.inventory.ShulkerBoxMenu;
|
||||
import net.minecraft.world.inventory.SimpleContainerData;
|
||||
import net.minecraft.world.inventory.Slot;
|
||||
import net.minecraft.world.inventory.SmithingMenu;
|
||||
import net.minecraft.world.inventory.SmokerMenu;
|
||||
import net.minecraft.world.inventory.StonecutterMenu;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Recipe;
|
||||
|
||||
import static net.minecraft.screen.ScreenHandlerType.*;
|
||||
import static net.minecraft.world.inventory.MenuType.*;
|
||||
|
||||
public class ScreenValue extends Value {
|
||||
private ScreenHandler screenHandler;
|
||||
private AbstractContainerMenu screenHandler;
|
||||
private ScreenHandlerInventory inventory;
|
||||
|
||||
private final Text name;
|
||||
private final Component name;
|
||||
private final String typestring;
|
||||
private final FunctionValue callback;
|
||||
private final String hostname;
|
||||
private final ServerPlayerEntity player;
|
||||
private final ServerPlayer player;
|
||||
|
||||
|
||||
public static Map<String,ScarpetScreenHandlerFactory> screenHandlerFactories;
|
||||
@@ -78,80 +77,80 @@ public class ScreenValue extends Value {
|
||||
{
|
||||
screenHandlerFactories = new HashMap<>();
|
||||
|
||||
screenHandlerFactories.put("anvil",(syncId, playerInventory) -> new AnvilScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("beacon",(syncId, playerInventory) -> new BeaconScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("blast_furnace",(syncId, playerInventory) -> new BlastFurnaceScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("brewing_stand",(syncId, playerInventory) -> new BrewingStandScreenHandler(syncId,playerInventory,new SimpleInventory(5),new ArrayPropertyDelegate(2)));
|
||||
screenHandlerFactories.put("cartography_table",(syncId, playerInventory) -> new CartographyTableScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("crafting",(syncId, playerInventory) -> new CraftingScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("enchantment",(syncId, playerInventory) -> new EnchantmentScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("furnace",(syncId, playerInventory) -> new FurnaceScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("generic_3x3",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_3X3,syncId,playerInventory,new SimpleInventory(9),1)));
|
||||
screenHandlerFactories.put("generic_9x1",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X1,syncId,playerInventory,new SimpleInventory(9),1)));
|
||||
screenHandlerFactories.put("generic_9x2",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X2,syncId,playerInventory,new SimpleInventory(9*2),2)));
|
||||
screenHandlerFactories.put("generic_9x3",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X3,syncId,playerInventory,new SimpleInventory(9*3),3)));
|
||||
screenHandlerFactories.put("generic_9x4",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X4,syncId,playerInventory,new SimpleInventory(9*4),4)));
|
||||
screenHandlerFactories.put("generic_9x5",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X5,syncId,playerInventory,new SimpleInventory(9*5),5)));
|
||||
screenHandlerFactories.put("generic_9x6",((syncId, playerInventory) -> new GenericContainerScreenHandler(GENERIC_9X6,syncId,playerInventory,new SimpleInventory(9*6),6)));
|
||||
screenHandlerFactories.put("grindstone",(syncId, playerInventory) -> new GrindstoneScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("hopper",(syncId, playerInventory) -> new HopperScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("lectern",(syncId, playerInventory) -> new LecternScreenHandler(syncId,new SimpleInventory(1),new ArrayPropertyDelegate(1)));
|
||||
screenHandlerFactories.put("loom",(syncId, playerInventory) -> new LoomScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("merchant",(syncId, playerInventory) -> new MerchantScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("shulker_box",(syncId, playerInventory) -> new ShulkerBoxScreenHandler(syncId,playerInventory,new SimpleInventory(9*3)));
|
||||
screenHandlerFactories.put("smithing",(syncId, playerInventory) -> new SmithingScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("smoker",(syncId, playerInventory) -> new SmokerScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("stonecutter",(syncId, playerInventory) -> new StonecutterScreenHandler(syncId,playerInventory));
|
||||
screenHandlerFactories.put("anvil",(syncId, playerInventory) -> new AnvilMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("beacon",(syncId, playerInventory) -> new BeaconMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("blast_furnace",(syncId, playerInventory) -> new BlastFurnaceMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("brewing_stand",(syncId, playerInventory) -> new BrewingStandMenu(syncId,playerInventory,new SimpleContainer(5),new SimpleContainerData(2)));
|
||||
screenHandlerFactories.put("cartography_table",(syncId, playerInventory) -> new CartographyTableMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("crafting",(syncId, playerInventory) -> new CraftingMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("enchantment",(syncId, playerInventory) -> new EnchantmentMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("furnace",(syncId, playerInventory) -> new FurnaceMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("generic_3x3",((syncId, playerInventory) -> new ChestMenu(GENERIC_3x3,syncId,playerInventory,new SimpleContainer(9),1)));
|
||||
screenHandlerFactories.put("generic_9x1",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x1,syncId,playerInventory,new SimpleContainer(9),1)));
|
||||
screenHandlerFactories.put("generic_9x2",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x2,syncId,playerInventory,new SimpleContainer(9*2),2)));
|
||||
screenHandlerFactories.put("generic_9x3",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x3,syncId,playerInventory,new SimpleContainer(9*3),3)));
|
||||
screenHandlerFactories.put("generic_9x4",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x4,syncId,playerInventory,new SimpleContainer(9*4),4)));
|
||||
screenHandlerFactories.put("generic_9x5",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x5,syncId,playerInventory,new SimpleContainer(9*5),5)));
|
||||
screenHandlerFactories.put("generic_9x6",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x6,syncId,playerInventory,new SimpleContainer(9*6),6)));
|
||||
screenHandlerFactories.put("grindstone",(syncId, playerInventory) -> new GrindstoneMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("hopper",(syncId, playerInventory) -> new HopperMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("lectern",(syncId, playerInventory) -> new LecternMenu(syncId,new SimpleContainer(1),new SimpleContainerData(1)));
|
||||
screenHandlerFactories.put("loom",(syncId, playerInventory) -> new LoomMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("merchant",(syncId, playerInventory) -> new MerchantMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("shulker_box",(syncId, playerInventory) -> new ShulkerBoxMenu(syncId,playerInventory,new SimpleContainer(9*3)));
|
||||
screenHandlerFactories.put("smithing",(syncId, playerInventory) -> new SmithingMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("smoker",(syncId, playerInventory) -> new SmokerMenu(syncId,playerInventory));
|
||||
screenHandlerFactories.put("stonecutter",(syncId, playerInventory) -> new StonecutterMenu(syncId,playerInventory));
|
||||
}
|
||||
|
||||
|
||||
protected interface ScarpetScreenHandlerFactory {
|
||||
ScreenHandler create(int syncId, PlayerInventory playerInventory);
|
||||
AbstractContainerMenu create(int syncId, Inventory playerInventory);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public ScreenValue(ServerPlayerEntity player, String type, Text name, FunctionValue callback, Context c) {
|
||||
public ScreenValue(ServerPlayer player, String type, Component name, FunctionValue callback, Context c) {
|
||||
this.name = name;
|
||||
this.typestring = type.toLowerCase();
|
||||
if(callback != null) callback.checkArgs(4);
|
||||
this.callback = callback;
|
||||
this.hostname = c.host.getName();
|
||||
this.player = player;
|
||||
NamedScreenHandlerFactory factory = this.createScreenHandlerFactory();
|
||||
MenuProvider factory = this.createScreenHandlerFactory();
|
||||
if(factory == null) throw new ThrowStatement(type, Throwables.UNKNOWN_SCREEN);
|
||||
this.openScreen(factory);
|
||||
this.inventory = new ScreenHandlerInventory(this.screenHandler);
|
||||
}
|
||||
|
||||
private NamedScreenHandlerFactory createScreenHandlerFactory() {
|
||||
private MenuProvider createScreenHandlerFactory() {
|
||||
if(!screenHandlerFactories.containsKey(this.typestring)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new SimpleNamedScreenHandlerFactory((i, playerInventory, playerEntity) -> {
|
||||
ScreenHandler screen = screenHandlerFactories.get(ScreenValue.this.typestring).create(i,playerInventory);
|
||||
return new SimpleMenuProvider((i, playerInventory, playerEntity) -> {
|
||||
AbstractContainerMenu screen = screenHandlerFactories.get(ScreenValue.this.typestring).create(i,playerInventory);
|
||||
ScreenValue.this.addListenerCallback(screen);
|
||||
ScreenValue.this.screenHandler = screen;
|
||||
return screen;
|
||||
}, this.name);
|
||||
}
|
||||
|
||||
private void openScreen(NamedScreenHandlerFactory factory) {
|
||||
private void openScreen(MenuProvider factory) {
|
||||
if(this.player == null) return;
|
||||
OptionalInt optionalSyncId = this.player.openHandledScreen(factory);
|
||||
if(optionalSyncId.isPresent() && this.player.currentScreenHandler.syncId == optionalSyncId.getAsInt()) {
|
||||
this.screenHandler = this.player.currentScreenHandler;
|
||||
OptionalInt optionalSyncId = this.player.openMenu(factory);
|
||||
if(optionalSyncId.isPresent() && this.player.containerMenu.containerId == optionalSyncId.getAsInt()) {
|
||||
this.screenHandler = this.player.containerMenu;
|
||||
}
|
||||
}
|
||||
|
||||
public void close() {
|
||||
if(this.player.currentScreenHandler != this.player.playerScreenHandler) {
|
||||
if(this.player.containerMenu != this.player.inventoryMenu) {
|
||||
//prevent recursion when closing screen in closing screen callback by doing this before triggering event
|
||||
this.inventory = null;
|
||||
this.player.currentScreenHandler = this.player.playerScreenHandler;
|
||||
this.player.closeHandledScreen();
|
||||
this.player.containerMenu = this.player.inventoryMenu;
|
||||
this.player.closeContainer();
|
||||
this.screenHandler = null;
|
||||
}
|
||||
}
|
||||
@@ -160,7 +159,7 @@ public class ScreenValue extends Value {
|
||||
if(this.screenHandler == null) {
|
||||
return false;
|
||||
}
|
||||
if(this.player.currentScreenHandler.syncId == this.screenHandler.syncId) {
|
||||
if(this.player.containerMenu.containerId == this.screenHandler.containerId) {
|
||||
return true;
|
||||
}
|
||||
this.screenHandler = null;
|
||||
@@ -168,7 +167,7 @@ public class ScreenValue extends Value {
|
||||
}
|
||||
|
||||
|
||||
private boolean callListener(ServerPlayerEntity player, String action, Map<Value,Value> data) {
|
||||
private boolean callListener(ServerPlayer player, String action, Map<Value,Value> data) {
|
||||
Value playerValue = EntityValue.of(player);
|
||||
Value actionValue = StringValue.of(action);
|
||||
Value dataValue = MapValue.wrap(data);
|
||||
@@ -179,11 +178,11 @@ public class ScreenValue extends Value {
|
||||
this.screenHandler = null;
|
||||
return false;
|
||||
}
|
||||
ServerCommandSource source = player.getCommandSource().withLevel(CarpetSettings.runPermissionLevel);
|
||||
CommandSourceStack source = player.createCommandSourceStack().withPermission(CarpetSettings.runPermissionLevel);
|
||||
CarpetScriptHost executingHost = appHost.retrieveForExecution(source,player);
|
||||
try
|
||||
{
|
||||
Value cancelValue = executingHost.callUDF(player.getBlockPos(), source.withLevel(CarpetSettings.runPermissionLevel), callback, args);
|
||||
Value cancelValue = executingHost.callUDF(player.blockPosition(), source.withPermission(CarpetSettings.runPermissionLevel), callback, args);
|
||||
return cancelValue.getString().equals("cancel");
|
||||
}
|
||||
catch (NullPointerException | InvalidCallbackException | IntegrityException error)
|
||||
@@ -193,52 +192,52 @@ public class ScreenValue extends Value {
|
||||
}
|
||||
}
|
||||
|
||||
private void addListenerCallback(ScreenHandler screenHandler) {
|
||||
private void addListenerCallback(AbstractContainerMenu screenHandler) {
|
||||
if(this.callback == null) return;
|
||||
|
||||
screenHandler.addListener(new ScarpetScreenHandlerListener() {
|
||||
screenHandler.addSlotListener(new ScarpetScreenHandlerListener() {
|
||||
@Override
|
||||
public boolean onSlotClick(ServerPlayerEntity player, SlotActionType actionType, int slot, int button) {
|
||||
public boolean onSlotClick(ServerPlayer player, ClickType actionType, int slot, int button) {
|
||||
Map<Value,Value> data = new HashMap<>();
|
||||
data.put(StringValue.of("slot"),slot == ScreenHandler.EMPTY_SPACE_SLOT_INDEX ? Value.NULL : NumericValue.of(slot));
|
||||
if(actionType == SlotActionType.QUICK_CRAFT) {
|
||||
data.put(StringValue.of("quick_craft_stage"),NumericValue.of(ScreenHandler.unpackQuickCraftStage(button)));
|
||||
button = ScreenHandler.unpackQuickCraftButton(button);
|
||||
data.put(StringValue.of("slot"),slot == AbstractContainerMenu.SLOT_CLICKED_OUTSIDE ? Value.NULL : NumericValue.of(slot));
|
||||
if(actionType == ClickType.QUICK_CRAFT) {
|
||||
data.put(StringValue.of("quick_craft_stage"),NumericValue.of(AbstractContainerMenu.getQuickcraftHeader(button)));
|
||||
button = AbstractContainerMenu.getQuickcraftType(button);
|
||||
}
|
||||
data.put(StringValue.of("button"),NumericValue.of(button));
|
||||
return ScreenValue.this.callListener(player,actionTypeToString(actionType),data);
|
||||
}
|
||||
@Override
|
||||
public boolean onButtonClick(ServerPlayerEntity player, int button) {
|
||||
public boolean onButtonClick(ServerPlayer player, int button) {
|
||||
Map<Value,Value> data = new HashMap<>();
|
||||
data.put(StringValue.of("button"),NumericValue.of(button));
|
||||
return ScreenValue.this.callListener(player,"button",data);
|
||||
}
|
||||
@Override
|
||||
public void onClose(ServerPlayerEntity player) {
|
||||
public void onClose(ServerPlayer player) {
|
||||
Map<Value,Value> data = new HashMap<>();
|
||||
ScreenValue.this.callListener(player,"close",data);
|
||||
}
|
||||
@Override
|
||||
public boolean onSelectRecipe(ServerPlayerEntity player, Recipe<?> recipe, boolean craftAll) {
|
||||
public boolean onSelectRecipe(ServerPlayer player, Recipe<?> recipe, boolean craftAll) {
|
||||
Map<Value,Value> data = new HashMap<>();
|
||||
data.put(StringValue.of("recipe"),StringValue.of(recipe.getId().toString()));
|
||||
data.put(StringValue.of("craft_all"),BooleanValue.of(craftAll));
|
||||
return ScreenValue.this.callListener(player,"select_recipe",data);
|
||||
}
|
||||
@Override
|
||||
public void onSlotUpdate(ScreenHandler handler, int slotId, ItemStack stack) {
|
||||
public void slotChanged(AbstractContainerMenu handler, int slotId, ItemStack stack) {
|
||||
Map<Value,Value> data = new HashMap<>();
|
||||
data.put(StringValue.of("slot"),NumericValue.of(slotId));
|
||||
data.put(StringValue.of("stack"),ValueConversions.of(stack));
|
||||
ScreenValue.this.callListener(ScreenValue.this.player,"slot_update",data);
|
||||
}
|
||||
@Override
|
||||
public void onPropertyUpdate(ScreenHandler handler, int property, int value) {}
|
||||
public void dataChanged(AbstractContainerMenu handler, int property, int value) {}
|
||||
});
|
||||
}
|
||||
|
||||
private Property getPropertyForType(Class<? extends ScreenHandler> screenHandlerClass, String requiredType, int propertyIndex, String propertyName) {
|
||||
private DataSlot getPropertyForType(Class<? extends AbstractContainerMenu> screenHandlerClass, String requiredType, int propertyIndex, String propertyName) {
|
||||
if(screenHandlerClass.isInstance(this.screenHandler)) {
|
||||
return ((ScreenHandlerInterface) this.screenHandler).getProperty(propertyIndex);
|
||||
}
|
||||
@@ -248,38 +247,38 @@ public class ScreenValue extends Value {
|
||||
throw new InternalExpressionException("Screen property " + propertyName + " expected a " + requiredType + " screen.");
|
||||
}
|
||||
|
||||
private Property getProperty(String propertyName) {
|
||||
private DataSlot getProperty(String propertyName) {
|
||||
return switch (propertyName) {
|
||||
case "fuel_progress" -> getPropertyForType(AbstractFurnaceScreenHandler.class, "furnace", 0, propertyName);
|
||||
case "max_fuel_progress" -> getPropertyForType(AbstractFurnaceScreenHandler.class, "furnace", 1, propertyName);
|
||||
case "cook_progress" -> getPropertyForType(AbstractFurnaceScreenHandler.class, "furnace", 2, propertyName);
|
||||
case "max_cook_progress" -> getPropertyForType(AbstractFurnaceScreenHandler.class, "furnace", 3, propertyName);
|
||||
case "fuel_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 0, propertyName);
|
||||
case "max_fuel_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 1, propertyName);
|
||||
case "cook_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 2, propertyName);
|
||||
case "max_cook_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 3, propertyName);
|
||||
|
||||
case "level_cost" -> getPropertyForType(AnvilScreenHandler.class, "anvil", 0, propertyName);
|
||||
case "level_cost" -> getPropertyForType(AnvilMenu.class, "anvil", 0, propertyName);
|
||||
|
||||
case "page" -> getPropertyForType(LecternScreenHandler.class, "lectern", 0, propertyName);
|
||||
case "page" -> getPropertyForType(LecternMenu.class, "lectern", 0, propertyName);
|
||||
|
||||
case "beacon_level" -> getPropertyForType(BeaconScreenHandler.class, "beacon", 0, propertyName);
|
||||
case "primary_effect" -> getPropertyForType(BeaconScreenHandler.class, "beacon", 1, propertyName);
|
||||
case "secondary_effect" -> getPropertyForType(BeaconScreenHandler.class, "beacon", 2, propertyName);
|
||||
case "beacon_level" -> getPropertyForType(BeaconMenu.class, "beacon", 0, propertyName);
|
||||
case "primary_effect" -> getPropertyForType(BeaconMenu.class, "beacon", 1, propertyName);
|
||||
case "secondary_effect" -> getPropertyForType(BeaconMenu.class, "beacon", 2, propertyName);
|
||||
|
||||
case "brew_time" -> getPropertyForType(BrewingStandScreenHandler.class, "brewing_stand", 0, propertyName);
|
||||
case "brewing_fuel" -> getPropertyForType(BrewingStandScreenHandler.class, "brewing_stand", 1, propertyName);
|
||||
case "brew_time" -> getPropertyForType(BrewingStandMenu.class, "brewing_stand", 0, propertyName);
|
||||
case "brewing_fuel" -> getPropertyForType(BrewingStandMenu.class, "brewing_stand", 1, propertyName);
|
||||
|
||||
case "enchantment_power_1" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 0, propertyName);
|
||||
case "enchantment_power_2" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 1, propertyName);
|
||||
case "enchantment_power_3" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 2, propertyName);
|
||||
case "enchantment_seed" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 3, propertyName);
|
||||
case "enchantment_id_1" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 4, propertyName);
|
||||
case "enchantment_id_2" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 5, propertyName);
|
||||
case "enchantment_id_3" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 6, propertyName);
|
||||
case "enchantment_level_1" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 7, propertyName);
|
||||
case "enchantment_level_2" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 8, propertyName);
|
||||
case "enchantment_level_3" -> getPropertyForType(EnchantmentScreenHandler.class, "enchantment", 9, propertyName);
|
||||
case "enchantment_power_1" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 0, propertyName);
|
||||
case "enchantment_power_2" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 1, propertyName);
|
||||
case "enchantment_power_3" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 2, propertyName);
|
||||
case "enchantment_seed" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 3, propertyName);
|
||||
case "enchantment_id_1" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 4, propertyName);
|
||||
case "enchantment_id_2" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 5, propertyName);
|
||||
case "enchantment_id_3" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 6, propertyName);
|
||||
case "enchantment_level_1" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 7, propertyName);
|
||||
case "enchantment_level_2" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 8, propertyName);
|
||||
case "enchantment_level_3" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 9, propertyName);
|
||||
|
||||
case "banner_pattern" -> getPropertyForType(LoomScreenHandler.class, "loom", 0, propertyName);
|
||||
case "banner_pattern" -> getPropertyForType(LoomMenu.class, "loom", 0, propertyName);
|
||||
|
||||
case "stonecutter_recipe" -> getPropertyForType(StonecutterScreenHandler.class, "stonecutter", 0, propertyName);
|
||||
case "stonecutter_recipe" -> getPropertyForType(StonecutterMenu.class, "stonecutter", 0, propertyName);
|
||||
|
||||
default -> throw new InternalExpressionException("Invalid screen property: " + propertyName);
|
||||
};
|
||||
@@ -289,27 +288,27 @@ public class ScreenValue extends Value {
|
||||
public Value queryProperty(String propertyName) {
|
||||
if(propertyName.equals("name")) return FormattedTextValue.of(this.name);
|
||||
if(propertyName.equals("open")) return BooleanValue.of(this.isOpen());
|
||||
Property property = getProperty(propertyName);
|
||||
DataSlot property = getProperty(propertyName);
|
||||
return NumericValue.of(property.get());
|
||||
}
|
||||
|
||||
public Value modifyProperty(String propertyName, List<Value> lv) {
|
||||
Property property = getProperty(propertyName);
|
||||
DataSlot property = getProperty(propertyName);
|
||||
int intValue = NumericValue.asNumber(lv.get(0)).getInt();
|
||||
property.set(intValue);
|
||||
this.screenHandler.syncState();
|
||||
this.screenHandler.sendAllDataToRemote();
|
||||
return Value.TRUE;
|
||||
}
|
||||
|
||||
public ScreenHandler getScreenHandler() {
|
||||
public AbstractContainerMenu getScreenHandler() {
|
||||
return this.screenHandler;
|
||||
}
|
||||
|
||||
public ServerPlayerEntity getPlayer() {
|
||||
public ServerPlayer getPlayer() {
|
||||
return this.player;
|
||||
}
|
||||
|
||||
public Inventory getInventory() {
|
||||
public Container getInventory() {
|
||||
return this.inventory;
|
||||
}
|
||||
|
||||
@@ -330,124 +329,124 @@ public class ScreenValue extends Value {
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force) {
|
||||
public Tag toTag(boolean force) {
|
||||
if(this.screenHandler == null) {
|
||||
return Value.NULL.toTag(true);
|
||||
}
|
||||
|
||||
NbtList nbtList = new NbtList();
|
||||
ListTag nbtList = new ListTag();
|
||||
for(int i = 0; i < this.screenHandler.slots.size(); i++) {
|
||||
ItemStack itemStack = this.screenHandler.getSlot(i).getStack();
|
||||
nbtList.add(itemStack.writeNbt(new NbtCompound()));
|
||||
ItemStack itemStack = this.screenHandler.getSlot(i).getItem();
|
||||
nbtList.add(itemStack.save(new CompoundTag()));
|
||||
}
|
||||
return nbtList;
|
||||
}
|
||||
|
||||
|
||||
public interface ScarpetScreenHandlerListener extends ScreenHandlerListener {
|
||||
boolean onSlotClick(ServerPlayerEntity player, SlotActionType actionType, int slot, int button);
|
||||
boolean onButtonClick(ServerPlayerEntity player, int button);
|
||||
void onClose(ServerPlayerEntity player);
|
||||
boolean onSelectRecipe(ServerPlayerEntity player, Recipe<?> recipe, boolean craftAll);
|
||||
public interface ScarpetScreenHandlerListener extends ContainerListener {
|
||||
boolean onSlotClick(ServerPlayer player, ClickType actionType, int slot, int button);
|
||||
boolean onButtonClick(ServerPlayer player, int button);
|
||||
void onClose(ServerPlayer player);
|
||||
boolean onSelectRecipe(ServerPlayer player, Recipe<?> recipe, boolean craftAll);
|
||||
}
|
||||
|
||||
public static class ScreenHandlerInventory implements Inventory {
|
||||
public static class ScreenHandlerInventory implements Container {
|
||||
|
||||
protected ScreenHandler screenHandler;
|
||||
protected AbstractContainerMenu screenHandler;
|
||||
|
||||
public ScreenHandlerInventory(ScreenHandler screenHandler) {
|
||||
public ScreenHandlerInventory(AbstractContainerMenu screenHandler) {
|
||||
this.screenHandler = screenHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
public int getContainerSize() {
|
||||
return this.screenHandler.slots.size() + 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
for(Slot slot : this.screenHandler.slots) {
|
||||
if(slot.hasStack() && !slot.getStack().isEmpty()) return false;
|
||||
if(slot.hasItem() && !slot.getItem().isEmpty()) return false;
|
||||
}
|
||||
return this.screenHandler.getCursorStack().isEmpty();
|
||||
return this.screenHandler.getCarried().isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getStack(int slot) {
|
||||
if(slot == this.size()-1) return this.screenHandler.getCursorStack();
|
||||
return slot >= -1 && slot < this.size() ? this.screenHandler.slots.get(slot).getStack() : ItemStack.EMPTY;
|
||||
public ItemStack getItem(int slot) {
|
||||
if(slot == this.getContainerSize()-1) return this.screenHandler.getCarried();
|
||||
return slot >= -1 && slot < this.getContainerSize() ? this.screenHandler.slots.get(slot).getItem() : ItemStack.EMPTY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack removeStack(int slot, int amount) {
|
||||
public ItemStack removeItem(int slot, int amount) {
|
||||
ItemStack itemStack;
|
||||
if(slot == this.size()-1)
|
||||
itemStack = this.screenHandler.getCursorStack().split(amount);
|
||||
if(slot == this.getContainerSize()-1)
|
||||
itemStack = this.screenHandler.getCarried().split(amount);
|
||||
else
|
||||
itemStack = ScreenHandlerInventory.splitStack(this.screenHandler.slots, slot, amount);
|
||||
if (!itemStack.isEmpty()) {
|
||||
this.markDirty();
|
||||
this.setChanged();
|
||||
}
|
||||
return itemStack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack removeStack(int slot) {
|
||||
public ItemStack removeItemNoUpdate(int slot) {
|
||||
ItemStack itemStack;
|
||||
if(slot == this.size()-1)
|
||||
itemStack = this.screenHandler.getCursorStack();
|
||||
if(slot == this.getContainerSize()-1)
|
||||
itemStack = this.screenHandler.getCarried();
|
||||
else
|
||||
itemStack = this.screenHandler.slots.get(slot).getStack();
|
||||
itemStack = this.screenHandler.slots.get(slot).getItem();
|
||||
if (itemStack.isEmpty()) {
|
||||
return ItemStack.EMPTY;
|
||||
} else {
|
||||
if(slot == this.size()-1)
|
||||
this.screenHandler.setCursorStack(ItemStack.EMPTY);
|
||||
if(slot == this.getContainerSize()-1)
|
||||
this.screenHandler.setCarried(ItemStack.EMPTY);
|
||||
else
|
||||
this.screenHandler.slots.get(slot).setStack(ItemStack.EMPTY);
|
||||
this.screenHandler.slots.get(slot).set(ItemStack.EMPTY);
|
||||
return itemStack;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setStack(int slot, ItemStack stack) {
|
||||
if(slot == this.size()-1)
|
||||
this.screenHandler.setCursorStack(stack);
|
||||
public void setItem(int slot, ItemStack stack) {
|
||||
if(slot == this.getContainerSize()-1)
|
||||
this.screenHandler.setCarried(stack);
|
||||
else
|
||||
this.screenHandler.slots.get(slot).setStack(stack);
|
||||
if (!stack.isEmpty() && stack.getCount() > this.getMaxCountPerStack()) {
|
||||
stack.setCount(this.getMaxCountPerStack());
|
||||
this.screenHandler.slots.get(slot).set(stack);
|
||||
if (!stack.isEmpty() && stack.getCount() > this.getMaxStackSize()) {
|
||||
stack.setCount(this.getMaxStackSize());
|
||||
}
|
||||
|
||||
this.markDirty();
|
||||
this.setChanged();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markDirty() {
|
||||
public void setChanged() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canPlayerUse(PlayerEntity player) {
|
||||
public boolean stillValid(Player player) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
public void clearContent() {
|
||||
for(Slot slot : this.screenHandler.slots) {
|
||||
slot.setStack(ItemStack.EMPTY);
|
||||
slot.set(ItemStack.EMPTY);
|
||||
}
|
||||
this.screenHandler.setCursorStack(ItemStack.EMPTY);
|
||||
this.markDirty();
|
||||
this.screenHandler.setCarried(ItemStack.EMPTY);
|
||||
this.setChanged();
|
||||
}
|
||||
|
||||
|
||||
public static ItemStack splitStack(List<Slot> slots, int slot, int amount) {
|
||||
return slot >= 0 && slot < slots.size() && !slots.get(slot).getStack().isEmpty() && amount > 0 ? slots.get(slot).getStack().split(amount) : ItemStack.EMPTY;
|
||||
return slot >= 0 && slot < slots.size() && !slots.get(slot).getItem().isEmpty() && amount > 0 ? slots.get(slot).getItem().split(amount) : ItemStack.EMPTY;
|
||||
}
|
||||
}
|
||||
|
||||
private static String actionTypeToString(SlotActionType actionType) {
|
||||
private static String actionTypeToString(ClickType actionType) {
|
||||
return switch (actionType) {
|
||||
case PICKUP -> "pickup";
|
||||
case QUICK_MOVE -> "quick_move";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package carpet.script.value;
|
||||
|
||||
import net.minecraft.nbt.NbtString;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
public class StringValue extends Value
|
||||
{
|
||||
@@ -43,8 +43,8 @@ public class StringValue extends Value
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
return NbtString.of(str);
|
||||
return StringTag.valueOf(str);
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,11 @@ import carpet.script.Tokenizer;
|
||||
import carpet.script.exception.ExitStatement;
|
||||
import carpet.script.exception.ExpressionException;
|
||||
import carpet.script.exception.InternalExpressionException;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
public class ThreadValue extends Value
|
||||
{
|
||||
@@ -127,7 +126,7 @@ public class ThreadValue extends Value
|
||||
}
|
||||
|
||||
@Override
|
||||
public NbtElement toTag(boolean force)
|
||||
public Tag toTag(boolean force)
|
||||
{
|
||||
if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this);
|
||||
return getValue().toTag(true);
|
||||
|
||||
@@ -4,8 +4,6 @@ import carpet.CarpetSettings;
|
||||
import carpet.script.exception.InternalExpressionException;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import net.minecraft.nbt.NbtElement;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
@@ -13,6 +11,7 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
public abstract class Value implements Comparable<Value>, Cloneable
|
||||
{
|
||||
@@ -237,7 +236,7 @@ public abstract class Value implements Comparable<Value>, Cloneable
|
||||
}
|
||||
}
|
||||
|
||||
public abstract NbtElement toTag(boolean force);
|
||||
public abstract Tag toTag(boolean force);
|
||||
|
||||
public JsonElement toJson()
|
||||
{
|
||||
|
||||
@@ -5,41 +5,38 @@ import carpet.script.exception.InternalExpressionException;
|
||||
import carpet.script.exception.ThrowStatement;
|
||||
import carpet.script.exception.Throwables;
|
||||
import carpet.utils.BlockInfo;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.block.MapColor;
|
||||
import net.minecraft.block.pattern.CachedBlockPosition;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.ai.brain.LookTarget;
|
||||
import net.minecraft.entity.ai.brain.WalkTarget;
|
||||
import net.minecraft.entity.ai.pathing.Path;
|
||||
import net.minecraft.entity.ai.pathing.PathNode;
|
||||
import net.minecraft.entity.damage.DamageSource;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.particle.ParticleEffect;
|
||||
import net.minecraft.predicate.NumberRange;
|
||||
import net.minecraft.scoreboard.ScoreboardCriterion;
|
||||
import net.minecraft.scoreboard.ScoreboardObjective;
|
||||
import net.minecraft.advancements.critereon.MinMaxBounds;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.GlobalPos;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.Vec3i;
|
||||
import net.minecraft.core.particles.ParticleOptions;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.world.ServerWorld;
|
||||
|
||||
import net.minecraft.state.property.Property;
|
||||
import net.minecraft.structure.StructurePiece;
|
||||
import net.minecraft.structure.StructureStart;
|
||||
import net.minecraft.tag.TagManager;
|
||||
import net.minecraft.util.Identifier;
|
||||
|
||||
import net.minecraft.util.StringIdentifiable;
|
||||
import net.minecraft.util.dynamic.GlobalPos;
|
||||
import net.minecraft.util.math.BlockBox;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Box;
|
||||
import net.minecraft.util.math.ColumnPos;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.util.math.Vec3i;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
import net.minecraft.util.registry.RegistryKey;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import net.minecraft.server.level.ColumnPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.tags.TagContainer;
|
||||
import net.minecraft.util.StringRepresentable;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.ai.behavior.PositionTracker;
|
||||
import net.minecraft.world.entity.ai.memory.WalkTarget;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
import net.minecraft.world.level.levelgen.structure.BoundingBox;
|
||||
import net.minecraft.world.level.levelgen.structure.StructurePiece;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureStart;
|
||||
import net.minecraft.world.level.material.MaterialColor;
|
||||
import net.minecraft.world.level.pathfinder.Node;
|
||||
import net.minecraft.world.level.pathfinder.Path;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraft.world.scores.Objective;
|
||||
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -63,43 +60,43 @@ public class ValueConversions
|
||||
return ListValue.of(new NumericValue(pos.getX()), new NumericValue(pos.getY()), new NumericValue(pos.getZ()));
|
||||
}
|
||||
|
||||
public static Value of(Vec3d vec)
|
||||
public static Value of(Vec3 vec)
|
||||
{
|
||||
return ListValue.of(new NumericValue(vec.x), new NumericValue(vec.y), new NumericValue(vec.z));
|
||||
}
|
||||
|
||||
public static Value of(ColumnPos cpos) { return ListValue.of(new NumericValue(cpos.x), new NumericValue(cpos.z));}
|
||||
|
||||
public static Value of(ServerWorld world)
|
||||
public static Value of(ServerLevel world)
|
||||
{
|
||||
return of(world.getRegistryKey().getValue());
|
||||
return of(world.dimension().location());
|
||||
}
|
||||
|
||||
public static Value of(MapColor color) {return ListValue.of(StringValue.of(BlockInfo.mapColourName.get(color)), ofRGB(color.color));}
|
||||
public static Value of(MaterialColor color) {return ListValue.of(StringValue.of(BlockInfo.mapColourName.get(color)), ofRGB(color.col));}
|
||||
|
||||
public static <T extends Number> Value of(NumberRange<T> range) { return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax()));}
|
||||
public static <T extends Number> Value of(MinMaxBounds<T> range) { return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax()));}
|
||||
|
||||
public static Value of(ItemStack stack)
|
||||
{
|
||||
if (stack == null || stack.isEmpty())
|
||||
return Value.NULL;
|
||||
return ListValue.of(
|
||||
of(Registry.ITEM.getId(stack.getItem())),
|
||||
of(Registry.ITEM.getKey(stack.getItem())),
|
||||
new NumericValue(stack.getCount()),
|
||||
NBTSerializableValue.fromStack(stack)
|
||||
);
|
||||
}
|
||||
|
||||
public static Value of(ScoreboardObjective objective)
|
||||
public static Value of(Objective objective)
|
||||
{
|
||||
return ListValue.of(
|
||||
StringValue.of(objective.getName()),
|
||||
StringValue.of(objective.getCriterion().getName())
|
||||
StringValue.of(objective.getCriteria().getName())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
public static Value of(ScoreboardCriterion criteria)
|
||||
public static Value of(ObjectiveCriteria criteria)
|
||||
{
|
||||
return ListValue.of(
|
||||
StringValue.of(criteria.getName()),
|
||||
@@ -108,20 +105,20 @@ public class ValueConversions
|
||||
}
|
||||
|
||||
|
||||
public static Value of(ParticleEffect particle)
|
||||
public static Value of(ParticleOptions particle)
|
||||
{
|
||||
String repr = particle.asString();
|
||||
String repr = particle.writeToString();
|
||||
if (repr.startsWith("minecraft:")) return StringValue.of(repr.substring(10));
|
||||
return StringValue.of(repr);
|
||||
}
|
||||
|
||||
public static Value ofRGB(int value) {return new NumericValue(value*256+255 );}
|
||||
|
||||
public static World dimFromValue(Value dimensionValue, MinecraftServer server)
|
||||
public static Level dimFromValue(Value dimensionValue, MinecraftServer server)
|
||||
{
|
||||
if (dimensionValue instanceof EntityValue)
|
||||
{
|
||||
return ((EntityValue)dimensionValue).getEntity().getEntityWorld();
|
||||
return ((EntityValue)dimensionValue).getEntity().getCommandSenderWorld();
|
||||
}
|
||||
else if (dimensionValue instanceof BlockValue bv)
|
||||
{
|
||||
@@ -141,20 +138,20 @@ public class ValueConversions
|
||||
{
|
||||
case "nether":
|
||||
case "the_nether":
|
||||
return server.getWorld(World.NETHER);
|
||||
return server.getLevel(Level.NETHER);
|
||||
case "end":
|
||||
case "the_end":
|
||||
return server.getWorld(World.END);
|
||||
return server.getLevel(Level.END);
|
||||
case "overworld":
|
||||
case "over_world":
|
||||
return server.getWorld(World.OVERWORLD);
|
||||
return server.getLevel(Level.OVERWORLD);
|
||||
default:
|
||||
RegistryKey<World> dim = null;
|
||||
Identifier id = new Identifier(dimString);
|
||||
ResourceKey<Level> dim = null;
|
||||
ResourceLocation id = new ResourceLocation(dimString);
|
||||
// not using RegistryKey.of since that one creates on check
|
||||
for (RegistryKey<World> world : (server.getWorldRegistryKeys()))
|
||||
for (ResourceKey<Level> world : (server.levelKeys()))
|
||||
{
|
||||
if (id.equals(world.getValue()))
|
||||
if (id.equals(world.location()))
|
||||
{
|
||||
dim = world;
|
||||
break;
|
||||
@@ -162,17 +159,17 @@ public class ValueConversions
|
||||
}
|
||||
if (dim == null)
|
||||
throw new ThrowStatement(dimString, Throwables.UNKNOWN_DIMENSION);
|
||||
return server.getWorld(dim);
|
||||
return server.getLevel(dim);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Value of(RegistryKey<World> dim)
|
||||
public static Value of(ResourceKey<Level> dim)
|
||||
{
|
||||
return of(dim.getValue());
|
||||
return of(dim.location());
|
||||
}
|
||||
|
||||
public static Value of(Identifier id)
|
||||
public static Value of(ResourceLocation id)
|
||||
{
|
||||
if (id == null) // should be Value.NULL
|
||||
return Value.NULL;
|
||||
@@ -181,7 +178,7 @@ public class ValueConversions
|
||||
return new StringValue(id.toString());
|
||||
}
|
||||
|
||||
public static String simplify(Identifier id)
|
||||
public static String simplify(ResourceLocation id)
|
||||
{
|
||||
if (id == null) // should be Value.NULL
|
||||
return "";
|
||||
@@ -193,23 +190,23 @@ public class ValueConversions
|
||||
public static Value of(GlobalPos pos)
|
||||
{
|
||||
return ListValue.of(
|
||||
ValueConversions.of(pos.getDimension()),
|
||||
ValueConversions.of(pos.getPos())
|
||||
ValueConversions.of(pos.dimension()),
|
||||
ValueConversions.of(pos.pos())
|
||||
);
|
||||
}
|
||||
|
||||
public static Value fromPath(ServerWorld world, Path path)
|
||||
public static Value fromPath(ServerLevel world, Path path)
|
||||
{
|
||||
List<Value> nodes = new ArrayList<>();
|
||||
//for (PathNode node: path.getNodes())
|
||||
for (int i = 0, len = path.getLength(); i < len; i++)
|
||||
for (int i = 0, len = path.getNodeCount(); i < len; i++)
|
||||
{
|
||||
PathNode node = path.getNode(i);
|
||||
Node node = path.getNode(i);
|
||||
nodes.add( ListValue.of(
|
||||
new BlockValue(null, world, node.getBlockPos()),
|
||||
new BlockValue(null, world, node.asBlockPos()),
|
||||
new StringValue(node.type.name().toLowerCase(Locale.ROOT)),
|
||||
new NumericValue(node.penalty),
|
||||
BooleanValue.of(node.visited)
|
||||
new NumericValue(node.costMalus),
|
||||
BooleanValue.of(node.closed)
|
||||
));
|
||||
}
|
||||
return ListValue.wrap(nodes);
|
||||
@@ -234,7 +231,7 @@ public class ValueConversions
|
||||
}
|
||||
if (v instanceof BlockPos)
|
||||
{
|
||||
return new BlockValue(null, (ServerWorld) e.getEntityWorld(), (BlockPos) v);
|
||||
return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), (BlockPos) v);
|
||||
}
|
||||
if (v instanceof Number)
|
||||
{
|
||||
@@ -246,29 +243,29 @@ public class ValueConversions
|
||||
}
|
||||
if (v instanceof UUID)
|
||||
{
|
||||
return ofUUID( (ServerWorld) e.getEntityWorld(), (UUID)v);
|
||||
return ofUUID( (ServerLevel) e.getCommandSenderWorld(), (UUID)v);
|
||||
}
|
||||
if (v instanceof DamageSource source)
|
||||
{
|
||||
return ListValue.of(
|
||||
new StringValue(source.getName()),
|
||||
source.getAttacker()==null?Value.NULL:new EntityValue(source.getAttacker())
|
||||
new StringValue(source.getMsgId()),
|
||||
source.getEntity()==null?Value.NULL:new EntityValue(source.getEntity())
|
||||
);
|
||||
}
|
||||
if (v instanceof Path)
|
||||
{
|
||||
return fromPath((ServerWorld)e.getEntityWorld(), (Path)v);
|
||||
return fromPath((ServerLevel)e.getCommandSenderWorld(), (Path)v);
|
||||
}
|
||||
if (v instanceof LookTarget)
|
||||
if (v instanceof PositionTracker)
|
||||
{
|
||||
return new BlockValue(null, (ServerWorld) e.getEntityWorld(), ((LookTarget)v).getBlockPos());
|
||||
return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((PositionTracker)v).currentBlockPosition());
|
||||
}
|
||||
if (v instanceof WalkTarget)
|
||||
{
|
||||
return ListValue.of(
|
||||
new BlockValue(null, (ServerWorld) e.getEntityWorld(), ((WalkTarget)v).getLookTarget().getBlockPos()),
|
||||
new NumericValue(((WalkTarget) v).getSpeed()),
|
||||
new NumericValue(((WalkTarget) v).getCompletionRange())
|
||||
new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((WalkTarget)v).getTarget().currentBlockPosition()),
|
||||
new NumericValue(((WalkTarget) v).getSpeedModifier()),
|
||||
new NumericValue(((WalkTarget) v).getCloseEnoughDist())
|
||||
);
|
||||
}
|
||||
if (v instanceof Set)
|
||||
@@ -291,7 +288,7 @@ public class ValueConversions
|
||||
return Value.NULL;
|
||||
}
|
||||
|
||||
private static Value ofUUID(ServerWorld entityWorld, UUID uuid)
|
||||
private static Value ofUUID(ServerLevel entityWorld, UUID uuid)
|
||||
{
|
||||
Entity current = entityWorld.getEntity(uuid);
|
||||
return ListValue.of(
|
||||
@@ -299,39 +296,39 @@ public class ValueConversions
|
||||
new StringValue(uuid.toString())
|
||||
);
|
||||
}
|
||||
public static Value of(Box box)
|
||||
public static Value of(AABB box)
|
||||
{
|
||||
return ListValue.of(
|
||||
ListValue.fromTriple(box.minX, box.minY, box.minZ),
|
||||
ListValue.fromTriple(box.maxX, box.maxY, box.maxZ)
|
||||
);
|
||||
}
|
||||
public static Value of(BlockBox box)
|
||||
public static Value of(BoundingBox box)
|
||||
{
|
||||
return ListValue.of(
|
||||
ListValue.fromTriple(box.getMinX(), box.getMinY(), box.getMinZ()),
|
||||
ListValue.fromTriple(box.getMaxX(), box.getMaxY(), box.getMaxZ())
|
||||
ListValue.fromTriple(box.minX(), box.minY(), box.minZ()),
|
||||
ListValue.fromTriple(box.maxX(), box.maxY(), box.maxZ())
|
||||
);
|
||||
}
|
||||
|
||||
public static Value of(StructureStart<?> structure)
|
||||
{
|
||||
if (structure == null || structure == StructureStart.DEFAULT) return Value.NULL;
|
||||
BlockBox boundingBox = structure.getBoundingBox();
|
||||
if (boundingBox.getMaxX() < boundingBox.getMinX() || boundingBox.getMaxY() < boundingBox.getMinY() || boundingBox.getMaxZ() < boundingBox.getMinZ()) return Value.NULL;
|
||||
if (structure == null || structure == StructureStart.INVALID_START) return Value.NULL;
|
||||
BoundingBox boundingBox = structure.getBoundingBox();
|
||||
if (boundingBox.maxX() < boundingBox.minX() || boundingBox.maxY() < boundingBox.minY() || boundingBox.maxZ() < boundingBox.minZ()) return Value.NULL;
|
||||
Map<Value, Value> ret = new HashMap<>();
|
||||
ret.put(new StringValue("box"), of(boundingBox));
|
||||
List<Value> pieces = new ArrayList<>();
|
||||
for (StructurePiece piece : structure.getChildren())
|
||||
for (StructurePiece piece : structure.getPieces())
|
||||
{
|
||||
BlockBox box = piece.getBoundingBox();
|
||||
if (box.getMaxX() >= box.getMinX() && box.getMaxY() >= box.getMinY() && box.getMaxZ() >= box.getMinZ())
|
||||
BoundingBox box = piece.getBoundingBox();
|
||||
if (box.maxX() >= box.minX() && box.maxY() >= box.minY() && box.maxZ() >= box.minZ())
|
||||
{
|
||||
pieces.add(ListValue.of(
|
||||
new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_PIECE.getId(piece.getType()))),
|
||||
(piece.getFacing() == null) ? Value.NULL : new StringValue(piece.getFacing().getName()),
|
||||
ListValue.fromTriple(box.getMinX(), box.getMinY(), box.getMinZ()),
|
||||
ListValue.fromTriple(box.getMaxX(), box.getMaxY(), box.getMaxZ())
|
||||
new StringValue(NBTSerializableValue.nameFromRegistryId(Registry.STRUCTURE_PIECE.getKey(piece.getType()))),
|
||||
(piece.getOrientation() == null) ? Value.NULL : new StringValue(piece.getOrientation().getName()),
|
||||
ListValue.fromTriple(box.minX(), box.minY(), box.minZ()),
|
||||
ListValue.fromTriple(box.maxX(), box.maxY(), box.maxZ())
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -341,11 +338,11 @@ public class ValueConversions
|
||||
|
||||
public static Value fromProperty(BlockState state, Property<?> p)
|
||||
{
|
||||
Comparable<?> object = state.get(p);
|
||||
Comparable<?> object = state.getValue(p);
|
||||
if (object instanceof Boolean || object instanceof Number) return StringValue.of(object.toString());
|
||||
if (object instanceof StringIdentifiable)
|
||||
if (object instanceof StringRepresentable)
|
||||
{
|
||||
return StringValue.of(((StringIdentifiable) object).asString());
|
||||
return StringValue.of(((StringRepresentable) object).getSerializedName());
|
||||
}
|
||||
throw new InternalExpressionException("Unknown property type: "+p.getName());
|
||||
}
|
||||
@@ -395,18 +392,18 @@ public class ValueConversions
|
||||
return ret;
|
||||
}
|
||||
|
||||
public static Value ofBlockPredicate(TagManager tagManager, Predicate<CachedBlockPosition> blockPredicate)
|
||||
public static Value ofBlockPredicate(TagContainer tagManager, Predicate<BlockInWorld> blockPredicate)
|
||||
{
|
||||
BlockPredicateInterface predicateData = (BlockPredicateInterface) blockPredicate;
|
||||
return ListValue.of(
|
||||
predicateData.getCMBlockState()==null?Value.NULL:of(Registry.BLOCK.getId(predicateData.getCMBlockState().getBlock())),
|
||||
predicateData.getCMBlockTag()==null?Value.NULL:of(tagManager.getOrCreateTagGroup(Registry.BLOCK_KEY).getUncheckedTagId(predicateData.getCMBlockTag())),
|
||||
predicateData.getCMBlockState()==null?Value.NULL:of(Registry.BLOCK.getKey(predicateData.getCMBlockState().getBlock())),
|
||||
predicateData.getCMBlockTag()==null?Value.NULL:of(tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getId(predicateData.getCMBlockTag())),
|
||||
MapValue.wrap(predicateData.getCMProperties()),
|
||||
predicateData.getCMDataTag() == null?Value.NULL:new NBTSerializableValue(predicateData.getCMDataTag())
|
||||
);
|
||||
}
|
||||
|
||||
public static Value guess(ServerWorld serverWorld, Object o) {
|
||||
public static Value guess(ServerLevel serverWorld, Object o) {
|
||||
if (o == null)
|
||||
return Value.NULL;
|
||||
if (o instanceof List)
|
||||
@@ -415,22 +412,22 @@ public class ValueConversions
|
||||
return new BlockValue(null, serverWorld, (BlockPos)o);
|
||||
if (o instanceof Entity)
|
||||
return EntityValue.of((Entity) o);
|
||||
if (o instanceof Vec3d)
|
||||
return of((Vec3d)o);
|
||||
if (o instanceof Vec3)
|
||||
return of((Vec3)o);
|
||||
if (o instanceof Vec3i)
|
||||
return of(new BlockPos((Vec3i)o));
|
||||
if (o instanceof Box)
|
||||
return of((Box)o);
|
||||
if (o instanceof BlockBox)
|
||||
return of((BlockBox) o);
|
||||
if (o instanceof AABB)
|
||||
return of((AABB)o);
|
||||
if (o instanceof BoundingBox)
|
||||
return of((BoundingBox) o);
|
||||
if (o instanceof ItemStack)
|
||||
return of((ItemStack)o);
|
||||
if (o instanceof Boolean)
|
||||
return BooleanValue.of((Boolean) o);
|
||||
if (o instanceof Number)
|
||||
return NumericValue.of((Number) o);
|
||||
if (o instanceof Identifier)
|
||||
return of((Identifier)o);
|
||||
if (o instanceof ResourceLocation)
|
||||
return of((ResourceLocation)o);
|
||||
return StringValue.of(o.toString());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user