diff --git a/gradle.properties b/gradle.properties index d5bf0e0b4..e8be3b960 100644 --- a/gradle.properties +++ b/gradle.properties @@ -13,14 +13,14 @@ minecraft_version=1.21.1 supported_versions=1.21.1, 1.21 mod_version=2101.7.2 -neoforge_version=21.1.42 +neoforge_version=21.1.83 parchment_mc_version=1.21 -parchment_mapping_version=2024.07.28 +parchment_mapping_version=2024.11.10 rhino_version=2101.2.5-build.54 -tiny_server_version=1.0.0-build.18 +tiny_server_version=1.0.0-build.25 gif_lib_version=1.7 -architectury_version=13.0.6 -rei_version=16.0.754 -jei_version=19.16.4.176 -emi_version=1.1.12+1.21 \ No newline at end of file +architectury_version=13.0.8 +rei_version=16.0.788 +jei_version=19.21.0.247 +emi_version=1.1.18+1.21.1 \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java b/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java index 4d53796fb..ea4f7102f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java +++ b/src/main/java/dev/latvian/mods/kubejs/BuiltinKubeJSPlugin.java @@ -16,6 +16,7 @@ import dev.latvian.mods.kubejs.bindings.ParticleOptionsWrapper; import dev.latvian.mods.kubejs.bindings.RegistryWrapper; import dev.latvian.mods.kubejs.bindings.SizedIngredientWrapper; +import dev.latvian.mods.kubejs.bindings.StringUtilsWrapper; import dev.latvian.mods.kubejs.bindings.TextIcons; import dev.latvian.mods.kubejs.bindings.TextWrapper; import dev.latvian.mods.kubejs.bindings.UUIDWrapper; @@ -145,8 +146,6 @@ import dev.latvian.mods.kubejs.util.JsonIO; import dev.latvian.mods.kubejs.util.JsonUtils; import dev.latvian.mods.kubejs.util.KubeResourceLocation; -import dev.latvian.mods.kubejs.util.ListJS; -import dev.latvian.mods.kubejs.util.MapJS; import dev.latvian.mods.kubejs.util.NBTIOWrapper; import dev.latvian.mods.kubejs.util.NBTUtils; import dev.latvian.mods.kubejs.util.NotificationToastData; @@ -256,12 +255,8 @@ import java.nio.file.Path; import java.time.Duration; import java.time.temporal.TemporalAmount; -import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; @@ -485,6 +480,7 @@ public void registerBindings(BindingRegistry bindings) { bindings.add("KMath", KMath.class); bindings.add("Utils", UtilsWrapper.class); + bindings.add("StringUtils", StringUtilsWrapper.class); bindings.add("Java", JavaWrapper.class); bindings.add("Text", TextWrapper.class); bindings.add("Component", TextWrapper.class); @@ -545,8 +541,8 @@ public void registerTypeWrappers(TypeWrapperRegistry registry) { registry.register(CharSequence.class, String::valueOf); registry.register(UUID.class, UUIDWrapper::fromString); registry.register(Pattern.class, RegExpKJS::wrap); - registry.register(JsonObject.class, MapJS::json); - registry.register(JsonArray.class, ListJS::json); + registry.register(JsonObject.class, JsonUtils::objectOf); + registry.register(JsonArray.class, JsonUtils::arrayOf); registry.register(JsonElement.class, JsonUtils::of); registry.register(JsonPrimitive.class, JsonUtils::primitiveOf); registry.register(Path.class, KubeJSTypeWrappers::pathOf); @@ -588,17 +584,12 @@ public void registerTypeWrappers(TypeWrapperRegistry registry) { registry.register(ColorRGBA.class, ColorWrapper::colorRGBAOf); // KubeJS // - registry.register(Map.class, MapJS::of); - registry.register(List.class, ListJS::of); - registry.register(Iterable.class, ListJS::of); - registry.register(Collection.class, ListJS::of); - registry.register(Set.class, ListJS::ofSet); registry.register(ItemStack.class, ItemStackJS::wrap); registry.register(Ingredient.class, IngredientJS::wrap); registry.register(ItemPredicate.class, ItemPredicate::wrap); registry.register(SizedIngredient.class, SizedIngredientWrapper::wrap); - registry.register(BlockStatePredicate.class, BlockStatePredicate::of); - registry.register(RuleTest.class, BlockStatePredicate::ruleTestOf); + registry.register(BlockStatePredicate.class, BlockStatePredicate::wrap); + registry.register(RuleTest.class, BlockStatePredicate::wrapRuleTest); registry.register(FluidStack.class, FluidWrapper::wrap); registry.register(FluidIngredient.class, FluidWrapper::wrapIngredient); registry.register(SizedFluidIngredient.class, FluidWrapper::wrapSizedIngredient); diff --git a/src/main/java/dev/latvian/mods/kubejs/KubeJSCodecs.java b/src/main/java/dev/latvian/mods/kubejs/KubeJSCodecs.java index a432791cc..046934a4f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/KubeJSCodecs.java +++ b/src/main/java/dev/latvian/mods/kubejs/KubeJSCodecs.java @@ -9,8 +9,8 @@ import com.mojang.serialization.DataResult; import com.mojang.serialization.JsonOps; import com.mojang.serialization.MapCodec; +import dev.latvian.mods.kubejs.bindings.StringUtilsWrapper; import dev.latvian.mods.kubejs.util.JsonUtils; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.type.EnumTypeInfo; import dev.latvian.mods.rhino.type.TypeInfo; import io.netty.buffer.ByteBuf; @@ -127,7 +127,7 @@ static JsonElement toJsonOrThrow(E value, Codec code } static String getUniqueId(T input, Codec codec) { - return UtilsJS.getUniqueId(input, o -> toJsonOrThrow(o, codec)); + return StringUtilsWrapper.getUniqueId(input, o -> toJsonOrThrow(o, codec)); } static JsonElement numberProviderJson(NumberProvider gen) { diff --git a/src/main/java/dev/latvian/mods/kubejs/KubeJSTypeWrappers.java b/src/main/java/dev/latvian/mods/kubejs/KubeJSTypeWrappers.java index 2c04fadde..1113849b5 100644 --- a/src/main/java/dev/latvian/mods/kubejs/KubeJSTypeWrappers.java +++ b/src/main/java/dev/latvian/mods/kubejs/KubeJSTypeWrappers.java @@ -1,9 +1,9 @@ package dev.latvian.mods.kubejs; +import dev.latvian.mods.kubejs.bindings.StringUtilsWrapper; import dev.latvian.mods.kubejs.level.LevelBlock; import dev.latvian.mods.kubejs.util.NBTUtils; import dev.latvian.mods.kubejs.util.RegistryAccessContainer; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import net.minecraft.core.BlockPos; import net.minecraft.util.valueproviders.ClampedInt; @@ -130,7 +130,7 @@ static Vec3 vec3Of(@Nullable Object o) { } else if (o instanceof Entity entity) { return entity.position(); } else if (o instanceof List list && list.size() >= 3) { - return new Vec3(UtilsJS.parseDouble(list.get(0), 0), UtilsJS.parseDouble(list.get(1), 0), UtilsJS.parseDouble(list.get(2), 0)); + return new Vec3(StringUtilsWrapper.parseDouble(list.get(0), 0), StringUtilsWrapper.parseDouble(list.get(1), 0), StringUtilsWrapper.parseDouble(list.get(2), 0)); } else if (o instanceof BlockPos pos) { return new Vec3(pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D); } else if (o instanceof LevelBlock block) { @@ -144,7 +144,7 @@ static BlockPos blockPosOf(@Nullable Object o) { if (o instanceof BlockPos pos) { return pos; } else if (o instanceof List list && list.size() >= 3) { - return new BlockPos(UtilsJS.parseInt(list.get(0), 0), UtilsJS.parseInt(list.get(1), 0), UtilsJS.parseInt(list.get(2), 0)); + return new BlockPos(StringUtilsWrapper.parseInt(list.get(0), 0), StringUtilsWrapper.parseInt(list.get(1), 0), StringUtilsWrapper.parseInt(list.get(2), 0)); } else if (o instanceof LevelBlock block) { return block.getPos(); } else if (o instanceof Vec3 vec) { @@ -156,7 +156,7 @@ static BlockPos blockPosOf(@Nullable Object o) { private static UniformInt parseIntBounds(Map m) { if (m.get("bounds") instanceof List bounds) { - return UniformInt.of(UtilsJS.parseInt(bounds.get(0), 0), UtilsJS.parseInt(bounds.get(1), 0)); + return UniformInt.of(StringUtilsWrapper.parseInt(bounds.get(0), 0), StringUtilsWrapper.parseInt(bounds.get(1), 0)); } else if (m.containsKey("min") && m.containsKey("max")) { return UniformInt.of(((Number) m.get("min")).intValue(), ((Number) m.get("max")).intValue()); } else if (m.containsKey("min_inclusive") && m.containsKey("max_inclusive")) { @@ -170,7 +170,7 @@ private static UniformInt parseIntBounds(Map m) { private static UniformFloat parseFloatBounds(Map m) { if (m.get("bounds") instanceof List bounds) { - return UniformFloat.of((float) UtilsJS.parseDouble(bounds.get(0), 0), (float) UtilsJS.parseDouble(bounds.get(1), 0)); + return UniformFloat.of((float) StringUtilsWrapper.parseDouble(bounds.get(0), 0), (float) StringUtilsWrapper.parseDouble(bounds.get(1), 0)); } else if (m.containsKey("min") && m.containsKey("max")) { return UniformFloat.of(((Number) m.get("min")).floatValue(), ((Number) m.get("max")).floatValue()); } else if (m.containsKey("min_inclusive") && m.containsKey("max_inclusive")) { diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/JavaWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/JavaWrapper.java index 4ac3dd05d..2c2584b36 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/JavaWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/JavaWrapper.java @@ -3,6 +3,11 @@ import dev.latvian.mods.kubejs.script.ConsoleJS; import dev.latvian.mods.kubejs.script.KubeJSContext; import dev.latvian.mods.kubejs.typings.Info; +import dev.latvian.mods.kubejs.util.Cast; +import dev.latvian.mods.rhino.BaseFunction; +import dev.latvian.mods.rhino.Context; +import dev.latvian.mods.rhino.type.TypeInfo; +import dev.latvian.mods.rhino.util.HideFromJS; import org.jetbrains.annotations.Nullable; import org.slf4j.LoggerFactory; @@ -31,4 +36,18 @@ static Object tryLoadClass(KubeJSContext cx, String className) { static ConsoleJS createConsole(KubeJSContext cx, String name) { return new ConsoleJS(cx.getType(), LoggerFactory.getLogger(name)); } + + static T makeFunctionProxy(Context cx, TypeInfo targetClass, BaseFunction function) { + return Cast.to(cx.createInterfaceAdapter(targetClass, function)); + } + + @Nullable + @HideFromJS + static Class tryLoadClass(String className) { + try { + return Class.forName(className); + } catch (Exception ignored) { + return null; + } + } } diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/StringUtilsWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/StringUtilsWrapper.java new file mode 100644 index 000000000..3c53a33ac --- /dev/null +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/StringUtilsWrapper.java @@ -0,0 +1,156 @@ +package dev.latvian.mods.kubejs.bindings; + +import com.google.gson.JsonElement; +import dev.latvian.mods.kubejs.typings.Info; +import dev.latvian.mods.kubejs.util.JsonIO; +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.StringJoiner; +import java.util.function.Function; +import java.util.regex.Pattern; + +public interface StringUtilsWrapper { + Pattern SNAKE_CASE_SPLIT = Pattern.compile("[:_/]"); + Set ALWAYS_LOWER_CASE = new HashSet<>(Arrays.asList("a", "an", "the", "of", "on", "in", "and", "or", "but", "for")); + String[] EMPTY_STRING_ARRAY = new String[0]; + + @Info("Tries to parse the first parameter as an integer, and returns that. The second parameter is returned if parsing fails") + static int parseInt(@Nullable Object object, int def) { + if (object == null) { + return def; + } else if (object instanceof Number num) { + return num.intValue(); + } + + try { + var s = object.toString(); + + if (s.isEmpty()) { + return def; + } + + return Integer.parseInt(s); + } catch (Exception ex) { + return def; + } + } + + static long parseLong(@Nullable Object object, long def) { + if (object == null) { + return def; + } else if (object instanceof Number num) { + return num.longValue(); + } + + try { + var s = object.toString(); + + if (s.isEmpty()) { + return def; + } + + return Long.parseLong(s); + } catch (Exception ex) { + return def; + } + } + + @Info("Tries to parse the first parameter as a double and returns that. The second parameter is returned if parsing fails") + static double parseDouble(@Nullable Object object, double def) { + if (object == null) { + return def; + } else if (object instanceof Number num) { + return num.doubleValue(); + } + + try { + var s = object.toString(); + + if (s.isEmpty()) { + return def; + } + + return Double.parseDouble(String.valueOf(object)); + } catch (Exception ex) { + return def; + } + } + + @Info("Returns the provided snake_case_string in camelCase") + static String snakeCaseToCamelCase(String string) { + if (string == null || string.isEmpty()) { + return string; + } + + var s = SNAKE_CASE_SPLIT.split(string, 0); + + var sb = new StringBuilder(); + var first = true; + + for (var value : s) { + if (!value.isEmpty()) { + if (first) { + first = false; + sb.append(value); + } else { + sb.append(Character.toUpperCase(value.charAt(0))); + sb.append(value, 1, value.length()); + } + } + } + + return sb.toString(); + } + + @Info("Returns the provided snake_case_string in Title Case") + static String snakeCaseToTitleCase(String string) { + StringJoiner joiner = new StringJoiner(" "); + String[] split = string.split("_"); + for (int i = 0; i < split.length; i++) { + String s = split[i]; + String titleCase = toTitleCase(s, i == 0); + joiner.add(titleCase); + } + return joiner.toString(); + } + + @Info("Capitalises the first letter of the string unless it is \"a\", \"an\", \"the\", \"of\", \"on\", \"in\", \"and\", \"or\", \"but\" or \"for\"") + static String toTitleCase(String s) { + return toTitleCase(s, false); + } + + @Info("Capitalises the first letter of the string. If ignoreSpecial is true, it will also capitalise articles and prepositions") + static String toTitleCase(String s, boolean ignoreSpecial) { + if (s.isEmpty()) { + return ""; + } else if (!ignoreSpecial && ALWAYS_LOWER_CASE.contains(s)) { + return s; + } else if (s.length() == 1) { + return s.toUpperCase(); + } + + char[] chars = s.toCharArray(); + chars[0] = Character.toUpperCase(chars[0]); + return new String(chars); + } + + static String stripIdForEvent(ResourceLocation id) { + return stripEventName(id.toString()); + } + + static String getUniqueId(JsonElement json) { + return getUniqueId(json, Function.identity()); + } + + static String getUniqueId(T input, Function toJson) { + return JsonIO.getJsonHashString(toJson.apply(input)); + } + + static String stripEventName(String s) { + return s.replaceAll("[/:]", ".").replace('-', '_'); + } +} diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/TextWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/TextWrapper.java index 5cbe558c2..86f625d16 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/TextWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/TextWrapper.java @@ -7,8 +7,6 @@ import dev.latvian.mods.kubejs.typings.Info; import dev.latvian.mods.kubejs.util.JSObjectType; import dev.latvian.mods.kubejs.util.JsonUtils; -import dev.latvian.mods.kubejs.util.ListJS; -import dev.latvian.mods.kubejs.util.MapJS; import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import net.minecraft.nbt.NbtOps; @@ -74,7 +72,7 @@ static MutableComponent of(Context cx, @Nullable Object o) { for (var e1 : a) { with[i] = e1; - if (with[i] instanceof MapJS || with[i] instanceof ListJS) { + if (with[i] instanceof Map || with[i] instanceof Collection) { with[i] = of(cx, e1); } @@ -148,7 +146,8 @@ static ClickEvent clickEventOf(Context cx, Object o) { return ce; } - var json = MapJS.json(cx, o); + var json = JsonUtils.objectOf(cx, o); + if (json != null) { var action = GsonHelper.getAsString(json, "action"); var value = GsonHelper.getAsString(json, "value"); diff --git a/src/main/java/dev/latvian/mods/kubejs/bindings/UtilsWrapper.java b/src/main/java/dev/latvian/mods/kubejs/bindings/UtilsWrapper.java index d5c0b24ac..beae2c761 100644 --- a/src/main/java/dev/latvian/mods/kubejs/bindings/UtilsWrapper.java +++ b/src/main/java/dev/latvian/mods/kubejs/bindings/UtilsWrapper.java @@ -74,16 +74,6 @@ static Pattern regex(String pattern, int flags) { return Pattern.compile(pattern, flags); } - @Info("Tries to parse the first parameter as an integer, and returns that. The second parameter is returned if parsing fails") - static int parseInt(@Nullable Object object, int def) { - return UtilsJS.parseInt(object, def); - } - - @Info("Tries to parse the first parameter as a double and returns that. The second parameter is returned if parsing fails") - static double parseDouble(@Nullable Object object, double def) { - return UtilsJS.parseDouble(object, def); - } - @Info(""" Returns a Stat of the passed in ResourceLocation. Note that this requires the same ResourceLocation to get the same stat, so should not be used unless you want to make your own stat, and are storing an actual ResourceLocation somewhere to access it. @@ -121,16 +111,6 @@ static boolean isWrapped(@Nullable Object o) { return o instanceof WrappedJS; } - @Info("Capitalises the first letter of the string unless it is \"a\", \"an\", \"the\", \"of\", \"on\", \"in\", \"and\", \"or\", \"but\" or \"for\"") - static String toTitleCase(String s) { - return UtilsJS.toTitleCase(s); - } - - @Info("Capitalises the first letter of the string. If ignoreSpecial is true, it will also capitalise articles and prepositions") - static String toTitleCase(String s, boolean ignoreSpecial) { - return UtilsJS.toTitleCase(s, ignoreSpecial); - } - @Info("Returns a lazy value with the supplier function as its value factory") static Lazy lazy(Supplier supplier) { return Lazy.of(supplier); @@ -156,14 +136,4 @@ static CompletableFuture runAsync(Runnable task) { static CompletableFuture supplyAsync(Supplier task) { return CompletableFuture.supplyAsync(task, Util.backgroundExecutor()); } - - @Info("Returns the provided snake_case_string in camelCase") - static String snakeCaseToCamelCase(String string) { - return UtilsJS.snakeCaseToCamelCase(string); - } - - @Info("Returns the provided snake_case_string in Title Case") - static String snakeCaseToTitleCase(String string) { - return UtilsJS.snakeCaseToTitleCase(string); - } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/block/BlockBuilder.java b/src/main/java/dev/latvian/mods/kubejs/block/BlockBuilder.java index 3cd78138f..faa60b905 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/BlockBuilder.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/BlockBuilder.java @@ -2,15 +2,15 @@ import com.mojang.serialization.JsonOps; import dev.latvian.mods.kubejs.bindings.AABBWrapper; -import dev.latvian.mods.kubejs.block.callbacks.AfterEntityFallenOnBlockCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.BlockExplodedCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.BlockStateMirrorCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.BlockStateModifyCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.BlockStateModifyPlacementCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.BlockStateRotateCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.CanBeReplacedCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.EntityFallenOnBlockCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.EntitySteppedOnBlockCallbackJS; +import dev.latvian.mods.kubejs.block.callback.AfterEntityFallenOnBlockCallback; +import dev.latvian.mods.kubejs.block.callback.BlockExplodedCallback; +import dev.latvian.mods.kubejs.block.callback.BlockStateMirrorCallback; +import dev.latvian.mods.kubejs.block.callback.BlockStateModifyCallback; +import dev.latvian.mods.kubejs.block.callback.BlockStateModifyPlacementCallback; +import dev.latvian.mods.kubejs.block.callback.BlockStateRotateCallback; +import dev.latvian.mods.kubejs.block.callback.CanBeReplacedCallback; +import dev.latvian.mods.kubejs.block.callback.EntityFallenOnBlockCallback; +import dev.latvian.mods.kubejs.block.callback.EntitySteppedOnBlockCallback; import dev.latvian.mods.kubejs.block.drop.BlockDropSupplier; import dev.latvian.mods.kubejs.block.drop.BlockDrops; import dev.latvian.mods.kubejs.block.entity.BlockEntityBuilder; @@ -97,15 +97,15 @@ public abstract class BlockBuilder extends ModelledBuilderBase { public transient boolean transparent; public transient NoteBlockInstrument instrument; public transient Set> blockStateProperties; - public transient Consumer defaultStateModification; - public transient Consumer placementStateModification; - public transient Predicate canBeReplacedFunction; - public transient Consumer stepOnCallback; - public transient Consumer fallOnCallback; - public transient Consumer afterFallenOnCallback; - public transient Consumer explodedCallback; - public transient Consumer rotateStateModification; - public transient Consumer mirrorStateModification; + public transient Consumer defaultStateModification; + public transient Consumer placementStateModification; + public transient Predicate canBeReplacedFunction; + public transient Consumer stepOnCallback; + public transient Consumer fallOnCallback; + public transient Consumer afterFallenOnCallback; + public transient Consumer explodedCallback; + public transient Consumer rotateStateModification; + public transient Consumer mirrorStateModification; public transient Consumer rightClick; public transient BlockEntityInfo blockEntityInfo; @@ -656,19 +656,19 @@ public BlockBuilder tagItem(ResourceLocation[] tag) { } @Info("Set the default state of the block.") - public BlockBuilder defaultState(Consumer callbackJS) { + public BlockBuilder defaultState(Consumer callbackJS) { defaultStateModification = callbackJS; return this; } @Info("Set the callback for determining the blocks state when placed.") - public BlockBuilder placementState(Consumer callbackJS) { + public BlockBuilder placementState(Consumer callbackJS) { placementStateModification = callbackJS; return this; } @Info("Set if the block can be replaced by something else.") - public BlockBuilder canBeReplaced(Predicate callbackJS) { + public BlockBuilder canBeReplaced(Predicate callbackJS) { canBeReplacedFunction = callbackJS; return this; } @@ -677,13 +677,13 @@ public BlockBuilder canBeReplaced(Predicate callbackJS) Set what happens when an entity steps on the block This is called every tick for every entity standing on the block, so be careful what you do here. """) - public BlockBuilder steppedOn(Consumer callbackJS) { + public BlockBuilder steppedOn(Consumer callbackJS) { stepOnCallback = callbackJS; return this; } @Info("Set what happens when an entity falls on the block. Do not use this for moving them, use bounce instead!") - public BlockBuilder fallenOn(Consumer callbackJS) { + public BlockBuilder fallenOn(Consumer callbackJS) { fallOnCallback = callbackJS; return this; } @@ -700,13 +700,13 @@ public BlockBuilder bounciness(float bounciness) { Set how this block bounces/moves entities that land on top of this. Do not use this to modify the block, use fallOn instead! Use ctx.bounce(height) or ctx.setVelocity(x, y, z) to change the entities velocity. """) - public BlockBuilder afterFallenOn(Consumer callbackJS) { + public BlockBuilder afterFallenOn(Consumer callbackJS) { afterFallenOnCallback = callbackJS; return this; } @Info("Set how this block reacts after an explosion. Note the block has already been destroyed at this point") - public BlockBuilder exploded(Consumer callbackJS) { + public BlockBuilder exploded(Consumer callbackJS) { explodedCallback = callbackJS; return this; } @@ -725,13 +725,13 @@ public BlockBuilder property(Property property) { } @Info("Set the callback used for determining how the block rotates") - public BlockBuilder rotateState(Consumer callbackJS) { + public BlockBuilder rotateState(Consumer callbackJS) { rotateStateModification = callbackJS; return this; } @Info("Set the callback used for determining how the block is mirrored") - public BlockBuilder mirrorState(Consumer callbackJS) { + public BlockBuilder mirrorState(Consumer callbackJS) { mirrorStateModification = callbackJS; return this; } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/AfterEntityFallenOnBlockCallbackJS.java b/src/main/java/dev/latvian/mods/kubejs/block/callback/AfterEntityFallenOnBlockCallback.java similarity index 86% rename from src/main/java/dev/latvian/mods/kubejs/block/callbacks/AfterEntityFallenOnBlockCallbackJS.java rename to src/main/java/dev/latvian/mods/kubejs/block/callback/AfterEntityFallenOnBlockCallback.java index 5b4b50c3b..2a19225f6 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/AfterEntityFallenOnBlockCallbackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/callback/AfterEntityFallenOnBlockCallback.java @@ -1,4 +1,4 @@ -package dev.latvian.mods.kubejs.block.callbacks; +package dev.latvian.mods.kubejs.block.callback; import dev.latvian.mods.kubejs.typings.Info; import dev.latvian.mods.rhino.util.HideFromJS; @@ -6,10 +6,10 @@ import net.minecraft.world.level.BlockGetter; import net.minecraft.world.phys.Vec3; -public class AfterEntityFallenOnBlockCallbackJS extends EntitySteppedOnBlockCallbackJS { +public class AfterEntityFallenOnBlockCallback extends EntitySteppedOnBlockCallback { private boolean hasChangedVelocity; - public AfterEntityFallenOnBlockCallbackJS(BlockGetter blockGetter, Entity entity) { + public AfterEntityFallenOnBlockCallback(BlockGetter blockGetter, Entity entity) { super(entity.level(), entity, entity.getOnPos(), blockGetter.getBlockState(entity.getOnPos())); this.hasChangedVelocity = false; } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockExplodedCallbackJS.java b/src/main/java/dev/latvian/mods/kubejs/block/callback/BlockExplodedCallback.java similarity index 87% rename from src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockExplodedCallbackJS.java rename to src/main/java/dev/latvian/mods/kubejs/block/callback/BlockExplodedCallback.java index dcf10fae7..30b947da7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockExplodedCallbackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/callback/BlockExplodedCallback.java @@ -1,4 +1,4 @@ -package dev.latvian.mods.kubejs.block.callbacks; +package dev.latvian.mods.kubejs.block.callback; import dev.latvian.mods.kubejs.level.LevelBlock; import net.minecraft.core.BlockPos; @@ -12,11 +12,11 @@ import java.util.List; -public class BlockExplodedCallbackJS { +public class BlockExplodedCallback { protected final LevelBlock block; protected final Explosion explosion; - public BlockExplodedCallbackJS(Level level, BlockPos pos, Explosion explosion) { + public BlockExplodedCallback(Level level, BlockPos pos, Explosion explosion) { this.block = level.kjs$getBlock(pos); this.explosion = explosion; } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateMirrorCallbackJS.java b/src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateMirrorCallback.java similarity index 78% rename from src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateMirrorCallbackJS.java rename to src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateMirrorCallback.java index 28c1e8759..35980db09 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateMirrorCallbackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateMirrorCallback.java @@ -1,4 +1,4 @@ -package dev.latvian.mods.kubejs.block.callbacks; +package dev.latvian.mods.kubejs.block.callback; import dev.latvian.mods.kubejs.typings.Info; import dev.latvian.mods.rhino.util.HideFromJS; @@ -7,11 +7,11 @@ import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.state.BlockState; -public class BlockStateMirrorCallbackJS extends BlockStateModifyCallbackJS { +public class BlockStateMirrorCallback extends BlockStateModifyCallback { private final Mirror mirror; - public BlockStateMirrorCallbackJS(BlockState state, Mirror mirror) { + public BlockStateMirrorCallback(BlockState state, Mirror mirror) { super(state); this.mirror = mirror; @@ -24,7 +24,7 @@ public Direction mirror(Direction dir) { @HideFromJS // I banish thee ambiguity to the depths of Rhino, never to be seen again! @Override - public BlockStateModifyCallbackJS mirror(Mirror mirror) { + public BlockStateModifyCallback mirror(Mirror mirror) { throw new IllegalCallerException("Do not call this or you will get stuck in a loop!"); } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateModifyCallbackJS.java b/src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateModifyCallback.java similarity index 78% rename from src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateModifyCallbackJS.java rename to src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateModifyCallback.java index 3b07fe14c..124ba4982 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateModifyCallbackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateModifyCallback.java @@ -1,4 +1,4 @@ -package dev.latvian.mods.kubejs.block.callbacks; +package dev.latvian.mods.kubejs.block.callback; import dev.latvian.mods.kubejs.typings.Info; import net.minecraft.core.BlockPos; @@ -17,15 +17,15 @@ import java.util.Map; import java.util.Optional; -public class BlockStateModifyCallbackJS { +public class BlockStateModifyCallback { private BlockState state; - public BlockStateModifyCallbackJS(BlockState state) { + public BlockStateModifyCallback(BlockState state) { this.state = state; } @Info("Cycles the property") - public > BlockStateModifyCallbackJS cycle(Property property) { + public > BlockStateModifyCallback cycle(Property property) { this.state = state.cycle(property); return this; } @@ -66,30 +66,30 @@ public > Optional getOptionalValue(Property proper } @Info("Sets the value of the specified property") - public , V extends T> BlockStateModifyCallbackJS setValue(Property property, V comparable) { + public , V extends T> BlockStateModifyCallback setValue(Property property, V comparable) { this.state = state.setValue(property, comparable); return this; } @Info("Sets the value of the specified boolean property") - public BlockStateModifyCallbackJS set(BooleanProperty property, boolean value) { + public BlockStateModifyCallback set(BooleanProperty property, boolean value) { this.state = state.setValue(property, value); return this; } @Info("Sets the value of the specified integer property") - public BlockStateModifyCallbackJS set(IntegerProperty property, Integer value) { + public BlockStateModifyCallback set(IntegerProperty property, Integer value) { this.state = state.setValue(property, value); return this; } @Info("Sets the value of the specified enum property") - public & StringRepresentable> BlockStateModifyCallbackJS set(EnumProperty property, String value) { + public & StringRepresentable> BlockStateModifyCallback set(EnumProperty property, String value) { this.state = state.setValue(property, property.getValue(value).get()); return this; } - public BlockStateModifyCallbackJS populateNeighbours(Map, Comparable>, BlockState> map) { + public BlockStateModifyCallback populateNeighbours(Map, Comparable>, BlockState> map) { state.populateNeighbours(map); return this; } @@ -100,19 +100,19 @@ public Map, Comparable> getValues() { } @Info("Rotate the block using the specified Rotation") - public BlockStateModifyCallbackJS rotate(Rotation rotation) { + public BlockStateModifyCallback rotate(Rotation rotation) { this.state = state.rotate(rotation); return this; } @Info("Mirror the block using the specified Mirror") - public BlockStateModifyCallbackJS mirror(Mirror mirror) { + public BlockStateModifyCallback mirror(Mirror mirror) { this.state = state.mirror(mirror); return this; } @Info("Updates the shape of this block. Mostly used in waterloggable blocks to update the water flow") - public BlockStateModifyCallbackJS updateShape(Direction direction, BlockState blockState, LevelAccessor levelAccessor, BlockPos blockPos, BlockPos blockPos2) { + public BlockStateModifyCallback updateShape(Direction direction, BlockState blockState, LevelAccessor levelAccessor, BlockPos blockPos, BlockPos blockPos2) { this.state = state.updateShape(direction, blockState, levelAccessor, blockPos, blockPos2); return this; } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateModifyPlacementCallbackJS.java b/src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateModifyPlacementCallback.java similarity index 93% rename from src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateModifyPlacementCallbackJS.java rename to src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateModifyPlacementCallback.java index bf20a7300..783467dd5 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateModifyPlacementCallbackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateModifyPlacementCallback.java @@ -1,4 +1,4 @@ -package dev.latvian.mods.kubejs.block.callbacks; +package dev.latvian.mods.kubejs.block.callback; import dev.latvian.mods.kubejs.level.LevelBlock; import dev.latvian.mods.kubejs.typings.Info; @@ -18,12 +18,12 @@ import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; -public class BlockStateModifyPlacementCallbackJS extends BlockStateModifyCallbackJS { +public class BlockStateModifyPlacementCallback extends BlockStateModifyCallback { public final BlockPlaceContext context; public final Block minecraftBlock; public LevelBlock block; - public BlockStateModifyPlacementCallbackJS(BlockPlaceContext context, Block block) { + public BlockStateModifyPlacementCallback(BlockPlaceContext context, Block block) { super(getBlockStateToModify(context, block)); this.context = context; this.minecraftBlock = block; @@ -135,13 +135,13 @@ public boolean isClickedPosIn(Fluid fluid) { } @Info("Set if this block is waterlogged or not") - public BlockStateModifyPlacementCallbackJS waterlogged(boolean waterlogged) { + public BlockStateModifyPlacementCallback waterlogged(boolean waterlogged) { setValue(BlockStateProperties.WATERLOGGED, waterlogged); return this; } @Info("Set this block as waterlogged if it is in water") - public BlockStateModifyPlacementCallbackJS waterlogged() { + public BlockStateModifyPlacementCallback waterlogged() { return waterlogged(isInWater()); } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateRotateCallbackJS.java b/src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateRotateCallback.java similarity index 72% rename from src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateRotateCallbackJS.java rename to src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateRotateCallback.java index 9f7eaf5e0..f3b5e197d 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/BlockStateRotateCallbackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/callback/BlockStateRotateCallback.java @@ -1,4 +1,4 @@ -package dev.latvian.mods.kubejs.block.callbacks; +package dev.latvian.mods.kubejs.block.callback; import dev.latvian.mods.kubejs.typings.Info; import dev.latvian.mods.rhino.util.HideFromJS; @@ -6,11 +6,11 @@ import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.state.BlockState; -public class BlockStateRotateCallbackJS extends BlockStateModifyCallbackJS { +public class BlockStateRotateCallback extends BlockStateModifyCallback { private final Rotation rotation; - public BlockStateRotateCallbackJS(BlockState state, Rotation rotation) { + public BlockStateRotateCallback(BlockState state, Rotation rotation) { super(state); this.rotation = rotation; } @@ -22,7 +22,7 @@ public Direction rotate(Direction dir) { @HideFromJS // begone ambiguity! @Override - public BlockStateModifyCallbackJS rotate(Rotation rotation) { + public BlockStateModifyCallback rotate(Rotation rotation) { throw new IllegalCallerException("Do not call this or you will get stuck in a loop!"); } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/CanBeReplacedCallbackJS.java b/src/main/java/dev/latvian/mods/kubejs/block/callback/CanBeReplacedCallback.java similarity index 92% rename from src/main/java/dev/latvian/mods/kubejs/block/callbacks/CanBeReplacedCallbackJS.java rename to src/main/java/dev/latvian/mods/kubejs/block/callback/CanBeReplacedCallback.java index 4fa6dc145..d0ca3bf11 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/CanBeReplacedCallbackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/callback/CanBeReplacedCallback.java @@ -1,4 +1,4 @@ -package dev.latvian.mods.kubejs.block.callbacks; +package dev.latvian.mods.kubejs.block.callback; import dev.latvian.mods.kubejs.level.LevelBlock; import net.minecraft.core.BlockPos; @@ -14,11 +14,11 @@ import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; -public class CanBeReplacedCallbackJS { +public class CanBeReplacedCallback { private final BlockPlaceContext context; - public CanBeReplacedCallbackJS(BlockPlaceContext blockPlaceContext, BlockState state) { + public CanBeReplacedCallback(BlockPlaceContext blockPlaceContext, BlockState state) { context = blockPlaceContext; } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/EntityFallenOnBlockCallbackJS.java b/src/main/java/dev/latvian/mods/kubejs/block/callback/EntityFallenOnBlockCallback.java similarity index 87% rename from src/main/java/dev/latvian/mods/kubejs/block/callbacks/EntityFallenOnBlockCallbackJS.java rename to src/main/java/dev/latvian/mods/kubejs/block/callback/EntityFallenOnBlockCallback.java index 5b2d0e412..75b4e8d3b 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/EntityFallenOnBlockCallbackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/callback/EntityFallenOnBlockCallback.java @@ -1,4 +1,4 @@ -package dev.latvian.mods.kubejs.block.callbacks; +package dev.latvian.mods.kubejs.block.callback; import dev.latvian.mods.kubejs.typings.Info; import net.minecraft.core.BlockPos; @@ -7,11 +7,11 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -public class EntityFallenOnBlockCallbackJS extends EntitySteppedOnBlockCallbackJS { +public class EntityFallenOnBlockCallback extends EntitySteppedOnBlockCallback { private final float fallHeight; - public EntityFallenOnBlockCallbackJS(Level level, Entity entity, BlockPos pos, BlockState state, float fallHeight) { + public EntityFallenOnBlockCallback(Level level, Entity entity, BlockPos pos, BlockState state, float fallHeight) { super(level, entity, pos, state); this.fallHeight = fallHeight; } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/EntitySteppedOnBlockCallbackJS.java b/src/main/java/dev/latvian/mods/kubejs/block/callback/EntitySteppedOnBlockCallback.java similarity index 85% rename from src/main/java/dev/latvian/mods/kubejs/block/callbacks/EntitySteppedOnBlockCallbackJS.java rename to src/main/java/dev/latvian/mods/kubejs/block/callback/EntitySteppedOnBlockCallback.java index d1c5be94b..c82e1b7d8 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/callbacks/EntitySteppedOnBlockCallbackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/callback/EntitySteppedOnBlockCallback.java @@ -1,4 +1,4 @@ -package dev.latvian.mods.kubejs.block.callbacks; +package dev.latvian.mods.kubejs.block.callback; import dev.latvian.mods.kubejs.level.LevelBlock; import dev.latvian.mods.kubejs.typings.Info; @@ -7,13 +7,13 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -public class EntitySteppedOnBlockCallbackJS { +public class EntitySteppedOnBlockCallback { protected final Level level; protected final Entity entity; protected final LevelBlock block; protected final BlockState state; - public EntitySteppedOnBlockCallbackJS(Level level, Entity entity, BlockPos pos, BlockState state) { + public EntitySteppedOnBlockCallback(Level level, Entity entity, BlockPos pos, BlockState state) { this.level = level; this.entity = entity; this.block = level.kjs$getBlock(pos); diff --git a/src/main/java/dev/latvian/mods/kubejs/block/custom/BasicBlockJS.java b/src/main/java/dev/latvian/mods/kubejs/block/custom/BasicBlockJS.java index 99665c55e..83f6e1669 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/custom/BasicBlockJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/custom/BasicBlockJS.java @@ -4,15 +4,15 @@ import dev.latvian.mods.kubejs.block.BlockRightClickedKubeEvent; import dev.latvian.mods.kubejs.block.KubeJSBlockProperties; import dev.latvian.mods.kubejs.block.RandomTickCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.AfterEntityFallenOnBlockCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.BlockExplodedCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.BlockStateMirrorCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.BlockStateModifyCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.BlockStateModifyPlacementCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.BlockStateRotateCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.CanBeReplacedCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.EntityFallenOnBlockCallbackJS; -import dev.latvian.mods.kubejs.block.callbacks.EntitySteppedOnBlockCallbackJS; +import dev.latvian.mods.kubejs.block.callback.AfterEntityFallenOnBlockCallback; +import dev.latvian.mods.kubejs.block.callback.BlockExplodedCallback; +import dev.latvian.mods.kubejs.block.callback.BlockStateMirrorCallback; +import dev.latvian.mods.kubejs.block.callback.BlockStateModifyCallback; +import dev.latvian.mods.kubejs.block.callback.BlockStateModifyPlacementCallback; +import dev.latvian.mods.kubejs.block.callback.BlockStateRotateCallback; +import dev.latvian.mods.kubejs.block.callback.CanBeReplacedCallback; +import dev.latvian.mods.kubejs.block.callback.EntityFallenOnBlockCallback; +import dev.latvian.mods.kubejs.block.callback.EntitySteppedOnBlockCallback; import dev.latvian.mods.kubejs.block.entity.KubeBlockEntity; import dev.latvian.mods.kubejs.script.ScriptType; import net.minecraft.core.BlockPos; @@ -96,7 +96,7 @@ public BasicBlockJS(BlockBuilder p) { var blockState = stateDefinition.any(); if (blockBuilder.defaultStateModification != null) { - var callbackJS = new BlockStateModifyCallbackJS(blockState); + var callbackJS = new BlockStateModifyCallback(blockState); if (safeCallback(blockBuilder.defaultStateModification, callbackJS, "Error while creating default blockState for block " + p.id)) { registerDefaultState(callbackJS.getState()); } @@ -136,7 +136,7 @@ public FluidState getFluidState(BlockState state) { @Override public BlockState getStateForPlacement(BlockPlaceContext context) { if (blockBuilder.placementStateModification != null) { - var callbackJS = new BlockStateModifyPlacementCallbackJS(context, this); + var callbackJS = new BlockStateModifyPlacementCallback(context, this); if (safeCallback(blockBuilder.placementStateModification, callbackJS, "Error while modifying BlockState placement of " + blockBuilder.id)) { return callbackJS.getState(); } @@ -152,7 +152,7 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { @Override public boolean canBeReplaced(BlockState blockState, BlockPlaceContext context) { if (blockBuilder.canBeReplacedFunction != null) { - var callbackJS = new CanBeReplacedCallbackJS(context, blockState); + var callbackJS = new CanBeReplacedCallback(context, blockState); return blockBuilder.canBeReplacedFunction.test(callbackJS); } return super.canBeReplaced(blockState, context); @@ -256,7 +256,7 @@ public Optional getPickupSound() { @Override public void stepOn(Level level, BlockPos blockPos, BlockState blockState, Entity entity) { if (blockBuilder.stepOnCallback != null) { - var callbackJS = new EntitySteppedOnBlockCallbackJS(level, entity, blockPos, blockState); + var callbackJS = new EntitySteppedOnBlockCallback(level, entity, blockPos, blockState); safeCallback(blockBuilder.stepOnCallback, callbackJS, "Error while an entity stepped on custom block "); } else { super.stepOn(level, blockPos, blockState, entity); @@ -266,7 +266,7 @@ public void stepOn(Level level, BlockPos blockPos, BlockState blockState, Entity @Override public void fallOn(Level level, BlockState blockState, BlockPos blockPos, Entity entity, float f) { if (blockBuilder.fallOnCallback != null) { - var callbackJS = new EntityFallenOnBlockCallbackJS(level, entity, blockPos, blockState, f); + var callbackJS = new EntityFallenOnBlockCallback(level, entity, blockPos, blockState, f); safeCallback(blockBuilder.fallOnCallback, callbackJS, "Error while an entity fell on custom block "); } else { super.fallOn(level, blockState, blockPos, entity, f); @@ -276,7 +276,7 @@ public void fallOn(Level level, BlockState blockState, BlockPos blockPos, Entity @Override public void updateEntityAfterFallOn(BlockGetter blockGetter, Entity entity) { if (blockBuilder.afterFallenOnCallback != null) { - var callbackJS = new AfterEntityFallenOnBlockCallbackJS(blockGetter, entity); + var callbackJS = new AfterEntityFallenOnBlockCallback(blockGetter, entity); safeCallback(blockBuilder.afterFallenOnCallback, callbackJS, "Error while bouncing entity from custom block "); // if they did not change the entity's velocity, then use the default method to reset the velocity. if (!callbackJS.hasChangedVelocity()) { @@ -290,7 +290,7 @@ public void updateEntityAfterFallOn(BlockGetter blockGetter, Entity entity) { @Override public void wasExploded(Level level, BlockPos blockPos, Explosion explosion) { if (blockBuilder.explodedCallback != null) { - var callbackJS = new BlockExplodedCallbackJS(level, blockPos, explosion); + var callbackJS = new BlockExplodedCallback(level, blockPos, explosion); safeCallback(blockBuilder.explodedCallback, callbackJS, "Error while exploding custom block "); } else { super.wasExploded(level, blockPos, explosion); @@ -300,7 +300,7 @@ public void wasExploded(Level level, BlockPos blockPos, Explosion explosion) { @Override public BlockState rotate(BlockState blockState, Rotation rotation) { if (blockBuilder.rotateStateModification != null) { - var callbackJS = new BlockStateRotateCallbackJS(blockState, rotation); + var callbackJS = new BlockStateRotateCallback(blockState, rotation); if (safeCallback(blockBuilder.rotateStateModification, callbackJS, "Error while rotating BlockState of ")) { return callbackJS.getState(); } @@ -312,7 +312,7 @@ public BlockState rotate(BlockState blockState, Rotation rotation) { @Override public BlockState mirror(BlockState blockState, Mirror mirror) { if (blockBuilder.mirrorStateModification != null) { - var callbackJS = new BlockStateMirrorCallbackJS(blockState, mirror); + var callbackJS = new BlockStateMirrorCallback(blockState, mirror); if (safeCallback(blockBuilder.mirrorStateModification, callbackJS, "Error while mirroring BlockState of ")) { return callbackJS.getState(); } diff --git a/src/main/java/dev/latvian/mods/kubejs/block/state/BlockStatePredicate.java b/src/main/java/dev/latvian/mods/kubejs/block/state/BlockStatePredicate.java index 7a4cfbeff..dd4bc5321 100644 --- a/src/main/java/dev/latvian/mods/kubejs/block/state/BlockStatePredicate.java +++ b/src/main/java/dev/latvian/mods/kubejs/block/state/BlockStatePredicate.java @@ -53,7 +53,7 @@ default RuleTest asRuleTest() { return null; } - static BlockStatePredicate fromString(RegistryAccessContainer registries, String s) { + static BlockStatePredicate fromString(Context cx, String s) { if (s.equals("*")) { return Simple.ALL; } else if (s.equals("-")) { @@ -61,7 +61,7 @@ static BlockStatePredicate fromString(RegistryAccessContainer registries, String } else if (s.startsWith("#")) { return new TagMatch(Tags.block(ResourceLocation.parse(s.substring(1)))); } else if (s.indexOf('[') != -1) { - var state = BlockWrapper.parseBlockState(registries, s); + var state = BlockWrapper.parseBlockState(RegistryAccessContainer.of(cx), s); if (state != Blocks.AIR.defaultBlockState()) { return new StateMatch(state); @@ -77,7 +77,7 @@ static BlockStatePredicate fromString(RegistryAccessContainer registries, String return Simple.NONE; } - static BlockStatePredicate of(RegistryAccessContainer registries, Object o) { + static BlockStatePredicate wrap(Context cx, Object o) { if (o == null || o == Simple.ALL) { return Simple.ALL; } else if (o == Simple.NONE) { @@ -85,13 +85,14 @@ static BlockStatePredicate of(RegistryAccessContainer registries, Object o) { } var list = ListJS.orSelf(o); + if (list.isEmpty()) { return Simple.NONE; } else if (list.size() > 1) { var predicates = new ArrayList(); for (var o1 : list) { - var p = of(registries, o1); + var p = wrap(cx, o1); if (p == Simple.ALL) { return Simple.ALL; } else if (p != Simple.NONE) { @@ -111,37 +112,37 @@ static BlockStatePredicate of(RegistryAccessContainer registries, Object o) { var predicates = new ArrayList(); if (map.get("or") != null) { - predicates.add(of(registries, map.get("or"))); + predicates.add(wrap(cx, map.get("or"))); } if (map.get("not") != null) { - predicates.add(new NotMatch(of(registries, map.get("not")))); + predicates.add(new NotMatch(wrap(cx, map.get("not")))); } return new AndMatch(predicates); } - return ofSingle(registries, o); + return ofSingle(cx, o); } - static RuleTest ruleTestOf(Context cx, Object o) { + static RuleTest wrapRuleTest(Context cx, Object o) { if (o instanceof RuleTest rule) { return rule; } else if (o instanceof BlockStatePredicate bsp && bsp.asRuleTest() != null) { return bsp.asRuleTest(); } - RegistryAccessContainer registries = RegistryAccessContainer.of(cx); + var nbt = RegistryAccessContainer.of(cx).nbt(); return Optional.ofNullable(NBTUtils.toTagCompound(cx, o)) - .map(tag -> RuleTest.CODEC.parse(registries.nbt(), tag)) + .map(tag -> RuleTest.CODEC.parse(nbt, tag)) .flatMap(DataResult::result) - .or(() -> Optional.ofNullable(of(registries, o).asRuleTest())) + .or(() -> Optional.ofNullable(wrap(cx, o).asRuleTest())) .orElseThrow(() -> new IllegalArgumentException("Could not parse valid rule test from " + o + "!")); } @SuppressWarnings("unchecked") - private static BlockStatePredicate ofSingle(RegistryAccessContainer registries, Object o) { + private static BlockStatePredicate ofSingle(Context cx, Object o) { if (o instanceof BlockStatePredicate bsp) { return bsp; } else if (o instanceof Block block) { @@ -153,7 +154,7 @@ private static BlockStatePredicate ofSingle(RegistryAccessContainer registries, } var pattern = RegExpKJS.wrap(o); - return pattern == null ? BlockStatePredicate.fromString(registries, o.toString()) : new RegexMatch(pattern); + return pattern == null ? BlockStatePredicate.fromString(cx, o.toString()) : new RegexMatch(pattern); } default Collection getBlockStates() { diff --git a/src/main/java/dev/latvian/mods/kubejs/item/ItemStackJS.java b/src/main/java/dev/latvian/mods/kubejs/item/ItemStackJS.java index f51aeba80..af56a38e4 100644 --- a/src/main/java/dev/latvian/mods/kubejs/item/ItemStackJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/item/ItemStackJS.java @@ -6,6 +6,7 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.JsonOps; +import dev.latvian.mods.kubejs.bindings.StringUtilsWrapper; import dev.latvian.mods.kubejs.component.DataComponentWrapper; import dev.latvian.mods.kubejs.error.KubeRuntimeException; import dev.latvian.mods.kubejs.ingredient.RegExIngredient; @@ -14,7 +15,6 @@ import dev.latvian.mods.kubejs.util.MapJS; import dev.latvian.mods.kubejs.util.RegExpKJS; import dev.latvian.mods.kubejs.util.RegistryAccessContainer; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Wrapper; import dev.latvian.mods.rhino.regexp.NativeRegExp; import dev.latvian.mods.rhino.type.TypeInfo; @@ -161,7 +161,7 @@ static ItemStack wrap(RegistryAccessContainer registries, @Nullable Object o) { var stack = Ingredient.of(ItemTags.create(ID.mc(map.get("tag")))).kjs$getFirst(); if (map.containsKey("count")) { - stack.setCount(UtilsJS.parseInt(map.get("count"), 1)); + stack.setCount(StringUtilsWrapper.parseInt(map.get("count"), 1)); } return stack; diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/CachedTagLookup.java b/src/main/java/dev/latvian/mods/kubejs/recipe/CachedTagLookup.java index 132d3ec93..fd0c11be5 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/CachedTagLookup.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/CachedTagLookup.java @@ -110,7 +110,7 @@ public Set values(TagKey key) { public boolean isEmpty(TagKey key) { var set = values(key); - // noinspection RedundantCast + // noinspection RedundantCast,rawtypes,SuspiciousMethodCalls return set.size() - ((ResourceKey) registry.key() == Registries.ITEM ? ((set.contains(Items.AIR) ? 1 : 0) + (set.contains(Items.BARRIER) ? 1 : 0)) : 0) <= 0; } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/KubeRecipe.java b/src/main/java/dev/latvian/mods/kubejs/recipe/KubeRecipe.java index 2b958c678..4375bae76 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/KubeRecipe.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/KubeRecipe.java @@ -5,6 +5,7 @@ import com.mojang.serialization.DataResult; import dev.latvian.mods.kubejs.CommonProperties; import dev.latvian.mods.kubejs.DevProperties; +import dev.latvian.mods.kubejs.bindings.StringUtilsWrapper; import dev.latvian.mods.kubejs.core.RecipeLikeKJS; import dev.latvian.mods.kubejs.error.KubeRuntimeException; import dev.latvian.mods.kubejs.error.MissingComponentException; @@ -25,7 +26,6 @@ import dev.latvian.mods.kubejs.util.Cast; import dev.latvian.mods.kubejs.util.KubeResourceLocation; import dev.latvian.mods.kubejs.util.SlotFilter; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.Scriptable; import dev.latvian.mods.rhino.Wrapper; @@ -408,7 +408,7 @@ public ResourceLocation getOrCreateId() { var prefix = js.id.getNamespace() + ":kjs/"; if (ids == null || ids.isEmpty()) { - ids = UtilsJS.getUniqueId(json); + ids = StringUtilsWrapper.getUniqueId(json); } else { ids = ids.replace(':', '_'); } diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeTypeFunction.java b/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeTypeFunction.java index d8177334e..2e74d6f65 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeTypeFunction.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/RecipeTypeFunction.java @@ -6,7 +6,7 @@ import dev.latvian.mods.kubejs.recipe.schema.RecipeSchemaType; import dev.latvian.mods.kubejs.script.ConsoleJS; import dev.latvian.mods.kubejs.script.SourceLine; -import dev.latvian.mods.kubejs.util.MapJS; +import dev.latvian.mods.kubejs.util.JsonUtils; import dev.latvian.mods.kubejs.util.WrappedJS; import dev.latvian.mods.rhino.BaseFunction; import dev.latvian.mods.rhino.Context; @@ -64,7 +64,7 @@ public KubeRecipe createRecipe(Context cx, SourceLine sourceLine, Object[] args) if (constructor == null) { if (args.length == 1 && (args[0] instanceof Map || args[0] instanceof JsonObject)) { - var recipe = schemaType.schema.deserialize(sourceLine, this, null, MapJS.json(cx, args[0])); + var recipe = schemaType.schema.deserialize(sourceLine, this, null, JsonUtils.objectOf(cx, args[0])); recipe.afterLoaded(); return event.addRecipe(recipe, true); // throw new RecipeExceptionJS("Use event.custom(json) for json recipes!"); diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/RecipesKubeEvent.java b/src/main/java/dev/latvian/mods/kubejs/recipe/RecipesKubeEvent.java index 3b1c638b3..630a2506e 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/RecipesKubeEvent.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/RecipesKubeEvent.java @@ -8,6 +8,7 @@ import com.mojang.serialization.DataResult; import dev.latvian.mods.kubejs.CommonProperties; import dev.latvian.mods.kubejs.DevProperties; +import dev.latvian.mods.kubejs.bindings.StringUtilsWrapper; import dev.latvian.mods.kubejs.bindings.event.ServerEvents; import dev.latvian.mods.kubejs.core.RecipeManagerKJS; import dev.latvian.mods.kubejs.error.InvalidRecipeComponentException; @@ -37,7 +38,6 @@ import dev.latvian.mods.kubejs.util.JsonUtils; import dev.latvian.mods.kubejs.util.RegistryAccessContainer; import dev.latvian.mods.kubejs.util.TimeJS; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.util.HideFromJS; import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; @@ -145,7 +145,7 @@ public RecipesKubeEvent(ServerScriptManager manager, ResourceManager resourceMan for (var entry : new ArrayList<>(recipeFunctions.entrySet())) { if (entry.getValue() instanceof RecipeTypeFunction && entry.getKey().indexOf(':') != -1) { - var s = UtilsJS.snakeCaseToCamelCase(entry.getKey()); + var s = StringUtilsWrapper.snakeCaseToCamelCase(entry.getKey()); if (!s.equals(entry.getKey())) { recipeFunctions.put(s, entry.getValue()); @@ -328,6 +328,8 @@ public void applyChanges(Map map) { .peek(this::addToExport) .collect(Collectors.toConcurrentMap(KubeRecipe::getOrCreateId, recipe -> recipe.json, (a, b) -> { ConsoleJS.SERVER.warn("KubeJS has found two recipes with the same ID in your custom recipes! Picking the last one encountered!"); + ConsoleJS.SERVER.warn("Recipe A JSON: " + a); + ConsoleJS.SERVER.warn("Recipe B JSON: " + b); return b; }))); diff --git a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeSchema.java b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeSchema.java index 81c0b4968..2ce981193 100644 --- a/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeSchema.java +++ b/src/main/java/dev/latvian/mods/kubejs/recipe/schema/RecipeSchema.java @@ -21,7 +21,6 @@ import java.util.List; import java.util.Map; import java.util.SequencedCollection; -import java.util.function.Function; /** * A recipe schema is a set of keys that defines how a recipe is constructed @@ -36,8 +35,6 @@ * @see KubeRecipe */ public class RecipeSchema { - public static final Function DEFAULT_UNIQUE_ID_FUNCTION = r -> null; - public KubeRecipeFactory recipeFactory; public ResourceLocation typeOverride; public final List> keys; diff --git a/src/main/java/dev/latvian/mods/kubejs/registry/BuilderBase.java b/src/main/java/dev/latvian/mods/kubejs/registry/BuilderBase.java index e6925b79b..2215e03fc 100644 --- a/src/main/java/dev/latvian/mods/kubejs/registry/BuilderBase.java +++ b/src/main/java/dev/latvian/mods/kubejs/registry/BuilderBase.java @@ -1,12 +1,12 @@ package dev.latvian.mods.kubejs.registry; +import dev.latvian.mods.kubejs.bindings.StringUtilsWrapper; import dev.latvian.mods.kubejs.client.LangKubeEvent; import dev.latvian.mods.kubejs.error.KubeRuntimeException; import dev.latvian.mods.kubejs.generator.KubeAssetGenerator; import dev.latvian.mods.kubejs.generator.KubeDataGenerator; import dev.latvian.mods.kubejs.script.SourceLine; import dev.latvian.mods.kubejs.typings.Info; -import dev.latvian.mods.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.util.HideFromJS; import dev.latvian.mods.rhino.util.ReturnsSelf; import net.minecraft.Util; @@ -147,7 +147,7 @@ public void generateLang(LangKubeEvent lang) { if (displayName != null) { lang.add(id.getNamespace(), getBuilderTranslationKey(), displayName.getString()); } else { - lang.add(id.getNamespace(), getBuilderTranslationKey(), UtilsJS.snakeCaseToTitleCase(id.getPath())); + lang.add(id.getNamespace(), getBuilderTranslationKey(), StringUtilsWrapper.snakeCaseToTitleCase(id.getPath())); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/registry/RegistryType.java b/src/main/java/dev/latvian/mods/kubejs/registry/RegistryType.java index 2c80ea461..a1c9acefc 100644 --- a/src/main/java/dev/latvian/mods/kubejs/registry/RegistryType.java +++ b/src/main/java/dev/latvian/mods/kubejs/registry/RegistryType.java @@ -2,7 +2,7 @@ import dev.latvian.mods.kubejs.DevProperties; import dev.latvian.mods.kubejs.KubeJS; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.bindings.JavaWrapper; import dev.latvian.mods.rhino.type.TypeInfo; import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; import net.minecraft.Util; @@ -21,6 +21,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.stream.Stream; @@ -97,7 +98,7 @@ public static class Scanner { Set> set = new HashSet<>(); set.add(ResourceKey.class); set.add(Registry.class); - var registrar = UtilsJS.tryLoadClass("dev.architectury.registry.registries.Registrar"); + var registrar = JavaWrapper.tryLoadClass("dev.architectury.registry.registries.Registrar"); if (registrar != null) { set.add(registrar); } @@ -121,13 +122,15 @@ private static synchronized void startIfNotFrozen() { frozen = true; var startTime = Util.getNanos(); - processClass(CLASSES_TO_SCAN.stream().map(UtilsJS::tryLoadClass)); + processClass(CLASSES_TO_SCAN.stream().map(JavaWrapper::tryLoadClass)); CLASSES_TO_SCAN.clear(); KubeJS.LOGGER.debug("Took {} ms to discover registry classes.", (int) ((Util.getNanos() - startTime) / 1_000_000)); } private static void processClass(Stream> classStream) { - classStream.map(Class::getDeclaredFields) + classStream + .filter(Objects::nonNull) + .map(Class::getDeclaredFields) .flatMap(Stream::of) .forEach(field -> { try { diff --git a/src/main/java/dev/latvian/mods/kubejs/script/ConsoleJS.java b/src/main/java/dev/latvian/mods/kubejs/script/ConsoleJS.java index 5e8dcbddf..21771bf6d 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/ConsoleJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/ConsoleJS.java @@ -3,6 +3,7 @@ import dev.latvian.apps.tinyserver.http.response.HTTPResponse; import dev.latvian.apps.tinyserver.ws.WSHandler; import dev.latvian.mods.kubejs.DevProperties; +import dev.latvian.mods.kubejs.bindings.StringUtilsWrapper; import dev.latvian.mods.kubejs.bindings.TextIcons; import dev.latvian.mods.kubejs.error.KubeRuntimeException; import dev.latvian.mods.kubejs.util.JSObjectType; @@ -298,7 +299,7 @@ public synchronized void flush(boolean sync) { return; } - var lines = Arrays.asList(writeQueue.toArray(UtilsJS.EMPTY_STRING_ARRAY)); + var lines = Arrays.asList(writeQueue.toArray(StringUtilsWrapper.EMPTY_STRING_ARRAY)); writeQueue.clear(); if (sync) { diff --git a/src/main/java/dev/latvian/mods/kubejs/script/ScriptFile.java b/src/main/java/dev/latvian/mods/kubejs/script/ScriptFile.java index b5d28adbc..6b2a87f2d 100644 --- a/src/main/java/dev/latvian/mods/kubejs/script/ScriptFile.java +++ b/src/main/java/dev/latvian/mods/kubejs/script/ScriptFile.java @@ -1,7 +1,7 @@ package dev.latvian.mods.kubejs.script; import dev.latvian.mods.kubejs.CommonProperties; -import dev.latvian.mods.kubejs.util.UtilsJS; +import dev.latvian.mods.kubejs.bindings.StringUtilsWrapper; import net.neoforged.fml.ModList; import java.nio.file.Files; @@ -37,7 +37,7 @@ public ScriptFile(ScriptPack pack, ScriptFileInfo info) throws Exception { this.packMode = ""; this.requiredMods = new HashSet<>(0); - this.lines = Files.readAllLines(info.path).toArray(UtilsJS.EMPTY_STRING_ARRAY); + this.lines = Files.readAllLines(info.path).toArray(StringUtilsWrapper.EMPTY_STRING_ARRAY); try { this.lastModified = Files.getLastModifiedTime(this.info.path).toMillis(); @@ -69,7 +69,7 @@ public ScriptFile(ScriptPack pack, ScriptFileInfo info) throws Exception { public void load(KubeJSContext cx) throws Throwable { cx.evaluateString(cx.topLevelScope, String.join("\n", lines), info.location, 1, null); - lines = UtilsJS.EMPTY_STRING_ARRAY; // free memory + lines = StringUtilsWrapper.EMPTY_STRING_ARRAY; // free memory } public List getProperties(String s) { diff --git a/src/main/java/dev/latvian/mods/kubejs/util/ID.java b/src/main/java/dev/latvian/mods/kubejs/util/ID.java index 04d975718..ca6c0c161 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/ID.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/ID.java @@ -15,6 +15,7 @@ public interface ID { ResourceLocation UNKNOWN = ResourceLocation.fromNamespaceAndPath("unknown", "unknown"); + ResourceLocation AIR = ResourceLocation.withDefaultNamespace("air"); UnaryOperator BLOCKSTATE = s -> "blockstates/" + s; UnaryOperator BLOCK = s -> "block/" + s; UnaryOperator ITEM = s -> "item/" + s; diff --git a/src/main/java/dev/latvian/mods/kubejs/util/JsonUtils.java b/src/main/java/dev/latvian/mods/kubejs/util/JsonUtils.java index 58389bc81..9f534ff57 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/JsonUtils.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/JsonUtils.java @@ -13,6 +13,7 @@ import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import dev.latvian.mods.rhino.Context; +import dev.latvian.mods.rhino.type.TypeInfo; import dev.latvian.mods.rhino.util.HideFromJS; import net.minecraft.nbt.CompoundTag; import org.jetbrains.annotations.Nullable; @@ -23,7 +24,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; public interface JsonUtils { @@ -34,17 +34,17 @@ static JsonElement copy(@Nullable JsonElement element) { if (element == null || element.isJsonNull()) { return JsonNull.INSTANCE; } else if (element instanceof JsonArray) { - JsonArray a = new JsonArray(); + var a = new JsonArray(); - for (JsonElement e : (JsonArray) element) { + for (var e : (JsonArray) element) { a.add(copy(e)); } return a; } else if (element instanceof JsonObject) { - JsonObject o = new JsonObject(); + var o = new JsonObject(); - for (Map.Entry entry : ((JsonObject) element).entrySet()) { + for (var entry : ((JsonObject) element).entrySet()) { o.add(entry.getKey(), copy(entry.getValue())); } @@ -62,9 +62,9 @@ static JsonElement of(Context cx, @Nullable Object o) { case Boolean b -> new JsonPrimitive(b); case Number n -> new JsonPrimitive(n); case Character c -> new JsonPrimitive(c); - case Map map -> MapJS.json(cx, map); - case CompoundTag tag -> MapJS.json(cx, tag); - case Collection c -> ListJS.json(cx, c); + case Map map -> objectOf(cx, map); + case CompoundTag tag -> objectOf(cx, tag); + case Collection c -> arrayOf(cx, c); case null, default -> JsonNull.INSTANCE; }; } @@ -73,24 +73,86 @@ static JsonPrimitive primitiveOf(Context cx, @Nullable Object o) { return of(cx, o) instanceof JsonPrimitive p ? p : null; } + @Nullable + static JsonObject objectOf(Context cx, @Nullable Object map) { + if (map instanceof JsonObject json) { + return json; + } else if (map instanceof CharSequence) { + try { + return GSON.fromJson(map.toString(), JsonObject.class); + } catch (Exception ex) { + return null; + } + } + + var m = (Map) cx.jsToJava(map, TypeInfo.RAW_MAP); + + if (m != null) { + var json = new JsonObject(); + + for (var entry : m.entrySet()) { + var e = of(cx, entry.getValue()); + + if (e instanceof JsonPrimitive p && p.isNumber() && p.getAsNumber() instanceof Double d && d <= Long.MAX_VALUE && d >= Long.MIN_VALUE && d == d.longValue()) { + var l = d.longValue(); + + if (l >= Integer.MIN_VALUE && l <= Integer.MAX_VALUE) { + json.add(String.valueOf(entry.getKey()), new JsonPrimitive((int) l)); + } else { + json.add(String.valueOf(entry.getKey()), new JsonPrimitive(l)); + } + } else { + json.add(String.valueOf(entry.getKey()), e); + } + } + + return json; + } + + return null; + } + + @Nullable + static JsonArray arrayOf(Context cx, @Nullable Object array) { + if (array instanceof JsonArray arr) { + return arr; + } else if (array instanceof CharSequence) { + try { + return JsonUtils.GSON.fromJson(array.toString(), JsonArray.class); + } catch (Exception ex) { + return null; + } + } else if (array instanceof Iterable itr) { + JsonArray json = new JsonArray(); + + for (Object o1 : itr) { + json.add(JsonUtils.of(cx, o1)); + } + + return json; + } + + return null; + } + @Nullable static Object toObject(@Nullable JsonElement json) { if (json == null || json.isJsonNull()) { return null; } else if (json.isJsonObject()) { - LinkedHashMap map = new LinkedHashMap<>(); - JsonObject o = json.getAsJsonObject(); + var map = new LinkedHashMap(); + var o = json.getAsJsonObject(); - for (Map.Entry entry : o.entrySet()) { + for (var entry : o.entrySet()) { map.put(entry.getKey(), toObject(entry.getValue())); } return map; } else if (json.isJsonArray()) { - JsonArray a = json.getAsJsonArray(); - List objects = new ArrayList<>(a.size()); + var a = json.getAsJsonArray(); + var objects = new ArrayList<>(a.size()); - for (JsonElement e : a) { + for (var e : a) { objects.add(toObject(e)); } @@ -101,10 +163,10 @@ static Object toObject(@Nullable JsonElement json) { } static String toString(JsonElement json) { - StringWriter writer = new StringWriter(); + var writer = new StringWriter(); try { - JsonWriter jsonWriter = new JsonWriter(writer); + var jsonWriter = new JsonWriter(writer); jsonWriter.setSerializeNulls(true); jsonWriter.setLenient(true); jsonWriter.setHtmlSafe(false); @@ -117,10 +179,10 @@ static String toString(JsonElement json) { } static String toPrettyString(JsonElement json) { - StringWriter writer = new StringWriter(); + var writer = new StringWriter(); try { - JsonWriter jsonWriter = new JsonWriter(writer); + var jsonWriter = new JsonWriter(writer); jsonWriter.setIndent("\t"); jsonWriter.setSerializeNulls(true); jsonWriter.setLenient(true); @@ -139,9 +201,8 @@ static JsonElement fromString(@Nullable String string) { } try { - JsonReader jsonReader = new JsonReader(new StringReader(string)); + var jsonReader = new JsonReader(new StringReader(string)); JsonElement element; - boolean lenient = jsonReader.isLenient(); jsonReader.setLenient(true); element = Streams.parse(jsonReader); @@ -162,7 +223,7 @@ static Object toPrimitive(@Nullable JsonElement element) { if (element == null || element.isJsonNull()) { return null; } else if (element.isJsonPrimitive()) { - JsonPrimitive p = element.getAsJsonPrimitive(); + var p = element.getAsJsonPrimitive(); if (p.isBoolean()) { return p.getAsBoolean(); diff --git a/src/main/java/dev/latvian/mods/kubejs/util/ListJS.java b/src/main/java/dev/latvian/mods/kubejs/util/ListJS.java index 1f6712265..9058c29d7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/ListJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/ListJS.java @@ -1,7 +1,5 @@ package dev.latvian.mods.kubejs.util; -import com.google.gson.JsonArray; -import dev.latvian.mods.rhino.Context; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Array; @@ -173,27 +171,4 @@ static Set ofSet(@Nullable Object o) { var list = of(o); return list == null ? null : new LinkedHashSet<>(list); } - - @Nullable - static JsonArray json(Context cx, @Nullable Object array) { - if (array instanceof JsonArray arr) { - return arr; - } else if (array instanceof CharSequence) { - try { - return JsonUtils.GSON.fromJson(array.toString(), JsonArray.class); - } catch (Exception ex) { - return null; - } - } else if (array instanceof Iterable itr) { - JsonArray json = new JsonArray(); - - for (Object o1 : itr) { - json.add(JsonUtils.of(cx, o1)); - } - - return json; - } - - return null; - } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/util/MapJS.java b/src/main/java/dev/latvian/mods/kubejs/util/MapJS.java index 6b70e7c76..13e4f9342 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/MapJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/MapJS.java @@ -1,8 +1,6 @@ package dev.latvian.mods.kubejs.util; import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import dev.latvian.mods.rhino.Context; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import org.jetbrains.annotations.Nullable; @@ -35,48 +33,4 @@ public interface MapJS { return null; } - - static Map orEmpty(@Nullable Object o) { - var map = of(o); - return map != null ? map : Map.of(); - } - - @Nullable - @Deprecated - static CompoundTag nbt(Context cx, @Nullable Object map) { - return NBTUtils.toTagCompound(cx, map); - } - - @Nullable - static JsonObject json(Context cx, @Nullable Object map) { - if (map instanceof JsonObject json) { - return json; - } else if (map instanceof CharSequence) { - try { - return JsonUtils.GSON.fromJson(map.toString(), JsonObject.class); - } catch (Exception ex) { - return null; - } - } - - var m = of(map); - - if (m != null) { - var json = new JsonObject(); - - for (var entry : m.entrySet()) { - var e = JsonUtils.of(cx, entry.getValue()); - - if (e instanceof JsonPrimitive p && p.isNumber() && p.getAsNumber() instanceof Double d && d <= Long.MAX_VALUE && d >= Long.MIN_VALUE && d == d.longValue()) { - json.add(String.valueOf(entry.getKey()), new JsonPrimitive(d.longValue())); - } else { - json.add(String.valueOf(entry.getKey()), e); - } - } - - return json; - } - - return null; - } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/util/MutableBoolean.java b/src/main/java/dev/latvian/mods/kubejs/util/MutableBoolean.java deleted file mode 100644 index bdaec7d0f..000000000 --- a/src/main/java/dev/latvian/mods/kubejs/util/MutableBoolean.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.latvian.mods.kubejs.util; - -public class MutableBoolean { - public boolean value; - - public MutableBoolean(boolean value) { - this.value = value; - } -} diff --git a/src/main/java/dev/latvian/mods/kubejs/util/RegistryAccessContainer.java b/src/main/java/dev/latvian/mods/kubejs/util/RegistryAccessContainer.java index 87136b025..e4ee7a6ca 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/RegistryAccessContainer.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/RegistryAccessContainer.java @@ -164,7 +164,7 @@ public T decode(Context cx, Codec codec, Object o) { } else if (o instanceof Map) { return codec.decode(java, o).result().orElseThrow().getFirst(); } else { - return codec.decode(json, MapJS.json(cx, o)).result().orElseThrow().getFirst(); + return codec.decode(json, JsonUtils.of(cx, o)).result().orElseThrow().getFirst(); } } @@ -174,7 +174,7 @@ public T decodeMap(Context cx, MapCodec codec, Object o) { } else if (o instanceof Map map) { return codec.decode(java, java.getMap(map).getOrThrow()).result().orElseThrow(); } else { - return codec.decode(json, json.getMap(MapJS.json(cx, o)).getOrThrow()).result().orElseThrow(); + return codec.decode(json, json.getMap(JsonUtils.of(cx, o)).getOrThrow()).result().orElseThrow(); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/util/UtilsJS.java b/src/main/java/dev/latvian/mods/kubejs/util/UtilsJS.java index e87b63dc1..2f06306cd 100644 --- a/src/main/java/dev/latvian/mods/kubejs/util/UtilsJS.java +++ b/src/main/java/dev/latvian/mods/kubejs/util/UtilsJS.java @@ -1,6 +1,5 @@ package dev.latvian.mods.kubejs.util; -import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; @@ -10,12 +9,8 @@ import dev.latvian.mods.kubejs.block.BlockModificationKubeEvent; import dev.latvian.mods.kubejs.item.ItemModificationKubeEvent; import dev.latvian.mods.kubejs.script.ScriptType; -import dev.latvian.mods.rhino.BaseFunction; -import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.Wrapper; -import dev.latvian.mods.rhino.type.TypeInfo; import dev.latvian.mods.rhino.type.TypeUtils; -import dev.latvian.mods.rhino.util.HideFromJS; import net.minecraft.advancements.critereon.MinMaxBounds; import net.minecraft.commands.arguments.selector.EntitySelector; import net.minecraft.commands.arguments.selector.EntitySelectorParser; @@ -29,58 +24,28 @@ import net.minecraft.world.item.CreativeModeTab; import org.jetbrains.annotations.Nullable; -import java.io.IOException; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Set; -import java.util.StringJoiner; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; -import java.util.regex.Pattern; public class UtilsJS { public static final RandomSource RANDOM = RandomSource.create(); - public static final ResourceLocation AIR_LOCATION = ResourceLocation.parse("minecraft:air"); - public static final Pattern SNAKE_CASE_SPLIT = Pattern.compile("[:_/]"); - public static final Set ALWAYS_LOWER_CASE = new HashSet<>(Arrays.asList("a", "an", "the", "of", "on", "in", "and", "or", "but", "for")); + public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; - public static final String[] EMPTY_STRING_ARRAY = new String[0]; public static final Predicate ALWAYS_TRUE = o -> true; private static final Map ENTITY_SELECTOR_CACHE = new HashMap<>(); private static final EntitySelector ALL_ENTITIES_SELECTOR = new EntitySelector(EntitySelector.INFINITE, true, false, List.of(), MinMaxBounds.Doubles.ANY, Function.identity(), null, EntitySelectorParser.ORDER_RANDOM, false, null, null, null, true); - @FunctionalInterface - public interface TryIO { - void run() throws IOException; - } - - public static void tryIO(TryIO tryIO) { - try { - tryIO.run(); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - public static void queueIO(Runnable runnable) { - try { - runnable.run(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - // TODO: Remove this garbage @Nullable public static Object wrap(@Nullable Object o, JSObjectType type) { @@ -148,66 +113,6 @@ else if (o instanceof JsonObject json) { return o; } - public static int parseInt(@Nullable Object object, int def) { - if (object == null) { - return def; - } else if (object instanceof Number num) { - return num.intValue(); - } - - try { - var s = object.toString(); - - if (s.isEmpty()) { - return def; - } - - return Integer.parseInt(s); - } catch (Exception ex) { - return def; - } - } - - public static long parseLong(@Nullable Object object, long def) { - if (object == null) { - return def; - } else if (object instanceof Number num) { - return num.longValue(); - } - - try { - var s = object.toString(); - - if (s.isEmpty()) { - return def; - } - - return Long.parseLong(s); - } catch (Exception ex) { - return def; - } - } - - public static double parseDouble(@Nullable Object object, double def) { - if (object == null) { - return def; - } else if (object instanceof Number num) { - return num.doubleValue(); - } - - try { - var s = object.toString(); - - if (s.isEmpty()) { - return def; - } - - return Double.parseDouble(String.valueOf(object)); - } catch (Exception ex) { - return def; - } - } - public static Predicate onMatchDo(Predicate predicate, Consumer onMatch) { return t -> { var match = predicate.test(t); @@ -301,76 +206,6 @@ public static String toMappedTypeString(Type type) { throw new IllegalArgumentException("Expected a Class, ParameterizedType, GenericArrayType, TypeVariable or WildcardType, but <" + type + "> is of type " + className); } - public static String snakeCaseToCamelCase(String string) { - if (string == null || string.isEmpty()) { - return string; - } - - var s = SNAKE_CASE_SPLIT.split(string, 0); - - var sb = new StringBuilder(); - var first = true; - - for (var value : s) { - if (!value.isEmpty()) { - if (first) { - first = false; - sb.append(value); - } else { - sb.append(Character.toUpperCase(value.charAt(0))); - sb.append(value, 1, value.length()); - } - } - } - - return sb.toString(); - } - - public static String snakeCaseToTitleCase(String string) { - StringJoiner joiner = new StringJoiner(" "); - String[] split = string.split("_"); - for (int i = 0; i < split.length; i++) { - String s = split[i]; - String titleCase = toTitleCase(s, i == 0); - joiner.add(titleCase); - } - return joiner.toString(); - } - - public static String toTitleCase(String s) { - return toTitleCase(s, false); - } - - public static String toTitleCase(String s, boolean ignoreSpecial) { - if (s.isEmpty()) { - return ""; - } else if (!ignoreSpecial && ALWAYS_LOWER_CASE.contains(s)) { - return s; - } else if (s.length() == 1) { - return s.toUpperCase(); - } - - char[] chars = s.toCharArray(); - chars[0] = Character.toUpperCase(chars[0]); - return new String(chars); - } - - public static String stripIdForEvent(ResourceLocation id) { - return stripEventName(id.toString()); - } - - public static String getUniqueId(JsonElement json) { - return getUniqueId(json, Function.identity()); - } - - public static String getUniqueId(T input, Function toJson) { - return JsonIO.getJsonHashString(toJson.apply(input)); - } - - public static String stripEventName(String s) { - return s.replaceAll("[/:]", ".").replace('-', '_'); - } - public static EntitySelector entitySelector(@Nullable Object o) { if (o == null) { return ALL_ENTITIES_SELECTOR; @@ -404,18 +239,4 @@ public static EntitySelector entitySelector(@Nullable Object o) { public static CreativeModeTab findCreativeTab(ResourceLocation id) { return BuiltInRegistries.CREATIVE_MODE_TAB.get(id); } - - public static T makeFunctionProxy(Context cx, TypeInfo targetClass, BaseFunction function) { - return Cast.to(cx.createInterfaceAdapter(targetClass, function)); - } - - @Nullable - @HideFromJS - public static Class tryLoadClass(String className) { - try { - return Class.forName(className); - } catch (Exception ignored) { - return null; - } - } } \ No newline at end of file diff --git a/src/main/java/dev/latvian/mods/kubejs/web/KJSHTTPRequest.java b/src/main/java/dev/latvian/mods/kubejs/web/KJSHTTPRequest.java index 26dd7487f..110d5e4eb 100644 --- a/src/main/java/dev/latvian/mods/kubejs/web/KJSHTTPRequest.java +++ b/src/main/java/dev/latvian/mods/kubejs/web/KJSHTTPRequest.java @@ -30,7 +30,7 @@ public T supplyInMainThread(Supplier task) { } public ResourceLocation id(String ns, String path) { - return ResourceLocation.fromNamespaceAndPath(variable(ns), variable(path)); + return ResourceLocation.fromNamespaceAndPath(variable(ns).asString(), variable(path).asString()); } @Nullable @@ -39,6 +39,6 @@ public ResourceLocation id() { } public DataComponentPatch components(DynamicOps ops) throws CommandSyntaxException { - return DataComponentWrapper.patchOrEmptyOf(ops, "[" + query().getOrDefault("components", "") + "]"); + return DataComponentWrapper.patchOrEmptyOf(ops, "[" + query().get("components").asString() + "]"); } } diff --git a/src/main/java/dev/latvian/mods/kubejs/web/LocalWebServer.java b/src/main/java/dev/latvian/mods/kubejs/web/LocalWebServer.java index 544239945..cc30096a7 100644 --- a/src/main/java/dev/latvian/mods/kubejs/web/LocalWebServer.java +++ b/src/main/java/dev/latvian/mods/kubejs/web/LocalWebServer.java @@ -45,7 +45,8 @@ public static void start(BlockableEventLoop eventLoop) { registry.server.setMaxPortShift(10); registry.server.setMaxKeepAliveConnections(3); - var url = "http://localhost:" + registry.server.start(); + int port = registry.server.start(); + var url = "http://localhost:" + port; KubeJS.LOGGER.info("Started the local web server at " + url); var endpoints = new ArrayList<>(registry.endpoints); endpoints.sort(null); diff --git a/src/main/java/dev/latvian/mods/kubejs/web/local/KubeJSWeb.java b/src/main/java/dev/latvian/mods/kubejs/web/local/KubeJSWeb.java index a16b28583..0131e0e5f 100644 --- a/src/main/java/dev/latvian/mods/kubejs/web/local/KubeJSWeb.java +++ b/src/main/java/dev/latvian/mods/kubejs/web/local/KubeJSWeb.java @@ -6,6 +6,8 @@ import dev.latvian.apps.tinyserver.http.response.HTTPPayload; import dev.latvian.apps.tinyserver.http.response.HTTPResponse; import dev.latvian.apps.tinyserver.http.response.HTTPStatus; +import dev.latvian.apps.tinyserver.http.response.error.client.NotFoundError; +import dev.latvian.apps.tinyserver.http.response.error.server.InternalError; import dev.latvian.apps.tinyserver.ws.Frame; import dev.latvian.apps.tinyserver.ws.WSHandler; import dev.latvian.mods.kubejs.KubeJS; @@ -19,13 +21,21 @@ import dev.latvian.mods.kubejs.web.LocalWebServer; import dev.latvian.mods.kubejs.web.LocalWebServerRegistry; import net.minecraft.core.Holder; +import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceKey; +import net.minecraft.server.packs.PackLocationInfo; +import net.minecraft.server.packs.repository.PackSource; import net.minecraft.tags.TagKey; +import net.neoforged.fml.ModContainer; import net.neoforged.fml.ModList; import net.neoforged.fml.loading.FMLPaths; +import net.neoforged.neoforge.resource.ResourcePackLoader; import net.neoforged.neoforge.server.ServerLifecycleHooks; import org.jetbrains.annotations.Nullable; +import javax.imageio.ImageIO; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -103,8 +113,8 @@ public static void register(LocalWebServerRegistry registry) { addScriptTypeEndpoints(registry, ScriptType.SERVER, KubeJSWeb::reloadInternalServer); registry.get("/", KubeJSWeb::getHomepage); - registry.get("/api", KubeJSWeb::getApi); registry.get("/api/mods", KubeJSWeb::getMods); + registry.get("/api/mods/{id}/icon", KubeJSWeb::getModIcon); registry.get("/api/browse", KubeJSWeb::getBrowse); registry.get("/api/browse/{directory}", KubeJSWeb::getBrowseDir); @@ -146,15 +156,14 @@ private static HTTPResponse getHomepage(KJSHTTPRequest req) { list.add("- " + mod.getModInfo().getDisplayName() + " (" + mod.getModId() + " - " + mod.getModInfo().getVersion() + ")"); } - return HTTPResponse.ok().text(list); - } + list.add(""); + list.add("Available Endpoints:"); - private static HTTPResponse getApi(KJSHTTPRequest req) { - return HTTPResponse.ok().content(JsonContent.array(json -> { - for (var endpoint : LocalWebServer.instance().endpoints()) { - json.add(endpoint.method() + " " + endpoint.path()); - } - })); + for (var endpoint : LocalWebServer.instance().endpoints()) { + list.add("- " + endpoint.method() + "\t" + endpoint.path()); + } + + return HTTPResponse.ok().text(list); } private static HTTPResponse getMods(KJSHTTPRequest req) { @@ -169,12 +178,59 @@ private static HTTPResponse getMods(KJSHTTPRequest req) { })); } + private static HTTPResponse getModIcon(KJSHTTPRequest req) throws Exception { + var mod = ModList.get().getModContainerById(req.variable("id").asString()).map(ModContainer::getModInfo).orElse(null); + + if (mod == null) { + throw new NotFoundError("Mod not found"); + } + + var logo = mod.getLogoFile().orElse(""); + var img = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB); + + for (int i = 0; i < 128; i++) { + for (int j = 0; j < 128; j++) { + img.setRGB(i, j, 0xFF000000); + } + } + + if (!logo.isEmpty()) { + var resourcePack = ResourcePackLoader.getPackFor(mod.getModId()).orElse(ResourcePackLoader.getPackFor("neoforge").orElseThrow(() -> new InternalError("Can't find neoforge, WHAT!"))); + + try (var res = resourcePack.openPrimary(new PackLocationInfo("mod/" + mod.getModId(), Component.empty(), PackSource.BUILT_IN, Optional.empty()))) { + var logoResource = res.getRootResource(logo.split("[/\\\\]")); + + if (logoResource != null) { + var l = ImageIO.read(logoResource.get()); + var g = img.createGraphics(); + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, mod.getLogoBlur() ? RenderingHints.VALUE_INTERPOLATION_BILINEAR : RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); + + float r = l.getWidth() / (float) l.getHeight(); + int w, h; + + if (r > 1F) { + w = 128; + h = (int) (128 / r); + } else { + w = (int) (128 * r); + h = 128; + } + + g.drawImage(l, (128 - w) / 2, (128 - h) / 2, w, h, null); + g.dispose(); + } + } + } + + return HTTPResponse.ok().png(img); + } + private static HTTPResponse getBrowse(KJSHTTPRequest req) { return HTTPResponse.ok().content(JsonContent.array(json -> BROWSE.keySet().forEach(json::add))); } private static HTTPResponse getBrowseDir(KJSHTTPRequest req) { - var dirName = req.variable("directory"); + var dirName = req.variable("directory").asString(); var dir = BROWSE.get(dirName); if (dir == null) { @@ -205,13 +261,13 @@ private static HTTPResponse getBrowseDir(KJSHTTPRequest req) { } private static HTTPResponse getBrowseFile(KJSHTTPRequest req) { - var dir = BROWSE.get(req.variable("directory")); + var dir = BROWSE.get(req.variable("directory").asString()); if (dir == null) { return HTTPStatus.NOT_FOUND; } - var file = dir.resolve(req.variable("file")); + var file = dir.resolve(req.variable("file").asString()); if (Files.notExists(file)) { return HTTPStatus.NOT_FOUND; @@ -253,7 +309,7 @@ private static HTTPResponse getRegistryMatchResponse(KJSHTTPRequest req) { return HTTPStatus.NOT_FOUND; } - var regex = RegExpKJS.ofString(req.variable("regex")); + var regex = RegExpKJS.ofString(req.variable("regex").asString()); if (regex == null) { return HTTPStatus.BAD_REQUEST; diff --git a/src/main/java/dev/latvian/mods/kubejs/web/local/client/ImageGenerator.java b/src/main/java/dev/latvian/mods/kubejs/web/local/client/ImageGenerator.java index 65dd8b161..d4e4c22cf 100644 --- a/src/main/java/dev/latvian/mods/kubejs/web/local/client/ImageGenerator.java +++ b/src/main/java/dev/latvian/mods/kubejs/web/local/client/ImageGenerator.java @@ -90,7 +90,7 @@ public int hashCode() { @Override public boolean equals(Object o) { - return this == o || o instanceof BodyKey k && Arrays.equals(bytes, k.bytes); + return this == o || o instanceof BodyKey(byte[] bytes1) && Arrays.equals(bytes, bytes1); } } @@ -109,7 +109,7 @@ public static TextureTarget getCanvas(int size) { } private static HTTPResponse renderCanvas(KJSHTTPRequest req, int canvasSize, String dir, @Nullable ByteBuf cacheBuf, boolean wildcard, Consumer render) { - int size = Integer.parseInt(req.variable("size")); + int size = req.variable("size").asInt(); if (size < 1 || size > 1024) { return HTTPStatus.BAD_REQUEST.text("Invalid size, must be [1, 1024]"); @@ -203,7 +203,7 @@ private static HTTPResponse renderCanvas(KJSHTTPRequest req, int canvasSize, Str } private static HTTPResponse renderAnimated(KJSHTTPRequest req, String dir, @Nullable ByteBuf cacheBuf, List responses) throws Exception { - int size = Integer.parseInt(req.variable("size")); + int size = req.variable("size").asInt(); if (size < 1 || size > 1024) { return HTTPStatus.BAD_REQUEST.text("Invalid size, must be [1, 1024]"); diff --git a/src/main/java/dev/latvian/mods/kubejs/web/local/client/KubeJSClientWeb.java b/src/main/java/dev/latvian/mods/kubejs/web/local/client/KubeJSClientWeb.java index 95672473d..5066d00b3 100644 --- a/src/main/java/dev/latvian/mods/kubejs/web/local/client/KubeJSClientWeb.java +++ b/src/main/java/dev/latvian/mods/kubejs/web/local/client/KubeJSClientWeb.java @@ -95,7 +95,7 @@ private static HTTPResponse getScreenshot(KJSHTTPRequest req) { } private static HTTPResponse getTranslate(KJSHTTPRequest req) { - return HTTPResponse.ok().text(I18n.get(req.variable("key"))); + return HTTPResponse.ok().text(I18n.get(req.variable("key").asString())); } private static HTTPResponse getComponentString(KJSHTTPRequest req) { @@ -201,7 +201,7 @@ private static HTTPResponse getSearchFluids(KJSHTTPRequest req) { } private static HTTPResponse getAssetList(KJSHTTPRequest req) { - var prefix = req.variable("prefix"); + var prefix = req.variable("prefix").asString(); if (prefix.isEmpty()) { return HTTPStatus.BAD_REQUEST;