Migrate the Carpet codebase to Mojang Mappings

This commit is contained in:
altrisi committed 2022-01-24 20:33:16 +01:00
1 parent a1a2488bc3
commit 06af9ce8b1
346 files changed
+8353 -8492

No files matched your search

@@ -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);
}
}
+171 -172
View File
@@ -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);
+2 -3
View File
@@ -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());
}
}