9
0
mirror of https://github.com/Xiao-MoMi/craft-engine.git synced 2025-12-30 20:39:10 +00:00

优化boolean类型参数读取

This commit is contained in:
XiaoMoMi
2025-06-23 17:54:09 +08:00
parent ea3e45b047
commit 774336e0b0
52 changed files with 138 additions and 106 deletions

View File

@@ -21,7 +21,7 @@ dependencies {
implementation("net.momirealms:sparrow-nbt-codec:${rootProject.properties["sparrow_nbt_version"]}")
implementation("net.momirealms:sparrow-nbt-legacy-codec:${rootProject.properties["sparrow_nbt_version"]}")
// S3
implementation("net.momirealms:craft-engine-s3:0.1")
implementation("net.momirealms:craft-engine-s3:0.2")
// Util
compileOnly("net.momirealms:sparrow-util:${rootProject.properties["sparrow_util_version"]}")
// Adventure

View File

@@ -386,11 +386,11 @@ public class BlockSettings {
return settings -> settings.resistance(floatValue);
}));
registerFactory("is-randomly-ticking", (value -> {
boolean booleanValue = (boolean) value;
boolean booleanValue = ResourceConfigUtils.getAsBoolean(value, "is-randomly-ticking");
return settings -> settings.isRandomlyTicking(booleanValue);
}));
registerFactory("propagate-skylight", (value -> {
boolean booleanValue = (boolean) value;
boolean booleanValue = ResourceConfigUtils.getAsBoolean(value, "propagate-skylight");
return settings -> settings.propagatesSkylightDown(booleanValue ? Tristate.TRUE : Tristate.FALSE);
}));
registerFactory("push-reaction", (value -> {
@@ -402,7 +402,7 @@ public class BlockSettings {
return settings -> settings.mapColor(MapColor.get(intValue));
}));
registerFactory("burnable", (value -> {
boolean booleanValue = (boolean) value;
boolean booleanValue = ResourceConfigUtils.getAsBoolean(value, "burnable");
return settings -> settings.burnable(booleanValue);
}));
registerFactory("instrument", (value -> {
@@ -426,19 +426,19 @@ public class BlockSettings {
return settings -> settings.fireSpreadChance(intValue);
}));
registerFactory("replaceable", (value -> {
boolean booleanValue = (boolean) value;
boolean booleanValue = ResourceConfigUtils.getAsBoolean(value, "replaceable");
return settings -> settings.replaceable(booleanValue);
}));
registerFactory("is-redstone-conductor", (value -> {
boolean booleanValue = (boolean) value;
boolean booleanValue = ResourceConfigUtils.getAsBoolean(value, "is-redstone-conductor");
return settings -> settings.isRedstoneConductor(booleanValue);
}));
registerFactory("is-suffocating", (value -> {
boolean booleanValue = (boolean) value;
boolean booleanValue = ResourceConfigUtils.getAsBoolean(value, "is-suffocating");
return settings -> settings.isSuffocating(booleanValue);
}));
registerFactory("is-view-blocking", (value -> {
boolean booleanValue = (boolean) value;
boolean booleanValue = ResourceConfigUtils.getAsBoolean(value, "is-view-blocking");
return settings -> settings.isViewBlocking(booleanValue);
}));
registerFactory("sounds", (value -> {
@@ -446,11 +446,11 @@ public class BlockSettings {
return settings -> settings.sounds(BlockSounds.fromMap(soundMap));
}));
registerFactory("fluid-state", (value -> {
String state = (String) value;
String state = value.toString();
return settings -> settings.fluidState(state.equals("water"));
}));
registerFactory("can-occlude", (value -> {
boolean booleanValue = (boolean) value;
boolean booleanValue = ResourceConfigUtils.getAsBoolean(value, "can-occlude");
return settings -> settings.canOcclude(booleanValue ? Tristate.TRUE : Tristate.FALSE);
}));
registerFactory("correct-tools", (value -> {
@@ -458,15 +458,15 @@ public class BlockSettings {
return settings -> settings.correctTools(tools.stream().map(Key::of).collect(Collectors.toSet()));
}));
registerFactory("require-correct-tools", (value -> {
boolean booleanValue = (boolean) value;
boolean booleanValue = ResourceConfigUtils.getAsBoolean(value, "require-correct-tools");
return settings -> settings.requireCorrectTool(booleanValue);
}));
registerFactory("respect-tool-component", (value -> {
boolean booleanValue = (boolean) value;
boolean booleanValue = ResourceConfigUtils.getAsBoolean(value, "respect-tool-component");
return settings -> settings.respectToolComponent(booleanValue);
}));
registerFactory("use-shape-for-light-occlusion", (value -> {
boolean booleanValue = (boolean) value;
boolean booleanValue = ResourceConfigUtils.getAsBoolean(value, "use-shape-for-light-occlusion");
return settings -> settings.useShapeForLightOcclusion(booleanValue ? Tristate.TRUE : Tristate.FALSE);
}));
registerFactory("incorrect-tool-dig-speed", (value -> {

View File

@@ -1,5 +1,6 @@
package net.momirealms.craftengine.core.block.properties;
import net.momirealms.craftengine.core.util.ResourceConfigUtils;
import net.momirealms.sparrow.nbt.ByteTag;
import net.momirealms.sparrow.nbt.Tag;
@@ -73,7 +74,7 @@ public class BooleanProperty extends Property<Boolean> {
public static class Factory implements PropertyFactory {
@Override
public Property<?> create(String name, Map<String, Object> arguments) {
boolean bool = (boolean) arguments.getOrDefault("default", false);
boolean bool = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("default", false), "default");
return BooleanProperty.create(name, bool);
}
}

View File

@@ -112,7 +112,7 @@ public abstract class AbstractFurnitureManager implements FurnitureManager {
for (Map<String, Object> element : elementConfigs) {
FurnitureElement furnitureElement = furnitureElementBuilder()
.item(Key.of(ResourceConfigUtils.requireNonEmptyStringOrThrow(element.get("item"), "warning.config.furniture.element.missing_item")))
.applyDyedColor((boolean) element.getOrDefault("apply-dyed-color", true))
.applyDyedColor(ResourceConfigUtils.getAsBoolean(element.getOrDefault("apply-dyed-color", true), "apply-dyed-color"))
.billboard(ResourceConfigUtils.getOrDefault(element.get("billboard"), o -> Billboard.valueOf(o.toString().toUpperCase(Locale.ENGLISH)), Billboard.FIXED))
.transform(ResourceConfigUtils.getOrDefault(element.get("transform"), o -> ItemDisplayContext.valueOf(o.toString().toUpperCase(Locale.ENGLISH)), ItemDisplayContext.NONE))
.scale(MiscUtils.getAsVector3f(element.getOrDefault("scale", "1"), "scale"))

View File

@@ -414,8 +414,8 @@ public abstract class AbstractItemManager<I> extends AbstractModelGenerator impl
TreeMap<Integer, ModernItemModel> map = AbstractItemManager.this.modernOverrides.computeIfAbsent(clientBoundMaterial, k -> new TreeMap<>());
map.put(customModelData, new ModernItemModel(
modernModel,
(boolean) section.getOrDefault("oversized-in-gui", true),
(boolean) section.getOrDefault("hand-animation-on-swap", true)
ResourceConfigUtils.getAsBoolean(section.getOrDefault("oversized-in-gui", true), "oversized-in-gui"),
ResourceConfigUtils.getAsBoolean(section.getOrDefault("hand-animation-on-swap", true), "hand-animation-on-swap")
));
}
if (needsLegacyCompatibility() && legacyOverridesModels != null && !legacyOverridesModels.isEmpty()) {
@@ -429,8 +429,8 @@ public abstract class AbstractItemManager<I> extends AbstractModelGenerator impl
if (isModernFormatRequired() && modernModel != null) {
AbstractItemManager.this.modernItemModels1_21_4.put(itemModelKey, new ModernItemModel(
modernModel,
(boolean) section.getOrDefault("oversized-in-gui", true),
(boolean) section.getOrDefault("hand-animation-on-swap", true)
ResourceConfigUtils.getAsBoolean(section.getOrDefault("oversized-in-gui", true), "oversized-in-gui"),
ResourceConfigUtils.getAsBoolean(section.getOrDefault("hand-animation-on-swap", true), "hand-animation-on-swap")
));
}
if (Config.packMaxVersion() >= VERSION_1_21_2 && needsLegacyCompatibility() && legacyOverridesModels != null && !legacyOverridesModels.isEmpty()) {
@@ -529,7 +529,7 @@ public abstract class AbstractItemManager<I> extends AbstractModelGenerator impl
Map<String, Object> data = MiscUtils.castToMap(obj, false);
int nutrition = ResourceConfigUtils.getAsInt(data.get("nutrition"), "nutrition");
float saturation = ResourceConfigUtils.getAsFloat(data.get("saturation"), "saturation");
return new FoodModifier<>(nutrition, saturation, (boolean) data.getOrDefault("can-always-eat", false));
return new FoodModifier<>(nutrition, saturation, ResourceConfigUtils.getAsBoolean(data.getOrDefault("can-always-eat", false), "can-always-eat"));
}, "food");
}
if (VersionHelper.isOrAbove1_21()) {

View File

@@ -262,15 +262,15 @@ public class ItemSettings {
static {
registerFactory("repairable", (value -> {
boolean bool = (boolean) value;
boolean bool = ResourceConfigUtils.getAsBoolean(value, "repairable");
return settings -> settings.canRepair(bool);
}));
registerFactory("enchantable", (value -> {
boolean bool = (boolean) value;
boolean bool = ResourceConfigUtils.getAsBoolean(value, "enchantable");
return settings -> settings.canEnchant(bool);
}));
registerFactory("renameable", (value -> {
boolean bool = (boolean) value;
boolean bool = ResourceConfigUtils.getAsBoolean(value, "renameable");
return settings -> settings.renameable(bool);
}));
registerFactory("anvil-repair-item", (value -> {
@@ -318,7 +318,7 @@ public class ItemSettings {
return settings -> settings.equipment(equipment);
}));
registerFactory("can-place", (value -> {
boolean bool = (boolean) value;
boolean bool = ResourceConfigUtils.getAsBoolean(value, "can-place");
return settings -> settings.canPlaceRelatedVanillaBlock(bool);
}));
registerFactory("projectile", (value -> {
@@ -342,7 +342,7 @@ public class ItemSettings {
return settings -> settings.compostProbability(chance);
}));
registerFactory("dyeable", (value -> {
boolean bool = (boolean) value;
boolean bool = ResourceConfigUtils.getAsBoolean(value, "dyeable");
return settings -> settings.dyeable(bool);
}));
registerFactory("food", (value -> {

View File

@@ -133,7 +133,7 @@ public class CustomSmithingTransformRecipe<T> implements Recipe<T> {
List<String> base = MiscUtils.getAsStringList(arguments.get("base"));
List<String> addition = MiscUtils.getAsStringList(arguments.get("addition"));
List<String> template = MiscUtils.getAsStringList(arguments.get("template-type"));
boolean mergeComponents = (boolean) arguments.getOrDefault("merge-components", true);
boolean mergeComponents = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("merge-components", true), "merge-components");
@SuppressWarnings("unchecked")
List<Map<String, Object>> processors = (List<Map<String, Object>>) arguments.getOrDefault("post-processors", List.of());
return new CustomSmithingTransformRecipe<>(

View File

@@ -1,7 +1,9 @@
package net.momirealms.craftengine.core.item.setting;
import net.momirealms.craftengine.core.entity.EquipmentSlot;
import net.momirealms.craftengine.core.plugin.locale.LocalizedResourceConfigException;
import net.momirealms.craftengine.core.util.Key;
import net.momirealms.craftengine.core.util.ResourceConfigUtils;
import net.momirealms.craftengine.core.util.VersionHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -42,7 +44,7 @@ public class EquipmentData {
public static EquipmentData fromMap(@NotNull final Map<String, Object> data) {
String slot = (String) data.get("slot");
if (slot == null) {
throw new IllegalArgumentException("No `slot` option set for `equippable`");
throw new LocalizedResourceConfigException("warning.config.item.settings.equippable.missing_slot");
}
EquipmentSlot slotEnum = EquipmentSlot.valueOf(slot.toUpperCase(Locale.ENGLISH));
EquipmentData.Builder builder = EquipmentData.builder().slot(slotEnum);
@@ -53,16 +55,16 @@ public class EquipmentData {
builder.cameraOverlay(Key.of(data.get("camera-overlay").toString()));
}
if (data.containsKey("dispensable")) {
builder.dispensable((boolean) data.get("dispensable"));
builder.dispensable(ResourceConfigUtils.getAsBoolean(data.get("dispensable"), "dispensable"));
}
if (data.containsKey("swappable")) {
builder.swappable((boolean) data.get("swappable"));
builder.swappable(ResourceConfigUtils.getAsBoolean(data.get("swappable"), "swappable"));
}
if (data.containsKey("equip-on-interact")) {
builder.equipOnInteract((boolean) data.get("equip-on-interact"));
builder.equipOnInteract(ResourceConfigUtils.getAsBoolean(data.get("equip-on-interact"), "equip-on-interact"));
}
if (data.containsKey("damage-on-hurt")) {
builder.damageOnHurt((boolean) data.get("damage-on-hurt"));
builder.damageOnHurt(ResourceConfigUtils.getAsBoolean(data.get("damage-on-hurt"), "damage-on-hurt"));
}
return builder.build();
}

View File

@@ -43,7 +43,7 @@ public class SetCountFunction<T> extends AbstractLootConditionalFunction<T> {
@Override
public LootFunction<A> create(Map<String, Object> arguments) {
Object value = ResourceConfigUtils.requireNonNullOrThrow(arguments.get("count"), "warning.config.loot_table.function.set_count.missing_count");
boolean add = (boolean) arguments.getOrDefault("add", false);
boolean add = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("add", false), "add");
List<Condition<LootContext>> conditions = Optional.ofNullable(arguments.get("conditions"))
.map(it -> LootConditions.fromMapList((List<Map<String, Object>>) it))
.orElse(Collections.emptyList());

View File

@@ -5,6 +5,7 @@ import net.momirealms.craftengine.core.pack.conflict.PathContext;
import net.momirealms.craftengine.core.plugin.CraftEngine;
import net.momirealms.craftengine.core.util.GsonHelper;
import net.momirealms.craftengine.core.util.Key;
import net.momirealms.craftengine.core.util.ResourceConfigUtils;
import java.io.IOException;
import java.util.Map;
@@ -43,7 +44,7 @@ public class ResolutionMergeJson implements Resolution {
@Override
public Resolution create(Map<String, Object> arguments) {
boolean deeply = (boolean) arguments.getOrDefault("deeply", false);
boolean deeply = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("deeply", false), "deeply");
return new ResolutionMergeJson(deeply);
}
}

View File

@@ -90,8 +90,7 @@ public class AlistHost implements ResourcePackHost {
CraftEngine.instance().logger().info("[Alist] Loaded cached resource pack metadata");
} catch (Exception e) {
CraftEngine.instance().logger().warn(
"[Alist] Failed to load cache from disk: " + e.getMessage());
CraftEngine.instance().logger().warn("[Alist] Failed to load cache " + cachePath, e);
}
}
@@ -291,7 +290,7 @@ public class AlistHost implements ResourcePackHost {
@Override
public ResourcePackHost create(Map<String, Object> arguments) {
boolean useEnv = (boolean) arguments.getOrDefault("use-environment-variables", false);
boolean useEnv = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("use-environment-variables", false), "use-environment-variables");
String apiUrl = ResourceConfigUtils.requireNonEmptyStringOrThrow(arguments.get("api-url"), () -> new LocalizedException("warning.config.host.alist.missing_api_url"));
String userName = useEnv ? System.getenv("CE_ALIST_USERNAME") : Optional.ofNullable(arguments.get("username")).map(String::valueOf).orElse(null);
if (userName == null || userName.isEmpty()) {
@@ -305,7 +304,7 @@ public class AlistHost implements ResourcePackHost {
String otpCode = Optional.ofNullable(arguments.get("otp-code")).map(String::valueOf).orElse(null);
Duration jwtTokenExpiration = Duration.ofHours((int) arguments.getOrDefault("jwt-token-expiration", 48));
String uploadPath = ResourceConfigUtils.requireNonEmptyStringOrThrow(arguments.get("upload-path"), () -> new LocalizedException("warning.config.host.alist.missing_upload_path"));
boolean disableUpload = (boolean) arguments.getOrDefault("disable-upload", false);
boolean disableUpload = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("disable-upload", false), "disable-upload");
ProxySelector proxy = getProxySelector(MiscUtils.castToMap(arguments.get("proxy"), true));
return new AlistHost(apiUrl, userName, password, filePassword, otpCode, jwtTokenExpiration, uploadPath, disableUpload, proxy);
}

View File

@@ -63,7 +63,7 @@ public class DropboxHost implements ResourcePackHost {
CraftEngine.instance().logger().info("[Dropbox] Loaded cached resource pack info");
} catch (Exception e) {
CraftEngine.instance().logger().warn("[Dropbox] Failed to load cache", e);
CraftEngine.instance().logger().warn("[Dropbox] Failed to load cache " + cachePath, e);
}
}
@@ -263,7 +263,7 @@ public class DropboxHost implements ResourcePackHost {
@Override
public ResourcePackHost create(Map<String, Object> arguments) {
boolean useEnv = (boolean) arguments.getOrDefault("use-environment-variables", false);
boolean useEnv = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("use-environment-variables", false), "use-environment-variables");
String appKey = useEnv ? System.getenv("CE_DROPBOX_APP_KEY") : Optional.ofNullable(arguments.get("app-key")).map(String::valueOf).orElse(null);
if (appKey == null || appKey.isEmpty()) {
throw new LocalizedException("warning.config.host.dropbox.missing_app_key");

View File

@@ -7,10 +7,7 @@ import net.momirealms.craftengine.core.pack.host.ResourcePackHostFactory;
import net.momirealms.craftengine.core.pack.host.ResourcePackHosts;
import net.momirealms.craftengine.core.plugin.CraftEngine;
import net.momirealms.craftengine.core.plugin.locale.LocalizedException;
import net.momirealms.craftengine.core.util.GsonHelper;
import net.momirealms.craftengine.core.util.HashUtils;
import net.momirealms.craftengine.core.util.Key;
import net.momirealms.craftengine.core.util.MiscUtils;
import net.momirealms.craftengine.core.util.*;
import java.io.IOException;
import java.io.InputStream;
@@ -68,7 +65,7 @@ public class GitLabHost implements ResourcePackHost {
CraftEngine.instance().logger().info("[GitLab] Loaded cached resource pack info");
} catch (Exception e) {
CraftEngine.instance().logger().warn(
"[GitLab] Failed to read cache file: " + e.getMessage());
"[GitLab] Failed to read cache file: " + cachePath, e);
}
}
@@ -176,7 +173,7 @@ public class GitLabHost implements ResourcePackHost {
@Override
public ResourcePackHost create(Map<String, Object> arguments) {
boolean useEnv = (boolean) arguments.getOrDefault("use-environment-variables", false);
boolean useEnv = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("use-environment-variables", false), "use-environment-variables");
String gitlabUrl = Optional.ofNullable(arguments.get("gitlab-url")).map(String::valueOf).orElse(null);
if (gitlabUrl == null || gitlabUrl.isEmpty()) {
throw new LocalizedException("warning.config.host.gitlab.missing_url");

View File

@@ -10,6 +10,7 @@ import net.momirealms.craftengine.core.plugin.locale.LocalizedException;
import net.momirealms.craftengine.core.util.GsonHelper;
import net.momirealms.craftengine.core.util.Key;
import net.momirealms.craftengine.core.util.MiscUtils;
import net.momirealms.craftengine.core.util.ResourceConfigUtils;
import java.io.IOException;
import java.io.InputStream;
@@ -271,7 +272,7 @@ public class LobFileHost implements ResourcePackHost {
@Override
public ResourcePackHost create(Map<String, Object> arguments) {
boolean useEnv = (boolean) arguments.getOrDefault("use-environment-variables", false);
boolean useEnv = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("use-environment-variables", false), "use-environment-variables");
String apiKey = useEnv ? System.getenv("CE_LOBFILE_API_KEY") : Optional.ofNullable(arguments.get("api-key")).map(String::valueOf).orElse(null);
if (apiKey == null || apiKey.isEmpty()) {
throw new LocalizedException("warning.config.host.lobfile.missing_api_key");

View File

@@ -80,7 +80,7 @@ public class OneDriveHost implements ResourcePackHost {
CraftEngine.instance().logger().info("[OneDrive] Loaded cached resource pack info");
} catch (Exception e) {
CraftEngine.instance().logger().warn(
"[OneDrive] Failed to load cache from disk: " + e.getMessage());
"[OneDrive] Failed to load cache" + cachePath, e);
}
}
@@ -102,7 +102,7 @@ public class OneDriveHost implements ResourcePackHost {
);
} catch (IOException e) {
CraftEngine.instance().logger().warn(
"[OneDrive] Failed to persist cache to disk: " + e.getMessage());
"[OneDrive] Failed to persist cache", e);
}
}
@@ -230,7 +230,7 @@ public class OneDriveHost implements ResourcePackHost {
@Override
public ResourcePackHost create(Map<String, Object> arguments) {
boolean useEnv = (boolean) arguments.getOrDefault("use-environment-variables", false);
boolean useEnv = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("use-environment-variables", false), "use-environment-variables");
String clientId = useEnv ? System.getenv("CE_ONEDRIVE_CLIENT_ID") : Optional.ofNullable(arguments.get("client-id")).map(String::valueOf).orElse(null);
if (clientId == null || clientId.isEmpty()) {
throw new LocalizedException("warning.config.host.onedrive.missing_client_id");

View File

@@ -73,9 +73,9 @@ public class SelfHost implements ResourcePackHost {
}
if (!url.endsWith("/")) url += "/";
}
boolean oneTimeToken = (boolean) arguments.getOrDefault("one-time-token", true);
boolean oneTimeToken = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("one-time-token", true), "one-time-token");
String protocol = arguments.getOrDefault("protocol", "http").toString();
boolean denyNonMinecraftRequest = (boolean) arguments.getOrDefault("deny-non-minecraft-request", true);
boolean denyNonMinecraftRequest = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("deny-non-minecraft-request", true), "deny-non-minecraft-request");
Map<String, Object> rateMap = MiscUtils.castToMap(arguments.get("rate-map"), true);
int maxRequests = 5;
int resetInterval = 20_000;

View File

@@ -42,7 +42,7 @@ public class HasComponentConditionProperty implements ConditionProperty {
@Override
public ConditionProperty create(Map<String, Object> arguments) {
boolean ignoreDefault = (boolean) arguments.getOrDefault("ignore-default", false);
boolean ignoreDefault = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("ignore-default", false), "ignore-default");
String componentObj = ResourceConfigUtils.requireNonEmptyStringOrThrow(arguments.get("component"), "warning.config.item.model.condition.has_component.missing_component");
return new HasComponentConditionProperty(componentObj, ignoreDefault);
}

View File

@@ -8,6 +8,7 @@ import net.momirealms.craftengine.core.plugin.locale.LocalizedResourceConfigExce
import net.momirealms.craftengine.core.util.EnumUtils;
import net.momirealms.craftengine.core.util.Key;
import net.momirealms.craftengine.core.util.MiscUtils;
import net.momirealms.craftengine.core.util.ResourceConfigUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
@@ -54,7 +55,7 @@ public class ModelGeneration implements Supplier<JsonObject> {
}
});
BUILDER_FUNCTIONS.put("ambient-occlusion", (b, data) -> {
b.ambientOcclusion((boolean) data);
b.ambientOcclusion(ResourceConfigUtils.getAsBoolean(data, "ambient-occlusion"));
});
BUILDER_FUNCTIONS.put("parent", (b, data) -> {
String parentModelPath = data.toString();

View File

@@ -3,6 +3,7 @@ package net.momirealms.craftengine.core.pack.model.rangedisptach;
import com.google.gson.JsonObject;
import net.momirealms.craftengine.core.pack.model.LegacyModelPredicate;
import net.momirealms.craftengine.core.util.Key;
import net.momirealms.craftengine.core.util.ResourceConfigUtils;
import java.util.Map;
@@ -43,7 +44,7 @@ public class DamageRangeDispatchProperty implements RangeDispatchProperty, Legac
@Override
public RangeDispatchProperty create(Map<String, Object> arguments) {
boolean normalize = (boolean) arguments.getOrDefault("normalize", true);
boolean normalize = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("normalize", true), "normalize");
return new DamageRangeDispatchProperty(normalize);
}
}

View File

@@ -2,6 +2,7 @@ package net.momirealms.craftengine.core.pack.model.rangedisptach;
import com.google.gson.JsonObject;
import net.momirealms.craftengine.core.util.Key;
import net.momirealms.craftengine.core.util.ResourceConfigUtils;
import java.util.Map;
@@ -33,7 +34,7 @@ public class NormalizeRangeDispatchProperty implements RangeDispatchProperty {
@Override
public RangeDispatchProperty create(Map<String, Object> arguments) {
Key type = Key.of(arguments.get("property").toString());
boolean normalize = (boolean) arguments.getOrDefault("normalize", true);
boolean normalize = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("normalize", true), "normalize");
return new NormalizeRangeDispatchProperty(type, normalize);
}
}

View File

@@ -35,7 +35,7 @@ public class TimeRangeDispatchProperty implements RangeDispatchProperty {
@Override
public RangeDispatchProperty create(Map<String, Object> arguments) {
String sourceObj = ResourceConfigUtils.requireNonEmptyStringOrThrow(arguments.get("source"), "warning.config.item.model.range_dispatch.time.missing_source");
boolean wobble = (boolean) arguments.getOrDefault("wobble", true);
boolean wobble = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("wobble", true), "wobble");
return new TimeRangeDispatchProperty(sourceObj, wobble);
}
}

View File

@@ -4,6 +4,7 @@ import com.google.gson.JsonObject;
import net.momirealms.craftengine.core.item.ItemKeys;
import net.momirealms.craftengine.core.pack.model.LegacyModelPredicate;
import net.momirealms.craftengine.core.util.Key;
import net.momirealms.craftengine.core.util.ResourceConfigUtils;
import java.util.Map;
@@ -43,7 +44,7 @@ public class UseDurationRangeDispatchProperty implements RangeDispatchProperty,
@Override
public RangeDispatchProperty create(Map<String, Object> arguments) {
boolean remaining = (boolean) arguments.getOrDefault("remaining", false);
boolean remaining = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("remaining", false), "remaining");
return new UseDurationRangeDispatchProperty(remaining);
}
}

View File

@@ -7,6 +7,7 @@ import net.momirealms.craftengine.core.plugin.context.parameter.DirectContextPar
import net.momirealms.craftengine.core.plugin.locale.LocalizedResourceConfigException;
import net.momirealms.craftengine.core.util.Key;
import net.momirealms.craftengine.core.util.MiscUtils;
import net.momirealms.craftengine.core.util.ResourceConfigUtils;
import java.util.*;
@@ -50,7 +51,7 @@ public class MatchItemCondition<CTX extends Context> implements Condition<CTX> {
if (ids.isEmpty()) {
throw new LocalizedResourceConfigException("warning.config.condition.match_item.missing_id");
}
boolean regex = (boolean) arguments.getOrDefault("regex", false);
boolean regex = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("regex", false), "regex");
return new MatchItemCondition<>(ids, regex);
}
}

View File

@@ -69,7 +69,7 @@ public class CommandFunction<CTX extends Context> extends AbstractConditionalFun
public Function<CTX> create(Map<String, Object> arguments) {
Object command = ResourceConfigUtils.requireNonNullOrThrow(ResourceConfigUtils.get(arguments, "command", "commands"), "warning.config.function.command.missing_command");
List<TextProvider> commands = MiscUtils.getAsStringList(command).stream().map(TextProviders::fromString).toList();
boolean asPlayer = (boolean) arguments.getOrDefault("as-player", false);
boolean asPlayer = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("as-player", false), "as-player");
return new CommandFunction<>(getPredicates(arguments), PlayerSelectors.fromObject(arguments.get("target"), conditionFactory()), commands, asPlayer);
}
}

View File

@@ -61,7 +61,7 @@ public class MessageFunction<CTX extends Context> extends AbstractConditionalFun
public Function<CTX> create(Map<String, Object> arguments) {
Object message = ResourceConfigUtils.requireNonNullOrThrow(ResourceConfigUtils.get(arguments, "messages", "message"), "warning.config.function.command.missing_message");
List<TextProvider> messages = MiscUtils.getAsStringList(message).stream().map(TextProviders::fromString).toList();
boolean overlay = (boolean) arguments.getOrDefault("overlay", false);
boolean overlay = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("overlay", false), "overlay");
return new MessageFunction<>(getPredicates(arguments), PlayerSelectors.fromObject(arguments.get("target"), conditionFactory()), messages, overlay);
}
}

View File

@@ -61,8 +61,8 @@ public class PotionEffectFunction<CTX extends Context> extends AbstractCondition
Key effectType = Key.of(ResourceConfigUtils.requireNonEmptyStringOrThrow(arguments.get("potion-effect"), "warning.config.function.potion_effect.missing_potion_effect"));
NumberProvider duration = NumberProviders.fromObject(arguments.getOrDefault("duration", 20));
NumberProvider amplifier = NumberProviders.fromObject(arguments.getOrDefault("amplifier", 0));
boolean ambient = (boolean) arguments.getOrDefault("ambient", false);
boolean particles = (boolean) arguments.getOrDefault("particles", true);
boolean ambient = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("ambient", false), "ambient");
boolean particles = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("particles", true), "particles");
return new PotionEffectFunction<>(effectType, duration, amplifier, ambient, particles, PlayerSelectors.fromObject(arguments.get("target"), conditionFactory()), getPredicates(arguments));
}
}

View File

@@ -57,7 +57,7 @@ public class RemoveCooldownFunction<CTX extends Context> extends AbstractConditi
@Override
public Function<CTX> create(Map<String, Object> arguments) {
boolean all = (boolean) arguments.getOrDefault("all", false);
boolean all = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("all", false), "all");
if (all) {
return new RemoveCooldownFunction<>(null, true, PlayerSelectors.fromObject(arguments.get("target"), conditionFactory()), getPredicates(arguments));
} else {

View File

@@ -52,7 +52,7 @@ public class RemovePotionEffectFunction<CTX extends Context> extends AbstractCon
@Override
public Function<CTX> create(Map<String, Object> arguments) {
boolean all = (boolean) arguments.getOrDefault("all", false);
boolean all = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("all", false), "all");
if (all) {
return new RemovePotionEffectFunction<>(null, true, PlayerSelectors.fromObject(arguments.get("target"), conditionFactory()), getPredicates(arguments));
} else {

View File

@@ -65,7 +65,7 @@ public class SetCooldownFunction<CTX extends Context> extends AbstractConditiona
public Function<CTX> create(Map<String, Object> arguments) {
String id = ResourceConfigUtils.requireNonEmptyStringOrThrow(arguments.get("id"), "warning.config.function.set_cooldown.missing_id");
String time = ResourceConfigUtils.requireNonEmptyStringOrThrow(arguments.get("time"), "warning.config.function.set_cooldown.missing_time");
boolean add = (boolean) arguments.getOrDefault("add", false);
boolean add = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("add", false), "add");
return new SetCooldownFunction<>(TextProviders.fromString(time), id, add, PlayerSelectors.fromObject(arguments.get("target"), conditionFactory()), getPredicates(arguments));
}
}

View File

@@ -50,7 +50,7 @@ public class SetCountFunction<CTX extends Context> extends AbstractConditionalFu
@Override
public Function<CTX> create(Map<String, Object> arguments) {
Object value = ResourceConfigUtils.requireNonNullOrThrow(arguments.get("count"), "warning.config.function.set_count.missing_count");
boolean add = (boolean) arguments.getOrDefault("add", false);
boolean add = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("add", false), "add");
return new SetCountFunction<>(NumberProviders.fromObject(value), add, getPredicates(arguments));
}
}

View File

@@ -53,7 +53,7 @@ public class SetFoodFunction<CTX extends Context> extends AbstractConditionalFun
@Override
public Function<CTX> create(Map<String, Object> arguments) {
Object value = ResourceConfigUtils.requireNonNullOrThrow(arguments.get("food"), "warning.config.function.set_food.missing_food");
boolean add = (boolean) arguments.getOrDefault("add", false);
boolean add = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("add", false), "add");
return new SetFoodFunction<>(NumberProviders.fromObject(value), add, PlayerSelectors.fromObject(arguments.get("target"), conditionFactory()), getPredicates(arguments));
}
}

View File

@@ -53,7 +53,7 @@ public class SetSaturationFunction<CTX extends Context> extends AbstractConditio
@Override
public Function<CTX> create(Map<String, Object> arguments) {
Object value = ResourceConfigUtils.requireNonNullOrThrow(arguments.get("saturation"), "warning.config.function.set_saturation.missing_saturation");
boolean add = (boolean) arguments.getOrDefault("add", false);
boolean add = ResourceConfigUtils.getAsBoolean(arguments.getOrDefault("add", false), "add");
return new SetSaturationFunction<>(NumberProviders.fromObject(value), add, PlayerSelectors.fromObject(arguments.get("target"), conditionFactory()), getPredicates(arguments));
}
}

View File

@@ -117,7 +117,8 @@ public class ItemBrowserManagerImpl implements ItemBrowserManager {
List<String> members = MiscUtils.getAsStringList(section.getOrDefault("list", List.of()));
Key icon = Key.of(section.getOrDefault("icon", ItemKeys.STONE).toString());
int priority = ResourceConfigUtils.getAsInt(section.getOrDefault("priority", 0), "priority");
Category category = new Category(id, name, MiscUtils.getAsStringList(section.getOrDefault("lore", List.of())), icon, members.stream().distinct().toList(), priority, (boolean) section.getOrDefault("hidden", false));
Category category = new Category(id, name, MiscUtils.getAsStringList(section.getOrDefault("lore", List.of())), icon, members.stream().distinct().toList(), priority,
ResourceConfigUtils.getAsBoolean(section.getOrDefault("hidden", false), "hidden"));
if (ItemBrowserManagerImpl.this.byId.containsKey(id)) {
ItemBrowserManagerImpl.this.byId.get(id).merge(category);
} else {

View File

@@ -104,7 +104,7 @@ public abstract class AbstractSoundManager implements SoundManager {
if (AbstractSoundManager.this.byId.containsKey(id)) {
throw new LocalizedResourceConfigException("warning.config.sound.duplicate");
}
boolean replace = (boolean) section.getOrDefault("replace", false);
boolean replace = ResourceConfigUtils.getAsBoolean(section.getOrDefault("replace", false), "replace");
String subtitle = (String) section.get("subtitle");
List<?> soundList = (List<?>) ResourceConfigUtils.requireNonNullOrThrow(section.get("sounds"), "warning.config.sound.missing_sounds");
List<Sound> sounds = new ArrayList<>();

View File

@@ -172,4 +172,28 @@ public final class ResourceConfigUtils {
}
}
}
public static boolean getAsBoolean(Object o, String option) {
switch (o) {
case null -> {
return false;
}
case Boolean b -> {
return b;
}
case Number n -> {
if (n.byteValue() == 0) return false;
if (n.byteValue() == 1) return true;
throw new LocalizedResourceConfigException("warning.config.type.boolean", String.valueOf(n), option);
}
case String s -> {
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
throw new LocalizedResourceConfigException("warning.config.type.boolean", s, option);
}
default -> {
throw new LocalizedResourceConfigException("warning.config.type.boolean", o.toString(), option);
}
}
}
}