warning cleanup

This commit is contained in:
gnembon committed 2023-02-08 21:13:15 +01:00
1 parent 5ab4a9e442
commit 277872b33c
106 files changed
+4495 -4345

No files matched your search

@@ -9,7 +9,7 @@ public abstract class AbstractListValue extends Value implements Iterable<Value>
{
public List<Value> unpack()
{
final List<Value> retVal = Lists.newArrayList(iterator());
List<Value> retVal = Lists.newArrayList(iterator());
fatality();
return retVal;
}
@@ -18,7 +18,7 @@ public abstract class AbstractListValue extends Value implements Iterable<Value>
{
}
public void append(final Value v)
public void append(Value v)
{
throw new InternalExpressionException("Cannot append a value to an abstract list");
}
@@ -31,6 +31,7 @@ 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.Block;
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;
@@ -38,24 +39,30 @@ import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import javax.annotation.Nullable;
import static carpet.script.value.NBTSerializableValue.nameFromRegistryId;
import static carpet.script.value.NBTSerializableValue.nameFromResource;
public class BlockValue extends Value
{
private BlockState blockState;
private final BlockPos pos;
private final Level world;
private final ServerLevel world;
private CompoundTag data;
public static BlockValue fromCoords(final CarpetContext c, final int x, final int y, final int z)
// we only care for null values a few times, most of the time we would assume its all present
public static final BlockValue NONE = new BlockValue(Blocks.AIR.defaultBlockState(), null, BlockPos.ZERO, null);
public static BlockValue fromCoords(CarpetContext c, int x, int y, int z)
{
final BlockPos pos = locateBlockPos(c, x, y, z);
BlockPos pos = locateBlockPos(c, x, y, z);
return new BlockValue(null, c.level(), pos);
}
private static final Map<String, BlockValue> bvCache = new HashMap<>();
public static BlockValue fromString(final String str, final Level level)
public static BlockValue fromString(String str, ServerLevel level)
{
try
{
@@ -64,7 +71,7 @@ public class BlockValue extends Value
{
return bv;
}
final BlockStateParser.BlockResult foo = BlockStateParser.parseForBlock(level.registryAccess().lookupOrThrow(Registries.BLOCK), new StringReader(str), true);
BlockStateParser.BlockResult foo = BlockStateParser.parseForBlock(level.registryAccess().lookupOrThrow(Registries.BLOCK), new StringReader(str), true);
if (foo.blockState() != null)
{
CompoundTag bd = foo.nbt();
@@ -81,15 +88,15 @@ public class BlockValue extends Value
return bv;
}
}
catch (final CommandSyntaxException ignored)
catch (CommandSyntaxException ignored)
{
}
throw new ThrowStatement(str, Throwables.UNKNOWN_BLOCK);
}
public static BlockPos locateBlockPos(final CarpetContext c, final int xpos, final int ypos, final int zpos)
public static BlockPos locateBlockPos(CarpetContext c, int xpos, int ypos, int zpos)
{
final BlockPos pos = c.origin();
BlockPos pos = c.origin();
return new BlockPos(pos.getX() + xpos, pos.getY() + ypos, pos.getZ() + zpos);
}
@@ -107,7 +114,7 @@ public class BlockValue extends Value
throw new InternalExpressionException("Attempted to fetch block state without world or stored block state");
}
public static BlockEntity getBlockEntity(final Level level, final BlockPos pos)
public static BlockEntity getBlockEntity(Level level, BlockPos pos)
{
if (level instanceof final ServerLevel serverLevel)
{
@@ -127,7 +134,7 @@ public class BlockValue extends Value
}
if (pos != null)
{
final BlockEntity be = getBlockEntity(world, pos);
BlockEntity be = getBlockEntity(world, pos);
if (be == null)
{
data = new CompoundTag();
@@ -140,7 +147,7 @@ public class BlockValue extends Value
}
public BlockValue(final BlockState state, final Level world, final BlockPos position)
public BlockValue(BlockState state, ServerLevel world, BlockPos position)
{
this.world = world;
blockState = state;
@@ -148,7 +155,39 @@ public class BlockValue extends Value
data = null;
}
public BlockValue(final BlockState state, final Level world, final BlockPos position, final CompoundTag nbt)
public BlockValue(BlockState state)
{
this.world = null;
blockState = state;
pos = null;
data = null;
}
public BlockValue(ServerLevel world, BlockPos position)
{
this.world = world;
blockState = null;
pos = position;
data = null;
}
public BlockValue(BlockState state, CompoundTag nbt)
{
this.world = null;
blockState = state;
pos = null;
data = nbt;
}
public BlockValue(BlockState state, ServerLevel world, CompoundTag nbt)
{
this.world = world;
blockState = state;
pos = null;
data = nbt;
}
private BlockValue(@Nullable BlockState state, @Nullable ServerLevel world, @Nullable BlockPos position, @Nullable CompoundTag nbt)
{
this.world = world;
blockState = state;
@@ -160,8 +199,8 @@ public class BlockValue extends Value
@Override
public String getString()
{
final Registry<Block> blockRegistry = world.registryAccess().registryOrThrow(Registries.BLOCK);
return nameFromRegistryId(blockRegistry.getKey(getBlockState().getBlock()));
Registry<Block> blockRegistry = world.registryAccess().registryOrThrow(Registries.BLOCK);
return nameFromResource(blockRegistry.getKey(getBlockState().getBlock()));
}
@Override
@@ -201,29 +240,29 @@ public class BlockValue extends Value
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
if (!force)
{
throw new NBTSerializableValue.IncompatibleTypeException(this);
}
// follows falling block convertion
final CompoundTag tag = new CompoundTag();
final CompoundTag state = new CompoundTag();
final BlockState s = getBlockState();
CompoundTag tag = new CompoundTag();
CompoundTag state = new CompoundTag();
BlockState s = getBlockState();
state.put("Name", StringTag.valueOf(world.registryAccess().registryOrThrow(Registries.BLOCK).getKey(s.getBlock()).toString()));
final Collection<Property<?>> properties = s.getProperties();
Collection<Property<?>> properties = s.getProperties();
if (!properties.isEmpty())
{
final CompoundTag props = new CompoundTag();
for (final Property<?> p : properties)
CompoundTag props = new CompoundTag();
for (Property<?> p : properties)
{
props.put(p.getName(), StringTag.valueOf(s.getValue(p).toString().toLowerCase(Locale.ROOT)));
}
state.put("Properties", props);
}
tag.put("BlockState", state);
final CompoundTag dataTag = getData();
CompoundTag dataTag = getData();
if (dataTag != null)
{
tag.put("TileEntityData", dataTag);
@@ -265,7 +304,7 @@ public class BlockValue extends Value
private static final Map<String, SpecificDirection> DIRECTION_MAP = Arrays.stream(values()).collect(Collectors.toMap(SpecificDirection::getName, d -> d));
SpecificDirection(final String name, final double hitx, final double hity, final double hitz, final Direction blockFacing)
SpecificDirection(String name, double hitx, double hity, double hitz, Direction blockFacing)
{
this.name = name;
this.hitOffset = new Vec3(hitx, hity, hitz);
@@ -283,18 +322,18 @@ public class BlockValue extends Value
private final Direction facing;
private final boolean sneakPlace;
public static PlacementContext from(final Level world, final BlockPos pos, final String direction, final boolean sneakPlace, final ItemStack itemStack)
public static PlacementContext from(Level world, BlockPos pos, String direction, boolean sneakPlace, ItemStack itemStack)
{
final SpecificDirection dir = SpecificDirection.DIRECTION_MAP.get(direction);
SpecificDirection dir = SpecificDirection.DIRECTION_MAP.get(direction);
if (dir == null)
{
throw new InternalExpressionException("unknown block placement direction: " + direction);
}
final BlockHitResult hitres = new BlockHitResult(Vec3.atLowerCornerOf(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(final Level world_1, final Direction direction_1, final boolean sneakPlace, final ItemStack itemStack_1, final BlockHitResult 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;
@@ -304,9 +343,9 @@ public class BlockValue extends Value
@Override
public BlockPos getClickedPos()
{
final boolean prevcanReplaceExisting = replaceClicked;
boolean prevcanReplaceExisting = replaceClicked;
replaceClicked = true;
final BlockPos ret = super.getClickedPos();
BlockPos ret = super.getClickedPos();
replaceClicked = prevcanReplaceExisting;
return ret;
}
@@ -12,13 +12,13 @@ public class BooleanValue extends NumericValue
boolean boolValue;
private BooleanValue(final boolean boolval)
private BooleanValue(boolean boolval)
{
super(boolval ? 1L : 0L);
boolValue = boolval;
}
public static BooleanValue of(final boolean value)
public static BooleanValue of(boolean value)
{
return value ? TRUE : FALSE;
}
@@ -54,7 +54,7 @@ public class BooleanValue extends NumericValue
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
return ByteTag.valueOf(boolValue);
}
@@ -4,7 +4,7 @@ public interface ContainerValueInterface
{
boolean put(Value where, Value value);
default boolean put(final Value where, final Value value, final Value conditions)
default boolean put(Value where, Value value, Value conditions)
{
return put(where, value);
}
+145 -144
View File
@@ -74,6 +74,7 @@ import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
@@ -97,19 +98,19 @@ public class EntityValue extends Value
{
private Entity entity;
public EntityValue(final Entity e)
public EntityValue(Entity e)
{
entity = e;
}
public static Value of(final Entity e)
public static Value of(@Nullable Entity e)
{
return e == null ? Value.NULL : new EntityValue(e);
}
private static final Map<String, EntitySelector> selectorCache = new HashMap<>();
public static Collection<? extends Entity> getEntitiesFromSelector(final CommandSourceStack source, final String selector)
public static Collection<? extends Entity> getEntitiesFromSelector(CommandSourceStack source, String selector)
{
try
{
@@ -122,7 +123,7 @@ public class EntityValue extends Value
selectorCache.put(selector, entitySelector);
return entitySelector.findEntities(source.withMaximumPermission(4));
}
catch (final CommandSyntaxException e)
catch (CommandSyntaxException e)
{
throw new InternalExpressionException("Cannot select entities from " + selector);
}
@@ -132,7 +133,7 @@ public class EntityValue extends Value
{
if (entity instanceof final ServerPlayer serverPlayer && Vanilla.ServerPlayer_isInvalidEntityObject(serverPlayer))
{
final ServerPlayer newPlayer = entity.getServer().getPlayerList().getPlayer(entity.getUUID());
ServerPlayer newPlayer = entity.getServer().getPlayerList().getPlayer(entity.getUUID());
if (newPlayer != null)
{
entity = newPlayer;
@@ -141,7 +142,7 @@ public class EntityValue extends Value
return entity;
}
public static ServerPlayer getPlayerByValue(final MinecraftServer server, final Value value)
public static ServerPlayer getPlayerByValue(MinecraftServer server, Value value)
{
if (value instanceof final EntityValue ev && ev.getEntity() instanceof final ServerPlayer sp)
{
@@ -151,11 +152,11 @@ public class EntityValue extends Value
{
return null;
}
final String playerName = value.getString();
String playerName = value.getString();
return server.getPlayerList().getPlayerByName(playerName);
}
public static String getPlayerNameByValue(final Value value)
public static String getPlayerNameByValue(Value value)
{
if (value instanceof final EntityValue ev && ev.getEntity() instanceof final ServerPlayer sp)
{
@@ -181,7 +182,7 @@ public class EntityValue extends Value
}
@Override
public boolean equals(final Object v)
public boolean equals(Object v)
{
if (v instanceof final EntityValue ev)
{
@@ -191,12 +192,12 @@ public class EntityValue extends Value
}
@Override
public Value in(final Value v)
public Value in(Value v)
{
if (v instanceof final ListValue lv)
{
final List<Value> values = lv.getItems();
final String what = values.get(0).getString();
List<Value> values = lv.getItems();
String what = values.get(0).getString();
Value arg = null;
if (values.size() == 2)
{
@@ -208,7 +209,7 @@ public class EntityValue extends Value
}
return this.get(what, arg);
}
final String what = v.getString();
String what = v.getString();
return this.get(what, null);
}
@@ -226,9 +227,9 @@ public class EntityValue extends Value
public static final EntityTypeTest<Entity, ?> ANY = EntityTypeTest.forClass(Entity.class);
public static EntityClassDescriptor getEntityDescriptor(String who, final MinecraftServer server)
public static EntityClassDescriptor getEntityDescriptor(String who, MinecraftServer server)
{
final EntityClassDescriptor eDesc = EntityClassDescriptor.byName.get(who);
EntityClassDescriptor eDesc = EntityClassDescriptor.byName.get(who);
if (eDesc == null)
{
boolean positive = true;
@@ -237,16 +238,16 @@ public class EntityValue extends Value
positive = false;
who = who.substring(1);
}
final String booWho = who;
final HolderSet.Named<EntityType<?>> eTagValue = server.registryAccess().registryOrThrow(Registries.ENTITY_TYPE)
String booWho = who;
HolderSet.Named<EntityType<?>> eTagValue = server.registryAccess().registryOrThrow(Registries.ENTITY_TYPE)
.getTag(TagKey.create(Registries.ENTITY_TYPE, InputValidator.identifierOf(who)))
.orElseThrow(() -> new InternalExpressionException(booWho + " is not a valid entity descriptor"));
final Set<EntityType<?>> eTag = eTagValue.stream().map(Holder::value).collect(Collectors.toUnmodifiableSet());
Set<EntityType<?>> eTag = eTagValue.stream().map(Holder::value).collect(Collectors.toUnmodifiableSet());
if (positive)
{
if (eTag.size() == 1)
{
final EntityType<?> type = eTag.iterator().next();
EntityType<?> type = eTag.iterator().next();
return new EntityClassDescriptor(type, Entity::isAlive, eTag.stream());
}
else
@@ -270,36 +271,36 @@ public class EntityValue extends Value
public final Predicate<? super Entity> filteringPredicate;
public final List<EntityType<? extends Entity>> types;
EntityClassDescriptor(final EntityTypeTest<Entity, ?> type, final Predicate<? super Entity> predicate, final List<EntityType<?>> types)
EntityClassDescriptor(EntityTypeTest<Entity, ?> type, Predicate<? super Entity> predicate, List<EntityType<?>> types)
{
this.directType = type;
this.filteringPredicate = predicate;
this.types = types;
}
EntityClassDescriptor(final EntityTypeTest<Entity, ?> type, final Predicate<? super Entity> predicate, final Stream<EntityType<?>> types)
EntityClassDescriptor(EntityTypeTest<Entity, ?> type, Predicate<? super Entity> predicate, Stream<EntityType<?>> types)
{
this(type, predicate, types.toList());
}
public Value listValue(final RegistryAccess regs)
public Value listValue(RegistryAccess regs)
{
final Registry<EntityType> entityRegs = regs.registryOrThrow(Registries.ENTITY_TYPE);
return ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(entityRegs.getKey(et)))));
Registry<EntityType<?>> entityRegs = regs.registryOrThrow(Registries.ENTITY_TYPE);
return ListValue.wrap(types.stream().map(et -> nameFromRegistryId(entityRegs.getKey(et))));
}
public static final Map<String, EntityClassDescriptor> byName = new HashMap<>()
{{
final List<EntityType<?>> allTypes = BuiltInRegistries.ENTITY_TYPE.stream().toList();
List<EntityType<?>> allTypes = BuiltInRegistries.ENTITY_TYPE.stream().toList();
// nonliving types
final Set<EntityType<?>> projectiles = Set.of(
Set<EntityType<?>> projectiles = Set.of(
EntityType.ARROW, EntityType.DRAGON_FIREBALL, EntityType.FIREWORK_ROCKET,
EntityType.FIREBALL, EntityType.LLAMA_SPIT, EntityType.SMALL_FIREBALL,
EntityType.SNOWBALL, EntityType.SPECTRAL_ARROW, EntityType.EGG,
EntityType.ENDER_PEARL, EntityType.EXPERIENCE_BOTTLE, EntityType.POTION,
EntityType.TRIDENT, EntityType.WITHER_SKULL, EntityType.FISHING_BOBBER, EntityType.SHULKER_BULLET
);
final Set<EntityType<?>> deads = Set.of(
Set<EntityType<?>> deads = Set.of(
EntityType.AREA_EFFECT_CLOUD, EntityType.MARKER, EntityType.BOAT, EntityType.END_CRYSTAL,
EntityType.EVOKER_FANGS, EntityType.EXPERIENCE_ORB, EntityType.EYE_OF_ENDER,
EntityType.FALLING_BLOCK, EntityType.ITEM, EntityType.ITEM_FRAME, EntityType.GLOW_ITEM_FRAME,
@@ -307,37 +308,37 @@ public class EntityValue extends Value
EntityType.TNT, EntityType.ARMOR_STAND, EntityType.CHEST_BOAT
);
final Set<EntityType<?>> minecarts = Set.of(
Set<EntityType<?>> minecarts = Set.of(
EntityType.MINECART, EntityType.CHEST_MINECART, EntityType.COMMAND_BLOCK_MINECART,
EntityType.FURNACE_MINECART, EntityType.HOPPER_MINECART,
EntityType.SPAWNER_MINECART, EntityType.TNT_MINECART
);
// living mob groups - non-defeault
final Set<EntityType<?>> undeads = Set.of(
Set<EntityType<?>> undeads = Set.of(
EntityType.STRAY, EntityType.SKELETON, EntityType.WITHER_SKELETON,
EntityType.ZOMBIE, EntityType.DROWNED, EntityType.ZOMBIE_VILLAGER,
EntityType.ZOMBIE_HORSE, EntityType.SKELETON_HORSE, EntityType.PHANTOM,
EntityType.WITHER, EntityType.ZOGLIN, EntityType.HUSK, EntityType.ZOMBIFIED_PIGLIN
);
final Set<EntityType<?>> arthropods = Set.of(
Set<EntityType<?>> arthropods = Set.of(
EntityType.BEE, EntityType.ENDERMITE, EntityType.SILVERFISH, EntityType.SPIDER,
EntityType.CAVE_SPIDER
);
final Set<EntityType<?>> aquatique = Set.of(
Set<EntityType<?>> aquatique = Set.of(
EntityType.GUARDIAN, EntityType.TURTLE, EntityType.COD, EntityType.DOLPHIN, EntityType.PUFFERFISH,
EntityType.SALMON, EntityType.SQUID, EntityType.TROPICAL_FISH
);
final Set<EntityType<?>> illagers = Set.of(
Set<EntityType<?>> illagers = Set.of(
EntityType.PILLAGER, EntityType.ILLUSIONER, EntityType.VINDICATOR, EntityType.EVOKER,
EntityType.RAVAGER, EntityType.WITCH
);
final Set<EntityType<?>> living = allTypes.stream().filter(et ->
Set<EntityType<?>> living = allTypes.stream().filter(et ->
!deads.contains(et) && !projectiles.contains(et) && !minecarts.contains(et)
).collect(Collectors.toSet());
final Set<EntityType<?>> regular = allTypes.stream().filter(et ->
Set<EntityType<?>> regular = allTypes.stream().filter(et ->
living.contains(et) && !undeads.contains(et) && !arthropods.contains(et) && !aquatique.contains(et) && !illagers.contains(et)
).collect(Collectors.toSet());
@@ -373,23 +374,23 @@ public class EntityValue extends Value
put("regular", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.UNDEFINED && e.isAlive()), allTypes.stream().filter(regular::contains)));
put("!regular", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.UNDEFINED && e.isAlive()), allTypes.stream().filter(et -> !regular.contains(et) && living.contains(et))));
for (final ResourceLocation typeId : BuiltInRegistries.ENTITY_TYPE.keySet())
for (ResourceLocation typeId : BuiltInRegistries.ENTITY_TYPE.keySet())
{
final EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.get(typeId);
final String mobType = ValueConversions.simplify(typeId);
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.get(typeId);
String mobType = ValueConversions.simplify(typeId);
put(mobType, new EntityClassDescriptor(type, net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, Stream.of(type)));
put("!" + mobType, new EntityClassDescriptor(ANY, (e) -> e.getType() != type && e.isAlive(), allTypes.stream().filter(et -> et != type)));
}
for (final MobCategory catId : MobCategory.values())
for (MobCategory catId : MobCategory.values())
{
final String catStr = catId.getName();
String catStr = catId.getName();
put(catStr, new EntityClassDescriptor(ANY, e -> ((e.getType().getCategory() == catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() == catId)));
put("!" + catStr, new EntityClassDescriptor(ANY, e -> ((e.getType().getCategory() != catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() != catId)));
}
}};
}
public Value get(final String what, final Value arg)
public Value get(String what, @Nullable Value arg)
{
if (!(featureAccessors.containsKey(what)))
{
@@ -399,7 +400,7 @@ public class EntityValue extends Value
{
return featureAccessors.get(what).apply(getEntity(), arg);
}
catch (final NullPointerException npe)
catch (NullPointerException npe)
{
throw new InternalExpressionException("Cannot fetch '" + what + "' with these arguments");
}
@@ -427,7 +428,7 @@ public class EntityValue extends Value
put("z", (e, a) -> new NumericValue(e.getZ()));
put("motion", (e, a) ->
{
final Vec3 velocity = e.getDeltaMovement();
Vec3 velocity = e.getDeltaMovement();
return ListValue.of(new NumericValue(velocity.x), new NumericValue(velocity.y), new NumericValue(velocity.z));
});
put("motion_x", (e, a) -> new NumericValue(e.getDeltaMovement().x));
@@ -438,7 +439,7 @@ public class EntityValue extends Value
put("display_name", (e, a) -> new FormattedTextValue(e.getDisplayName()));
put("command_name", (e, a) -> new StringValue(e.getScoreboardName()));
put("custom_name", (e, a) -> e.hasCustomName() ? new StringValue(e.getCustomName().getString()) : Value.NULL);
put("type", (e, a) -> new StringValue(nameFromRegistryId(e.getLevel().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(e.getType()))));
put("type", (e, a) -> nameFromRegistryId(e.getLevel().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(e.getType())));
put("is_riding", (e, a) -> BooleanValue.of(e.isPassenger()));
put("is_ridden", (e, a) -> BooleanValue.of(e.isVehicle()));
put("passengers", (e, a) -> ListValue.wrap(e.getPassengers().stream().map(EntityValue::new)));
@@ -449,7 +450,7 @@ public class EntityValue extends Value
put("scoreboard_tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new)));
put("entity_tags", (e, a) -> {
final EntityType<?> type = e.getType();
EntityType<?> type = e.getType();
return ListValue.wrap(e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTags().filter(entry -> entry.getSecond().stream().anyMatch(h -> h.value() == type)).map(entry -> ValueConversions.of(entry.getFirst())));
});
// deprecated
@@ -457,7 +458,7 @@ public class EntityValue extends Value
put("has_scoreboard_tag", (e, a) -> BooleanValue.of(e.getTags().contains(a.getString())));
put("has_entity_tag", (e, a) -> {
final Optional<HolderSet.Named<EntityType<?>>> tag = e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTag(TagKey.create(Registries.ENTITY_TYPE, InputValidator.identifierOf(a.getString())));
Optional<HolderSet.Named<EntityType<?>>> tag = e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTag(TagKey.create(Registries.ENTITY_TYPE, InputValidator.identifierOf(a.getString())));
if (tag.isEmpty())
{
return Value.NULL;
@@ -465,7 +466,7 @@ public class EntityValue extends Value
//Tag<EntityType<?>> tag = e.getServer().getTags().getOrEmpty(Registry.ENTITY_TYPE_REGISTRY).getTag(InputValidator.identifierOf(a.getString()));
//if (tag == null) return Value.NULL;
//return BooleanValue.of(e.getType().is(tag));
final EntityType<?> type = e.getType();
EntityType<?> type = e.getType();
return BooleanValue.of(tag.get().stream().anyMatch(h -> h.value() == type));
});
@@ -475,7 +476,7 @@ public class EntityValue extends Value
put("pitch", (e, a) -> new NumericValue(e.getXRot()));
put("look", (e, a) -> {
final Vec3 look = e.getLookAngle();
Vec3 look = e.getLookAngle();
return ListValue.of(new NumericValue(look.x), new NumericValue(look.y), new NumericValue(look.z));
});
put("is_burning", (e, a) -> BooleanValue.of(e.isOnFire()));
@@ -488,7 +489,7 @@ public class EntityValue extends Value
put("immune_to_frost", (e, a) -> BooleanValue.of(!e.canFreeze()));
put("invulnerable", (e, a) -> BooleanValue.of(e.isInvulnerable()));
put("dimension", (e, a) -> new StringValue(nameFromRegistryId(e.level.dimension().location()))); // getDimId
put("dimension", (e, a) -> nameFromRegistryId(e.level.dimension().location())); // getDimId
put("height", (e, a) -> new NumericValue(e.getDimensions(Pose.STANDING).height));
put("width", (e, a) -> new NumericValue(e.getDimensions(Pose.STANDING).width));
put("eye_height", (e, a) -> new NumericValue(e.getEyeHeight()));
@@ -507,7 +508,7 @@ public class EntityValue extends Value
put("target", (e, a) -> {
if (e instanceof final Mob mob)
{
final LivingEntity target = mob.getTarget(); // there is also getAttacking in living....
LivingEntity target = mob.getTarget(); // there is also getAttacking in living....
if (target != null)
{
return new EntityValue(target);
@@ -515,7 +516,7 @@ public class EntityValue extends Value
}
return Value.NULL;
});
put("home", (e, a) -> e instanceof final Mob mob ? (mob.getRestrictRadius() > 0) ? new BlockValue(null, e.getCommandSenderWorld(), mob.getRestrictCenter()) : Value.FALSE : Value.NULL);
put("home", (e, a) -> e instanceof final Mob mob ? (mob.getRestrictRadius() > 0) ? new BlockValue(null, (ServerLevel) e.getLevel(), mob.getRestrictCenter()) : Value.FALSE : Value.NULL);
put("spawn_point", (e, a) -> {
if (e instanceof final ServerPlayer spe)
{
@@ -553,7 +554,7 @@ public class EntityValue extends Value
put("path", (e, a) -> {
if (e instanceof final Mob mob)
{
final Path path = mob.getNavigation().getPath();
Path path = mob.getNavigation().getPath();
if (path == null)
{
return Value.NULL;
@@ -564,22 +565,22 @@ public class EntityValue extends Value
});
put("brain", (e, a) -> {
final String module = a.getString();
final MemoryModuleType<?> moduleType = e.getLevel().registryAccess().registryOrThrow(Registries.MEMORY_MODULE_TYPE).get(InputValidator.identifierOf(module));
String module = a.getString();
MemoryModuleType<?> moduleType = e.getLevel().registryAccess().registryOrThrow(Registries.MEMORY_MODULE_TYPE).get(InputValidator.identifierOf(module));
if (moduleType == MemoryModuleType.DUMMY)
{
return Value.NULL;
}
if (e instanceof final LivingEntity livingEntity)
{
final Brain<?> brain = livingEntity.getBrain();
final Map<MemoryModuleType<?>, Optional<? extends ExpirableValue<?>>> memories = brain.getMemories();
final Optional<? extends ExpirableValue<?>> optmemory = memories.get(moduleType);
Brain<?> brain = livingEntity.getBrain();
Map<MemoryModuleType<?>, Optional<? extends ExpirableValue<?>>> memories = brain.getMemories();
Optional<? extends ExpirableValue<?>> optmemory = memories.get(moduleType);
if (optmemory == null || !optmemory.isPresent())
{
return Value.NULL;
}
final ExpirableValue<?> memory = optmemory.get();
ExpirableValue<?> memory = optmemory.get();
return ValueConversions.fromTimedMemory(e, memory.getTimeToLive(), memory.getValue());
}
return Value.NULL;
@@ -604,22 +605,22 @@ public class EntityValue extends Value
put("player_type", (e, a) -> {
if (e instanceof final Player p)
{
final String moddedType = Carpet.isModdedPlayer(p);
String moddedType = Carpet.isModdedPlayer(p);
if (moddedType != null)
{
return StringValue.of(moddedType);
}
final MinecraftServer server = p.getCommandSenderWorld().getServer();
MinecraftServer server = p.getCommandSenderWorld().getServer();
if (server.isDedicatedServer())
{
return new StringValue("multiplayer");
}
final boolean runningLan = server.isPublished();
boolean runningLan = server.isPublished();
if (!runningLan)
{
return new StringValue("singleplayer");
}
final boolean isowner = server.isSingleplayerOwner(p.getGameProfile());
boolean isowner = server.isSingleplayerOwner(p.getGameProfile());
if (isowner)
{
return new StringValue("lan_host");
@@ -644,8 +645,8 @@ public class EntityValue extends Value
}
if (a == null)
{
final List<Value> effects = new ArrayList<>();
for (final MobEffectInstance p : le.getActiveEffects())
List<Value> effects = new ArrayList<>();
for (MobEffectInstance p : le.getActiveEffects())
{
effects.add(ListValue.of(
new StringValue(p.getDescriptionId().replaceFirst("^effect\\.minecraft\\.", "")),
@@ -655,8 +656,8 @@ public class EntityValue extends Value
}
return ListValue.wrap(effects);
}
final String effectName = a.getString();
final MobEffect potion = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName));
String effectName = a.getString();
MobEffect potion = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName));
if (potion == null)
{
throw new InternalExpressionException("No such an effect: " + effectName);
@@ -665,7 +666,7 @@ public class EntityValue extends Value
{
return Value.NULL;
}
final MobEffectInstance pe = le.getEffect(potion);
MobEffectInstance pe = le.getEffect(potion);
return ListValue.of(new NumericValue(pe.getAmplifier()), new NumericValue(pe.getDuration()));
});
@@ -698,12 +699,12 @@ public class EntityValue extends Value
put("active_block", (e, a) -> {
if (e instanceof final ServerPlayer sp)
{
final BlockPos pos = Vanilla.ServerPlayerGameMode_getCurrentBlockPosition(sp.gameMode);
BlockPos pos = Vanilla.ServerPlayerGameMode_getCurrentBlockPosition(sp.gameMode);
if (pos == null)
{
return Value.NULL;
}
return new BlockValue(null, e.level, pos);
return new BlockValue(null, sp.getLevel(), pos);
}
return Value.NULL;
});
@@ -711,7 +712,7 @@ public class EntityValue extends Value
put("breaking_progress", (e, a) -> {
if (e instanceof final ServerPlayer sp)
{
final int progress = Vanilla.ServerPlayerGameMode_getCurrentBlockBreakingProgress (sp.gameMode);
int progress = Vanilla.ServerPlayerGameMode_getCurrentBlockBreakingProgress (sp.gameMode);
return progress < 0 ? Value.NULL : new NumericValue(progress);
}
return Value.NULL;
@@ -748,7 +749,7 @@ public class EntityValue extends Value
}
else
{
final List<Value> args = lv.getItems();
List<Value> args = lv.getItems();
if (args.size() == 0)
{
throw new InternalExpressionException("'trace' needs more arguments");
@@ -760,7 +761,7 @@ public class EntityValue extends Value
blocks = false;
for (int i = 1; i < args.size(); i++)
{
final String what = args.get(i).getString();
String what = args.get(i).getString();
if (what.equalsIgnoreCase("entities"))
{
entities = true;
@@ -791,7 +792,7 @@ public class EntityValue extends Value
reach = 5.0f;
}
final HitResult hitres;
HitResult hitres;
if (entities && !blocks)
{
hitres = Tracer.rayTraceEntities(e, 1, reach, reach * reach);
@@ -818,7 +819,7 @@ public class EntityValue extends Value
case MISS:
return Value.NULL;
case BLOCK:
return new BlockValue(null, e.getCommandSenderWorld(), ((BlockHitResult) hitres).getBlockPos());
return new BlockValue((ServerLevel) e.getCommandSenderWorld(), ((BlockHitResult) hitres).getBlockPos());
case ENTITY:
return new EntityValue(((EntityHitResult) hitres).getEntity());
}
@@ -830,14 +831,14 @@ public class EntityValue extends Value
{
return Value.NULL;
}
final Registry<Attribute> attributes = e.getLevel().registryAccess().registryOrThrow(Registries.ATTRIBUTE);
Registry<Attribute> attributes = e.getLevel().registryAccess().registryOrThrow(Registries.ATTRIBUTE);
if (a == null)
{
final AttributeMap container = el.getAttributes();
AttributeMap container = el.getAttributes();
return MapValue.wrap(attributes.stream().filter(container::hasAttribute).collect(Collectors.toMap(aa -> ValueConversions.of(attributes.getKey(aa)), aa -> NumericValue.of(container.getValue(aa)))));
}
final ResourceLocation id = InputValidator.identifierOf(a.getString());
final Attribute attrib = attributes.getOptional(id).orElseThrow(
ResourceLocation id = InputValidator.identifierOf(a.getString());
Attribute attrib = attributes.getOptional(id).orElseThrow(
() -> new InternalExpressionException("Unknown attribute: " + a.getString())
);
if (!el.getAttributes().hasAttribute(attrib))
@@ -848,7 +849,7 @@ public class EntityValue extends Value
});
put("nbt", (e, a) -> {
final CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag()));
CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag()));
if (a == null)
{
return new NBTSerializableValue(nbttagcompound);
@@ -861,7 +862,7 @@ public class EntityValue extends Value
});
}};
public void set(final String what, final Value toWhat)
public void set(String what, @Nullable Value toWhat)
{
if (!(featureModifiers.containsKey(what)))
{
@@ -871,17 +872,17 @@ public class EntityValue extends Value
{
featureModifiers.get(what).accept(getEntity(), toWhat);
}
catch (final NullPointerException npe)
catch (NullPointerException npe)
{
throw new InternalExpressionException("'modify' for '" + what + "' expects a value");
}
catch (final IndexOutOfBoundsException ind)
catch (IndexOutOfBoundsException ind)
{
throw new InternalExpressionException("Wrong number of arguments for `modify` option: " + what);
}
}
private static void updatePosition(final Entity e, final double x, final double y, final double z, final float yaw, final float pitch)
private static void updatePosition(Entity e, double x, double y, double z, float yaw, float pitch)
{
if (
!Double.isFinite(x) || Double.isNaN(x) ||
@@ -896,7 +897,7 @@ public class EntityValue extends Value
if (e instanceof final ServerPlayer sp)
{
// this forces position but doesn't angles for some reason. Need both in the API in the future.
final EnumSet<RelativeMovement> set = EnumSet.noneOf(RelativeMovement.class);
EnumSet<RelativeMovement> set = EnumSet.noneOf(RelativeMovement.class);
set.add(RelativeMovement.X_ROT);
set.add(RelativeMovement.Y_ROT);
sp.connection.teleport(x, y, z, yaw, pitch, set);
@@ -921,7 +922,7 @@ public class EntityValue extends Value
}
}
private static void updateVelocity(final Entity e, final double scale)
private static void updateVelocity(Entity e, double scale)
{
e.hurtMarked = true;
if (Math.abs(scale) > 10000)
@@ -935,7 +936,7 @@ public class EntityValue extends Value
put("remove", (entity, value) -> entity.discard()); // using discard here - will see other options if valid
put("age", (e, v) -> e.tickCount = Math.abs((int) NumericValue.asNumber(v).getLong()));
put("health", (e, v) -> {
final float health = (float) NumericValue.asNumber(v).getDouble();
float health = (float) NumericValue.asNumber(v).getDouble();
if (health <= 0f && e instanceof final ServerPlayer player)
{
if (player.containerMenu != null)
@@ -954,7 +955,7 @@ public class EntityValue extends Value
});
put("may_fly", (e, v) -> {
final boolean mayFly = v.getBoolean();
boolean mayFly = v.getBoolean();
if (e instanceof final ServerPlayer player)
{
player.getAbilities().mayfly = mayFly;
@@ -967,7 +968,7 @@ public class EntityValue extends Value
});
put("flying", (e, v) -> {
final boolean flying = v.getBoolean();
boolean flying = v.getBoolean();
if (e instanceof final ServerPlayer player)
{
player.getAbilities().flying = flying;
@@ -976,7 +977,7 @@ public class EntityValue extends Value
});
put("may_build", (e, v) -> {
final boolean mayBuild = v.getBoolean();
boolean mayBuild = v.getBoolean();
if (e instanceof final ServerPlayer player)
{
player.getAbilities().mayBuild = mayBuild;
@@ -985,7 +986,7 @@ public class EntityValue extends Value
});
put("insta_build", (e, v) -> {
final boolean instaBuild = v.getBoolean();
boolean instaBuild = v.getBoolean();
if (e instanceof final ServerPlayer player)
{
player.getAbilities().instabuild = instaBuild;
@@ -994,7 +995,7 @@ public class EntityValue extends Value
});
put("fly_speed", (e, v) -> {
final float flySpeed = NumericValue.asNumber(v).getFloat();
float flySpeed = NumericValue.asNumber(v).getFloat();
if (e instanceof final ServerPlayer player)
{
player.getAbilities().setFlyingSpeed(flySpeed);
@@ -1003,7 +1004,7 @@ public class EntityValue extends Value
});
put("walk_speed", (e, v) -> {
final float walkSpeed = NumericValue.asNumber(v).getFloat();
float walkSpeed = NumericValue.asNumber(v).getFloat();
if (e instanceof final ServerPlayer player)
{
player.getAbilities().setWalkingSpeed(walkSpeed);
@@ -1015,7 +1016,7 @@ public class EntityValue extends Value
{
if (e instanceof final ServerPlayer player)
{
final int slot = NumericValue.asNumber(v).getInt();
int slot = NumericValue.asNumber(v).getInt();
player.connection.send(new ClientboundSetCarriedItemPacket(slot));
}
});
@@ -1042,7 +1043,7 @@ public class EntityValue extends Value
{
throw new InternalExpressionException("Expected a list of 5 parameters as a second argument");
}
final List<Value> coords = lv.getItems();
List<Value> coords = lv.getItems();
updatePosition(e,
NumericValue.asNumber(coords.get(0)).getDouble(),
NumericValue.asNumber(coords.get(1)).getDouble(),
@@ -1057,7 +1058,7 @@ public class EntityValue extends Value
{
throw new InternalExpressionException("Expected a list of 3 parameters as a second argument");
}
final List<Value> coords = lv.getItems();
List<Value> coords = lv.getItems();
updatePosition(e,
NumericValue.asNumber(coords.get(0)).getDouble(),
NumericValue.asNumber(coords.get(1)).getDouble(),
@@ -1092,11 +1093,11 @@ public class EntityValue extends Value
{
throw new InternalExpressionException("Expected a list of 3 parameters as a second argument");
}
final List<Value> vec = lv.getItems();
List<Value> vec = lv.getItems();
float x = NumericValue.asNumber(vec.get(0)).getFloat();
float y = NumericValue.asNumber(vec.get(1)).getFloat();
float z = NumericValue.asNumber(vec.get(2)).getFloat();
final float l = Mth.sqrt(x * x + y * y + z * z);
float l = Mth.sqrt(x * x + y * y + z * z);
if (l == 0)
{
return;
@@ -1104,8 +1105,8 @@ public class EntityValue extends Value
x /= l;
y /= l;
z /= l;
final float pitch = (float) -Math.asin(y) / 0.017453292F;
final float yaw = (float) (x == 0 && z == 0 ? e.getYRot() : Mth.atan2(-x, z) / 0.017453292F);
float pitch = (float) -Math.asin(y) / 0.017453292F;
float yaw = (float) (x == 0 && z == 0 ? e.getYRot() : Mth.atan2(-x, z) / 0.017453292F);
updatePosition(e, e.getX(), e.getY(), e.getZ(), yaw, pitch);
});
@@ -1118,7 +1119,7 @@ public class EntityValue extends Value
{
throw new InternalExpressionException("Expected a list of 3 parameters as a second argument");
}
final List<Value> coords = lv.getItems();
List<Value> coords = lv.getItems();
updatePosition(e,
e.getX() + NumericValue.asNumber(coords.get(0)).getDouble(),
e.getY() + NumericValue.asNumber(coords.get(1)).getDouble(),
@@ -1134,31 +1135,31 @@ public class EntityValue extends Value
{
throw new InternalExpressionException("Expected a list of 3 parameters as a second argument");
}
final List<Value> coords = lv.getItems();
final double dx = NumericValue.asNumber(coords.get(0)).getDouble();
final double dy = NumericValue.asNumber(coords.get(1)).getDouble();
final double dz = NumericValue.asNumber(coords.get(2)).getDouble();
List<Value> coords = lv.getItems();
double dx = NumericValue.asNumber(coords.get(0)).getDouble();
double dy = NumericValue.asNumber(coords.get(1)).getDouble();
double dz = NumericValue.asNumber(coords.get(2)).getDouble();
e.setDeltaMovement(dx, dy, dz);
updateVelocity(e, Mth.absMax(Mth.absMax(dx, dy), dz));
});
put("motion_x", (e, v) ->
{
final Vec3 velocity = e.getDeltaMovement();
final double dv = NumericValue.asNumber(v).getDouble();
Vec3 velocity = e.getDeltaMovement();
double dv = NumericValue.asNumber(v).getDouble();
e.setDeltaMovement(dv, velocity.y, velocity.z);
updateVelocity(e, dv);
});
put("motion_y", (e, v) ->
{
final Vec3 velocity = e.getDeltaMovement();
final double dv = NumericValue.asNumber(v).getDouble();
Vec3 velocity = e.getDeltaMovement();
double dv = NumericValue.asNumber(v).getDouble();
e.setDeltaMovement(velocity.x, dv, velocity.z);
updateVelocity(e, dv);
});
put("motion_z", (e, v) ->
{
final Vec3 velocity = e.getDeltaMovement();
final double dv = NumericValue.asNumber(v).getDouble();
Vec3 velocity = e.getDeltaMovement();
double dv = NumericValue.asNumber(v).getDouble();
e.setDeltaMovement(velocity.x, velocity.y, dv);
updateVelocity(e, dv);
});
@@ -1169,7 +1170,7 @@ public class EntityValue extends Value
{
throw new InternalExpressionException("Expected a list of 3 parameters as a second argument");
}
final List<Value> coords = lv.getItems();
List<Value> coords = lv.getItems();
e.push(
NumericValue.asNumber(coords.get(0)).getDouble(),
NumericValue.asNumber(coords.get(1)).getDouble(),
@@ -1232,7 +1233,7 @@ public class EntityValue extends Value
}
else if (v instanceof final ListValue lv)
{
for (final Value element : lv.getItems())
for (Value element : lv.getItems())
{
if (element instanceof final EntityValue ev)
{
@@ -1248,7 +1249,7 @@ public class EntityValue extends Value
}
if (v instanceof final ListValue lv)
{
for (final Value element : lv.getItems())
for (Value element : lv.getItems())
{
e.addTag(element.getString());
}
@@ -1265,7 +1266,7 @@ public class EntityValue extends Value
}
if (v instanceof final ListValue lv)
{
for (final Value element : lv.getItems())
for (Value element : lv.getItems())
{
e.removeTag(element.getString());
}
@@ -1309,13 +1310,13 @@ public class EntityValue extends Value
if (v.isNull())
{
ec.restrictTo(BlockPos.ZERO, -1);
final Map<String, Goal> tasks = Vanilla.Mob_getTemporaryTasks(ec);
Map<String, Goal> tasks = Vanilla.Mob_getTemporaryTasks(ec);
Vanilla.Mob_getAI(ec, false).removeGoal(tasks.get("home"));
tasks.remove("home");
return;
}
final BlockPos pos;
BlockPos pos;
int distance = 16;
if (v instanceof final BlockValue bv)
@@ -1328,8 +1329,8 @@ public class EntityValue extends Value
}
else if (v instanceof final ListValue lv)
{
final List<Value> list = lv.getItems();
final Vector3Argument locator = Vector3Argument.findIn(list, 0, false, false);
List<Value> list = lv.getItems();
Vector3Argument locator = Vector3Argument.findIn(list, 0, false, false);
pos = new BlockPos(locator.vec.x, locator.vec.y, locator.vec.z);
if (list.size() > locator.offset)
{
@@ -1342,10 +1343,10 @@ public class EntityValue extends Value
}
ec.restrictTo(pos, distance);
final Map<String, Goal> tasks = Vanilla.Mob_getTemporaryTasks(ec);
Map<String, Goal> tasks = Vanilla.Mob_getTemporaryTasks(ec);
if (!tasks.containsKey("home"))
{
final Goal task = new MoveTowardsRestrictionGoal(ec, 1.0D);
Goal task = new MoveTowardsRestrictionGoal(ec, 1.0D);
tasks.put("home", task);
Vanilla.Mob_getAI(ec, false).addGoal(10, task);
}
@@ -1362,15 +1363,15 @@ public class EntityValue extends Value
}
else if (a instanceof final ListValue lv)
{
final List<Value> params = lv.getItems();
final Vector3Argument blockLocator = Vector3Argument.findIn(params, 0, false, false);
final BlockPos pos = new BlockPos(blockLocator.vec);
List<Value> params = lv.getItems();
Vector3Argument blockLocator = Vector3Argument.findIn(params, 0, false, false);
BlockPos pos = new BlockPos(blockLocator.vec);
ResourceKey<Level> world = spe.getCommandSenderWorld().dimension();
float angle = spe.getYHeadRot();
boolean forced = false;
if (params.size() > blockLocator.offset)
{
final Value worldValue = params.get(blockLocator.offset + 0);
Value worldValue = params.get(blockLocator.offset + 0);
world = ValueConversions.dimFromValue(worldValue, spe.getServer()).dimension();
if (params.size() > blockLocator.offset + 1)
{
@@ -1467,11 +1468,11 @@ public class EntityValue extends Value
}
else if (v instanceof final ListValue lv)
{
final List<Value> list = lv.getItems();
List<Value> list = lv.getItems();
if (list.size() >= 1 && list.size() <= 6)
{
final String effectName = list.get(0).getString();
final MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName));
String effectName = list.get(0).getString();
MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName));
if (effect == null)
{
throw new InternalExpressionException("Wrong effect name: " + effectName);
@@ -1481,7 +1482,7 @@ public class EntityValue extends Value
le.removeEffect(effect);
return;
}
final int duration = (int) NumericValue.asNumber(list.get(1)).getLong();
int duration = (int) NumericValue.asNumber(list.get(1)).getLong();
if (duration <= 0)
{
le.removeEffect(effect);
@@ -1513,8 +1514,8 @@ public class EntityValue extends Value
}
else
{
final String effectName = v.getString();
final MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName));
String effectName = v.getString();
MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName));
if (effect == null)
{
throw new InternalExpressionException("Wrong effect name: " + effectName);
@@ -1530,7 +1531,7 @@ public class EntityValue extends Value
{
return;
}
final GameType toSet = v instanceof NumericValue ?
GameType toSet = v instanceof NumericValue ?
GameType.byId(((NumericValue) v).getInt()) :
GameType.byName(v.getString().toLowerCase(Locale.ROOT), null);
if (toSet != null)
@@ -1564,7 +1565,7 @@ public class EntityValue extends Value
InteractionHand hand = InteractionHand.MAIN_HAND;
if (v != null)
{
final String handString = v.getString().toLowerCase(Locale.ROOT);
String handString = v.getString().toLowerCase(Locale.ROOT);
if (handString.equals("offhand") || handString.equals("off_hand"))
{
hand = InteractionHand.OFF_HAND;
@@ -1579,7 +1580,7 @@ public class EntityValue extends Value
put("gravity", (e, v) -> e.setNoGravity(!v.getBoolean()));
put("invulnerable", (e, v) -> {
final boolean invulnerable = v.getBoolean();
boolean invulnerable = v.getBoolean();
if (e instanceof final ServerPlayer player)
{
player.getAbilities().invulnerable = invulnerable;
@@ -1663,7 +1664,7 @@ public class EntityValue extends Value
put("breaking_progress", (e, a) -> {
if (e instanceof final ServerPlayer sp)
{
final int progress = (a == null || a.isNull()) ? -1 : NumericValue.asNumber(a).getInt();
int progress = (a == null || a.isNull()) ? -1 : NumericValue.asNumber(a).getInt();
Vanilla.ServerPlayerGameMode_setBlockBreakingProgress(sp.gameMode, progress);
}
});
@@ -1671,8 +1672,8 @@ public class EntityValue extends Value
put("nbt", (e, v) -> {
if (!(e instanceof Player))
{
final UUID uUID = e.getUUID();
final Value tagValue = NBTSerializableValue.fromValue(v);
UUID uUID = e.getUUID();
Value tagValue = NBTSerializableValue.fromValue(v);
if (tagValue instanceof final NBTSerializableValue nbtsv)
{
e.load(nbtsv.getCompoundTag());
@@ -1683,11 +1684,11 @@ public class EntityValue extends Value
put("nbt_merge", (e, v) -> {
if (!(e instanceof Player))
{
final UUID uUID = e.getUUID();
final Value tagValue = NBTSerializableValue.fromValue(v);
UUID uUID = e.getUUID();
Value tagValue = NBTSerializableValue.fromValue(v);
if (tagValue instanceof final NBTSerializableValue nbtsv)
{
final CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag()));
CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag()));
nbttagcompound.merge(nbtsv.getCompoundTag());
e.load(nbttagcompound);
e.setUUID(uUID);
@@ -1710,7 +1711,7 @@ public class EntityValue extends Value
});
put("item", (e, v) -> {
final ItemStack item = ValueConversions.getItemStackFromValue(v, true, e.level.registryAccess());
ItemStack item = ValueConversions.getItemStackFromValue(v, true, e.level.registryAccess());
if (e instanceof final ItemEntity itementity)
{
itementity.setItem(item);
@@ -1725,9 +1726,9 @@ public class EntityValue extends Value
// "effect_"name []
}};
public void setEvent(final CarpetContext cc, final String eventName, final FunctionValue fun, final List<Value> args)
public void setEvent(CarpetContext cc, String eventName, FunctionValue fun, List<Value> args)
{
final EntityEventsGroup.Event event = EntityEventsGroup.Event.byName.get(eventName);
EntityEventsGroup.Event event = EntityEventsGroup.Event.byName.get(eventName);
if (event == null)
{
throw new InternalExpressionException("Unknown entity event: " + eventName);
@@ -1736,15 +1737,15 @@ public class EntityValue extends Value
}
@Override
public net.minecraft.nbt.Tag toTag(final boolean force)
public net.minecraft.nbt.Tag toTag(boolean force)
{
if (!force)
{
throw new NBTSerializableValue.IncompatibleTypeException(this);
}
final CompoundTag tag = new CompoundTag();
CompoundTag tag = new CompoundTag();
tag.put("Data", getEntity().saveWithoutId(new CompoundTag()));
final Registry<EntityType<?>> reg = getEntity().level.registryAccess().registryOrThrow(Registries.ENTITY_TYPE);
Registry<EntityType<?>> reg = getEntity().level.registryAccess().registryOrThrow(Registries.ENTITY_TYPE);
tag.put("Name", StringTag.valueOf(reg.getKey(getEntity().getType()).toString()));
return tag;
}
@@ -10,15 +10,15 @@ public class FormattedTextValue extends StringValue
{
Component text;
public FormattedTextValue(final Component text)
public FormattedTextValue(Component text)
{
super(null);
this.text = text;
}
public static Value combine(final Value left, final Value right)
public static Value combine(Value left, Value right)
{
final MutableComponent text;
MutableComponent text;
if (left instanceof final FormattedTextValue ftv)
{
text = ftv.getText().copy();
@@ -45,7 +45,7 @@ public class FormattedTextValue extends StringValue
return new FormattedTextValue(text);
}
public static Value of(final Component text)
public static Value of(Component text)
{
return text == null ? Value.NULL : new FormattedTextValue(text);
}
@@ -80,7 +80,7 @@ public class FormattedTextValue extends StringValue
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
if (!force)
{
@@ -96,7 +96,7 @@ public class FormattedTextValue extends StringValue
}
@Override
public Value add(final Value o)
public Value add(Value o)
{
return combine(this, o);
}
@@ -106,12 +106,12 @@ public class FormattedTextValue extends StringValue
return Component.Serializer.toJson(text);
}
public static FormattedTextValue deserialize(final String serialized)
public static FormattedTextValue deserialize(String serialized)
{
return new FormattedTextValue(Component.Serializer.fromJson(serialized));
}
public static Component getTextByValue(final Value value)
public static Component getTextByValue(Value value)
{
return (value instanceof final FormattedTextValue ftv) ? ftv.getText() : Component.literal(value.getString());
}
@@ -29,7 +29,7 @@ public abstract class FrameworkValue extends Value
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
throw new UnsupportedOperationException("Scarpet language component cannot be serialized to the tag");
}
@@ -12,7 +12,7 @@ public class FunctionAnnotationValue extends Value
public Type type;
public FunctionAnnotationValue(final Value variable, final Type type)
public FunctionAnnotationValue(Value variable, Type type)
{
if (variable.boundVariable == null)
{
@@ -41,7 +41,7 @@ public class FunctionAnnotationValue extends Value
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
throw new UnsupportedOperationException("Global value cannot be serialized to the tag");
}
@@ -4,12 +4,12 @@ import java.util.List;
public class FunctionSignatureValue extends FrameworkValue
{
private String identifier;
private List<String> arguments;
private List<String> globals;
private String varArgs;
private final String identifier;
private final List<String> arguments;
private final List<String> globals;
private final String varArgs;
public FunctionSignatureValue(final String name, final List<String> args, final String varArgs, final List<String> globals)
public FunctionSignatureValue(String name, List<String> args, String varArgs, List<String> globals)
{
this.identifier = name;
this.arguments = args;
@@ -4,7 +4,7 @@ import java.util.List;
public class FunctionUnpackedArgumentsValue extends ListValue
{
public FunctionUnpackedArgumentsValue(final List<Value> list)
public FunctionUnpackedArgumentsValue(List<Value> list)
{
super(list);
}
@@ -34,7 +34,7 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
private static long variantCounter = 1;
private long variant;
private FunctionValue(final Expression expression, final Tokenizer.Token token, final String name, final LazyValue body, final List<String> args, final String varArgs)
private FunctionValue(Expression expression, Tokenizer.Token token, String name, LazyValue body, List<String> args, String varArgs)
{
this.expression = expression;
this.token = token;
@@ -46,7 +46,7 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
variant = 0L;
}
public FunctionValue(final Expression expression, final Tokenizer.Token token, final String name, final LazyValue body, final List<String> args, final String varArgs, final Map<String, LazyValue> outerState)
public FunctionValue(Expression expression, Tokenizer.Token token, String name, LazyValue body, List<String> args, String varArgs, Map<String, LazyValue> outerState)
{
this.expression = expression;
this.token = token;
@@ -72,7 +72,7 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
@Override
public String getPrettyString()
{
final List<String> stringArgs = new ArrayList<>(args);
List<String> stringArgs = new ArrayList<>(args);
if (outerState != null)
{
stringArgs.addAll(outerState.entrySet().stream().map(e ->
@@ -95,7 +95,7 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
@Override
protected Value clone()
{
final FunctionValue ret = new FunctionValue(expression, token, name, body, args, varArgs);
FunctionValue ret = new FunctionValue(expression, token, name, body, args, varArgs);
ret.outerState = this.outerState;
ret.variant = this.variant;
return ret;
@@ -108,17 +108,17 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
}
@Override
public boolean equals(final Object o)
public boolean equals(Object o)
{
return o instanceof final FunctionValue fv && name.equals(fv.name) && variant == fv.variant;
}
@Override
public int compareTo(final Value o)
public int compareTo(Value o)
{
if (o instanceof final FunctionValue fv)
{
final int nameSame = this.name.compareTo(fv.name);
int nameSame = this.name.compareTo(fv.name);
return nameSame != 0 ? nameSame : (int) (variant - fv.variant);
}
return getString().compareTo(o.getString());
@@ -137,7 +137,7 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
}
@Override
public Value slice(final long from, final Long to)
public Value slice(long from, Long to)
{
throw new InternalExpressionException("Cannot slice a function");
}
@@ -154,31 +154,31 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
return varArgs != null;
}
public LazyValue callInContext(final Context c, final Context.Type type, final List<Value> params)
public LazyValue callInContext(Context c, Context.Type type, List<Value> params)
{
try
{
return execute(c, type, expression, token, params);
}
catch (final ExpressionException exc)
catch (ExpressionException exc)
{
exc.stack.add(this);
throw exc;
}
catch (final InternalExpressionException exc)
catch (InternalExpressionException exc)
{
exc.stack.add(this);
throw new ExpressionException(c, expression, token, exc.getMessage(), exc.stack);
}
catch (final ArithmeticException exc)
catch (ArithmeticException exc)
{
throw new ExpressionException(c, expression, token, "Your math is wrong, " + exc.getMessage(), Collections.singletonList(this));
}
}
public void checkArgs(final int candidates)
public void checkArgs(int candidates)
{
final int actual = getArguments().size();
int actual = getArguments().size();
if (candidates < actual)
{
@@ -190,13 +190,13 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
}
}
public static List<Value> unpackArgs(final List<LazyValue> lazyParams, final Context c)
public static List<Value> unpackArgs(List<LazyValue> lazyParams, Context c)
{
// TODO we shoudn't need that if all fuctions are not lazy really
final List<Value> params = new ArrayList<>();
for (final LazyValue lv : lazyParams)
List<Value> params = new ArrayList<>();
for (LazyValue lv : lazyParams)
{
final Value param = lv.evalValue(c, Context.NONE);
Value param = lv.evalValue(c, Context.NONE);
if (param instanceof FunctionUnpackedArgumentsValue)
{
CarpetScriptServer.LOG.error("How did we get here?");
@@ -211,13 +211,13 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
}
@Override
public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List<LazyValue> lazyParams)
public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, List<LazyValue> lazyParams)
{
final List<Value> resolvedParams = unpackArgs(lazyParams, c);
List<Value> resolvedParams = unpackArgs(lazyParams, c);
return execute(c, type, e, t, resolvedParams);
}
public LazyValue execute(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List<Value> params)
public LazyValue execute(Context c, Context.Type type, Expression e, Tokenizer.Token t, List<Value> params)
{
assertArgsOk(params, fixedArgs -> {
if (fixedArgs) // wrong number of args for fixed args
@@ -229,14 +229,14 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
}
// too few args for varargs
final List<String> argList = new ArrayList<>(args);
List<String> argList = new ArrayList<>(args);
argList.add("... " + varArgs);
throw new ExpressionException(c, e, t,
"Incorrect number of arguments for function " + name +
". Should be at least " + args.size() + ", not " + params.size() + " like " + argList
);
});
final Context newFrame = c.recreate();
Context newFrame = c.recreate();
if (outerState != null)
{
@@ -244,18 +244,18 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
}
for (int i = 0; i < args.size(); i++)
{
final String arg = args.get(i);
final Value val = params.get(i).reboundedTo(arg); // todo check if we need to copy that
String arg = args.get(i);
Value val = params.get(i).reboundedTo(arg); // todo check if we need to copy that
newFrame.setVariable(arg, (cc, tt) -> val);
}
if (varArgs != null)
{
final List<Value> extraParams = new ArrayList<>();
List<Value> extraParams = new ArrayList<>();
for (int i = args.size(), mx = params.size(); i < mx; i++)
{
extraParams.add(params.get(i).reboundedTo(null)); // copy by value I guess
}
final Value rest = ListValue.wrap(extraParams).bindTo(varArgs); // didn't we just copied that?
Value rest = ListValue.wrap(extraParams).bindTo(varArgs); // didn't we just copied that?
newFrame.setVariable(varArgs, (cc, tt) -> rest);
}
@@ -264,15 +264,15 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
{
retVal = body.evalValue(newFrame, type); // todo not sure if we need to propagete type / consider boolean context in defined functions - answer seems ye
}
catch (final BreakStatement | ContinueStatement exc)
catch (BreakStatement | ContinueStatement exc)
{
throw new ExpressionException(c, e, t, "'continue' and 'break' can only be called inside loop function bodies");
}
catch (final ReturnStatement returnStatement)
catch (ReturnStatement returnStatement)
{
retVal = returnStatement.retval;
}
final Value otherRetVal = retVal;
Value otherRetVal = retVal;
return (cc, tt) -> otherRetVal;
}
@@ -297,7 +297,7 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
if (!force)
{
@@ -306,9 +306,9 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction
return StringTag.valueOf(getString());
}
public void assertArgsOk(final List<?> list, final Consumer<Boolean> feedback)
public void assertArgsOk(List<?> list, Consumer<Boolean> feedback)
{
final int size = list.size();
int size = list.size();
if (varArgs == null && args.size() != size) // wrong number of args for fixed args
{
feedback.accept(true);
@@ -6,7 +6,7 @@ public class LContainerValue extends FrameworkValue
private final Value address;
public static final LContainerValue NULL_CONTAINER = new LContainerValue(null, null);
public LContainerValue(final ContainerValueInterface c, final Value v)
public LContainerValue(ContainerValueInterface c, Value v)
{
container = c;
address = v;
@@ -12,7 +12,7 @@ import net.minecraft.nbt.Tag;
public abstract class LazyListValue extends AbstractListValue implements Iterator<Value>
{
public static LazyListValue rangeDouble(final double from, final double to, final double step)
public static LazyListValue rangeDouble(double from, double to, double step)
{
return new LazyListValue()
{
@@ -35,7 +35,7 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato
@Override
public Value next()
{
final Value val = new NumericValue(current);
Value val = new NumericValue(current);
current += stepp;
return val;
}
@@ -60,7 +60,7 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato
};
}
public static LazyListValue rangeLong(final long from, final long to, final long step)
public static LazyListValue rangeLong(long from, long to, long step)
{
return new LazyListValue()
{
@@ -83,7 +83,7 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato
@Override
public Value next()
{
final Value val = new NumericValue(current);
Value val = new NumericValue(current);
current += stepp;
return val;
}
@@ -136,7 +136,7 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato
public List<Value> unroll()
{
final List<Value> result = new ArrayList<>();
List<Value> result = new ArrayList<>();
this.forEachRemaining(result::add);
fatality();
return result;
@@ -157,7 +157,7 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato
{
return ListValue.of();
}
final List<Value> result = new ArrayList<>();
List<Value> result = new ArrayList<>();
int i;
for (i = 0; i < from; i++)
{
@@ -187,13 +187,13 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato
}
@Override
public Value add(final Value other)
public Value add(Value other)
{
throw new InternalExpressionException("Cannot add to iterators");
}
@Override
public boolean equals(final Object o)
public boolean equals(Object o)
{
return false;
}
@@ -207,12 +207,12 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato
@Override
public Object clone()
{
final Object copy;
Object copy;
try
{
copy = super.clone();
}
catch (final CloneNotSupportedException e)
catch (CloneNotSupportedException e)
{
throw new InternalExpressionException("Cannot copy iterators");
}
@@ -233,7 +233,7 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
if (!force)
{
@@ -60,54 +60,54 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
@Override
public Value deepcopy()
{
final List<Value> copyItems = new ArrayList<>(items.size());
for (final Value entry : items)
List<Value> copyItems = new ArrayList<>(items.size());
for (Value entry : items)
{
copyItems.add(entry.deepcopy());
}
return new ListValue(copyItems);
}
public ListValue(final Collection<? extends Value> list)
public ListValue(Collection<? extends Value> list)
{
items = new ArrayList<>(list);
}
protected ListValue(final List<Value> list)
protected ListValue(List<Value> list)
{
items = list;
}
public static Value fromTriple(final double a, final double b, final double c)
public static Value fromTriple(double a, double b, double c)
{
return ListValue.of(new NumericValue(a), new NumericValue(b), new NumericValue(c));
}
public static Value fromTriple(final int a, final int b, final int c)
public static Value fromTriple(int a, int b, int c)
{
return fromTriple((double) a, b, c);
}
public static ListValue wrap(final Stream<Value> stream)
public static ListValue wrap(Stream<Value> stream)
{
return wrap(stream.collect(Collectors.toList()));
}
public static ListValue wrap(final List<Value> list)
public static ListValue wrap(List<Value> list)
{
return new ListValue(list);
}
public static ListValue of(final Value... list)
public static ListValue of(Value... list)
{
return new ListValue(new ArrayList<>(Arrays.asList(list)));
}
public static ListValue ofNums(final Number... list)
public static ListValue ofNums(Number... list)
{
final List<Value> valList = new ArrayList<>();
for (final Number i : list)
List<Value> valList = new ArrayList<>();
for (Number i : list)
{
valList.add(new NumericValue(i.doubleValue()));
}
@@ -116,7 +116,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
public static LazyValue lazyEmpty()
{
final Value ret = new ListValue();
Value ret = new ListValue();
return (c, t) -> ret;
}
@@ -126,12 +126,12 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
@Override
public Value add(final Value other)
public Value add(Value other)
{
final ListValue output = new ListValue();
ListValue output = new ListValue();
if (other instanceof final ListValue list)
{
final List<Value> otherItems = list.items;
List<Value> otherItems = list.items;
if (otherItems.size() == items.size())
{
for (int i = 0, size = items.size(); i < size; i++)
@@ -146,7 +146,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
else
{
for (final Value v : items)
for (Value v : items)
{
output.items.add(v.add(other));
}
@@ -155,18 +155,18 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
@Override
public void append(final Value v)
public void append(Value v)
{
items.add(v);
}
@Override
public Value subtract(final Value other)
public Value subtract(Value other)
{
final ListValue output = new ListValue();
ListValue output = new ListValue();
if (other instanceof final ListValue list)
{
final List<Value> otherItems = list.items;
List<Value> otherItems = list.items;
if (otherItems.size() == items.size())
{
for (int i = 0, size = items.size(); i < size; i++)
@@ -181,7 +181,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
else
{
for (final Value v : items)
for (Value v : items)
{
output.items.add(v.subtract(other));
}
@@ -189,19 +189,19 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
return output;
}
public void subtractFrom(final Value v) // if I ever do -= then it wouod remove items
public void subtractFrom(Value v) // if I ever do -= then it wouod remove items
{
throw new UnsupportedOperationException(); // TODO
}
@Override
public Value multiply(final Value other)
public Value multiply(Value other)
{
final ListValue output = new ListValue();
ListValue output = new ListValue();
if (other instanceof final ListValue list)
{
final List<Value> otherItems = list.items;
List<Value> otherItems = list.items;
if (otherItems.size() == items.size())
{
for (int i = 0, size = items.size(); i < size; i++)
@@ -216,7 +216,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
else
{
for (final Value v : items)
for (Value v : items)
{
output.items.add(v.multiply(other));
}
@@ -225,12 +225,12 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
@Override
public Value divide(final Value other)
public Value divide(Value other)
{
final ListValue output = new ListValue();
ListValue output = new ListValue();
if (other instanceof final ListValue list)
{
final List<Value> otherItems = list.items;
List<Value> otherItems = list.items;
if (otherItems.size() == items.size())
{
for (int i = 0, size = items.size(); i < size; i++)
@@ -245,7 +245,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
else
{
for (final Value v : items)
for (Value v : items)
{
output.items.add(v.divide(other));
}
@@ -254,12 +254,12 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
@Override
public int compareTo(final Value o)
public int compareTo(Value o)
{
if (o instanceof final ListValue ol)
{
final int size = this.getItems().size();
final int otherSize = ol.getItems().size();
int size = this.getItems().size();
int otherSize = ol.getItems().size();
if (size != otherSize)
{
return size - otherSize;
@@ -270,7 +270,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
for (int i = 0; i < size; i++)
{
final int res = this.items.get(i).compareTo(ol.items.get(i));
int res = this.items.get(i).compareTo(ol.items.get(i));
if (res != 0)
{
return res;
@@ -282,7 +282,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
@Override
public boolean equals(final Object o)
public boolean equals(Object o)
{
return o instanceof final ListValue list && getItems().equals(list.getItems());
}
@@ -304,7 +304,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
return new ArrayList<>(items);
}
public void extend(final List<Value> subList)
public void extend(List<Value> subList)
{
items.addAll(subList);
}
@@ -316,13 +316,13 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
* @param len
* @return
*/
public static int normalizeIndex(long idx, final int len)
public static int normalizeIndex(long idx, int len)
{
if (idx >= 0 && idx < len)
{
return (int) idx;
}
final long range = abs(idx) / len;
long range = abs(idx) / len;
idx += (range + 2) * len;
idx = idx % len;
return (int) idx;
@@ -330,7 +330,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
public static class ListConstructorValue extends ListValue
{
public ListConstructorValue(final Collection<? extends Value> list)
public ListConstructorValue(Collection<? extends Value> list)
{
super(list);
}
@@ -343,11 +343,11 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
@Override
public Value in(final Value value1)
public Value in(Value value1)
{
for (int i = 0; i < items.size(); i++)
{
final Value v = items.get(i);
Value v = items.get(i);
if (v.equals(value1))
{
return new NumericValue(i);
@@ -357,16 +357,16 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
@Override
public Value slice(final long fromDesc, final Long toDesc)
public Value slice(long fromDesc, Long toDesc)
{
final List<Value> items = getItems();
final int size = items.size();
final int from = normalizeIndex(fromDesc, size);
List<Value> items = getItems();
int size = items.size();
int from = normalizeIndex(fromDesc, size);
if (toDesc == null)
{
return new ListValue(new ArrayList<>(getItems().subList(from, size)));
}
final int to = normalizeIndex(toDesc, size + 1);
int to = normalizeIndex(toDesc, size + 1);
if (from > to)
{
return ListValue.of();
@@ -375,9 +375,9 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
@Override
public Value split(final Value delimiter)
public Value split(Value delimiter)
{
final ListValue result = new ListValue();
ListValue result = new ListValue();
if (delimiter == null)
{
this.forEach(item -> result.items.add(of(item)));
@@ -385,7 +385,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
int startIndex = 0;
int index = 0;
for (final Value val : this.items)
for (Value val : this.items)
{
index++;
if (val.equals(delimiter))
@@ -405,9 +405,9 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
@Override
public boolean put(final Value where, final Value value, final Value conditionValue)
public boolean put(Value where, Value value, Value conditionValue)
{
final String condition = conditionValue.getString();
String condition = conditionValue.getString();
if (condition.equalsIgnoreCase("insert"))
{
return put(where, value, false, false);
@@ -424,12 +424,12 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
@Override
public boolean put(final Value ind, final Value value)
public boolean put(Value ind, Value value)
{
return put(ind, value, true, false);
}
private boolean put(final Value ind, final Value value, final boolean replace, final boolean extend)
private boolean put(Value ind, Value value, boolean replace, boolean extend)
{
if (ind.isNull())
{
@@ -444,7 +444,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
else
{
final int numitems = items.size();
int numitems = items.size();
if (!(ind instanceof NumericValue))
{
return false;
@@ -470,8 +470,8 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
if (extend && value instanceof AbstractListValue)
{
final Iterable<Value> iterable = ((AbstractListValue) value)::iterator;
final List<Value> appendix = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());
Iterable<Value> iterable = ((AbstractListValue) value)::iterator;
List<Value> appendix = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());
items.addAll(index, appendix);
return true;
}
@@ -481,27 +481,27 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
}
@Override
public Value get(final Value value)
public Value get(Value value)
{
final int size = items.size();
int size = items.size();
return size == 0 ? Value.NULL : items.get(normalizeIndex(NumericValue.asNumber(value, "'address' to a list index").getLong(), size));
}
@Override
public boolean has(final Value where)
public boolean has(Value where)
{
final long index = NumericValue.asNumber(where, "'address' to a list index").getLong();
long index = NumericValue.asNumber(where, "'address' to a list index").getLong();
return index >= 0 && index < items.size();
}
@Override
public boolean delete(final Value where)
public boolean delete(Value where)
{
if (!(where instanceof NumericValue) || items.isEmpty())
{
return false;
}
final long index = ((NumericValue) where).getLong();
long index = ((NumericValue) where).getLong();
items.remove(normalizeIndex(index, items.size()));
return true;
}
@@ -527,7 +527,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
MAP,
STRING;
private static TagTypeCompat getType(final Tag tag)
private static TagTypeCompat getType(Tag tag)
{
if (tag instanceof IntTag)
{
@@ -555,23 +555,23 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
final int argSize = items.size();
int argSize = items.size();
if (argSize == 0)
{
return new ListTag();
}
final ListTag tag = new ListTag();
ListTag tag = new ListTag();
if (argSize == 1)
{
tag.add(items.get(0).toTag(force));
return tag;
}
// figuring out the types
final List<Tag> tags = new ArrayList<>();
List<Tag> tags = new ArrayList<>();
items.forEach(v -> tags.add(v.toTag(force)));
final Set<TagTypeCompat> cases = EnumSet.noneOf(TagTypeCompat.class);
Set<TagTypeCompat> cases = EnumSet.noneOf(TagTypeCompat.class);
tags.forEach(t -> cases.add(TagTypeCompat.getType(t)));
if (cases.size() == 1) // well, one type of items
{
@@ -599,8 +599,8 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
@Override
public JsonElement toJson()
{
final JsonArray array = new JsonArray();
for (final Value el : items)
JsonArray array = new JsonArray();
for (Value el : items)
{
array.add(el.toJson());
}
+29 -29
View File
@@ -25,13 +25,13 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa
map = new HashMap<>();
}
public MapValue(final List<Value> kvPairs)
public MapValue(List<Value> kvPairs)
{
this();
kvPairs.forEach(this::put);
}
public MapValue(final Set<Value> keySet)
public MapValue(Set<Value> keySet)
{
this();
keySet.forEach(v -> map.put(v, Value.NULL));
@@ -62,8 +62,8 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa
{
return "{" + map.entrySet().stream().map(p -> p.getKey().getPrettyString() + ": " + p.getValue().getPrettyString()).collect(Collectors.joining(", ")) + "}";
}
final List<Value> keys = new ArrayList<>(map.keySet());
final int max = keys.size();
List<Value> keys = new ArrayList<>(map.keySet());
int max = keys.size();
return "{" + keys.get(0).getPrettyString() + ": " + map.get(keys.get(0)).getPrettyString() + ", " +
keys.get(1).getPrettyString() + ": " + map.get(keys.get(1)).getPrettyString() + ", ..., " +
keys.get(max - 2).getPrettyString() + ": " + map.get(keys.get(max - 2)).getPrettyString() + ", " +
@@ -85,32 +85,32 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa
@Override
public Value deepcopy()
{
final Map<Value, Value> copyMap = new HashMap<>();
Map<Value, Value> copyMap = new HashMap<>();
map.forEach((key, value) -> copyMap.put(key.deepcopy(), value.deepcopy()));
return new MapValue(copyMap);
}
private MapValue(final Map<Value, Value> other)
private MapValue(Map<Value, Value> other)
{
map = other;
}
public static MapValue wrap(final Map<Value, Value> other)
public static MapValue wrap(Map<Value, Value> other)
{
return new MapValue(other);
}
@Override
public Value add(final Value o)
public Value add(Value o)
{
final Map<Value, Value> newItems = new HashMap<>(map);
Map<Value, Value> newItems = new HashMap<>(map);
if (o instanceof final MapValue mapValue)
{
newItems.putAll(mapValue.map);
}
else if (o instanceof final AbstractListValue alv)
{
for (final Value value : alv)
for (Value value : alv)
{
newItems.put(value, Value.NULL);
}
@@ -123,24 +123,24 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa
}
@Override
public Value subtract(final Value v)
public Value subtract(Value v)
{
throw new InternalExpressionException("Cannot subtract from a map value");
}
@Override
public Value multiply(final Value v)
public Value multiply(Value v)
{
throw new InternalExpressionException("Cannot multiply with a map value");
}
@Override
public Value divide(final Value v)
public Value divide(Value v)
{
throw new InternalExpressionException("Cannot divide a map value");
}
public void put(final Value v)
public void put(Value v)
{
if (!(v instanceof final ListValue pair))
{
@@ -155,19 +155,19 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa
}
@Override
public void append(final Value v)
public void append(Value v)
{
map.put(v, Value.NULL);
}
@Override
public int compareTo(final Value o)
public int compareTo(Value o)
{
throw new InternalExpressionException("Cannot compare with a map value");
}
@Override
public boolean equals(final Object o)
public boolean equals(Object o)
{
return o instanceof final MapValue mapValue && map.equals(mapValue.map);
}
@@ -177,7 +177,7 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa
return map;
}
public void extend(final List<Value> subList)
public void extend(List<Value> subList)
{
subList.forEach(this::put);
}
@@ -189,19 +189,19 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa
}
@Override
public Value in(final Value value)
public Value in(Value value)
{
return map.containsKey(value) ? value : Value.NULL;
}
@Override
public Value slice(final long from, final Long to)
public Value slice(long from, Long to)
{
throw new InternalExpressionException("Cannot slice a map value");
}
@Override
public Value split(final Value delimiter)
public Value split(Value delimiter)
{
throw new InternalExpressionException("Cannot split a map value");
}
@@ -213,25 +213,25 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa
}
@Override
public Value get(final Value v2)
public Value get(Value v2)
{
return map.getOrDefault(v2, Value.NULL);
}
@Override
public boolean has(final Value where)
public boolean has(Value where)
{
return map.containsKey(where);
}
@Override
public boolean delete(final Value where)
public boolean delete(Value where)
{
return map.remove(where) != null;
}
@Override
public boolean put(final Value key, final Value value)
public boolean put(Value key, Value value)
{
return map.put(key, value) != null;
}
@@ -249,9 +249,9 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
final CompoundTag tag = new CompoundTag();
CompoundTag tag = new CompoundTag();
map.forEach((k, v) ->
{
if (!force && !(k instanceof StringValue))
@@ -266,8 +266,8 @@ public class MapValue extends AbstractListValue implements ContainerValueInterfa
@Override
public JsonElement toJson()
{
final JsonObject jsonMap = new JsonObject();
final List<Value> keys = new ArrayList<>(map.keySet());
JsonObject jsonMap = new JsonObject();
List<Value> keys = new ArrayList<>(map.keySet());
Collections.sort(keys);
keys.forEach(k -> jsonMap.add(k.getString(), map.get(k).toJson()));
return jsonMap;
@@ -55,6 +55,8 @@ import net.minecraft.world.level.block.entity.ChestBlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import javax.annotation.Nullable;
public class NBTSerializableValue extends Value implements ContainerValueInterface
{
private String nbtString = null;
@@ -66,7 +68,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
{
}
public NBTSerializableValue(final String nbtString)
public NBTSerializableValue(String nbtString)
{
nbtSupplier = () ->
{
@@ -74,7 +76,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
{
return (new TagParser(new StringReader(nbtString))).readValue();
}
catch (final CommandSyntaxException e)
catch (CommandSyntaxException e)
{
throw new InternalExpressionException("Incorrect NBT data: " + nbtString);
}
@@ -82,13 +84,13 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
owned = true;
}
public NBTSerializableValue(final Tag tag)
public NBTSerializableValue(Tag tag)
{
nbtTag = tag;
owned = true;
}
public static Value of(final Tag tag)
public static Value of(Tag tag)
{
if (tag == null)
{
@@ -97,49 +99,57 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
return new NBTSerializableValue(tag);
}
public NBTSerializableValue(final Supplier<Tag> tagSupplier)
public NBTSerializableValue(Supplier<Tag> tagSupplier)
{
nbtSupplier = tagSupplier;
}
public static Value fromStack(final ItemStack stack)
public static Value fromStack(ItemStack stack)
{
if (stack.hasTag())
{
final NBTSerializableValue value = new NBTSerializableValue();
NBTSerializableValue value = new NBTSerializableValue();
value.nbtSupplier = stack::getTag;
return value;
}
return Value.NULL;
}
public static String nameFromRegistryId(final ResourceLocation id)
public static Value nameFromRegistryId(@Nullable ResourceLocation id)
{
if (id == null) // should be Value.NULL
{
return "";
}
return id.getNamespace().equals("minecraft") ? id.getPath() : id.toString();
return StringValue.of(nameFromResource(id));
}
public static NBTSerializableValue parseString(final String nbtString, final boolean fail)
@Nullable
public static String nameFromResource(@Nullable ResourceLocation id)
{
return id == null ? null : id.getNamespace().equals("minecraft") ? id.getPath() : id.toString();
}
@Nullable
public static NBTSerializableValue parseString(String nbtString)
{
final Tag tag;
try
{
tag = (new TagParser(new StringReader(nbtString))).readValue();
Tag tag = (new TagParser(new StringReader(nbtString))).readValue();
NBTSerializableValue value = new NBTSerializableValue(tag);
value.nbtString = null;
return value;
}
catch (final CommandSyntaxException e)
catch (CommandSyntaxException e)
{
if (fail)
{
throw new InternalExpressionException("Incorrect NBT tag: " + nbtString);
}
return null;
}
final NBTSerializableValue value = new NBTSerializableValue(tag);
value.nbtString = null;
return value;
}
public static NBTSerializableValue parseStringOrFail(String nbtString)
{
NBTSerializableValue result = parseString(nbtString);
if (result == null)
{
throw new InternalExpressionException("Incorrect NBT tag: " + nbtString);
}
return result;
}
@@ -147,7 +157,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
public Value clone()
{
// sets only nbttag, even if emtpy;
final NBTSerializableValue copy = new NBTSerializableValue(nbtTag);
NBTSerializableValue copy = new NBTSerializableValue(nbtTag);
copy.nbtSupplier = this.nbtSupplier;
copy.nbtString = this.nbtString;
copy.owned = this.owned;
@@ -157,7 +167,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
@Override
public Value deepcopy()
{
final NBTSerializableValue copy = (NBTSerializableValue) clone();
NBTSerializableValue copy = (NBTSerializableValue) clone();
copy.owned = false;
ensureOwnership();
return copy;
@@ -170,18 +180,18 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
// stolen from HopperBlockEntity, adjusted for threaded operation
public static Container getInventoryAt(final ServerLevel world, final BlockPos blockPos)
public static Container getInventoryAt(ServerLevel world, BlockPos blockPos)
{
Container inventory = null;
final BlockState blockState = world.getBlockState(blockPos);
final Block block = blockState.getBlock();
BlockState blockState = world.getBlockState(blockPos);
Block block = blockState.getBlock();
if (block instanceof final WorldlyContainerHolder containerHolder)
{
inventory = containerHolder.getContainer(blockState, world, blockPos);
}
else if (blockState.hasBlockEntity())
{
final BlockEntity blockEntity = BlockValue.getBlockEntity(world, blockPos);
BlockEntity blockEntity = BlockValue.getBlockEntity(world, blockPos);
if (blockEntity instanceof final Container inventoryHolder)
{
inventory = inventoryHolder;
@@ -194,7 +204,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
if (inventory == null)
{
final List<Entity> list = world.getEntities(
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,
@@ -210,7 +220,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
return inventory;
}
public static InventoryLocator locateInventory(final CarpetContext c, final List<Value> params, int offset)
public static InventoryLocator locateInventory(CarpetContext c, List<Value> params, int offset)
{
try
{
@@ -225,8 +235,8 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
String strVal = v1.getString().toLowerCase(Locale.ROOT);
if (strVal.equals("enderchest"))
{
final Value v2 = params.get(1 + offset);
final ServerPlayer player = EntityValue.getPlayerByValue(c.server(), v2);
Value v2 = params.get(1 + offset);
ServerPlayer player = EntityValue.getPlayerByValue(c.server(), v2);
if (player == null)
{
throw new InternalExpressionException("enderchest inventory requires player argument");
@@ -235,24 +245,24 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
if (strVal.equals("equipment"))
{
final Value v2 = params.get(1 + offset);
Value v2 = params.get(1 + offset);
if (!(v2 instanceof final EntityValue ev))
{
throw new InternalExpressionException("Equipment inventory requires a living entity argument");
}
final Entity e = ev.getEntity();
Entity e = ev.getEntity();
if (!(e instanceof final LivingEntity le))
{
throw new InternalExpressionException("Equipment inventory requires a living entity argument");
}
return new InventoryLocator(e, e.blockPosition(), new EquipmentInventory(le), offset + 2);
}
final boolean isEnder = strVal.startsWith("enderchest_");
boolean isEnder = strVal.startsWith("enderchest_");
if (isEnder)
{
strVal = strVal.substring(11); // len("enderchest_")
}
final ServerPlayer player = c.server().getPlayerList().getPlayerByName(strVal);
ServerPlayer player = c.server().getPlayerList().getPlayerByName(strVal);
if (player == null)
{
throw new InternalExpressionException("String description of an inventory should either denote a player or player's enderchest");
@@ -268,7 +278,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
if (v1 instanceof final EntityValue ev)
{
Container inv = null;
final Entity e = ev.getEntity();
Entity e = ev.getEntity();
if (e instanceof final Player pe)
{
inv = pe.getInventory();
@@ -294,36 +304,36 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
if (v1 instanceof final BlockValue bv)
{
final BlockPos pos = bv.getPos();
BlockPos pos = bv.getPos();
if (pos == null)
{
throw new InternalExpressionException("Block to access inventory needs to be positioned in the world");
}
final Container inv = getInventoryAt(c.level(), pos);
Container inv = getInventoryAt(c.level(), pos);
return inv == null ? null : new InventoryLocator(pos, pos, inv, offset + 1);
}
if (v1 instanceof final ListValue lv)
{
final List<Value> args = lv.getItems();
final BlockPos pos = new BlockPos(
List<Value> args = lv.getItems();
BlockPos pos = new BlockPos(
NumericValue.asNumber(args.get(0)).getDouble(),
NumericValue.asNumber(args.get(1)).getDouble(),
NumericValue.asNumber(args.get(2)).getDouble());
final Container inv = getInventoryAt(c.level(), pos);
Container inv = getInventoryAt(c.level(), pos);
return inv == null ? null : new InventoryLocator(pos, pos, inv, offset + 1);
}
if (v1 instanceof final ScreenValue screenValue)
{
return !screenValue.isOpen() ? null : new InventoryLocator(screenValue.getPlayer(), screenValue.getPlayer().blockPosition(), screenValue.getInventory(), offset + 1);
}
final BlockPos pos = new BlockPos(
BlockPos pos = new BlockPos(
NumericValue.asNumber(v1).getDouble(),
NumericValue.asNumber(params.get(1 + offset)).getDouble(),
NumericValue.asNumber(params.get(2 + offset)).getDouble());
final Container inv = getInventoryAt(c.level(), pos);
Container inv = getInventoryAt(c.level(), pos);
return inv == null ? null : new InventoryLocator(pos, pos, inv, offset + 3);
}
catch (final IndexOutOfBoundsException e)
catch (IndexOutOfBoundsException e)
{
throw new InternalExpressionException("Inventory should be defined either by three coordinates, a block value, an entity, or a screen");
}
@@ -331,12 +341,12 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
private static final Map<String, ItemInput> itemCache = new HashMap<>();
public static ItemInput parseItem(final String itemString, final RegistryAccess regs)
public static ItemInput parseItem(String itemString, RegistryAccess regs)
{
return parseItem(itemString, null, regs);
}
public static ItemInput parseItem(final String itemString, final CompoundTag customTag, final RegistryAccess regs)
public static ItemInput parseItem(String itemString, @Nullable CompoundTag customTag, RegistryAccess regs)
{
try
{
@@ -345,7 +355,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
{
return customTag == null ? res : new ItemInput(Holder.direct(res.getItem()), customTag);
}
final ItemParser.ItemResult parser = ItemParser.parseForItem(regs.lookupOrThrow(Registries.ITEM), new StringReader(itemString));
ItemParser.ItemResult parser = ItemParser.parseForItem(regs.lookupOrThrow(Registries.ITEM), new StringReader(itemString));
res = new ItemInput(parser.item(), parser.nbt());
itemCache.put(itemString, res);
@@ -355,15 +365,15 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
return customTag == null ? res : new ItemInput(Holder.direct(res.getItem()), customTag);
}
catch (final CommandSyntaxException e)
catch (CommandSyntaxException e)
{
throw new ThrowStatement(itemString, Throwables.UNKNOWN_ITEM);
}
}
public static int validateSlot(int slot, final Container inv)
public static int validateSlot(int slot, Container inv)
{
final int invSize = inv.getContainerSize();
int invSize = inv.getContainerSize();
if (slot < 0)
{
slot = invSize + slot;
@@ -371,7 +381,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
return slot < 0 || slot >= invSize ? inv.getContainerSize() : slot; // outside of inventory
}
private static Value decodeSimpleTag(final Tag t)
private static Value decodeSimpleTag(Tag t)
{
if (t instanceof final NumericTag number)
{
@@ -389,17 +399,17 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
throw new InternalExpressionException("How did we get here: Unknown nbt element class: " + t.getType().getName());
}
private static Value decodeTag(final Tag t)
private static Value decodeTag(Tag t)
{
return t instanceof CompoundTag || t instanceof CollectionTag ? new NBTSerializableValue(() -> t) : decodeSimpleTag(t);
}
private static Value decodeTagDeep(final Tag t)
private static Value decodeTagDeep(Tag t)
{
if (t instanceof final CompoundTag ctag)
{
final Map<Value, Value> pairs = new HashMap<>();
for (final String key : ctag.getAllKeys())
Map<Value, Value> pairs = new HashMap<>();
for (String key : ctag.getAllKeys())
{
pairs.put(new StringValue(key), decodeTagDeep(ctag.get(key)));
}
@@ -407,8 +417,8 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
if (t instanceof final CollectionTag<?> ltag)
{
final List<Value> elems = new ArrayList<>();
for (final Tag elem : ltag)
List<Value> elems = new ArrayList<>();
for (Tag elem : ltag)
{
elems.add(decodeTagDeep(elem));
}
@@ -422,7 +432,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
return decodeTagDeep(this.getTag());
}
public static Value fromValue(final Value v)
public static Value fromValue(Value v)
{
if (v instanceof NBTSerializableValue)
{
@@ -432,7 +442,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
{
return Value.NULL;
}
return NBTSerializableValue.parseString(v.getString(), true);
return NBTSerializableValue.parseStringOrFail(v.getString());
}
public Tag getTag()
@@ -445,7 +455,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
@Override
public boolean equals(final Object o)
public boolean equals(Object o)
{
return o instanceof final NBTSerializableValue nbtsv ? getTag().equals(nbtsv.getTag()) : super.equals(o);
}
@@ -463,7 +473,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
@Override
public boolean getBoolean()
{
final Tag tag = getTag();
Tag tag = getTag();
if (tag instanceof final CompoundTag ctag)
{
return !(ctag).isEmpty();
@@ -490,35 +500,35 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
ensureOwnership();
return (CompoundTag) getTag();
}
catch (final ClassCastException e)
catch (ClassCastException e)
{
throw new InternalExpressionException(getString() + " is not a valid compound tag");
}
}
@Override
public boolean put(final Value where, final Value value)
public boolean put(Value where, Value value)
{
return put(where, value, new StringValue("replace"));
}
@Override
public boolean put(final Value where, final Value value, final Value conditions)
public boolean put(Value where, Value value, Value conditions)
{
/// WIP
ensureOwnership();
final NbtPathArgument.NbtPath path = cachePath(where.getString());
final Tag tagToInsert = value instanceof final NBTSerializableValue nbtsv
NbtPathArgument.NbtPath path = cachePath(where.getString());
Tag tagToInsert = value instanceof final NBTSerializableValue nbtsv
? nbtsv.getTag()
: new NBTSerializableValue(value.getString()).getTag();
final boolean modifiedTag;
boolean modifiedTag;
if (conditions instanceof final NumericValue number)
{
modifiedTag = modifyInsert((int) number.getLong(), path, tagToInsert);
}
else
{
final String ops = conditions.getString();
String ops = conditions.getString();
if (ops.equalsIgnoreCase("merge"))
{
modifiedTag = modifyMerge(path, tagToInsert);
@@ -540,25 +550,25 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
private boolean modifyInsert(final int index, final NbtPathArgument.NbtPath nbtPath, final Tag newElement)
private boolean modifyInsert(int index, NbtPathArgument.NbtPath nbtPath, Tag newElement)
{
return modifyInsert(index, nbtPath, newElement, this.getTag());
}
private boolean modifyInsert(final int index, final NbtPathArgument.NbtPath nbtPath, final Tag newElement, final Tag currentTag)
private boolean modifyInsert(int index, NbtPathArgument.NbtPath nbtPath, Tag newElement, Tag currentTag)
{
final Collection<Tag> targets;
Collection<Tag> targets;
try
{
targets = nbtPath.getOrCreate(currentTag, ListTag::new);
}
catch (final CommandSyntaxException e)
catch (CommandSyntaxException e)
{
return false;
}
boolean modified = false;
for (final Tag target : targets)
for (Tag target : targets)
{
if (!(target instanceof final CollectionTag<?> targetList))
{
@@ -572,7 +582,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
modified = true;
}
catch (final IndexOutOfBoundsException ignored)
catch (IndexOutOfBoundsException ignored)
{
}
}
@@ -580,16 +590,16 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
private boolean modifyMerge(final NbtPathArgument.NbtPath nbtPath, final Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1)
private boolean modifyMerge(NbtPathArgument.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1)
{
if (!(replacement instanceof final CompoundTag replacementCompound))
{
return false;
}
final Tag ownTag = getTag();
Tag ownTag = getTag();
try
{
for (final Tag target : nbtPath.getOrCreate(ownTag, CompoundTag::new))
for (Tag target : nbtPath.getOrCreate(ownTag, CompoundTag::new))
{
if (!(target instanceof final CompoundTag targetCompound))
{
@@ -598,31 +608,31 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
targetCompound.merge(replacementCompound);
}
}
catch (final CommandSyntaxException ignored)
catch (CommandSyntaxException ignored)
{
return false;
}
return true;
}
private boolean modifyReplace(final NbtPathArgument.NbtPath nbtPath, final Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1)
private boolean modifyReplace(NbtPathArgument.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1)
{
final Tag tag = getTag();
final String pathText = nbtPath.toString();
Tag tag = getTag();
String pathText = nbtPath.toString();
if (pathText.endsWith("]")) // workaround for array replacement or item in the array replacement
{
if (nbtPath.remove(tag) == 0)
{
return false;
}
final Pattern pattern = Pattern.compile("\\[[^\\[]*]$");
final Matcher matcher = pattern.matcher(pathText);
Pattern pattern = Pattern.compile("\\[[^\\[]*]$");
Matcher matcher = pattern.matcher(pathText);
if (!matcher.find()) // malformed path
{
return false;
}
final String arrAccess = matcher.group();
final int pos;
String arrAccess = matcher.group();
int pos;
if (arrAccess.length() == 2) // we just removed entire array
{
pos = 0;
@@ -633,19 +643,19 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
{
pos = Integer.parseInt(arrAccess.substring(1, arrAccess.length() - 1));
}
catch (final NumberFormatException e)
catch (NumberFormatException e)
{
return false;
}
}
final NbtPathArgument.NbtPath newPath = cachePath(pathText.substring(0, pathText.length() - arrAccess.length()));
NbtPathArgument.NbtPath newPath = cachePath(pathText.substring(0, pathText.length() - arrAccess.length()));
return modifyInsert(pos, newPath, replacement, tag);
}
try
{
nbtPath.set(tag, replacement);
}
catch (final CommandSyntaxException e)
catch (CommandSyntaxException e)
{
return false;
}
@@ -653,13 +663,13 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
@Override
public Value get(final Value value)
public Value get(Value value)
{
final String valString = value.getString();
final NbtPathArgument.NbtPath path = cachePath(valString);
String valString = value.getString();
NbtPathArgument.NbtPath path = cachePath(valString);
try
{
final List<Tag> tags = path.get(getTag());
List<Tag> tags = path.get(getTag());
if (tags.isEmpty())
{
return Value.NULL;
@@ -670,14 +680,14 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
return ListValue.wrap(tags.stream().map(NBTSerializableValue::decodeTag));
}
catch (final CommandSyntaxException ignored)
catch (CommandSyntaxException ignored)
{
}
return Value.NULL;
}
@Override
public boolean has(final Value where)
public boolean has(Value where)
{
return cachePath(where.getString()).countMatching(getTag()) > 0;
}
@@ -699,11 +709,11 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
}
@Override
public boolean delete(final Value where)
public boolean delete(Value where)
{
final NbtPathArgument.NbtPath path = cachePath(where.getString());
NbtPathArgument.NbtPath path = cachePath(where.getString());
ensureOwnership();
final int removed = path.remove(getTag());
int removed = path.remove(getTag());
if (removed > 0)
{
dirty();
@@ -715,7 +725,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
public record InventoryLocator(Object owner, BlockPos position, Container inventory, int offset,
boolean isEnder)
{
InventoryLocator(final Object owner, final BlockPos pos, final Container i, final int o)
InventoryLocator(Object owner, BlockPos pos, Container i, int o)
{
this(owner, pos, i, o, false);
}
@@ -723,7 +733,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
private static final Map<String, NbtPathArgument.NbtPath> pathCache = new HashMap<>();
private static NbtPathArgument.NbtPath cachePath(final String arg)
private static NbtPathArgument.NbtPath cachePath(String arg)
{
NbtPathArgument.NbtPath res = pathCache.get(arg);
if (res != null)
@@ -734,7 +744,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
{
res = NbtPathArgument.nbtPath().parse(new StringReader(arg));
}
catch (final CommandSyntaxException exc)
catch (CommandSyntaxException exc)
{
throw new InternalExpressionException("Incorrect nbt path: " + arg);
}
@@ -754,7 +764,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
if (!force)
{
@@ -768,7 +778,7 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
{
public final Value val;
public IncompatibleTypeException(final Value val)
public IncompatibleTypeException(Value val)
{
this.val = val;
}
@@ -41,13 +41,13 @@ public class NullValue extends NumericValue // TODO check nonsingleton code
}
@Override
public boolean equals(final Object o)
public boolean equals(Object o)
{
return o instanceof Value value && value.isNull();
}
@Override
public Value slice(final long fromDesc, final Long toDesc)
public Value slice(long fromDesc, Long toDesc)
{
return Value.NULL;
}
@@ -65,13 +65,13 @@ public class NullValue extends NumericValue // TODO check nonsingleton code
}
@Override
public int compareTo(final Value o)
public int compareTo(Value o)
{
return o.isNull() ? 0 : -1;
}
@Override
public Value in(final Value value)
public Value in(Value value)
{
return Value.NULL;
}
@@ -89,7 +89,7 @@ public class NullValue extends NumericValue // TODO check nonsingleton code
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
if (!force)
{
@@ -99,7 +99,7 @@ public class NullValue extends NumericValue // TODO check nonsingleton code
}
@Override
public Value split(final Value delimiter)
public Value split(Value delimiter)
{
return ListValue.wrap(new ArrayList<>());
}
@@ -25,7 +25,7 @@ public class NumericValue extends Value
private static final double epsilon = abs(32 * ((7 * 0.1) * 10 - 7));
private static final MathContext displayRounding = new MathContext(12, RoundingMode.HALF_EVEN);
public static NumericValue asNumber(final Value v1, final String id)
public static NumericValue asNumber(Value v1, String id)
{
if (v1 instanceof final NumericValue nv)
{
@@ -34,7 +34,7 @@ public class NumericValue extends Value
throw new InternalExpressionException("Argument " + id + " has to be of a numeric type");
}
public static NumericValue asNumber(final Value v1)
public static NumericValue asNumber(Value v1)
{
if (v1 instanceof final NumericValue nv)
{
@@ -43,7 +43,7 @@ public class NumericValue extends Value
throw new InternalExpressionException("Operand has to be of a numeric type");
}
public static <T extends Number> Value of(final T value)
public static <T extends Number> Value of(T value)
{
if (value == null)
{
@@ -85,7 +85,7 @@ public class NumericValue extends Value
// dobules have 16 point precision, 12 is plenty to display
return BigDecimal.valueOf(value).round(displayRounding).stripTrailingZeros().toPlainString();
}
catch (final NumberFormatException exc)
catch (NumberFormatException exc)
{
throw new InternalExpressionException("Incorrect number format for " + value);
}
@@ -115,9 +115,9 @@ public class NumericValue extends Value
return (float) value;
}
private static long floor(final double v)
private static long floor(double v)
{
final long invValue = (long) v;
long invValue = (long) v;
return v < invValue ? invValue - 1 : invValue;
}
@@ -127,7 +127,7 @@ public class NumericValue extends Value
}
@Override
public Value add(final Value v)
public Value add(Value v)
{ // TODO test if definintn add(NumericVlaue) woud solve the casting
if (v instanceof final NumericValue nv)
{
@@ -137,7 +137,7 @@ public class NumericValue extends Value
}
@Override
public Value subtract(final Value v)
public Value subtract(Value v)
{ // TODO test if definintn add(NumericVlaue) woud solve the casting
if (v instanceof final NumericValue nv)
{
@@ -147,7 +147,7 @@ public class NumericValue extends Value
}
@Override
public Value multiply(final Value v)
public Value multiply(Value v)
{
if (v instanceof final NumericValue nv)
{
@@ -157,7 +157,7 @@ public class NumericValue extends Value
}
@Override
public Value divide(final Value v)
public Value divide(Value v)
{
return v instanceof final NumericValue nv ? new NumericValue(getDouble() / nv.getDouble()) : super.divide(v);
}
@@ -169,7 +169,7 @@ public class NumericValue extends Value
}
@Override
public int compareTo(final Value o)
public int compareTo(Value o)
{
if (o.isNull())
{
@@ -183,7 +183,7 @@ public class NumericValue extends Value
}
@Override
public boolean equals(final Object o)
public boolean equals(Object o)
{
if (o instanceof final Value otherValue)
{
@@ -200,34 +200,34 @@ public class NumericValue extends Value
return false;
}
public NumericValue(final double value)
public NumericValue(double value)
{
this.value = value;
}
private NumericValue(final double value, final Long longValue)
private NumericValue(double value, Long longValue)
{
this.value = value;
this.longValue = longValue;
}
public NumericValue(final String value)
public NumericValue(String value)
{
final BigDecimal decimal = new BigDecimal(value);
BigDecimal decimal = new BigDecimal(value);
if (decimal.stripTrailingZeros().scale() <= 0)
{
try
{
longValue = decimal.longValueExact();
}
catch (final ArithmeticException ignored)
catch (ArithmeticException ignored)
{
}
}
this.value = decimal.doubleValue();
}
public NumericValue(final long value)
public NumericValue(long value)
{
this.longValue = value;
this.value = (double) value;
@@ -271,7 +271,7 @@ public class NumericValue extends Value
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
if (longValue != null)
{
@@ -281,7 +281,7 @@ public class NumericValue extends Value
}
return LongTag.valueOf(longValue);
}
final long lv = getLong();
long lv = getLong();
if (value == (double) lv)
{
if (abs(value) < Integer.MAX_VALUE - 2)
@@ -303,7 +303,7 @@ public class NumericValue extends Value
{
return new JsonPrimitive(longValue);
}
final long lv = getLong();
long lv = getLong();
return new JsonPrimitive(value == lv ? getLong() : value);
}
@@ -317,14 +317,14 @@ public class NumericValue extends Value
return longValue != null || getDouble() == getLong();
}
public Value mod(final NumericValue n2)
public Value mod(NumericValue n2)
{
if (this.longValue != null && n2.longValue != null)
{
return new NumericValue(Math.floorMod(longValue, n2.longValue));
}
final double x = value;
final double y = n2.value;
double x = value;
double y = n2.value;
if (y == 0)
{
throw new ArithmeticException("Division by zero");
@@ -57,6 +57,8 @@ import net.minecraft.world.inventory.StonecutterMenu;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Recipe;
import javax.annotation.Nullable;
import static net.minecraft.world.inventory.MenuType.*;
public class ScreenValue extends Value
@@ -109,7 +111,7 @@ public class ScreenValue extends Value
AbstractContainerMenu create(int syncId, Inventory playerInventory);
}
public ScreenValue(final ServerPlayer player, final String type, final Component name, final FunctionValue callback, final Context c)
public ScreenValue(ServerPlayer player, String type, Component name, @Nullable FunctionValue callback, Context c)
{
this.name = name;
this.typestring = type.toLowerCase();
@@ -121,7 +123,7 @@ public class ScreenValue extends Value
this.hostname = c.host.getName();
this.scriptServer = (CarpetScriptServer) c.host.scriptServer();
this.player = player;
final MenuProvider factory = this.createScreenHandlerFactory();
MenuProvider factory = this.createScreenHandlerFactory();
if (factory == null)
{
throw new ThrowStatement(type, Throwables.UNKNOWN_SCREEN);
@@ -138,20 +140,20 @@ public class ScreenValue extends Value
}
return new SimpleMenuProvider((i, playerInventory, playerEntity) -> {
final AbstractContainerMenu screen = screenHandlerFactories.get(ScreenValue.this.typestring).create(i, playerInventory);
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(final MenuProvider factory)
private void openScreen(MenuProvider factory)
{
if (this.player == null)
{
return;
}
final OptionalInt optionalSyncId = this.player.openMenu(factory);
OptionalInt optionalSyncId = this.player.openMenu(factory);
if (optionalSyncId.isPresent() && this.player.containerMenu.containerId == optionalSyncId.getAsInt())
{
this.screenHandler = this.player.containerMenu;
@@ -185,35 +187,35 @@ public class ScreenValue extends Value
}
private boolean callListener(final ServerPlayer player, final String action, final Map<Value, Value> data)
private boolean callListener(ServerPlayer player, String action, Map<Value, Value> data)
{
final Value playerValue = EntityValue.of(player);
final Value actionValue = StringValue.of(action);
final Value dataValue = MapValue.wrap(data);
final List<Value> args = Arrays.asList(this, playerValue, actionValue, dataValue);
final CarpetScriptHost appHost = scriptServer.getAppHostByName(this.hostname);
Value playerValue = EntityValue.of(player);
Value actionValue = StringValue.of(action);
Value dataValue = MapValue.wrap(data);
List<Value> args = Arrays.asList(this, playerValue, actionValue, dataValue);
CarpetScriptHost appHost = scriptServer.getAppHostByName(this.hostname);
if (appHost == null)
{
this.close();
this.screenHandler = null;
return false;
}
final int runPermissionLevel = Vanilla.MinecraftServer_getRunPermissionLevel(player.server);
final CommandSourceStack source = player.createCommandSourceStack().withPermission(runPermissionLevel);
final CarpetScriptHost executingHost = appHost.retrieveForExecution(source, player);
int runPermissionLevel = Vanilla.MinecraftServer_getRunPermissionLevel(player.server);
CommandSourceStack source = player.createCommandSourceStack().withPermission(runPermissionLevel);
CarpetScriptHost executingHost = appHost.retrieveForExecution(source, player);
try
{
final Value cancelValue = executingHost.callUDF(source, callback, args);
Value cancelValue = executingHost.callUDF(source, callback, args);
return cancelValue.getString().equals("cancel");
}
catch (final NullPointerException | InvalidCallbackException | IntegrityException error)
catch (NullPointerException | InvalidCallbackException | IntegrityException error)
{
CarpetScriptServer.LOG.error("Got exception when running screen event call ", error);
return false;
}
}
private void addListenerCallback(final AbstractContainerMenu screenHandler)
private void addListenerCallback(AbstractContainerMenu screenHandler)
{
if (this.callback == null)
{
@@ -223,9 +225,9 @@ public class ScreenValue extends Value
screenHandler.addSlotListener(new ScarpetScreenHandlerListener()
{
@Override
public boolean onSlotClick(final ServerPlayer player, final ClickType actionType, final int slot, int button)
public boolean onSlotClick(ServerPlayer player, ClickType actionType, int slot, int button)
{
final Map<Value, Value> data = new HashMap<>();
Map<Value, Value> data = new HashMap<>();
data.put(StringValue.of("slot"), slot == AbstractContainerMenu.SLOT_CLICKED_OUTSIDE ? Value.NULL : NumericValue.of(slot));
if (actionType == ClickType.QUICK_CRAFT)
{
@@ -237,46 +239,46 @@ public class ScreenValue extends Value
}
@Override
public boolean onButtonClick(final ServerPlayer player, final int button)
public boolean onButtonClick(ServerPlayer player, int button)
{
final Map<Value, Value> data = new HashMap<>();
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(final ServerPlayer player)
public void onClose(ServerPlayer player)
{
final Map<Value, Value> data = new HashMap<>();
Map<Value, Value> data = new HashMap<>();
ScreenValue.this.callListener(player, "close", data);
}
@Override
public boolean onSelectRecipe(final ServerPlayer player, final Recipe<?> recipe, final boolean craftAll)
public boolean onSelectRecipe(ServerPlayer player, Recipe<?> recipe, boolean craftAll)
{
final Map<Value, Value> data = new HashMap<>();
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 slotChanged(final AbstractContainerMenu handler, final int slotId, final ItemStack stack)
public void slotChanged(AbstractContainerMenu handler, int slotId, ItemStack stack)
{
final Map<Value, Value> data = new HashMap<>();
Map<Value, Value> data = new HashMap<>();
data.put(StringValue.of("slot"), NumericValue.of(slotId));
data.put(StringValue.of("stack"), ValueConversions.of(stack, player.level.registryAccess()));
ScreenValue.this.callListener(ScreenValue.this.player, "slot_update", data);
}
@Override
public void dataChanged(final AbstractContainerMenu handler, final int property, final int value)
public void dataChanged(AbstractContainerMenu handler, int property, int value)
{
}
});
}
private DataSlot getPropertyForType(final Class<? extends AbstractContainerMenu> screenHandlerClass, final String requiredType, final int propertyIndex, final String propertyName)
private DataSlot getPropertyForType(Class<? extends AbstractContainerMenu> screenHandlerClass, String requiredType, int propertyIndex, String propertyName)
{
if (screenHandlerClass.isInstance(this.screenHandler))
{
@@ -289,7 +291,7 @@ public class ScreenValue extends Value
throw new InternalExpressionException("Screen property " + propertyName + " expected a " + requiredType + " screen.");
}
private DataSlot getProperty(final String propertyName)
private DataSlot getProperty(String propertyName)
{
return switch (propertyName)
{
@@ -321,7 +323,7 @@ public class ScreenValue extends Value
}
public Value queryProperty(final String propertyName)
public Value queryProperty(String propertyName)
{
if (propertyName.equals("name"))
{
@@ -331,14 +333,14 @@ public class ScreenValue extends Value
{
return BooleanValue.of(this.isOpen());
}
final DataSlot property = getProperty(propertyName);
DataSlot property = getProperty(propertyName);
return NumericValue.of(property.get());
}
public Value modifyProperty(final String propertyName, final List<Value> lv)
public Value modifyProperty(String propertyName, List<Value> lv)
{
final DataSlot property = getProperty(propertyName);
final int intValue = NumericValue.asNumber(lv.get(0)).getInt();
DataSlot property = getProperty(propertyName);
int intValue = NumericValue.asNumber(lv.get(0)).getInt();
property.set(intValue);
this.screenHandler.sendAllDataToRemote();
return Value.TRUE;
@@ -373,17 +375,17 @@ public class ScreenValue extends Value
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
if (this.screenHandler == null)
{
return Value.NULL.toTag(true);
}
final ListTag nbtList = new ListTag();
ListTag nbtList = new ListTag();
for (int i = 0; i < this.screenHandler.slots.size(); i++)
{
final ItemStack itemStack = this.screenHandler.getSlot(i).getItem();
ItemStack itemStack = this.screenHandler.getSlot(i).getItem();
nbtList.add(itemStack.save(new CompoundTag()));
}
return nbtList;
@@ -405,7 +407,7 @@ public class ScreenValue extends Value
{
protected AbstractContainerMenu screenHandler;
public ScreenHandlerInventory(final AbstractContainerMenu screenHandler)
public ScreenHandlerInventory(AbstractContainerMenu screenHandler)
{
this.screenHandler = screenHandler;
}
@@ -419,7 +421,7 @@ public class ScreenValue extends Value
@Override
public boolean isEmpty()
{
for (final Slot slot : this.screenHandler.slots)
for (Slot slot : this.screenHandler.slots)
{
if (slot.hasItem() && !slot.getItem().isEmpty())
{
@@ -430,7 +432,7 @@ public class ScreenValue extends Value
}
@Override
public ItemStack getItem(final int slot)
public ItemStack getItem(int slot)
{
if (slot == this.getContainerSize() - 1)
{
@@ -440,9 +442,9 @@ public class ScreenValue extends Value
}
@Override
public ItemStack removeItem(final int slot, final int amount)
public ItemStack removeItem(int slot, int amount)
{
final ItemStack itemStack;
ItemStack itemStack;
if (slot == this.getContainerSize() - 1)
{
itemStack = this.screenHandler.getCarried().split(amount);
@@ -459,9 +461,9 @@ public class ScreenValue extends Value
}
@Override
public ItemStack removeItemNoUpdate(final int slot)
public ItemStack removeItemNoUpdate(int slot)
{
final ItemStack itemStack;
ItemStack itemStack;
if (slot == this.getContainerSize() - 1)
{
itemStack = this.screenHandler.getCarried();
@@ -489,7 +491,7 @@ public class ScreenValue extends Value
}
@Override
public void setItem(final int slot, final ItemStack stack)
public void setItem(int slot, ItemStack stack)
{
if (slot == this.getContainerSize() - 1)
{
@@ -513,7 +515,7 @@ public class ScreenValue extends Value
}
@Override
public boolean stillValid(final Player player)
public boolean stillValid(Player player)
{
return true;
}
@@ -521,7 +523,7 @@ public class ScreenValue extends Value
@Override
public void clearContent()
{
for (final Slot slot : this.screenHandler.slots)
for (Slot slot : this.screenHandler.slots)
{
slot.set(ItemStack.EMPTY);
}
@@ -530,13 +532,13 @@ public class ScreenValue extends Value
}
public static ItemStack splitStack(final List<Slot> slots, final int slot, final int amount)
public static ItemStack splitStack(List<Slot> slots, int slot, int amount)
{
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(final ClickType actionType)
private static String actionTypeToString(ClickType actionType)
{
return switch (actionType)
{
@@ -3,6 +3,8 @@ package carpet.script.value;
import net.minecraft.nbt.StringTag;
import net.minecraft.nbt.Tag;
import javax.annotation.Nullable;
public class StringValue extends Value
{
public static Value EMPTY = StringValue.of("");
@@ -27,12 +29,12 @@ public class StringValue extends Value
return new StringValue(str);
}
public StringValue(final String str)
public StringValue(String str)
{
this.str = str;
}
public static Value of(final String value)
public static Value of(@Nullable String value)
{
return value == null ? Value.NULL : new StringValue(value);
}
@@ -44,7 +46,7 @@ public class StringValue extends Value
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
return StringTag.valueOf(str);
}
@@ -20,21 +20,21 @@ public class ThreadValue extends Value
private final long id;
private static long sequence = 0L;
public ThreadValue(final CompletableFuture<Value> taskFuture)
public ThreadValue(CompletableFuture<Value> taskFuture)
{
this.taskFuture = taskFuture;
this.id = sequence++;
}
public ThreadValue(final Value pool, final FunctionValue function, final Expression expr, final Tokenizer.Token token, final Context ctx, final List<Value> args)
public ThreadValue(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List<Value> args)
{
this(getCompletableFutureFromFunction(pool, function, expr, token, ctx, args));
Thread.yield();
}
public static CompletableFuture<Value> getCompletableFutureFromFunction(final Value pool, final FunctionValue function, final Expression expr, final Tokenizer.Token token, final Context ctx, final List<Value> args)
public static CompletableFuture<Value> getCompletableFutureFromFunction(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List<Value> args)
{
final ExecutorService executor = ctx.host.getExecutor(pool);
ExecutorService executor = ctx.host.getExecutor(pool);
if (executor == null)
{
// app is shutting down - no more threads can be spawned.
@@ -47,12 +47,12 @@ public class ThreadValue extends Value
{
return function.execute(ctx, Context.NONE, expr, token, args).evalValue(ctx);
}
catch (final ExitStatement exit)
catch (ExitStatement exit)
{
// app stopped
return exit.retval;
}
catch (final ExpressionException exc)
catch (ExpressionException exc)
{
ctx.host.handleExpressionException("Thread failed\n", exc);
return Value.NULL;
@@ -84,12 +84,12 @@ public class ThreadValue extends Value
{
return taskFuture.get();
}
catch (final ExitStatement exit)
catch (ExitStatement exit)
{
taskFuture.complete(exit.retval);
return exit.retval;
}
catch (final InterruptedException | ExecutionException e)
catch (InterruptedException | ExecutionException e)
{
return Value.NULL;
}
@@ -101,13 +101,13 @@ public class ThreadValue extends Value
}
@Override
public boolean equals(final Object o)
public boolean equals(Object o)
{
return o instanceof final ThreadValue tv && tv.id == this.id;
}
@Override
public int compareTo(final Value o)
public int compareTo(Value o)
{
if (!(o instanceof final ThreadValue tv))
{
@@ -123,7 +123,7 @@ public class ThreadValue extends Value
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
if (!force)
{
@@ -38,13 +38,13 @@ public class UndefValue extends NullValue
}
@Override
public boolean equals(final Object o)
public boolean equals(Object o)
{
throw getError();
}
@Override
public Value slice(final long fromDesc, final Long toDesc)
public Value slice(long fromDesc, Long toDesc)
{
throw getError();
}
@@ -62,13 +62,13 @@ public class UndefValue extends NullValue
}
@Override
public int compareTo(final Value o)
public int compareTo(Value o)
{
throw getError();
}
@Override
public Value in(final Value value)
public Value in(Value value)
{
throw getError();
}
@@ -86,13 +86,13 @@ public class UndefValue extends NullValue
}
@Override
public Tag toTag(final boolean force)
public Tag toTag(boolean force)
{
throw getError();
}
@Override
public Value split(final Value delimiter)
public Value split(Value delimiter)
{
throw getError();
}
@@ -110,25 +110,25 @@ public class UndefValue extends NullValue
}
@Override
public Value add(final Value v)
public Value add(Value v)
{
throw getError();
}
@Override
public Value subtract(final Value v)
public Value subtract(Value v)
{
throw getError();
}
@Override
public Value multiply(final Value v)
public Value multiply(Value v)
{
throw getError();
}
@Override
public Value divide(final Value v)
public Value divide(Value v)
{
throw getError();
}
+32 -30
View File
@@ -14,6 +14,8 @@ import java.util.regex.PatternSyntaxException;
import net.minecraft.nbt.Tag;
import javax.annotation.Nullable;
public abstract class Value implements Comparable<Value>, Cloneable
{
public static final NumericValue FALSE = BooleanValue.FALSE;
@@ -36,14 +38,14 @@ public abstract class Value implements Comparable<Value>, Cloneable
return boundVariable;
}
public Value reboundedTo(final String value)
public Value reboundedTo(String value)
{
final Value copy;
Value copy;
try
{
copy = (Value) clone();
}
catch (final CloneNotSupportedException e)
catch (CloneNotSupportedException e)
{
// should not happen
CarpetScriptServer.LOG.error("Failed to clone variable", e);
@@ -53,7 +55,7 @@ public abstract class Value implements Comparable<Value>, Cloneable
return copy;
}
public Value bindTo(final String value)
public Value bindTo(String value)
{
this.boundVariable = value;
return this;
@@ -69,34 +71,34 @@ public abstract class Value implements Comparable<Value>, Cloneable
public abstract boolean getBoolean();
public Value add(final Value o)
public Value add(Value o)
{
if (o instanceof FormattedTextValue)
{
return FormattedTextValue.combine(this, o);
}
final String leftStr = this.getString();
final String rightStr = o.getString();
String leftStr = this.getString();
String rightStr = o.getString();
return new StringValue(leftStr + rightStr);
}
public Value subtract(final Value v)
public Value subtract(Value v)
{
return new StringValue(this.getString().replace(v.getString(), ""));
}
public Value multiply(final Value v)
public Value multiply(Value v)
{
return v instanceof NumericValue || v instanceof ListValue
? v.multiply(this)
: new StringValue(this.getString() + "." + v.getString());
}
public Value divide(final Value v)
public Value divide(Value v)
{
if (v instanceof final NumericValue number)
{
final String lstr = getString();
String lstr = getString();
return new StringValue(lstr.substring(0, (int) (lstr.length() / number.getDouble())));
}
return new StringValue(getString() + "/" + v.getString());
@@ -108,7 +110,7 @@ public abstract class Value implements Comparable<Value>, Cloneable
}
@Override
public int compareTo(final Value o)
public int compareTo(Value o)
{
return o instanceof NumericValue || o instanceof ListValue || o instanceof ThreadValue
? -o.compareTo(this)
@@ -116,7 +118,7 @@ public abstract class Value implements Comparable<Value>, Cloneable
}
@Override // for hashmap key access, and == operator
public boolean equals(final Object o)
public boolean equals(Object o)
{
if (o instanceof final Value v)
{
@@ -137,23 +139,23 @@ public abstract class Value implements Comparable<Value>, Cloneable
}
}
public Value in(final Value value1)
public Value in(Value value1)
{
final Pattern p;
Pattern p;
try
{
p = Pattern.compile(value1.getString());
}
catch (final PatternSyntaxException pse)
catch (PatternSyntaxException pse)
{
throw new InternalExpressionException("Incorrect matching pattern: " + pse.getMessage());
}
final Matcher m = p.matcher(this.getString());
Matcher m = p.matcher(this.getString());
if (!m.find())
{
return Value.NULL;
}
final int gc = m.groupCount();
int gc = m.groupCount();
if (gc == 0)
{
return new StringValue(m.group());
@@ -162,7 +164,7 @@ public abstract class Value implements Comparable<Value>, Cloneable
{
return StringValue.of(m.group(1));
}
final List<Value> groups = new ArrayList<>(gc);
List<Value> groups = new ArrayList<>(gc);
for (int i = 1; i <= gc; i++)
{
groups.add(StringValue.of(m.group(i)));
@@ -175,16 +177,16 @@ public abstract class Value implements Comparable<Value>, Cloneable
return getString().length();
}
public Value slice(final long fromDesc, final Long toDesc)
public Value slice(long fromDesc, @Nullable Long toDesc)
{
final String value = this.getString();
final int size = value.length();
final int from = ListValue.normalizeIndex(fromDesc, size);
String value = this.getString();
int size = value.length();
int from = ListValue.normalizeIndex(fromDesc, size);
if (toDesc == null)
{
return new StringValue(value.substring(from));
}
final int to = ListValue.normalizeIndex(toDesc, size + 1);
int to = ListValue.normalizeIndex(toDesc, size + 1);
if (from > to)
{
return StringValue.EMPTY;
@@ -192,7 +194,7 @@ public abstract class Value implements Comparable<Value>, Cloneable
return new StringValue(value.substring(from, to));
}
public Value split(Value delimiter)
public Value split(@Nullable Value delimiter)
{
if (delimiter == null)
{
@@ -202,7 +204,7 @@ public abstract class Value implements Comparable<Value>, Cloneable
{
return ListValue.wrap(Arrays.stream(getString().split(delimiter.getString())).map(StringValue::new));
}
catch (final PatternSyntaxException pse)
catch (PatternSyntaxException pse)
{
throw new InternalExpressionException("Incorrect pattern for 'split': " + pse.getMessage());
}
@@ -210,12 +212,12 @@ public abstract class Value implements Comparable<Value>, Cloneable
public double readDoubleNumber()
{
final String s = getString();
String s = getString();
try
{
return Double.parseDouble(s);
}
catch (final NumberFormatException e)
catch (NumberFormatException e)
{
return Double.NaN;
}
@@ -234,7 +236,7 @@ public abstract class Value implements Comparable<Value>, Cloneable
@Override
public int hashCode()
{
final String stringVal = getString();
String stringVal = getString();
return stringVal.isEmpty() ? 0 : ("s" + stringVal).hashCode();
}
@@ -244,7 +246,7 @@ public abstract class Value implements Comparable<Value>, Cloneable
{
return (Value) this.clone();
}
catch (final CloneNotSupportedException e)
catch (CloneNotSupportedException e)
{
// should never happen
throw new InternalExpressionException("Cannot make a copy of value: " + this);
@@ -59,40 +59,42 @@ import java.util.stream.StreamSupport;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import javax.annotation.Nullable;
public class ValueConversions
{
public static Value of(final BlockPos pos)
public static Value of(BlockPos pos)
{
return ListValue.of(new NumericValue(pos.getX()), new NumericValue(pos.getY()), new NumericValue(pos.getZ()));
}
public static Value of(final Vec3 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(final ColumnPos cpos)
public static Value of(ColumnPos cpos)
{
return ListValue.of(new NumericValue(cpos.x()), new NumericValue(cpos.z()));
}
public static Value of(final ServerLevel world)
public static Value of(ServerLevel world)
{
return of(world.dimension().location());
}
public static Value of(final MaterialColor color)
public static Value of(MaterialColor color)
{
return ListValue.of(StringValue.of(Carpet.getMapColorNames().get(color)), ofRGB(color.col));
}
public static <T extends Number> Value of(final MinMaxBounds<T> range)
public static <T extends Number> Value of(MinMaxBounds<T> range)
{
return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax()));
}
@Deprecated
public static Value of(final ItemStack stack)
public static Value of(ItemStack stack)
{
return stack == null || stack.isEmpty() ? Value.NULL : ListValue.of(
of(BuiltInRegistries.ITEM.getKey(stack.getItem())),
@@ -101,7 +103,7 @@ public class ValueConversions
);
}
public static Value of(final ItemStack stack, final RegistryAccess regs)
public static Value of(ItemStack stack, RegistryAccess regs)
{
return stack == null || stack.isEmpty() ? Value.NULL : ListValue.of(
of(regs.registryOrThrow(Registries.ITEM).getKey(stack.getItem())),
@@ -110,7 +112,7 @@ public class ValueConversions
);
}
public static Value of(final Objective objective)
public static Value of(Objective objective)
{
return ListValue.of(
StringValue.of(objective.getName()),
@@ -119,7 +121,7 @@ public class ValueConversions
}
public static Value of(final ObjectiveCriteria criteria)
public static Value of(ObjectiveCriteria criteria)
{
return ListValue.of(
StringValue.of(criteria.getName()),
@@ -128,18 +130,18 @@ public class ValueConversions
}
public static Value of(final ParticleOptions particle)
public static Value of(ParticleOptions particle)
{
final String repr = particle.writeToString();
String repr = particle.writeToString();
return StringValue.of(repr.startsWith("minecraft:") ? repr.substring(10) : repr);
}
public static Value ofRGB(final int value)
public static Value ofRGB(int value)
{
return new NumericValue(value * 256 + 255);
}
public static Level dimFromValue(final Value dimensionValue, final MinecraftServer server)
public static Level dimFromValue(Value dimensionValue, MinecraftServer server)
{
if (dimensionValue instanceof EntityValue)
{
@@ -158,16 +160,16 @@ public class ValueConversions
}
else
{
final String dimString = dimensionValue.getString().toLowerCase(Locale.ROOT);
String dimString = dimensionValue.getString().toLowerCase(Locale.ROOT);
return switch (dimString) {
case "nether", "the_nether" -> server.getLevel(Level.NETHER);
case "end", "the_end" -> server.getLevel(Level.END);
case "overworld", "over_world" -> server.getLevel(Level.OVERWORLD);
default -> {
ResourceKey<Level> dim = null;
final ResourceLocation id = new ResourceLocation(dimString);
ResourceLocation id = new ResourceLocation(dimString);
// not using RegistryKey.of since that one creates on check
for (final ResourceKey<Level> world : (server.levelKeys()))
for (ResourceKey<Level> world : (server.levelKeys()))
{
if (id.equals(world.location()))
{
@@ -185,17 +187,17 @@ public class ValueConversions
}
}
public static Value of(final ResourceKey<?> dim)
public static Value of(ResourceKey<?> dim)
{
return of(dim.location());
}
public static Value of(final TagKey<?> tagKey)
public static Value of(TagKey<?> tagKey)
{
return of(tagKey.location());
}
public static Value of(final ResourceLocation id)
public static Value of(@Nullable ResourceLocation id)
{
if (id == null) // should be Value.NULL
{
@@ -204,7 +206,7 @@ public class ValueConversions
return new StringValue(simplify(id));
}
public static String simplify(final ResourceLocation id)
public static String simplify(ResourceLocation id)
{
if (id == null) // should be Value.NULL
{
@@ -217,7 +219,7 @@ public class ValueConversions
return id.toString();
}
public static Value of(final GlobalPos pos)
public static Value of(GlobalPos pos)
{
return ListValue.of(
ValueConversions.of(pos.dimension()),
@@ -225,12 +227,12 @@ public class ValueConversions
);
}
public static Value fromPath(final ServerLevel world, final Path path)
public static Value fromPath(ServerLevel world, Path path)
{
final List<Value> nodes = new ArrayList<>();
List<Value> nodes = new ArrayList<>();
for (int i = 0, len = path.getNodeCount(); i < len; i++)
{
final Node node = path.getNode(i);
Node node = path.getNode(i);
nodes.add(ListValue.of(
new BlockValue(null, world, node.asBlockPos()),
new StringValue(node.type.name().toLowerCase(Locale.ROOT)),
@@ -241,13 +243,13 @@ public class ValueConversions
return ListValue.wrap(nodes);
}
public static Value fromTimedMemory(final Entity e, final long expiry, final Object v)
public static Value fromTimedMemory(Entity e, long expiry, Object v)
{
final Value ret = fromEntityMemory(e, v);
Value ret = fromEntityMemory(e, v);
return ret.isNull() || expiry == Long.MAX_VALUE ? ret : ListValue.of(ret, new NumericValue(expiry));
}
private static Value fromEntityMemory(final Entity e, Object v)
private static Value fromEntityMemory(Entity e, Object v)
{
if (v instanceof GlobalPos pos)
{
@@ -259,7 +261,7 @@ public class ValueConversions
}
if (v instanceof final BlockPos pos)
{
return new BlockValue(null, e.getCommandSenderWorld(), pos);
return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), pos);
}
if (v instanceof final Number number)
{
@@ -286,12 +288,12 @@ public class ValueConversions
}
if (v instanceof final PositionTracker tracker)
{
return new BlockValue(null, e.getCommandSenderWorld(), tracker.currentBlockPosition());
return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), tracker.currentBlockPosition());
}
if (v instanceof final WalkTarget target)
{
return ListValue.of(
new BlockValue(null, e.getCommandSenderWorld(), target.getTarget().currentBlockPosition()),
new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), target.getTarget().currentBlockPosition()),
new NumericValue(target.getSpeedModifier()),
new NumericValue(target.getCloseEnoughDist())
);
@@ -310,7 +312,7 @@ public class ValueConversions
{
return ListValue.of();
}
final Object el = l.get(0);
Object el = l.get(0);
if (el instanceof final Entity entity)
{
return ListValue.wrap(l.stream().map(o -> new EntityValue(entity)));
@@ -323,16 +325,16 @@ public class ValueConversions
return Value.NULL;
}
private static Value ofUUID(final ServerLevel entityWorld, final UUID uuid)
private static Value ofUUID(ServerLevel entityWorld, UUID uuid)
{
final Entity current = entityWorld.getEntity(uuid);
Entity current = entityWorld.getEntity(uuid);
return ListValue.of(
current == null ? Value.NULL : new EntityValue(current),
new StringValue(uuid.toString())
);
}
public static Value of(final AABB box)
public static Value of(AABB box)
{
return ListValue.of(
ListValue.fromTriple(box.minX, box.minY, box.minZ),
@@ -340,7 +342,7 @@ public class ValueConversions
);
}
public static Value of(final BoundingBox box)
public static Value of(BoundingBox box)
{
return ListValue.of(
ListValue.fromTriple(box.minX(), box.minY(), box.minZ()),
@@ -348,27 +350,27 @@ public class ValueConversions
);
}
public static Value of(final StructureStart structure, final RegistryAccess regs)
public static Value of(StructureStart structure, RegistryAccess regs)
{
if (structure == null || structure == StructureStart.INVALID_START)
{
return Value.NULL;
}
final BoundingBox boundingBox = structure.getBoundingBox();
BoundingBox boundingBox = structure.getBoundingBox();
if (boundingBox.maxX() < boundingBox.minX() || boundingBox.maxY() < boundingBox.minY() || boundingBox.maxZ() < boundingBox.minZ())
{
return Value.NULL;
}
final Map<Value, Value> ret = new HashMap<>();
Map<Value, Value> ret = new HashMap<>();
ret.put(new StringValue("box"), of(boundingBox));
final List<Value> pieces = new ArrayList<>();
for (final StructurePiece piece : structure.getPieces())
List<Value> pieces = new ArrayList<>();
for (StructurePiece piece : structure.getPieces())
{
final BoundingBox box = piece.getBoundingBox();
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(regs.registryOrThrow(Registries.STRUCTURE_PIECE).getKey(piece.getType()))),
NBTSerializableValue.nameFromRegistryId(regs.registryOrThrow(Registries.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())
@@ -379,9 +381,9 @@ public class ValueConversions
return MapValue.wrap(ret);
}
public static Value fromProperty(final BlockState state, final Property<?> p)
public static Value fromProperty(BlockState state, Property<?> p)
{
final Comparable<?> object = state.getValue(p);
Comparable<?> object = state.getValue(p);
if (object instanceof Boolean || object instanceof Number)
{
return StringValue.of(object.toString());
@@ -443,16 +445,16 @@ public class ValueConversions
//hashMap.put("horse.chest", 499);
}};
public static Value ofVanillaSlotResult(final int itemSlot)
public static Value ofVanillaSlotResult(int itemSlot)
{
final SlotParam ret = slotIdsToSlotParams.get(itemSlot);
SlotParam ret = slotIdsToSlotParams.get(itemSlot);
return ret == null ? ListValue.of(Value.NULL, new NumericValue(itemSlot)) : ret.build();
}
public static Value ofBlockPredicate(final RegistryAccess registryAccess, final Predicate<BlockInWorld> blockPredicate)
public static Value ofBlockPredicate(RegistryAccess registryAccess, Predicate<BlockInWorld> blockPredicate)
{
final Vanilla.BlockPredicatePayload payload = Vanilla.BlockPredicatePayload.of(blockPredicate);
final Registry<Block> blocks = registryAccess.registryOrThrow(Registries.BLOCK);
Vanilla.BlockPredicatePayload payload = Vanilla.BlockPredicatePayload.of(blockPredicate);
Registry<Block> blocks = registryAccess.registryOrThrow(Registries.BLOCK);
return ListValue.of(
payload.state() == null ? Value.NULL : of(blocks.getKey(payload.state().getBlock())),
payload.tagKey() == null ? Value.NULL : of(blocks.getTag(payload.tagKey()).get().key()),
@@ -461,13 +463,13 @@ public class ValueConversions
);
}
public static ItemStack getItemStackFromValue(final Value value, final boolean withCount, final RegistryAccess regs)
public static ItemStack getItemStackFromValue(Value value, boolean withCount, RegistryAccess regs)
{
if (value.isNull())
{
return ItemStack.EMPTY;
}
final String name;
String name;
int count = 1;
CompoundTag nbtTag = null;
if (value instanceof ListValue list)
@@ -476,13 +478,13 @@ public class ValueConversions
{
throw new ThrowStatement("item definition from list of size " + list.length(), Throwables.UNKNOWN_ITEM);
}
final List<Value> items = list.getItems();
List<Value> items = list.getItems();
name = items.get(0).getString();
if (withCount)
{
count = NumericValue.asNumber(items.get(1)).getInt();
}
final Value nbtValue = items.get(2);
Value nbtValue = items.get(2);
if (!nbtValue.isNull())
{
nbtTag = ((NBTSerializableValue) NBTSerializableValue.fromValue(nbtValue)).getCompoundTag();
@@ -492,12 +494,12 @@ public class ValueConversions
{
name = value.getString();
}
final ItemInput itemInput = NBTSerializableValue.parseItem(name, nbtTag, regs);
ItemInput itemInput = NBTSerializableValue.parseItem(name, nbtTag, regs);
try
{
return itemInput.createItemStack(count, false);
}
catch (final CommandSyntaxException cse)
catch (CommandSyntaxException cse)
{
if (!withCount)
{
@@ -510,7 +512,7 @@ public class ValueConversions
}
}
public static Value guess(final ServerLevel serverWorld, final Object o)
public static Value guess(ServerLevel serverWorld, Object o)
{
if (o == null)
{