Use newer Java features in places where it makes sense and more (#1009)

This commit is contained in:
altrisi authored and GitHub committed 2021-08-03 07:32:40 -03:00
1 parent 28cb136c6b
commit 7fb5e47da5
34 files changed
+336 -397

No files matched your search

@@ -2,7 +2,6 @@ package carpet.helpers;
import carpet.CarpetSettings; import carpet.CarpetSettings;
import carpet.fakes.StructureFeatureInterface; import carpet.fakes.StructureFeatureInterface;
import com.google.common.collect.ImmutableList;
import com.mojang.datafixers.util.Pair; import com.mojang.datafixers.util.Pair;
import net.minecraft.server.world.ServerWorld; import net.minecraft.server.world.ServerWorld;
import net.minecraft.structure.StructureManager; import net.minecraft.structure.StructureManager;
@@ -36,6 +35,7 @@ import net.minecraft.world.gen.feature.StructurePoolFeatureConfig;
import net.minecraft.world.gen.feature.TreeFeatureConfig; import net.minecraft.world.gen.feature.TreeFeatureConfig;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
public class FeatureGenerator public class FeatureGenerator
@@ -175,13 +175,13 @@ public class FeatureGenerator
} }
public static final Map<String, Thing> featureMap = new HashMap<String, Thing>() {{ public static final Map<String, Thing> featureMap = new HashMap<String, Thing>() {{
put("oak_bees", simpleTree(ConfiguredFeatures.OAK.getConfig().setTreeDecorators(ImmutableList.of(new BeehiveTreeDecorator(1.0F))))); put("oak_bees", simpleTree(ConfiguredFeatures.OAK.getConfig().setTreeDecorators(List.of(new BeehiveTreeDecorator(1.0F)))));
put("fancy_oak_bees", simpleTree(ConfiguredFeatures.FANCY_OAK.getConfig().setTreeDecorators(ImmutableList.of(new BeehiveTreeDecorator(1.0F))))); put("fancy_oak_bees", simpleTree(ConfiguredFeatures.FANCY_OAK.getConfig().setTreeDecorators(List.of(new BeehiveTreeDecorator(1.0F)))));
put("birch_bees", simpleTree(ConfiguredFeatures.BIRCH.getConfig().setTreeDecorators(ImmutableList.of(new BeehiveTreeDecorator(1.0F))))); put("birch_bees", simpleTree(ConfiguredFeatures.BIRCH.getConfig().setTreeDecorators(List.of(new BeehiveTreeDecorator(1.0F)))));
put("coral_tree", simplePlop(Feature.CORAL_TREE.configure(FeatureConfig.DEFAULT))); put("coral_tree", simplePlop(Feature.CORAL_TREE.configure(FeatureConfig.DEFAULT)));
put("coral_claw", simplePlop(Feature.CORAL_CLAW.configure(FeatureConfig.DEFAULT))); put("coral_claw", simplePlop(Feature.CORAL_CLAW.configure(FeatureConfig.DEFAULT)));
put("coral_mushroom", simplePlop(Feature.CORAL_MUSHROOM.configure(FeatureConfig.DEFAULT))); put("coral_mushroom", simplePlop(Feature.CORAL_MUSHROOM.configure(FeatureConfig.DEFAULT)));
put("coral", simplePlop(Feature.SIMPLE_RANDOM_SELECTOR.configure(new SimpleRandomFeatureConfig(ImmutableList.of( put("coral", simplePlop(Feature.SIMPLE_RANDOM_SELECTOR.configure(new SimpleRandomFeatureConfig(List.of(
() -> Feature.CORAL_TREE.configure(FeatureConfig.DEFAULT), () -> Feature.CORAL_TREE.configure(FeatureConfig.DEFAULT),
() -> Feature.CORAL_CLAW.configure(FeatureConfig.DEFAULT), () -> Feature.CORAL_CLAW.configure(FeatureConfig.DEFAULT),
() -> Feature.CORAL_MUSHROOM.configure(FeatureConfig.DEFAULT) () -> Feature.CORAL_MUSHROOM.configure(FeatureConfig.DEFAULT)
@@ -191,7 +191,7 @@ public class FeatureGenerator
new StructurePoolFeatureConfig(() -> new StructurePool( new StructurePoolFeatureConfig(() -> new StructurePool(
new Identifier("bastion/starts"), new Identifier("bastion/starts"),
new Identifier("empty"), new Identifier("empty"),
ImmutableList.of( List.of(
Pair.of(StructurePoolElement.ofProcessedSingle("bastion/units/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) Pair.of(StructurePoolElement.ofProcessedSingle("bastion/units/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
), ),
StructurePool.Projection.RIGID StructurePool.Projection.RIGID
@@ -203,7 +203,7 @@ public class FeatureGenerator
new StructurePoolFeatureConfig(() -> new StructurePool( new StructurePoolFeatureConfig(() -> new StructurePool(
new Identifier("bastion/starts"), new Identifier("bastion/starts"),
new Identifier("empty"), new Identifier("empty"),
ImmutableList.of( List.of(
Pair.of(StructurePoolElement.ofProcessedSingle("bastion/hoglin_stable/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) Pair.of(StructurePoolElement.ofProcessedSingle("bastion/hoglin_stable/air_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
), ),
StructurePool.Projection.RIGID StructurePool.Projection.RIGID
@@ -215,7 +215,7 @@ public class FeatureGenerator
new StructurePoolFeatureConfig(() -> new StructurePool( new StructurePoolFeatureConfig(() -> new StructurePool(
new Identifier("bastion/starts"), new Identifier("bastion/starts"),
new Identifier("empty"), new Identifier("empty"),
ImmutableList.of( List.of(
Pair.of(StructurePoolElement.ofProcessedSingle("bastion/treasure/big_air_full", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) Pair.of(StructurePoolElement.ofProcessedSingle("bastion/treasure/big_air_full", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
), ),
StructurePool.Projection.RIGID StructurePool.Projection.RIGID
@@ -227,7 +227,7 @@ public class FeatureGenerator
new StructurePoolFeatureConfig(() -> new StructurePool( new StructurePoolFeatureConfig(() -> new StructurePool(
new Identifier("bastion/starts"), new Identifier("bastion/starts"),
new Identifier("empty"), new Identifier("empty"),
ImmutableList.of( List.of(
Pair.of(StructurePoolElement.ofProcessedSingle("bastion/bridge/starting_pieces/entrance_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1) Pair.of(StructurePoolElement.ofProcessedSingle("bastion/bridge/starting_pieces/entrance_base", StructureProcessorLists.BASTION_GENERIC_DEGRADATION), 1)
), ),
StructurePool.Projection.RIGID StructurePool.Projection.RIGID
+88 -89
View File
@@ -5,8 +5,6 @@ import carpet.fakes.IngredientInterface;
import carpet.fakes.RecipeManagerInterface; import carpet.fakes.RecipeManagerInterface;
import carpet.utils.WoolTool; import carpet.utils.WoolTool;
import carpet.utils.Messenger; import carpet.utils.Messenger;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongMap;
import net.minecraft.block.AbstractBannerBlock; import net.minecraft.block.AbstractBannerBlock;
@@ -42,6 +40,8 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static java.util.Map.entry;
/** /**
* The actual object residing in each hopper counter which makes them count the items and saves them. There is one for each * The actual object residing in each hopper counter which makes them count the items and saves them. There is one for each
* colour in MC. * colour in MC.
@@ -67,7 +67,7 @@ public class HopperCounter
{ {
counterMap.put(color, new HopperCounter(color)); counterMap.put(color, new HopperCounter(color));
} }
COUNTERS = Maps.immutableEnumMap(counterMap); COUNTERS = Collections.unmodifiableMap(counterMap);
} }
/** /**
@@ -243,92 +243,91 @@ public class HopperCounter
* Maps items that don't get a good block to reference for colour, or those that colour is wrong to a number of blocks, so we can get their colours easily with the * Maps items that don't get a good block to reference for colour, or those that colour is wrong to a number of blocks, so we can get their colours easily with the
* {@link Block#getDefaultMaterialColor()} method as these items have those same colours. * {@link Block#getDefaultMaterialColor()} method as these items have those same colours.
*/ */
private static final ImmutableMap<Item, Block> DEFAULTS = new ImmutableMap.Builder<Item, Block>() private static final Map<Item, Block> DEFAULTS = Map.ofEntries(
.put(Items.DANDELION, Blocks.YELLOW_WOOL) entry(Items.DANDELION, Blocks.YELLOW_WOOL),
.put(Items.POPPY, Blocks.RED_WOOL) entry(Items.POPPY, Blocks.RED_WOOL),
.put(Items.BLUE_ORCHID, Blocks.LIGHT_BLUE_WOOL) entry(Items.BLUE_ORCHID, Blocks.LIGHT_BLUE_WOOL),
.put(Items.ALLIUM, Blocks.MAGENTA_WOOL) entry(Items.ALLIUM, Blocks.MAGENTA_WOOL),
.put(Items.AZURE_BLUET, Blocks.SNOW_BLOCK) entry(Items.AZURE_BLUET, Blocks.SNOW_BLOCK),
.put(Items.RED_TULIP, Blocks.RED_WOOL) entry(Items.RED_TULIP, Blocks.RED_WOOL),
.put(Items.ORANGE_TULIP, Blocks.ORANGE_WOOL) entry(Items.ORANGE_TULIP, Blocks.ORANGE_WOOL),
.put(Items.WHITE_TULIP, Blocks.SNOW_BLOCK) entry(Items.WHITE_TULIP, Blocks.SNOW_BLOCK),
.put(Items.PINK_TULIP, Blocks.PINK_WOOL) entry(Items.PINK_TULIP, Blocks.PINK_WOOL),
.put(Items.OXEYE_DAISY, Blocks.SNOW_BLOCK) entry(Items.OXEYE_DAISY, Blocks.SNOW_BLOCK),
.put(Items.CORNFLOWER, Blocks.BLUE_WOOL) entry(Items.CORNFLOWER, Blocks.BLUE_WOOL),
.put(Items.WITHER_ROSE, Blocks.BLACK_WOOL) entry(Items.WITHER_ROSE, Blocks.BLACK_WOOL),
.put(Items.LILY_OF_THE_VALLEY, Blocks.WHITE_WOOL) entry(Items.LILY_OF_THE_VALLEY, Blocks.WHITE_WOOL),
.put(Items.BROWN_MUSHROOM, Blocks.BROWN_MUSHROOM_BLOCK) entry(Items.BROWN_MUSHROOM, Blocks.BROWN_MUSHROOM_BLOCK),
.put(Items.RED_MUSHROOM, Blocks.RED_MUSHROOM_BLOCK) entry(Items.RED_MUSHROOM, Blocks.RED_MUSHROOM_BLOCK),
.put(Items.STICK, Blocks.OAK_PLANKS) entry(Items.STICK, Blocks.OAK_PLANKS),
.put(Items.GOLD_INGOT, Blocks.GOLD_BLOCK) entry(Items.GOLD_INGOT, Blocks.GOLD_BLOCK),
.put(Items.IRON_INGOT, Blocks.IRON_BLOCK) entry(Items.IRON_INGOT, Blocks.IRON_BLOCK),
.put(Items.DIAMOND, Blocks.DIAMOND_BLOCK) entry(Items.DIAMOND, Blocks.DIAMOND_BLOCK),
.put(Items.NETHERITE_INGOT, Blocks.NETHERITE_BLOCK) entry(Items.NETHERITE_INGOT, Blocks.NETHERITE_BLOCK),
.put(Items.SUNFLOWER, Blocks.YELLOW_WOOL) entry(Items.SUNFLOWER, Blocks.YELLOW_WOOL),
.put(Items.LILAC, Blocks.MAGENTA_WOOL) entry(Items.LILAC, Blocks.MAGENTA_WOOL),
.put(Items.ROSE_BUSH, Blocks.RED_WOOL) entry(Items.ROSE_BUSH, Blocks.RED_WOOL),
.put(Items.PEONY, Blocks.PINK_WOOL) entry(Items.PEONY, Blocks.PINK_WOOL),
.put(Items.CARROT, Blocks.ORANGE_WOOL) entry(Items.CARROT, Blocks.ORANGE_WOOL),
.put(Items.APPLE,Blocks.RED_WOOL) entry(Items.APPLE,Blocks.RED_WOOL),
.put(Items.WHEAT,Blocks.HAY_BLOCK) entry(Items.WHEAT,Blocks.HAY_BLOCK),
.put(Items.PORKCHOP, Blocks.PINK_WOOL) entry(Items.PORKCHOP, Blocks.PINK_WOOL),
.put(Items.RABBIT,Blocks.PINK_WOOL) entry(Items.RABBIT,Blocks.PINK_WOOL),
.put(Items.CHICKEN,Blocks.WHITE_TERRACOTTA) entry(Items.CHICKEN,Blocks.WHITE_TERRACOTTA),
.put(Items.BEEF,Blocks.NETHERRACK) entry(Items.BEEF,Blocks.NETHERRACK),
.put(Items.ENCHANTED_GOLDEN_APPLE,Blocks.GOLD_BLOCK) entry(Items.ENCHANTED_GOLDEN_APPLE,Blocks.GOLD_BLOCK),
.put(Items.COD,Blocks.WHITE_TERRACOTTA) entry(Items.COD,Blocks.WHITE_TERRACOTTA),
.put(Items.SALMON,Blocks.ACACIA_PLANKS) entry(Items.SALMON,Blocks.ACACIA_PLANKS),
.put(Items.ROTTEN_FLESH,Blocks.BROWN_WOOL) entry(Items.ROTTEN_FLESH,Blocks.BROWN_WOOL),
.put(Items.PUFFERFISH,Blocks.YELLOW_TERRACOTTA) entry(Items.PUFFERFISH,Blocks.YELLOW_TERRACOTTA),
.put(Items.TROPICAL_FISH,Blocks.ORANGE_WOOL) entry(Items.TROPICAL_FISH,Blocks.ORANGE_WOOL),
.put(Items.POTATO,Blocks.WHITE_TERRACOTTA) entry(Items.POTATO,Blocks.WHITE_TERRACOTTA),
.put(Items.MUTTON, Blocks.RED_WOOL) entry(Items.MUTTON, Blocks.RED_WOOL),
.put(Items.BEETROOT,Blocks.NETHERRACK) entry(Items.BEETROOT,Blocks.NETHERRACK),
.put(Items.MELON_SLICE,Blocks.MELON) entry(Items.MELON_SLICE,Blocks.MELON),
.put(Items.POISONOUS_POTATO,Blocks.SLIME_BLOCK) entry(Items.POISONOUS_POTATO,Blocks.SLIME_BLOCK),
.put(Items.SPIDER_EYE,Blocks.NETHERRACK) entry(Items.SPIDER_EYE,Blocks.NETHERRACK),
.put(Items.GUNPOWDER,Blocks.GRAY_WOOL) entry(Items.GUNPOWDER,Blocks.GRAY_WOOL),
.put(Items.SCUTE,Blocks.LIME_WOOL) entry(Items.SCUTE,Blocks.LIME_WOOL),
.put(Items.FEATHER,Blocks.WHITE_WOOL) entry(Items.FEATHER,Blocks.WHITE_WOOL),
.put(Items.FLINT,Blocks.BLACK_WOOL) entry(Items.FLINT,Blocks.BLACK_WOOL),
.put(Items.LEATHER,Blocks.SPRUCE_PLANKS) entry(Items.LEATHER,Blocks.SPRUCE_PLANKS),
.put(Items.GLOWSTONE_DUST,Blocks.GLOWSTONE) entry(Items.GLOWSTONE_DUST,Blocks.GLOWSTONE),
.put(Items.PAPER,Blocks.WHITE_WOOL) entry(Items.PAPER,Blocks.WHITE_WOOL),
.put(Items.BRICK,Blocks.BRICKS) entry(Items.BRICK,Blocks.BRICKS),
.put(Items.INK_SAC,Blocks.BLACK_WOOL) entry(Items.INK_SAC,Blocks.BLACK_WOOL),
.put(Items.SNOWBALL,Blocks.SNOW_BLOCK) entry(Items.SNOWBALL,Blocks.SNOW_BLOCK),
.put(Items.WATER_BUCKET,Blocks.WATER) entry(Items.WATER_BUCKET,Blocks.WATER),
.put(Items.LAVA_BUCKET,Blocks.LAVA) entry(Items.LAVA_BUCKET,Blocks.LAVA),
.put(Items.MILK_BUCKET,Blocks.WHITE_WOOL) entry(Items.MILK_BUCKET,Blocks.WHITE_WOOL),
.put(Items.CLAY_BALL, Blocks.CLAY) entry(Items.CLAY_BALL, Blocks.CLAY),
.put(Items.COCOA_BEANS,Blocks.COCOA) entry(Items.COCOA_BEANS,Blocks.COCOA),
.put(Items.BONE,Blocks.BONE_BLOCK) entry(Items.BONE,Blocks.BONE_BLOCK),
.put(Items.COD_BUCKET,Blocks.BROWN_TERRACOTTA) entry(Items.COD_BUCKET,Blocks.BROWN_TERRACOTTA),
.put(Items.PUFFERFISH_BUCKET,Blocks.YELLOW_TERRACOTTA) entry(Items.PUFFERFISH_BUCKET,Blocks.YELLOW_TERRACOTTA),
.put(Items.SALMON_BUCKET,Blocks.PINK_TERRACOTTA) entry(Items.SALMON_BUCKET,Blocks.PINK_TERRACOTTA),
.put(Items.TROPICAL_FISH_BUCKET,Blocks.ORANGE_TERRACOTTA) entry(Items.TROPICAL_FISH_BUCKET,Blocks.ORANGE_TERRACOTTA),
.put(Items.SUGAR,Blocks.WHITE_WOOL) entry(Items.SUGAR,Blocks.WHITE_WOOL),
.put(Items.BLAZE_POWDER,Blocks.GOLD_BLOCK) entry(Items.BLAZE_POWDER,Blocks.GOLD_BLOCK),
.put(Items.ENDER_PEARL,Blocks.WARPED_PLANKS) entry(Items.ENDER_PEARL,Blocks.WARPED_PLANKS),
.put(Items.NETHER_STAR,Blocks.DIAMOND_BLOCK) entry(Items.NETHER_STAR,Blocks.DIAMOND_BLOCK),
.put(Items.PRISMARINE_CRYSTALS,Blocks.SEA_LANTERN) entry(Items.PRISMARINE_CRYSTALS,Blocks.SEA_LANTERN),
.put(Items.PRISMARINE_SHARD,Blocks.PRISMARINE) entry(Items.PRISMARINE_SHARD,Blocks.PRISMARINE),
.put(Items.RABBIT_HIDE,Blocks.OAK_PLANKS) entry(Items.RABBIT_HIDE,Blocks.OAK_PLANKS),
.put(Items.CHORUS_FRUIT,Blocks.PURPUR_BLOCK) entry(Items.CHORUS_FRUIT,Blocks.PURPUR_BLOCK),
.put(Items.SHULKER_SHELL,Blocks.SHULKER_BOX) entry(Items.SHULKER_SHELL,Blocks.SHULKER_BOX),
.put(Items.NAUTILUS_SHELL,Blocks.BONE_BLOCK) entry(Items.NAUTILUS_SHELL,Blocks.BONE_BLOCK),
.put(Items.HEART_OF_THE_SEA,Blocks.CONDUIT) entry(Items.HEART_OF_THE_SEA,Blocks.CONDUIT),
.put(Items.HONEYCOMB,Blocks.HONEYCOMB_BLOCK) entry(Items.HONEYCOMB,Blocks.HONEYCOMB_BLOCK),
.put(Items.NAME_TAG,Blocks.BONE_BLOCK) entry(Items.NAME_TAG,Blocks.BONE_BLOCK),
.put(Items.TOTEM_OF_UNDYING,Blocks.YELLOW_TERRACOTTA) entry(Items.TOTEM_OF_UNDYING,Blocks.YELLOW_TERRACOTTA),
.put(Items.TRIDENT,Blocks.PRISMARINE) entry(Items.TRIDENT,Blocks.PRISMARINE),
.put(Items.GHAST_TEAR,Blocks.WHITE_WOOL) entry(Items.GHAST_TEAR,Blocks.WHITE_WOOL),
.put(Items.PHANTOM_MEMBRANE,Blocks.BONE_BLOCK) entry(Items.PHANTOM_MEMBRANE,Blocks.BONE_BLOCK),
.put(Items.EGG,Blocks.BONE_BLOCK) entry(Items.EGG,Blocks.BONE_BLOCK),
//.put(Items.,Blocks.) //entry(Items.,Blocks.),
.put(Items.COPPER_INGOT,Blocks.COPPER_BLOCK) entry(Items.COPPER_INGOT,Blocks.COPPER_BLOCK),
.put(Items.AMETHYST_SHARD, Blocks.AMETHYST_BLOCK) entry(Items.AMETHYST_SHARD, Blocks.AMETHYST_BLOCK));
.build();
/** /**
* Gets the colour to print an item in when printing its count in a hopper counter. * Gets the colour to print an item in when printing its count in a hopper counter.
@@ -92,33 +92,11 @@ public class ExplosionLogHelper
} }
public static class EntityChangedStatusWithCount public static record EntityChangedStatusWithCount(Vec3d pos, EntityType type, Vec3d accel)
{ {
public final Vec3d pos;
public final EntityType type;
public final Vec3d accel;
public EntityChangedStatusWithCount(Entity e, Vec3d accel) public EntityChangedStatusWithCount(Entity e, Vec3d accel)
{ {
this.pos = e.getPos(); this(e.getPos(), e.getType(), accel);
this.type = e.getType();
this.accel = accel;
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof EntityChangedStatusWithCount other)
{
return other.pos.equals(pos) && other.accel.equals(accel) && other.type.equals(type);
}
return super.equals(obj);
}
@Override
public int hashCode()
{
return pos.hashCode()+ type.hashCode()+accel.hashCode();
} }
} }
} }
@@ -134,18 +134,8 @@ public class CarpetEventServer
{ {
return function.getString()+((host==null)?"":"(from "+host+(optionalTarget == null?"":"/"+optionalTarget)+")"); return function.getString()+((host==null)?"":"(from "+host+(optionalTarget == null?"":"/"+optionalTarget)+")");
} }
public static class Signature public static record Signature(String function, String host, String target) {}
{
String function;
String host;
String target;
public Signature(String fun, String h, String t)
{
function = fun;
host = h;
target = t;
}
}
public static Signature fromString(String str) public static Signature fromString(String str)
{ {
Pattern find = Pattern.compile("(\\w+)(?:\\(from (\\w+)(?:/(\\w+))?\\))?"); Pattern find = Pattern.compile("(\\w+)(?:\\(from (\\w+)(?:/(\\w+))?\\))?");
@@ -412,16 +412,11 @@ public class CarpetScriptServer
}); });
} }
static class TransferData private static record TransferData(boolean perUser, Predicate<ServerCommandSource> commandValidator, boolean isRuleApp)
{ {
boolean perUser;
Predicate<ServerCommandSource> commandValidator;
boolean isRuleApp;
private TransferData(CarpetScriptHost host) private TransferData(CarpetScriptHost host)
{ {
perUser = host.perUser; this(host.perUser, host.commandValidator, host.isRuleApp);
commandValidator = host.commandValidator;
isRuleApp = host.isRuleApp;
} }
} }
@@ -9,7 +9,6 @@ import carpet.script.value.StringValue;
import carpet.script.value.Value; import carpet.script.value.Value;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.damage.DamageSource;
import org.apache.commons.lang3.tuple.Pair;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@@ -20,7 +19,8 @@ import java.util.Map;
public class EntityEventsGroup public class EntityEventsGroup
{ {
private final Map<Event, Map<Pair<String,String>, CarpetEventServer.Callback>> actions; private static record EventKey(String host, String user) {}
private final Map<Event, Map<EventKey, CarpetEventServer.Callback>> actions;
private final Entity entity; private final Entity entity;
public EntityEventsGroup(Entity e) public EntityEventsGroup(Entity e)
{ {
@@ -31,22 +31,22 @@ public class EntityEventsGroup
public void onEvent(Event type, Object... args) public void onEvent(Event type, Object... args)
{ {
if (actions.isEmpty()) return; // most of the cases, trying to be nice if (actions.isEmpty()) return; // most of the cases, trying to be nice
Map<Pair<String,String>, CarpetEventServer.Callback> actionSet = actions.get(type); Map<EventKey, CarpetEventServer.Callback> actionSet = actions.get(type);
if (actionSet == null) return; if (actionSet == null) return;
if (CarpetServer.scriptServer == null) return; // executed after world is closin down if (CarpetServer.scriptServer == null) return; // executed after world is closin down
for (Iterator<Map.Entry<Pair<String,String>, CarpetEventServer.Callback>> iterator = actionSet.entrySet().iterator(); iterator.hasNext(); ) for (Iterator<Map.Entry<EventKey, CarpetEventServer.Callback>> iterator = actionSet.entrySet().iterator(); iterator.hasNext(); )
{ {
Map.Entry<Pair<String,String>, CarpetEventServer.Callback> action = iterator.next(); Map.Entry<EventKey, CarpetEventServer.Callback> action = iterator.next();
Pair<String,String> key = action.getKey(); EventKey key = action.getKey();
ScriptHost host = CarpetServer.scriptServer.getAppHostByName(key.getLeft()); ScriptHost host = CarpetServer.scriptServer.getAppHostByName(key.host());
if (host == null) if (host == null)
{ {
iterator.remove(); iterator.remove();
continue; continue;
} }
if (key.getRight() != null) if (key.user() != null)
{ {
if (entity.getServer().getPlayerManager().getPlayer(key.getRight())==null) if (entity.getServer().getPlayerManager().getPlayer(key.user())==null)
{ {
iterator.remove(); iterator.remove();
continue; continue;
@@ -60,7 +60,7 @@ public class EntityEventsGroup
public void addEvent(Event type, ScriptHost host, FunctionValue fun, List<Value> extraargs) public void addEvent(Event type, ScriptHost host, FunctionValue fun, List<Value> extraargs)
{ {
Pair<String,String> key = Pair.of(host.getName(), host.user); EventKey key = new EventKey(host.getName(), host.user);
if (fun != null) if (fun != null)
{ {
CarpetEventServer.Callback call = type.create(key, fun, extraargs); CarpetEventServer.Callback call = type.create(key, fun, extraargs);
@@ -117,13 +117,13 @@ public class EntityEventsGroup
argcount = args+1; // entity is not extra argcount = args+1; // entity is not extra
byName.put(identifier, this); byName.put(identifier, this);
} }
public CarpetEventServer.Callback create(Pair<String,String> key, FunctionValue function, List<Value> extraArgs) public CarpetEventServer.Callback create(EventKey key, FunctionValue function, List<Value> extraArgs)
{ {
if ((function.getArguments().size()-(extraArgs == null ? 0 : extraArgs.size())) != argcount) if ((function.getArguments().size()-(extraArgs == null ? 0 : extraArgs.size())) != argcount)
{ {
return null; return null;
} }
return new CarpetEventServer.Callback(key.getLeft(), key.getRight(), function, extraArgs); return new CarpetEventServer.Callback(key.host(), key.user(), function, extraArgs);
} }
public CarpetEventServer.CallbackResult call(CarpetEventServer.Callback tickCall, Entity entity, Object ... args) public CarpetEventServer.CallbackResult call(CarpetEventServer.Callback tickCall, Entity entity, Object ... args)
{ {
+2 -4
View File
@@ -33,8 +33,6 @@ import carpet.script.value.FunctionValue;
import carpet.script.value.NumericValue; import carpet.script.value.NumericValue;
import carpet.script.value.StringValue; import carpet.script.value.StringValue;
import carpet.script.value.Value; import carpet.script.value.Value;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import java.math.BigInteger; import java.math.BigInteger;
@@ -98,7 +96,7 @@ public class Expression
functionalEquivalence.put(operator, function); functionalEquivalence.put(operator, function);
} }
private final Map<String, Value> constants = ImmutableMap.of( private final Map<String, Value> constants = Map.of(
"euler", Arithmetic.euler, "euler", Arithmetic.euler,
"pi", Arithmetic.PI, "pi", Arithmetic.PI,
"null", Value.NULL, "null", Value.NULL,
@@ -972,7 +970,7 @@ public class Expression
final ExpressionNode v1 = nodeStack.pop(); final ExpressionNode v1 = nodeStack.pop();
final ExpressionNode v2 = nodeStack.pop(); final ExpressionNode v2 = nodeStack.pop();
LazyValue result = (c,t) -> operators.get(token.surface).lazyEval(c, t,this, token, v2.op, v1.op).evalValue(c, t); LazyValue result = (c,t) -> operators.get(token.surface).lazyEval(c, t,this, token, v2.op, v1.op).evalValue(c, t);
nodeStack.push(new ExpressionNode(result, ImmutableList.of(v2, v1), token )); nodeStack.push(new ExpressionNode(result, List.of(v2, v1), token ));
break; break;
case VARIABLE: case VARIABLE:
Value constant = getConstantFor(token.surface); Value constant = getConstantFor(token.surface);
+5
View File
@@ -101,10 +101,12 @@ public abstract class Fluff
return name; return name;
} }
@Override
public int getNumParams() { public int getNumParams() {
return numParams; return numParams;
} }
@Override
public boolean numParamsVaries() { public boolean numParamsVaries() {
return numParams < 0; return numParams < 0;
} }
@@ -162,6 +164,7 @@ public abstract class Fluff
return new LazyValue() return new LazyValue()
{ // eager evaluation always ignores the required type and evals params by none default { // eager evaluation always ignores the required type and evals params by none default
private List<Value> params; private List<Value> params;
@Override
public Value evalValue(Context c, Context.Type type) public Value evalValue(Context c, Context.Type type)
{ {
ILazyFunction.checkInterrupts(); ILazyFunction.checkInterrupts();
@@ -202,10 +205,12 @@ public abstract class Fluff
this.leftAssoc = leftAssoc; this.leftAssoc = leftAssoc;
} }
@Override
public int getPrecedence() { public int getPrecedence() {
return precedence; return precedence;
} }
@Override
public boolean isLeftAssoc() { public boolean isLeftAssoc() {
return leftAssoc; return leftAssoc;
} }
@@ -12,8 +12,6 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import org.apache.commons.lang3.tuple.Pair;
import carpet.CarpetServer; import carpet.CarpetServer;
import carpet.script.Context; import carpet.script.Context;
import carpet.script.value.BooleanValue; import carpet.script.value.BooleanValue;
@@ -195,12 +193,8 @@ public interface Param
} }
}; };
/** static record StrictConverterInfo(Class<?> type, boolean shallow) {}
* <p>Strict converters</p> private static final Map<StrictConverterInfo, ValueConverter<?>> strictParamsByClassAndShallowness = new HashMap<>();
*
* <p>Stored as {@code <Pair<Type, shallow?>, Converter>}</p>
*/
private static final Map<Pair<Class<?>, Boolean>, ValueConverter<?>> strictParamsByClassAndShallowness = new HashMap<>();
static static
{ // TODO Specify strictness in name? { // TODO Specify strictness in name?
registerStrictConverter(String.class, false, new SimpleTypeConverter<>(StringValue.class, StringValue::getString, "string")); registerStrictConverter(String.class, false, new SimpleTypeConverter<>(StringValue.class, StringValue::getString, "string"));
@@ -224,7 +218,7 @@ public interface Param
{ {
boolean shallow = type.getAnnotation(Strict.class).shallow(); boolean shallow = type.getAnnotation(Strict.class).shallow();
Class<?> clazz = (Class<?>) type.getType(); Class<?> clazz = (Class<?>) type.getType();
Pair<Class<?>, Boolean> key = Pair.of(clazz, shallow); var key = new StrictConverterInfo(clazz, shallow);
ValueConverter<?> converter = strictParamsByClassAndShallowness.get(key); ValueConverter<?> converter = strictParamsByClassAndShallowness.get(key);
if (converter != null) if (converter != null)
return converter; return converter;
@@ -245,7 +239,7 @@ public interface Param
*/ */
public static <T> void registerStrictConverter(Class<T> type, boolean shallow, ValueConverter<T> converter) public static <T> void registerStrictConverter(Class<T> type, boolean shallow, ValueConverter<T> converter)
{ {
Pair<Class<?>, Boolean> key = Pair.of(type, shallow); var key = new StrictConverterInfo(type, shallow);
if (strictParamsByClassAndShallowness.containsKey(key)) if (strictParamsByClassAndShallowness.containsKey(key))
throw new IllegalArgumentException(type + " already has a registered " + (shallow ? "" : "non-") + "shallow StrictConverter"); throw new IllegalArgumentException(type + " already has a registered " + (shallow ? "" : "non-") + "shallow StrictConverter");
strictParamsByClassAndShallowness.put(key, converter); strictParamsByClassAndShallowness.put(key, converter);
@@ -37,8 +37,6 @@ import carpet.script.value.StringValue;
import carpet.script.value.Value; import carpet.script.value.Value;
import carpet.script.value.ValueConversions; import carpet.script.value.ValueConversions;
import carpet.utils.Messenger; import carpet.utils.Messenger;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.minecraft.SharedConstants; import net.minecraft.SharedConstants;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
@@ -103,7 +101,6 @@ import net.minecraft.world.gen.chunk.ChunkGenerator;
import net.minecraft.world.level.UnmodifiableLevelProperties; import net.minecraft.world.level.UnmodifiableLevelProperties;
import net.minecraft.world.level.storage.LevelStorage; import net.minecraft.world.level.storage.LevelStorage;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.tuple.Pair;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@@ -333,7 +330,7 @@ public class Auxiliary {
ServerWorld world = cc.s.getWorld(); ServerWorld world = cc.s.getWorld();
MinecraftServer server = world.getServer(); MinecraftServer server = world.getServer();
Set<ServerPlayerEntity> playerTargets = new HashSet<>(); Set<ServerPlayerEntity> playerTargets = new HashSet<>();
List<Pair<ShapeDispatcher.ExpiringShape, Map<String,Value>>> shapes = new ArrayList<>(); List<ShapeDispatcher.ShapeWithConfig> shapes = new ArrayList<>();
if (lv.size() == 1) // bulk if (lv.size() == 1) // bulk
{ {
Value specLoad = lv.get(0); Value specLoad = lv.get(0);
@@ -1061,10 +1058,10 @@ public class Auxiliary {
{ {
try { try {
//Files.createDirectory(packFloder); //Files.createDirectory(packFloder);
try (FileSystem zipfs = FileSystems.newFileSystem(URI.create("jar:" + packFloder.toUri().toString()), ImmutableMap.of("create", "true"))) { try (FileSystem zipfs = FileSystems.newFileSystem(URI.create("jar:" + packFloder.toUri().toString()), Map.of("create", "true"))) {
Path zipRoot = zipfs.getPath("/"); Path zipRoot = zipfs.getPath("/");
zipValueToJson(zipRoot.resolve("pack.mcmeta"), MapValue.wrap( zipValueToJson(zipRoot.resolve("pack.mcmeta"), MapValue.wrap(
ImmutableMap.of(StringValue.of("pack"), MapValue.wrap(ImmutableMap.of( Map.of(StringValue.of("pack"), MapValue.wrap(Map.of(
StringValue.of("pack_format"), new NumericValue(SharedConstants.getGameVersion().getPackVersion()), StringValue.of("pack_format"), new NumericValue(SharedConstants.getGameVersion().getPackVersion()),
StringValue.of("description"), StringValue.of(name), StringValue.of("description"), StringValue.of(name),
StringValue.of("source"), StringValue.of("scarpet") StringValue.of("source"), StringValue.of("scarpet")
@@ -1143,7 +1140,7 @@ public class Auxiliary {
DimensionType dimensionType3 = entry.getValue().getDimensionType(); DimensionType dimensionType3 = entry.getValue().getDimensionType();
ChunkGenerator chunkGenerator3 = entry.getValue().getChunkGenerator(); ChunkGenerator chunkGenerator3 = entry.getValue().getChunkGenerator();
UnmodifiableLevelProperties unmodifiableLevelProperties = new UnmodifiableLevelProperties(saveProperties, ((ServerWorldInterface) server.getOverworld()).getWorldPropertiesCM()); UnmodifiableLevelProperties unmodifiableLevelProperties = new UnmodifiableLevelProperties(saveProperties, ((ServerWorldInterface) server.getOverworld()).getWorldPropertiesCM());
ServerWorld serverWorld2 = new ServerWorld(server, Util.getMainWorkerExecutor(), session, unmodifiableLevelProperties, registryKey2, dimensionType3, WorldTools.NOOP_LISTENER, chunkGenerator3, bl, m, ImmutableList.of(), false); ServerWorld serverWorld2 = new ServerWorld(server, Util.getMainWorkerExecutor(), session, unmodifiableLevelProperties, registryKey2, dimensionType3, WorldTools.NOOP_LISTENER, chunkGenerator3, bl, m, List.of(), false);
server.getOverworld().getWorldBorder().addListener(new WorldBorderListener.WorldBorderSyncer(serverWorld2.getWorldBorder())); server.getOverworld().getWorldBorder().addListener(new WorldBorderListener.WorldBorderSyncer(serverWorld2.getWorldBorder()));
existing_worlds.put(registryKey2, serverWorld2); existing_worlds.put(registryKey2, serverWorld2);
} }
@@ -181,7 +181,7 @@ public class Inventories {
CarpetContext cc = (CarpetContext) c; CarpetContext cc = (CarpetContext) c;
NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0);
if (inventoryLocator == null) return Value.NULL; if (inventoryLocator == null) return Value.NULL;
return new NumericValue(inventoryLocator.inventory.size()); return new NumericValue(inventoryLocator.inventory().size());
}); });
expression.addContextFunction("inventory_has_items", -1, (c, t, lv) -> expression.addContextFunction("inventory_has_items", -1, (c, t, lv) ->
@@ -189,7 +189,7 @@ public class Inventories {
CarpetContext cc = (CarpetContext) c; CarpetContext cc = (CarpetContext) c;
NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0);
if (inventoryLocator == null) return Value.NULL; if (inventoryLocator == null) return Value.NULL;
return BooleanValue.of(!inventoryLocator.inventory.isEmpty()); return BooleanValue.of(!inventoryLocator.inventory().isEmpty());
}); });
//inventory_get(<b, e>, <n>) -> item_triple //inventory_get(<b, e>, <n>) -> item_triple
@@ -198,17 +198,17 @@ public class Inventories {
CarpetContext cc = (CarpetContext) c; CarpetContext cc = (CarpetContext) c;
NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0);
if (inventoryLocator == null) return Value.NULL; if (inventoryLocator == null) return Value.NULL;
if (lv.size() == inventoryLocator.offset) if (lv.size() == inventoryLocator.offset())
{ {
List<Value> fullInventory = new ArrayList<>(); List<Value> fullInventory = new ArrayList<>();
for (int i = 0, maxi = inventoryLocator.inventory.size(); i < maxi; i++) for (int i = 0, maxi = inventoryLocator.inventory().size(); i < maxi; i++)
fullInventory.add(ValueConversions.of(inventoryLocator.inventory.getStack(i))); fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getStack(i)));
return ListValue.wrap(fullInventory); return ListValue.wrap(fullInventory);
} }
int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset)).getLong(); int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong();
slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory());
if (slot == inventoryLocator.inventory.size()) return Value.NULL; if (slot == inventoryLocator.inventory().size()) return Value.NULL;
return ValueConversions.of(inventoryLocator.inventory.getStack(slot)); return ValueConversions.of(inventoryLocator.inventory().getStack(slot));
}); });
//inventory_set(<b,e>, <n>, <count>, <item>, <nbt>) //inventory_set(<b,e>, <n>, <count>, <item>, <nbt>)
@@ -217,33 +217,33 @@ public class Inventories {
CarpetContext cc = (CarpetContext) c; CarpetContext cc = (CarpetContext) c;
NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0);
if (inventoryLocator == null) return Value.NULL; if (inventoryLocator == null) return Value.NULL;
if (lv.size() < inventoryLocator.offset+2) if (lv.size() < inventoryLocator.offset()+2)
throw new InternalExpressionException("'inventory_set' requires at least slot number and new stack size, and optional new item"); throw new InternalExpressionException("'inventory_set' requires at least slot number and new stack size, and optional new item");
int slot = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset+0)).getLong(); int slot = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+0)).getLong();
slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory());
if (slot == inventoryLocator.inventory.size()) return Value.NULL; if (slot == inventoryLocator.inventory().size()) return Value.NULL;
int count = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset+1)).getLong(); int count = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
if (count == 0) if (count == 0)
{ {
// clear slot // clear slot
ItemStack removedStack = inventoryLocator.inventory.removeStack(slot); ItemStack removedStack = inventoryLocator.inventory().removeStack(slot);
syncPlayerInventory(inventoryLocator, slot); syncPlayerInventory(inventoryLocator, slot);
//Value res = ListValue.fromItemStack(removedStack); // that tuple will be read only but cheaper if noone cares //Value res = ListValue.fromItemStack(removedStack); // that tuple will be read only but cheaper if noone cares
return ValueConversions.of(removedStack); return ValueConversions.of(removedStack);
} }
if (lv.size() < inventoryLocator.offset+3) if (lv.size() < inventoryLocator.offset()+3)
{ {
ItemStack previousStack = inventoryLocator.inventory.getStack(slot); ItemStack previousStack = inventoryLocator.inventory().getStack(slot);
ItemStack newStack = previousStack.copy(); ItemStack newStack = previousStack.copy();
newStack.setCount(count); newStack.setCount(count);
inventoryLocator.inventory.setStack(slot, newStack); inventoryLocator.inventory().setStack(slot, newStack);
syncPlayerInventory(inventoryLocator, slot); syncPlayerInventory(inventoryLocator, slot);
return ValueConversions.of(previousStack); return ValueConversions.of(previousStack);
} }
NbtCompound nbt = null; // skipping one argument NbtCompound nbt = null; // skipping one argument
if (lv.size() > inventoryLocator.offset+3) if (lv.size() > inventoryLocator.offset()+3)
{ {
Value nbtValue = lv.get(inventoryLocator.offset+3); Value nbtValue = lv.get(inventoryLocator.offset()+3);
if (nbtValue instanceof NBTSerializableValue) if (nbtValue instanceof NBTSerializableValue)
nbt = ((NBTSerializableValue)nbtValue).getCompoundTag(); nbt = ((NBTSerializableValue)nbtValue).getCompoundTag();
else if (nbtValue instanceof NullValue) else if (nbtValue instanceof NullValue)
@@ -251,11 +251,11 @@ public class Inventories {
else else
nbt = new NBTSerializableValue(nbtValue.getString()).getCompoundTag(); nbt = new NBTSerializableValue(nbtValue.getString()).getCompoundTag();
} }
ItemStackArgument newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset+2).getString(), nbt); ItemStackArgument newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()+2).getString(), nbt);
ItemStack previousStack = inventoryLocator.inventory.getStack(slot); ItemStack previousStack = inventoryLocator.inventory().getStack(slot);
try try
{ {
inventoryLocator.inventory.setStack(slot, newitem.createStack(count, false)); inventoryLocator.inventory().setStack(slot, newitem.createStack(count, false));
syncPlayerInventory(inventoryLocator, slot); syncPlayerInventory(inventoryLocator, slot);
} }
catch (CommandSyntaxException e) catch (CommandSyntaxException e)
@@ -272,21 +272,21 @@ public class Inventories {
NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0);
if (inventoryLocator == null) return Value.NULL; if (inventoryLocator == null) return Value.NULL;
ItemStackArgument itemArg = null; ItemStackArgument itemArg = null;
if (lv.size() > inventoryLocator.offset) if (lv.size() > inventoryLocator.offset())
{ {
Value secondArg = lv.get(inventoryLocator.offset+0); Value secondArg = lv.get(inventoryLocator.offset()+0);
if (!(secondArg instanceof NullValue)) if (!(secondArg instanceof NullValue))
itemArg = NBTSerializableValue.parseItem(secondArg.getString()); itemArg = NBTSerializableValue.parseItem(secondArg.getString());
} }
int startIndex = 0; int startIndex = 0;
if (lv.size() > inventoryLocator.offset+1) if (lv.size() > inventoryLocator.offset()+1)
{ {
startIndex = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset+1)).getLong(); startIndex = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
} }
startIndex = NBTSerializableValue.validateSlot(startIndex, inventoryLocator.inventory); startIndex = NBTSerializableValue.validateSlot(startIndex, inventoryLocator.inventory());
for (int i = startIndex, maxi = inventoryLocator.inventory.size(); i < maxi; i++) for (int i = startIndex, maxi = inventoryLocator.inventory().size(); i < maxi; i++)
{ {
ItemStack stack = inventoryLocator.inventory.getStack(i); ItemStack stack = inventoryLocator.inventory().getStack(i);
if ( (itemArg == null && stack.isEmpty()) || (itemArg != null && itemArg.getItem().equals(stack.getItem())) ) if ( (itemArg == null && stack.isEmpty()) || (itemArg != null && itemArg.getItem().equals(stack.getItem())) )
return new NumericValue(i); return new NumericValue(i);
} }
@@ -299,18 +299,18 @@ public class Inventories {
CarpetContext cc = (CarpetContext) c; CarpetContext cc = (CarpetContext) c;
NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0);
if (inventoryLocator == null) return Value.NULL; if (inventoryLocator == null) return Value.NULL;
if (lv.size() <= inventoryLocator.offset) if (lv.size() <= inventoryLocator.offset())
throw new InternalExpressionException("'inventory_remove' requires at least an item to be removed"); throw new InternalExpressionException("'inventory_remove' requires at least an item to be removed");
ItemStackArgument searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset).getString()); ItemStackArgument searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString());
int amount = 1; int amount = 1;
if (lv.size() > inventoryLocator.offset+1) if (lv.size() > inventoryLocator.offset()+1)
amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset+1)).getLong(); amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
// not enough // not enough
if (((amount == 1) && (!inventoryLocator.inventory.containsAny(Sets.newHashSet(searchItem.getItem())))) if (((amount == 1) && (!inventoryLocator.inventory().containsAny(Sets.newHashSet(searchItem.getItem()))))
|| (inventoryLocator.inventory.count(searchItem.getItem()) < amount)) return Value.FALSE; || (inventoryLocator.inventory().count(searchItem.getItem()) < amount)) return Value.FALSE;
for (int i = 0, maxi = inventoryLocator.inventory.size(); i < maxi; i++) for (int i = 0, maxi = inventoryLocator.inventory().size(); i < maxi; i++)
{ {
ItemStack stack = inventoryLocator.inventory.getStack(i); ItemStack stack = inventoryLocator.inventory().getStack(i);
if (stack.isEmpty()) if (stack.isEmpty())
continue; continue;
if (!stack.getItem().equals(searchItem.getItem())) if (!stack.getItem().equals(searchItem.getItem()))
@@ -319,13 +319,13 @@ public class Inventories {
if (left > 0) if (left > 0)
{ {
stack.setCount(left); stack.setCount(left);
inventoryLocator.inventory.setStack(i, stack); inventoryLocator.inventory().setStack(i, stack);
syncPlayerInventory(inventoryLocator, i); syncPlayerInventory(inventoryLocator, i);
return Value.TRUE; return Value.TRUE;
} }
else else
{ {
inventoryLocator.inventory.removeStack(i); inventoryLocator.inventory().removeStack(i);
syncPlayerInventory(inventoryLocator, i); syncPlayerInventory(inventoryLocator, i);
amount -= stack.getCount(); amount -= stack.getCount();
} }
@@ -341,22 +341,22 @@ public class Inventories {
CarpetContext cc = (CarpetContext) c; CarpetContext cc = (CarpetContext) c;
NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0);
if (inventoryLocator == null) return Value.NULL; if (inventoryLocator == null) return Value.NULL;
if (lv.size() == inventoryLocator.offset) if (lv.size() == inventoryLocator.offset())
throw new InternalExpressionException("Slot number is required for inventory_drop"); throw new InternalExpressionException("Slot number is required for inventory_drop");
int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset)).getLong(); int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong();
slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory());
if (slot == inventoryLocator.inventory.size()) return Value.NULL; if (slot == inventoryLocator.inventory().size()) return Value.NULL;
int amount = 0; int amount = 0;
if (lv.size() > inventoryLocator.offset+1) if (lv.size() > inventoryLocator.offset()+1)
amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset+1)).getLong(); amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong();
if (amount < 0) if (amount < 0)
throw new InternalExpressionException("Cannot throw negative number of items"); throw new InternalExpressionException("Cannot throw negative number of items");
ItemStack stack = inventoryLocator.inventory.getStack(slot); ItemStack stack = inventoryLocator.inventory().getStack(slot);
if (stack == null || stack.isEmpty()) return Value.ZERO; if (stack == null || stack.isEmpty()) return Value.ZERO;
if (amount == 0) amount = stack.getCount(); if (amount == 0) amount = stack.getCount();
ItemStack droppedStack = inventoryLocator.inventory.removeStack(slot, amount); ItemStack droppedStack = inventoryLocator.inventory().removeStack(slot, amount);
if (droppedStack.isEmpty()) return Value.ZERO; if (droppedStack.isEmpty()) return Value.ZERO;
Object owner = inventoryLocator.owner; Object owner = inventoryLocator.owner();
ItemEntity item; ItemEntity item;
if (owner instanceof PlayerEntity) if (owner instanceof PlayerEntity)
{ {
@@ -374,7 +374,7 @@ public class Inventories {
} }
else else
{ {
Vec3d point = Vec3d.ofCenter(inventoryLocator.position); //pos+0.5v Vec3d point = Vec3d.ofCenter(inventoryLocator.position()); //pos+0.5v
item = new ItemEntity(cc.s.getWorld(), point.x, point.y, point.z, droppedStack); item = new ItemEntity(cc.s.getWorld(), point.x, point.y, point.z, droppedStack);
item.setToDefaultPickupDelay(); item.setToDefaultPickupDelay();
cc.s.getWorld().spawnEntity(item); cc.s.getWorld().spawnEntity(item);
@@ -385,12 +385,12 @@ public class Inventories {
private static void syncPlayerInventory(NBTSerializableValue.InventoryLocator inventory, int int_1) private static void syncPlayerInventory(NBTSerializableValue.InventoryLocator inventory, int int_1)
{ {
if (inventory.owner instanceof ServerPlayerEntity player && !inventory.isEnder) if (inventory.owner() instanceof ServerPlayerEntity player && !inventory.isEnder())
{ {
player.networkHandler.sendPacket(new ScreenHandlerSlotUpdateS2CPacket( player.networkHandler.sendPacket(new ScreenHandlerSlotUpdateS2CPacket(
-2, 0, // resolve mystery argument -2, 0, // resolve mystery argument
int_1, int_1,
inventory.inventory.getStack(int_1) inventory.inventory().getStack(int_1)
)); ));
} }
} }
@@ -3,7 +3,6 @@ package carpet.script.api;
import carpet.fakes.SpawnHelperInnerInterface; import carpet.fakes.SpawnHelperInnerInterface;
import carpet.script.CarpetContext; import carpet.script.CarpetContext;
import carpet.script.Expression; import carpet.script.Expression;
import carpet.script.LazyValue;
import carpet.script.exception.InternalExpressionException; import carpet.script.exception.InternalExpressionException;
import carpet.script.utils.SystemInfo; import carpet.script.utils.SystemInfo;
import carpet.script.value.ListValue; import carpet.script.value.ListValue;
@@ -9,7 +9,6 @@ import carpet.script.exception.Throwables;
import carpet.script.value.MapValue; import carpet.script.value.MapValue;
import carpet.script.value.StringValue; import carpet.script.value.StringValue;
import carpet.script.value.Value; import carpet.script.value.Value;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
@@ -523,7 +522,7 @@ public class FileArgument
Throwable exc = e; Throwable exc = e;
if(e.getCause() != null) if(e.getCause() != null)
exc = e.getCause(); exc = e.getCause();
throw new ThrowStatement(MapValue.wrap(ImmutableMap.of( throw new ThrowStatement(MapValue.wrap(Map.of(
StringValue.of("error"), StringValue.of(exc.getMessage()), StringValue.of("error"), StringValue.of(exc.getMessage()),
StringValue.of("path"), StringValue.of(filePath.toString()) StringValue.of("path"), StringValue.of(filePath.toString())
)), Throwables.JSON_ERROR); )), Throwables.JSON_ERROR);
@@ -4,7 +4,6 @@ import carpet.CarpetServer;
import carpet.fakes.BlockStateArgumentInterface; import carpet.fakes.BlockStateArgumentInterface;
import carpet.script.CarpetScriptHost; import carpet.script.CarpetScriptHost;
import carpet.script.argument.FunctionArgument; import carpet.script.argument.FunctionArgument;
import carpet.script.exception.InternalExpressionException;
import carpet.script.value.BlockValue; import carpet.script.value.BlockValue;
import carpet.script.value.BooleanValue; import carpet.script.value.BooleanValue;
import carpet.script.value.EntityValue; import carpet.script.value.EntityValue;
@@ -17,6 +16,9 @@ import carpet.script.value.StringValue;
import carpet.script.value.Value; import carpet.script.value.Value;
import carpet.script.value.ValueConversions; import carpet.script.value.ValueConversions;
import carpet.utils.CarpetProfiler; import carpet.utils.CarpetProfiler;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.arguments.ArgumentType;
@@ -84,7 +86,6 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction; import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec2f; import net.minecraft.util.math.Vec2f;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -102,7 +103,6 @@ import java.util.stream.Collectors;
import static net.minecraft.server.command.CommandManager.argument; import static net.minecraft.server.command.CommandManager.argument;
public abstract class CommandArgument public abstract class CommandArgument
{ {
public static CommandSyntaxException error(String text) public static CommandSyntaxException error(String text)
@@ -878,49 +878,50 @@ public abstract class CommandArgument
} }
private static class SlotArgument extends CommandArgument private static class SlotArgument extends CommandArgument
{ {
private static record ContainerIds(IntSet numericalIds, Set<String> commandIds) {}
private String restrict; private String restrict;
private static final Map<String, Pair<Set<Integer>, Set<String>>> RESTRICTED_CONTAINERS = new HashMap<String, Pair<Set<Integer>, Set<String>>>(){{ private static final Map<String, ContainerIds> RESTRICTED_CONTAINERS = new HashMap<String, ContainerIds>(){{
int i; int i;
for (String source : Arrays.asList("player", "enderchest", "equipment", "armor", "weapon", "container", "villager", "horse")) for (String source : Arrays.asList("player", "enderchest", "equipment", "armor", "weapon", "container", "villager", "horse"))
put(source, Pair.of(new HashSet<>(), new HashSet<>())); put(source, new ContainerIds(new IntOpenHashSet(), new HashSet<>()));
for (i = 0; i < 41; i++) get("player").getLeft().add(i); for (i = 0; i < 41; i++) get("player").numericalIds().add(i);
for(i = 0; i < 41; i++) get("player").getRight().add("container." + i); for(i = 0; i < 41; i++) get("player").commandIds().add("container." + i);
for(i = 0; i < 9; i++) get("player").getRight().add("hotbar." + i); for(i = 0; i < 9; i++) get("player").commandIds().add("hotbar." + i);
for(i = 0; i < 27; i++) get("player").getRight().add("inventory." + i); for(i = 0; i < 27; i++) get("player").commandIds().add("inventory." + i);
for (String place : Arrays.asList("weapon", "weapon.mainhand", "weapon.offhand")) for (String place : Arrays.asList("weapon", "weapon.mainhand", "weapon.offhand"))
{ {
get("player").getRight().add(place); get("player").commandIds().add(place);
get("equipment").getRight().add(place); get("equipment").commandIds().add(place);
get("weapon").getRight().add(place); get("weapon").commandIds().add(place);
} }
for (String place : Arrays.asList("armor.feet","armor.legs", "armor.chest","armor.head")) for (String place : Arrays.asList("armor.feet","armor.legs", "armor.chest","armor.head"))
{ {
get("player").getRight().add(place); get("player").commandIds().add(place);
get("equipment").getRight().add(place); get("equipment").commandIds().add(place);
get("armor").getRight().add(place); get("armor").commandIds().add(place);
} }
for (i = 0; i < 27; i++) get("enderchest").getLeft().add(200+i); for (i = 0; i < 27; i++) get("enderchest").numericalIds().add(200+i);
for(i = 0; i < 27; i++) get("enderchest").getRight().add("enderchest." + i); for(i = 0; i < 27; i++) get("enderchest").commandIds().add("enderchest." + i);
for (i = 0; i < 6; i++) get("equipment").getLeft().add(98+i); for (i = 0; i < 6; i++) get("equipment").numericalIds().add(98+i);
for (i = 0; i < 4; i++) get("armor").getLeft().add(100+i); for (i = 0; i < 4; i++) get("armor").numericalIds().add(100+i);
for (i = 0; i < 2; i++) get("weapon").getLeft().add(98+i); for (i = 0; i < 2; i++) get("weapon").numericalIds().add(98+i);
for (i = 0; i < 54; i++) get("container").getLeft().add(i); for (i = 0; i < 54; i++) get("container").numericalIds().add(i);
for(i = 0; i < 41; i++) get("container").getRight().add("container." + i); for(i = 0; i < 41; i++) get("container").commandIds().add("container." + i);
for (i = 0; i < 8; i++) get("villager").getLeft().add(i); for (i = 0; i < 8; i++) get("villager").numericalIds().add(i);
for(i = 0; i < 8; i++) get("villager").getRight().add("villager." + i); for(i = 0; i < 8; i++) get("villager").commandIds().add("villager." + i);
for (i = 0; i < 15; i++) get("horse").getLeft().add(500+i); for (i = 0; i < 15; i++) get("horse").numericalIds().add(500+i);
for(i = 0; i < 15; i++) get("horse").getRight().add("horse." + i); for(i = 0; i < 15; i++) get("horse").commandIds().add("horse." + i);
get("horse").getLeft().add(400); get("horse").numericalIds().add(400);
get("horse").getRight().add("horse.saddle"); get("horse").commandIds().add("horse.saddle");
get("horse").getLeft().add(401); get("horse").numericalIds().add(401);
get("horse").getRight().add("horse.armor"); get("horse").commandIds().add("horse.armor");
}}; }};
protected SlotArgument() protected SlotArgument()
@@ -938,7 +939,7 @@ public abstract class CommandArgument
protected Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException protected Value getValueFromContext(CommandContext<ServerCommandSource> context, String param) throws CommandSyntaxException
{ {
int slot = ItemSlotArgumentType.getItemSlot(context, param); int slot = ItemSlotArgumentType.getItemSlot(context, param);
if (restrict != null && !RESTRICTED_CONTAINERS.get(restrict).getLeft().contains(slot)) if (restrict != null && !RESTRICTED_CONTAINERS.get(restrict).numericalIds().contains(slot))
{ {
throw new SimpleCommandExceptionType(new LiteralText("Incorrect slot restricted to "+restrict+" for custom type "+suffix)).create(); throw new SimpleCommandExceptionType(new LiteralText("Incorrect slot restricted to "+restrict+" for custom type "+suffix)).create();
} }
@@ -961,7 +962,7 @@ public abstract class CommandArgument
@Override @Override
protected Collection<String> getOptions(CommandContext<ServerCommandSource> context, CarpetScriptHost host) throws CommandSyntaxException protected Collection<String> getOptions(CommandContext<ServerCommandSource> context, CarpetScriptHost host) throws CommandSyntaxException
{ {
return restrict==null?super.getOptions(context, host):RESTRICTED_CONTAINERS.get(restrict).getRight(); return restrict==null?super.getOptions(context, host):RESTRICTED_CONTAINERS.get(restrict).commandIds();
} }
@Override @Override
@@ -13,8 +13,8 @@ import carpet.script.value.MapValue;
import carpet.script.value.NumericValue; import carpet.script.value.NumericValue;
import carpet.script.value.StringValue; import carpet.script.value.StringValue;
import carpet.script.value.Value; import carpet.script.value.Value;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ControlFlow { public class ControlFlow {
@@ -106,7 +106,7 @@ public class ControlFlow {
LazyValue __ = c.getVariable("_"); LazyValue __ = c.getVariable("_");
c.setVariable("_", (__c, __t) -> ret.data.reboundedTo("_")); c.setVariable("_", (__c, __t) -> ret.data.reboundedTo("_"));
LazyValue _trace = c.getVariable("_trace"); LazyValue _trace = c.getVariable("_trace");
c.setVariable("_trace", (__c, __t) -> MapValue.wrap(ImmutableMap.of( c.setVariable("_trace", (__c, __t) -> MapValue.wrap(Map.of(
StringValue.of("stack"), ListValue.wrap(ret.stack.stream().map(f -> ListValue.of( StringValue.of("stack"), ListValue.wrap(ret.stack.stream().map(f -> ListValue.of(
StringValue.of(f.getModule().getName()), StringValue.of(f.getModule().getName()),
StringValue.of(f.getString()), StringValue.of(f.getString()),
@@ -18,7 +18,6 @@ import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.command.CommandException; import net.minecraft.command.CommandException;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.util.WorldSavePath; import net.minecraft.util.WorldSavePath;
import org.apache.commons.lang3.tuple.Triple;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
@@ -55,6 +54,7 @@ public class AppStoreManager
*/ */
private static String scarpetRepoLink = "https://api.github.com/repos/gnembon/scarpet/contents/programs/"; private static String scarpetRepoLink = "https://api.github.com/repos/gnembon/scarpet/contents/programs/";
private static record AppInfo(String name, String url, StoreNode source) {}
public static class ScarpetAppStoreValidator extends Validator<String> public static class ScarpetAppStoreValidator extends Validator<String>
{ {
@@ -253,23 +253,23 @@ public class AppStoreManager
public static int downloadScript(ServerCommandSource source, String path) public static int downloadScript(ServerCommandSource source, String path)
{ {
Triple<String, String, StoreNode> nodeInfo = getFileNode(path); AppInfo nodeInfo = getFileNode(path);
return downloadScript(source, path, nodeInfo, false); return downloadScript(source, path, nodeInfo, false);
} }
private static int downloadScript(ServerCommandSource source, String path, Triple<String, String, StoreNode> nodeInfo, boolean useTrash) private static int downloadScript(ServerCommandSource source, String path, AppInfo nodeInfo, boolean useTrash)
{ {
String code; String code;
try try
{ {
code = getStringFromStream(nodeInfo.getMiddle()); code = getStringFromStream(nodeInfo.url());
} }
catch (IOException e) catch (IOException e)
{ {
throw new CommandException(Messenger.c("rb Failed to obtain app file content: "+e.getMessage())); throw new CommandException(Messenger.c("rb Failed to obtain app file content: "+e.getMessage()));
} }
if (!saveScriptToFile(source, path, nodeInfo.getLeft(), code, false, useTrash)) return 0; if (!saveScriptToFile(source, path, nodeInfo.name(), code, false, useTrash)) return 0;
boolean success = CarpetServer.scriptServer.addScriptHost(source, nodeInfo.getLeft().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.getRight()); boolean success = CarpetServer.scriptServer.addScriptHost(source, nodeInfo.name().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.source());
return success?1:0; return success?1:0;
} }
@@ -278,12 +278,12 @@ public class AppStoreManager
* @param appPath The user inputted path to the scarpet script * @param appPath The user inputted path to the scarpet script
* @return Pair of app file name and content * @return Pair of app file name and content
*/ */
public static Triple<String, String, StoreNode> getFileNode(String appPath) public static AppInfo getFileNode(String appPath)
{ {
return getFileNodeFrom(APP_STORE_ROOT, appPath); return getFileNodeFrom(APP_STORE_ROOT, appPath);
} }
public static Triple<String, String, StoreNode> getFileNodeFrom(StoreNode start, String appPath) public static AppInfo getFileNodeFrom(StoreNode start, String appPath)
{ {
String[] path = appPath.split("/"); String[] path = appPath.split("/");
StoreNode appKiosk = start; StoreNode appKiosk = start;
@@ -293,7 +293,7 @@ public class AppStoreManager
appKiosk = appKiosk.drillDown(pathElement); appKiosk = appKiosk.drillDown(pathElement);
String appName = path[path.length-1]; String appName = path[path.length-1];
appKiosk.getValue(appName); appKiosk.getValue(appName);
return Triple.of(appName, appKiosk.getValue(appName), appKiosk); return new AppInfo(appName, appKiosk.getValue(appName), appKiosk);
} }
catch (IOException e) catch (IOException e)
{ {
@@ -390,8 +390,8 @@ public class AppStoreManager
if (original.matches("^https?://.*$")) // We've got a full url here: Just use it if (original.matches("^https?://.*$")) // We've got a full url here: Just use it
return original; return original;
if (original.charAt(0) == '/') // We've got an absolute path: Use app store root if (original.charAt(0) == '/') // We've got an absolute path: Use app store root
return getFileNode(original.substring(1)).getMiddle(); return getFileNode(original.substring(1)).url();
return getFileNodeFrom(storeSource, original).getMiddle(); // Relative path: Use download location return getFileNodeFrom(storeSource, original).url(); // Relative path: Use download location
} }
public static void addResource(CarpetScriptHost carpetScriptHost, StoreNode storeSource, Value resource) public static void addResource(CarpetScriptHost carpetScriptHost, StoreNode storeSource, Value resource)
@@ -461,7 +461,7 @@ public class AppStoreManager
throw new InternalExpressionException("App resource tried to leave script reserved space"); throw new InternalExpressionException("App resource tried to leave script reserved space");
try try
{ {
downloadScript(carpetScriptHost.responsibleSource, target, Triple.of(target, contentUrl, getNewStoreNode(storeSource, source, contentUrl)), true); downloadScript(carpetScriptHost.responsibleSource, target, new AppInfo(target, contentUrl, getNewStoreNode(storeSource, source, contentUrl)), true);
} }
catch (CommandException e) catch (CommandException e)
{ {
@@ -2,7 +2,6 @@ package carpet.script.utils;
import carpet.CarpetSettings; import carpet.CarpetSettings;
import carpet.network.ServerNetworkHandler; import carpet.network.ServerNetworkHandler;
import carpet.script.CarpetContext;
import carpet.script.exception.InternalExpressionException; import carpet.script.exception.InternalExpressionException;
import carpet.script.exception.ThrowStatement; import carpet.script.exception.ThrowStatement;
import carpet.script.exception.Throwables; import carpet.script.exception.Throwables;
@@ -16,8 +15,6 @@ import carpet.script.value.MapValue;
import carpet.script.value.NumericValue; import carpet.script.value.NumericValue;
import carpet.script.value.StringValue; import carpet.script.value.StringValue;
import carpet.script.value.Value; import carpet.script.value.Value;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.mojang.brigadier.StringReader; import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.CommandSyntaxException;
@@ -45,7 +42,6 @@ import net.minecraft.util.math.Vec3d;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.util.registry.RegistryKey; import net.minecraft.util.registry.RegistryKey;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@@ -60,11 +56,14 @@ import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier; import java.util.function.Supplier;
import static java.util.Map.entry;
public class ShapeDispatcher public class ShapeDispatcher
{ {
private static final Map<String, ParticleEffect> particleCache = new HashMap<>(); private static final Map<String, ParticleEffect> particleCache = new HashMap<>();
public static record ShapeWithConfig(ExpiringShape shape, Map<String, Value> config) {}
public static Pair<ExpiringShape,Map<String, Value>> fromFunctionArgs( public static ShapeWithConfig fromFunctionArgs(
MinecraftServer server, ServerWorld world, MinecraftServer server, ServerWorld world,
List<Value> lv, List<Value> lv,
Set<ServerPlayerEntity> playerSet Set<ServerPlayerEntity> playerSet
@@ -114,10 +113,10 @@ public class ShapeDispatcher
} }
params.remove("player"); params.remove("player");
} }
return Pair.of(ShapeDispatcher.create(server, shapeType, params), params); return new ShapeWithConfig(ShapeDispatcher.create(server, shapeType, params), params);
} }
public static void sendShape(Collection<ServerPlayerEntity> players, List<Pair<ExpiringShape,Map<String, Value>>> shapes) public static void sendShape(Collection<ServerPlayerEntity> players, List<ShapeWithConfig> shapes)
{ {
List<ServerPlayerEntity> clientPlayers = new ArrayList<>(); List<ServerPlayerEntity> clientPlayers = new ArrayList<>();
List<ServerPlayerEntity> alternativePlayers = new ArrayList<>(); List<ServerPlayerEntity> alternativePlayers = new ArrayList<>();
@@ -137,9 +136,9 @@ public class ShapeDispatcher
NbtList tag = new NbtList(); NbtList tag = new NbtList();
int tagcount = 0; int tagcount = 0;
for (Pair<ExpiringShape, Map<String, Value>> s : shapes) for (ShapeWithConfig s : shapes)
{ {
tag.add(ExpiringShape.toTag(s.getRight())); // 4000 shapes limit boxes tag.add(ExpiringShape.toTag(s.config())); // 4000 shapes limit boxes
if (tagcount++>1000) if (tagcount++>1000)
{ {
tagcount = 0; tagcount = 0;
@@ -154,7 +153,7 @@ public class ShapeDispatcher
if (!alternativePlayers.isEmpty()) if (!alternativePlayers.isEmpty())
{ {
List<Consumer<ServerPlayerEntity>> alternatives = new ArrayList<>(); List<Consumer<ServerPlayerEntity>> alternatives = new ArrayList<>();
shapes.forEach(s -> alternatives.add(s.getLeft().alternative())); shapes.forEach(s -> alternatives.add(s.shape().alternative()));
alternativePlayers.forEach(p -> alternatives.forEach( a -> a.accept(p))); alternativePlayers.forEach(p -> alternatives.forEach( a -> a.accept(p)));
} }
} }
@@ -405,8 +404,8 @@ public class ShapeDispatcher
} }
// list of params that need to be there // list of params that need to be there
private final Set<String> required = ImmutableSet.of("duration", "shape", "dim"); private final Set<String> required = Set.of("duration", "shape", "dim");
private final Map<String, Value> optional = ImmutableMap.of( private final Map<String, Value> optional = Map.of(
"color", new NumericValue(-1), "color", new NumericValue(-1),
"follow", new NumericValue(-1), "follow", new NumericValue(-1),
"line", new NumericValue(2.0), "line", new NumericValue(2.0),
@@ -425,20 +424,19 @@ public class ShapeDispatcher
public static class DisplayedText extends ExpiringShape public static class DisplayedText extends ExpiringShape
{ {
private final Set<String> required = ImmutableSet.of("pos", "text"); private final Set<String> required = Set.of("pos", "text");
private final Map<String, Value> optional = ImmutableMap.<String, Value>builder(). private final Map<String, Value> optional = Map.ofEntries(
put("facing", new StringValue("player")). entry("facing", new StringValue("player")),
put("raise", new NumericValue(0)). entry("raise", new NumericValue(0)),
put("tilt", new NumericValue(0)). entry("tilt", new NumericValue(0)),
put("lean", new NumericValue(0)). entry("lean", new NumericValue(0)),
put("turn", new NumericValue(0)). entry("turn", new NumericValue(0)),
put("indent", new NumericValue(0)). entry("indent", new NumericValue(0)),
put("height", new NumericValue(0)). entry("height", new NumericValue(0)),
put("align", new StringValue("center")). entry("align", new StringValue("center")),
put("size", new NumericValue(10)). entry("size", new NumericValue(10)),
put("value", Value.NULL). entry("value", Value.NULL),
put("doublesided", new NumericValue(0)). entry("doublesided", new NumericValue(0)));
build();
@Override @Override
protected Set<String> requiredParams() { return Sets.union(super.requiredParams(), required); } protected Set<String> requiredParams() { return Sets.union(super.requiredParams(), required); }
@Override @Override
@@ -552,8 +550,8 @@ public class ShapeDispatcher
public static class Box extends ExpiringShape public static class Box extends ExpiringShape
{ {
private final Set<String> required = ImmutableSet.of("from", "to"); private final Set<String> required = Set.of("from", "to");
private final Map<String, Value> optional = ImmutableMap.of(); private final Map<String, Value> optional = Map.of();
@Override @Override
protected Set<String> requiredParams() { return Sets.union(super.requiredParams(), required); } protected Set<String> requiredParams() { return Sets.union(super.requiredParams(), required); }
@Override @Override
@@ -630,8 +628,8 @@ public class ShapeDispatcher
public static class Line extends ExpiringShape public static class Line extends ExpiringShape
{ {
private final Set<String> required = ImmutableSet.of("from", "to"); private final Set<String> required = Set.of("from", "to");
private final Map<String, Value> optional = ImmutableMap.of(); private final Map<String, Value> optional = Map.of();
@Override @Override
protected Set<String> requiredParams() { return Sets.union(super.requiredParams(), required); } protected Set<String> requiredParams() { return Sets.union(super.requiredParams(), required); }
@Override @Override
@@ -683,8 +681,8 @@ public class ShapeDispatcher
public static class Sphere extends ExpiringShape public static class Sphere extends ExpiringShape
{ {
private final Set<String> required = ImmutableSet.of("center", "radius"); private final Set<String> required = Set.of("center", "radius");
private final Map<String, Value> optional = ImmutableMap.of("level", Value.ZERO); private final Map<String, Value> optional = Map.of("level", Value.ZERO);
@Override @Override
protected Set<String> requiredParams() { return Sets.union(super.requiredParams(), required); } protected Set<String> requiredParams() { return Sets.union(super.requiredParams(), required); }
@Override @Override
@@ -755,8 +753,8 @@ public class ShapeDispatcher
} }
public static class Cylinder extends ExpiringShape public static class Cylinder extends ExpiringShape
{ {
private final Set<String> required = ImmutableSet.of("center", "radius"); private final Set<String> required = Set.of("center", "radius");
private final Map<String, Value> optional = ImmutableMap.of( private final Map<String, Value> optional = Map.of(
"level", Value.ZERO, "level", Value.ZERO,
"height", Value.ZERO, "height", Value.ZERO,
"axis", new StringValue("y") "axis", new StringValue("y")
@@ -913,6 +911,7 @@ public class ShapeDispatcher
@Override @Override
public NbtElement toTag(Value value) { return NbtString.of(value.getString()); } public NbtElement toTag(Value value) { return NbtString.of(value.getString()); }
@Override
public Value decode(NbtElement tag) { return new StringValue(tag.asString()); } public Value decode(NbtElement tag) { return new StringValue(tag.asString()); }
} }
public static class TextParam extends StringParam public static class TextParam extends StringParam
@@ -1149,6 +1148,7 @@ public class ShapeDispatcher
throw new InternalExpressionException("'"+p.id+"' requires a triple, block or entity to indicate position"); throw new InternalExpressionException("'"+p.id+"' requires a triple, block or entity to indicate position");
} }
@Override
public Value decode(NbtElement tag) public Value decode(NbtElement tag)
{ {
NbtList ctag = (NbtList)tag; NbtList ctag = (NbtList)tag;
@@ -1187,6 +1187,7 @@ public class ShapeDispatcher
return ListValue.wrap(points); return ListValue.wrap(points);
} }
@Override
public Value decode(NbtElement tag) public Value decode(NbtElement tag)
{ {
NbtList ltag = (NbtList)tag; NbtList ltag = (NbtList)tag;
@@ -1228,6 +1229,7 @@ public class ShapeDispatcher
super(id); super(id);
} }
@Override
public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); } public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); }
@Override @Override
public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); } public NbtElement toTag(Value value) { return NbtInt.of(NumericValue.asNumber(value, id).getInt()); }
@@ -1254,6 +1256,7 @@ public class ShapeDispatcher
return new NumericValue(player.getId()); return new NumericValue(player.getId());
} }
@Override
public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); } public Value decode(NbtElement tag) { return new NumericValue(((NbtInt)tag).intValue()); }
} }
@@ -38,6 +38,7 @@ public class SimplexNoiseSampler extends PerlinNoiseSampler {
return g; return g;
} }
@Override
public double sample2d(double x, double y) { public double sample2d(double x, double y) {
x = x/2; x = x/2;
y = y/2; y = y/2;
@@ -75,6 +76,7 @@ public class SimplexNoiseSampler extends PerlinNoiseSampler {
return 35.0D * (aa + ab + ac)+0.5; return 35.0D * (aa + ab + ac)+0.5;
} }
@Override
public double sample3d(double d, double e, double f) { public double sample3d(double d, double e, double f) {
d = d/2; d = d/2;
e = e/2; e = e/2;
@@ -122,6 +122,7 @@ public class SnoopyCommandSource extends ServerCommandSource
return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, error, chatOutput); return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, error, chatOutput);
} }
@Override
public ServerCommandSource mergeConsumers(ResultConsumer<ServerCommandSource> consumer, BinaryOperator<ResultConsumer<ServerCommandSource>> binaryOperator) public ServerCommandSource mergeConsumers(ResultConsumer<ServerCommandSource> consumer, BinaryOperator<ResultConsumer<ServerCommandSource>> binaryOperator)
{ {
ResultConsumer<ServerCommandSource> resultConsumer = binaryOperator.apply(this.resultConsumer, consumer); ResultConsumer<ServerCommandSource> resultConsumer = binaryOperator.apply(this.resultConsumer, consumer);
@@ -133,7 +133,7 @@ public class SystemInfo {
put("java_system_cpu_load", c -> { put("java_system_cpu_load", c -> {
OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean( OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
OperatingSystemMXBean.class); OperatingSystemMXBean.class);
return new NumericValue(osBean.getSystemCpuLoad()); return new NumericValue(osBean.getCpuLoad());
}); });
put("java_process_cpu_load", c -> { put("java_process_cpu_load", c -> {
OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean( OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
@@ -1,7 +1,6 @@
package carpet.script.utils; package carpet.script.utils;
import carpet.fakes.MinecraftServerInterface; import carpet.fakes.MinecraftServerInterface;
import com.google.common.collect.ImmutableList;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.minecraft.network.packet.s2c.play.ChunkDataS2CPacket; import net.minecraft.network.packet.s2c.play.ChunkDataS2CPacket;
@@ -93,7 +92,7 @@ public class WorldTools
boolean bl = generatorOptions.isDebugWorld(); boolean bl = generatorOptions.isDebugWorld();
long l = generatorOptions.getSeed(); long l = generatorOptions.getSeed();
long m = BiomeAccess.hashSeed(l); long m = BiomeAccess.hashSeed(l);
List<Spawner> list = ImmutableList.of(); List<Spawner> list = List.of();
SimpleRegistry<DimensionOptions> simpleRegistry = generatorOptions.getDimensions(); SimpleRegistry<DimensionOptions> simpleRegistry = generatorOptions.getDimensions();
DimensionOptions dimensionOptions = simpleRegistry.get(DimensionOptions.OVERWORLD); DimensionOptions dimensionOptions = simpleRegistry.get(DimensionOptions.OVERWORLD);
ChunkGenerator chunkGenerator2; ChunkGenerator chunkGenerator2;
@@ -8,7 +8,7 @@ import java.util.List;
public abstract class AbstractListValue extends Value implements Iterable<Value> public abstract class AbstractListValue extends Value implements Iterable<Value>
{ {
public abstract Iterator<Value> iterator(); @Override public abstract Iterator<Value> iterator();
public List<Value> unpack() { return Lists.newArrayList(iterator()); } public List<Value> unpack() { return Lists.newArrayList(iterator()); }
public void fatality() { } public void fatality() { }
public void append(Value v) public void append(Value v)
@@ -12,7 +12,7 @@ public class BooleanValue extends NumericValue
boolean boolValue; boolean boolValue;
private BooleanValue(boolean boolval) { private BooleanValue(boolean boolval) {
super(boolval); super(boolval ? 1L : 0L);
boolValue = boolval; boolValue = boolval;
} }
@@ -412,14 +412,14 @@ public class EntityValue extends Value
throw new InternalExpressionException("Cannot fetch '"+what+"' with these arguments"); throw new InternalExpressionException("Cannot fetch '"+what+"' with these arguments");
} }
} }
private static final Map<String, EquipmentSlot> inventorySlots = new HashMap<String, EquipmentSlot>(){{ private static final Map<String, EquipmentSlot> inventorySlots = Map.of(
put("mainhand", EquipmentSlot.MAINHAND); "mainhand", EquipmentSlot.MAINHAND,
put("offhand", EquipmentSlot.OFFHAND); "offhand", EquipmentSlot.OFFHAND,
put("head", EquipmentSlot.HEAD); "head", EquipmentSlot.HEAD,
put("chest", EquipmentSlot.CHEST); "chest", EquipmentSlot.CHEST,
put("legs", EquipmentSlot.LEGS); "legs", EquipmentSlot.LEGS,
put("feet", EquipmentSlot.FEET); "feet", EquipmentSlot.FEET
}}; );
private static final Map<String, BiFunction<Entity, Value, Value>> featureAccessors = new HashMap<String, BiFunction<Entity, Value, Value>>() {{ private static final Map<String, BiFunction<Entity, Value, Value>> featureAccessors = new HashMap<String, BiFunction<Entity, Value, Value>>() {{
//put("test", (e, a) -> a == null ? Value.NULL : new StringValue(a.getString())); //put("test", (e, a) -> a == null ? Value.NULL : new StringValue(a.getString()));
@@ -109,9 +109,9 @@ public abstract class LazyListValue extends AbstractListValue implements Iterato
{ {
return hasNext(); return hasNext();
} }
public abstract boolean hasNext(); @Override public abstract boolean hasNext();
public abstract Value next(); @Override public abstract Value next();
@Override @Override
public void fatality() {reset();} public void fatality() {reset();}
@@ -149,6 +149,8 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
{ {
items.add(v); items.add(v);
} }
@Override
public Value subtract(Value other) public Value subtract(Value other)
{ {
ListValue output = new ListValue(); ListValue output = new ListValue();
@@ -182,6 +184,7 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
} }
@Override
public Value multiply(Value other) public Value multiply(Value other)
{ {
ListValue output = new ListValue(); ListValue output = new ListValue();
@@ -209,6 +212,8 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
} }
return output; return output;
} }
@Override
public Value divide(Value other) public Value divide(Value other)
{ {
ListValue output = new ListValue(); ListValue output = new ListValue();
@@ -272,8 +277,10 @@ public class ListValue extends AbstractListValue implements ContainerValueInterf
return items; return items;
} }
@Override
public Iterator<Value> iterator() { return new ArrayList<>(items).iterator(); } // should be thread safe public Iterator<Value> iterator() { return new ArrayList<>(items).iterator(); } // should be thread safe
@Override
public List<Value> unpack() public List<Value> unpack()
{ {
return new ArrayList<>(items); return new ArrayList<>(items);
@@ -633,26 +633,12 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa
return false; return false;
} }
public static class InventoryLocator public static record InventoryLocator(Object owner, BlockPos position, Inventory inventory, int offset, boolean isEnder)
{ {
public Object owner;
public BlockPos position;
public Inventory inventory;
public int offset;
public boolean isEnder;
InventoryLocator(Object owner, BlockPos pos, Inventory i, int o) InventoryLocator(Object owner, BlockPos pos, Inventory i, int o)
{ {
this(owner, pos, i, o, false); this(owner, pos, i, o, false);
} }
InventoryLocator(Object owner, BlockPos pos, Inventory i, int o, boolean isEnder)
{
this.owner = owner;
position = pos;
inventory = i;
offset = o;
this.isEnder = isEnder;
}
} }
private static Map<String, NbtPathArgumentType.NbtPath> pathCache = new HashMap<>(); private static Map<String, NbtPathArgumentType.NbtPath> pathCache = new HashMap<>();
@@ -33,7 +33,7 @@ public class NullValue extends NumericValue // TODO check nonsingleton code
{ {
return new NullValue(); return new NullValue();
} }
private NullValue() {super(false);} private NullValue() {super(0);}
@Override @Override
public boolean equals(final Object o) public boolean equals(final Object o)
@@ -120,6 +120,8 @@ public class NumericValue extends Value
} }
return super.add(v); return super.add(v);
} }
@Override
public Value subtract(Value v) { // TODO test if definintn add(NumericVlaue) woud solve the casting public Value subtract(Value v) { // TODO test if definintn add(NumericVlaue) woud solve the casting
if (v instanceof NumericValue nv) if (v instanceof NumericValue nv)
{ {
@@ -131,6 +133,8 @@ public class NumericValue extends Value
} }
return super.subtract(v); return super.subtract(v);
} }
@Override
public Value multiply(Value v) public Value multiply(Value v)
{ {
if (v instanceof NumericValue nv) if (v instanceof NumericValue nv)
@@ -147,6 +151,8 @@ public class NumericValue extends Value
} }
return new StringValue(StringUtils.repeat(v.getString(), (int) getLong())); return new StringValue(StringUtils.repeat(v.getString(), (int) getLong()));
} }
@Override
public Value divide(Value v) public Value divide(Value v)
{ {
//if (1+2==3) throw new ArithmeticException("Booyah"); //if (1+2==3) throw new ArithmeticException("Booyah");
@@ -223,17 +229,6 @@ public class NumericValue extends Value
this.value = (double)value; this.value = (double)value;
} }
/**
* Creates a legacy {@link NumericValue} for a {@code boolean}.
* @param boolval The boolean to set 1 or 0 for this {@link NumericValue}
* @deprecated Use {@link BooleanValue#of(boolean)} instead
*/
@Deprecated
public NumericValue(boolean boolval)
{
this(boolval?1L:0L);
}
@Override @Override
public int length() public int length()
{ {
+11 -11
View File
@@ -2,7 +2,6 @@ package carpet.settings;
import carpet.utils.Translations; import carpet.utils.Translations;
import carpet.utils.Messenger; import carpet.utils.Messenger;
import com.google.common.collect.ImmutableList;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
@@ -11,6 +10,7 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.ClassUtils;
@@ -29,9 +29,9 @@ public final class ParsedRule<T> implements Comparable<ParsedRule> {
public final String name; public final String name;
public final String description; public final String description;
public final String scarpetApp; public final String scarpetApp;
public final ImmutableList<String> extraInfo; public final List<String> extraInfo;
public final ImmutableList<String> categories; public final List<String> categories;
public final ImmutableList<String> options; public final List<String> options;
public boolean isStrict; public boolean isStrict;
public boolean isClient; public boolean isClient;
public final Class<T> type; public final Class<T> type;
@@ -47,8 +47,8 @@ public final class ParsedRule<T> implements Comparable<ParsedRule> {
this.type = (Class<T>) field.getType(); this.type = (Class<T>) field.getType();
this.description = rule.desc(); this.description = rule.desc();
this.isStrict = rule.strict(); this.isStrict = rule.strict();
this.extraInfo = ImmutableList.copyOf(rule.extra()); this.extraInfo = List.of(rule.extra());
this.categories = ImmutableList.copyOf(rule.category()); this.categories = List.of(rule.category());
this.scarpetApp = rule.appSource(); this.scarpetApp = rule.appSource();
this.settingsManager = settingsManager; this.settingsManager = settingsManager;
this.validators = new ArrayList<>(); this.validators = new ArrayList<>();
@@ -76,22 +76,22 @@ public final class ParsedRule<T> implements Comparable<ParsedRule> {
this.defaultAsString = convertToString(this.defaultValue); this.defaultAsString = convertToString(this.defaultValue);
if (rule.options().length > 0) if (rule.options().length > 0)
{ {
this.options = ImmutableList.copyOf(rule.options()); this.options = List.of(rule.options());
} }
else if (this.type == boolean.class){ else if (this.type == boolean.class){
this.options = ImmutableList.of("true","false"); this.options = List.of("true","false");
} }
else if(this.type == String.class && categories.contains(RuleCategory.COMMAND)) else if(this.type == String.class && categories.contains(RuleCategory.COMMAND))
{ {
this.options = ImmutableList.of("true", "false", "ops"); this.options = List.of("true", "false", "ops");
} }
else if (this.type.isEnum()) else if (this.type.isEnum())
{ {
this.options = Arrays.stream(this.type.getEnumConstants()).map(e -> ((Enum) e).name().toLowerCase(Locale.ROOT)).collect(ImmutableList.toImmutableList()); this.options = Arrays.stream(this.type.getEnumConstants()).map(e -> ((Enum) e).name().toLowerCase(Locale.ROOT)).collect(Collectors.toUnmodifiableList());
} }
else else
{ {
this.options = ImmutableList.of(); this.options = List.of();
} }
if (isStrict && !this.options.isEmpty()) if (isStrict && !this.options.isEmpty())
{ {
@@ -5,7 +5,6 @@ import carpet.CarpetSettings;
import carpet.network.ServerNetworkHandler; import carpet.network.ServerNetworkHandler;
import carpet.utils.Translations; import carpet.utils.Translations;
import carpet.utils.Messenger; import carpet.utils.Messenger;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.arguments.StringArgumentType;
@@ -72,6 +71,7 @@ public class SettingsManager
private MinecraftServer server; private MinecraftServer server;
private List<TriConsumer<ServerCommandSource, ParsedRule<?>, String>> observers = new ArrayList<>(); private List<TriConsumer<ServerCommandSource, ParsedRule<?>, String>> observers = new ArrayList<>();
private static List<TriConsumer<ServerCommandSource, ParsedRule<?>, String>> staticObservers = new ArrayList<>(); private static List<TriConsumer<ServerCommandSource, ParsedRule<?>, String>> staticObservers = new ArrayList<>();
static record ConfigReadResult(Map<String, String> ruleMap, boolean locked) {}
/** /**
* Creates a new {@link SettingsManager} without a fancy name. * Creates a new {@link SettingsManager} without a fancy name.
@@ -264,7 +264,7 @@ public class SettingsManager
*/ */
public Collection<ParsedRule<?>> findStartupOverrides() public Collection<ParsedRule<?>> findStartupOverrides()
{ {
Set<String> defaults = readSettingsFromConf(getFile()).getLeft().keySet(); Set<String> defaults = readSettingsFromConf(getFile()).ruleMap().keySet();
return rules.values().stream().filter(r -> defaults.contains(r.name)). return rules.values().stream().filter(r -> defaults.contains(r.name)).
sorted().collect(Collectors.toList()); sorted().collect(Collectors.toList());
} }
@@ -396,30 +396,30 @@ public class SettingsManager
private void loadConfigurationFromConf() private void loadConfigurationFromConf()
{ {
for (ParsedRule<?> rule : rules.values()) rule.resetToDefault(server.getCommandSource()); for (ParsedRule<?> rule : rules.values()) rule.resetToDefault(server.getCommandSource());
Pair<Map<String, String>, Boolean> conf = readSettingsFromConf(getFile()); ConfigReadResult conf = readSettingsFromConf(getFile());
locked = false; locked = false;
if (conf.getRight()) if (conf.locked())
{ {
CarpetSettings.LOG.info("[CM]: "+fancyName+" features are locked by the administrator"); CarpetSettings.LOG.info("[CM]: "+fancyName+" features are locked by the administrator");
disableBooleanCommands(); disableBooleanCommands();
} }
for (String key: conf.getLeft().keySet()) for (String key: conf.ruleMap().keySet())
{ {
try try
{ {
if (rules.get(key).set(server.getCommandSource(), conf.getLeft().get(key)) != null) if (rules.get(key).set(server.getCommandSource(), conf.ruleMap().get(key)) != null)
CarpetSettings.LOG.info("[CM]: loaded setting " + key + " as " + conf.getLeft().get(key) + " from " + identifier + ".conf"); CarpetSettings.LOG.info("[CM]: loaded setting " + key + " as " + conf.ruleMap().get(key) + " from " + identifier + ".conf");
} }
catch (Exception exc) catch (Exception exc)
{ {
CarpetSettings.LOG.error("[CM Error]: Failed to load setting: "+key+", "+exc); CarpetSettings.LOG.error("[CM Error]: Failed to load setting: "+key+", "+exc);
} }
} }
locked = conf.getRight(); locked = conf.locked();
} }
private Pair<Map<String, String>, Boolean> readSettingsFromConf(Path path) private ConfigReadResult readSettingsFromConf(Path path)
{ {
try (BufferedReader reader = Files.newBufferedReader(path)) try (BufferedReader reader = Files.newBufferedReader(path))
{ {
@@ -452,7 +452,7 @@ public class SettingsManager
} }
} }
return Pair.of(result, confLocked); return new ConfigReadResult(result, confLocked);
} }
catch (NoSuchFileException e) catch (NoSuchFileException e)
{ {
@@ -467,15 +467,15 @@ public class SettingsManager
} }
return readSettingsFromConf(defaultsPath); return readSettingsFromConf(defaultsPath);
} catch (IOException e2) { } catch (IOException e2) {
CarpetSettings.LOG.error("Exception when loading fallback default config: ", e); CarpetSettings.LOG.error("Exception when loading fallback default config: ", e2);
} }
} }
return Pair.of(new HashMap<>(), false); return new ConfigReadResult(new HashMap<>(), false);
} }
catch (IOException e) catch (IOException e)
{ {
e.printStackTrace(); e.printStackTrace();
return Pair.of(new HashMap<>(), false); return new ConfigReadResult(new HashMap<>(), false);
} }
} }
@@ -486,7 +486,7 @@ public class SettingsManager
if (rule.name.toLowerCase(Locale.ROOT).contains(lcSearch)) return true; // substring match, case insensitive if (rule.name.toLowerCase(Locale.ROOT).contains(lcSearch)) return true; // substring match, case insensitive
for (String c : rule.categories) if (c.equals(search)) return true; // category exactly, case sensitive for (String c : rule.categories) if (c.equals(search)) return true; // category exactly, case sensitive
return Sets.newHashSet(rule.description.toLowerCase(Locale.ROOT).split("\\W+")).contains(lcSearch); // contains full term in description, but case insensitive return Sets.newHashSet(rule.description.toLowerCase(Locale.ROOT).split("\\W+")).contains(lcSearch); // contains full term in description, but case insensitive
}).sorted().collect(ImmutableList.toImmutableList()); }).sorted().collect(Collectors.toUnmodifiableList());
} }
/** /**
@@ -647,9 +647,9 @@ public class SettingsManager
{ {
if (locked) return 0; if (locked) return 0;
if (!rules.containsKey(rule.name)) return 0; if (!rules.containsKey(rule.name)) return 0;
Pair<Map<String, String>,Boolean> conf = readSettingsFromConf(getFile()); ConfigReadResult conf = readSettingsFromConf(getFile());
conf.getLeft().put(rule.name, stringValue); conf.ruleMap().put(rule.name, stringValue);
writeSettingsToConf(conf.getLeft()); // this may feels weird, but if conf writeSettingsToConf(conf.ruleMap()); // this may feels weird, but if conf
// is locked, it will never reach this point. // is locked, it will never reach this point.
rule.set(source,stringValue); rule.set(source,stringValue);
Messenger.m(source ,"gi "+String.format(tr("ui.rule_%(rule)s_will_now_default_to_%(value)s","Rule %s will now default to %s"), rule.translatedName(), stringValue)); Messenger.m(source ,"gi "+String.format(tr("ui.rule_%(rule)s_will_now_default_to_%(value)s","Rule %s will now default to %s"), rule.translatedName(), stringValue));
@@ -660,9 +660,9 @@ public class SettingsManager
{ {
if (locked) return 0; if (locked) return 0;
if (!rules.containsKey(rule.name)) return 0; if (!rules.containsKey(rule.name)) return 0;
Pair<Map<String, String>,Boolean> conf = readSettingsFromConf(getFile()); ConfigReadResult conf = readSettingsFromConf(getFile());
conf.getLeft().remove(rule.name); conf.ruleMap().remove(rule.name);
writeSettingsToConf(conf.getLeft()); writeSettingsToConf(conf.ruleMap());
rules.get(rule.name).resetToDefault(source); rules.get(rule.name).resetToDefault(source);
Messenger.m(source ,"gi "+String.format(tr("ui.rule_%(rule)s_not_set_restart","Rule %s will now not be set on restart"), rule.translatedName())); Messenger.m(source ,"gi "+String.format(tr("ui.rule_%(rule)s_not_set_restart","Rule %s will now not be set on restart"), rule.translatedName()));
return 1; return 1;
+4 -4
View File
@@ -2,9 +2,9 @@ package carpet.settings;
import carpet.CarpetServer; import carpet.CarpetServer;
import carpet.utils.Messenger; import carpet.utils.Messenger;
import com.google.common.collect.ImmutableList;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -48,7 +48,7 @@ public abstract class Validator<T>
} }
public static class _COMMAND_LEVEL_VALIDATOR extends Validator<String> { public static class _COMMAND_LEVEL_VALIDATOR extends Validator<String> {
private static ImmutableList<String> OPTIONS = ImmutableList.of("true", "false", "ops", "0", "1", "2", "3", "4"); private static List<String> OPTIONS = List.of("true", "false", "ops", "0", "1", "2", "3", "4");
@Override public String validate(ServerCommandSource source, ParsedRule<String> currentRule, String newValue, String userString) { @Override public String validate(ServerCommandSource source, ParsedRule<String> currentRule, String newValue, String userString) {
if (!OPTIONS.contains(userString.toLowerCase(Locale.ROOT))) if (!OPTIONS.contains(userString.toLowerCase(Locale.ROOT)))
{ {
@@ -59,7 +59,7 @@ public abstract class Validator<T>
} }
return userString.toLowerCase(Locale.ROOT); return userString.toLowerCase(Locale.ROOT);
} }
public String description() { return "Can be limited to 'ops' only, or a custom permission level";} @Override public String description() { return "Can be limited to 'ops' only, or a custom permission level";}
} }
public static class _SCARPET<T> extends Validator<T> { public static class _SCARPET<T> extends Validator<T> {
@@ -68,7 +68,7 @@ public abstract class Validator<T>
{ {
return newValue; return newValue;
} }
public String description() { @Override public String description() {
return "It controls an accompanying Scarpet App"; return "It controls an accompanying Scarpet App";
} }
} }
+2 -10
View File
@@ -50,19 +50,11 @@ public class CarpetProfiler
TILEENTITY TILEENTITY
} }
public static class ProfilerToken public static record ProfilerToken(TYPE type, Object section, long start, World world)
{ {
public final TYPE type;
public final Object section;
public final long start;
public final World world;
public ProfilerToken(TYPE type, Object section, World world) public ProfilerToken(TYPE type, Object section, World world)
{ {
this.type = type; this(type, section, System.nanoTime(), world);
this.section = section;
this.start = System.nanoTime();
this.world = world;
} }
} }
@@ -1,4 +1,3 @@
package carpet.utils; package carpet.utils;
import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntMap;