diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 00000000..d40c32c0 --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "pose-calibrator", + "runtimeExecutable": "python", + "runtimeArgs": ["-m", "http.server", "8765"], + "port": 8765 + } + ] +} diff --git a/.github/dependabot.yml b/.github/dependabot.yml index fe13a041..35058f5f 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,9 +1,18 @@ version: 2 updates: - - package-ecosystem: "maven" + - package-ecosystem: "gradle" directory: "/" + target-branch: "develop" schedule: interval: "weekly" open-pull-requests-limit: 10 commit-message: prefix: "deps" + + - package-ecosystem: "github-actions" + directory: "/" + target-branch: "develop" + schedule: + interval: "weekly" + commit-message: + prefix: "ci" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..53f8bfec --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,36 @@ +name: Build + +# Every push and pull request, on any branch. The job name "Build" is a required check of the +# master ruleset (docs/BRANCHING_PLAN.md): renaming it breaks merging into master. +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + name: Build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 21 + 25 + + - uses: gradle/actions/setup-gradle@v4 + + - name: Build and test + run: ./gradlew build --console=plain + + - name: Upload plugin jar + uses: actions/upload-artifact@v4 + with: + name: CraftEngineConverter + path: Plugin/build/libs/CraftEngineConverter-*.jar diff --git a/.github/workflows/dev-build.yml b/.github/workflows/dev-build.yml new file mode 100644 index 00000000..a6fffc06 --- /dev/null +++ b/.github/workflows/dev-build.yml @@ -0,0 +1,88 @@ +name: Dev build + +# Every push to develop makes a dev build (docs/BRANCHING_PLAN.md): version -dev. +# (0.0.3-dev.5, from the -SNAPSHOT version in gradle.properties), built and tested, then posted as +# the rolling GitHub pre-release "dev" (tag moved to the commit, jar replaced). It is never marked +# latest, so the newest real release stays the one GitHub shows first. +# +# A newer push cancels a build still building or testing (only the newest commit is worth +# publishing), but never a publish under way: that one finishes, and the newer publish waits. +# +# "[skip dev]" in the last commit message of a push skips the dev build (the Build workflow still +# runs); a skipped push does not cancel a build under way. "[skip ci]" skips every workflow. +on: + push: + branches: [develop] + paths-ignore: + - "docs/**" + - "**.md" + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + if: github.repository == '1robie/CraftEngineConverter' && !contains(github.event.head_commit.message, '[skip dev]') + runs-on: ubuntu-latest + concurrency: + group: dev-build-build + cancel-in-progress: true + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + + - name: Version + id: version + run: | + base=$(grep -oP '^version\s*=\s*\K.+' gradle.properties) + echo "version=${base%-SNAPSHOT}-dev.${{ github.run_number }}" >> "$GITHUB_OUTPUT" + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 21 + 25 + + - uses: gradle/actions/setup-gradle@v4 + + - name: Build and test + run: ./gradlew build -Pversion="${{ steps.version.outputs.version }}" --console=plain + + publish: + needs: build + runs-on: ubuntu-latest + concurrency: + group: dev-build-publish + cancel-in-progress: false + permissions: + contents: write + env: + VERSION: ${{ needs.build.outputs.version }} + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 21 + 25 + + - uses: gradle/actions/setup-gradle@v4 + + # Tested in the build job; this only assembles the same commit's jar again. + - name: Plugin jar + run: ./gradlew :Plugin:shadowJar -Pversion="$VERSION" --console=plain + + - name: GitHub pre-release "dev" + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release delete dev --cleanup-tag --yes || true + gh release create dev "Plugin/build/libs/CraftEngineConverter-$VERSION.jar" \ + --target "$GITHUB_SHA" --prerelease --latest=false \ + --title "CraftEngineConverter dev build ($VERSION)" \ + --notes "Unstable build of \`develop\` at $GITHUB_SHA, replaced on every push. Releases: https://github.com/1robie/CraftEngineConverter/releases" diff --git a/.github/workflows/release-source.yml b/.github/workflows/release-source.yml new file mode 100644 index 00000000..6c0ae871 --- /dev/null +++ b/.github/workflows/release-source.yml @@ -0,0 +1,38 @@ +name: Release source + +# master only takes releases (docs/BRANCHING_PLAN.md): a pull request into it must be opened by the +# repository owner, from develop or a hotfix/* branch of this repository. Everyone else targets +# develop. The master ruleset requires this check; a ruleset cannot restrict the author or the source +# branch on its own. +on: + pull_request: + branches: [master] + types: [opened, reopened, synchronize, edited] + +permissions: {} + +jobs: + release-source: + name: Release source + runs-on: ubuntu-latest + steps: + - name: Check the source branch + env: + HEAD_REF: ${{ github.head_ref }} + HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }} + AUTHOR: ${{ github.event.pull_request.user.login }} + OWNER: ${{ github.repository_owner }} + run: | + if [ "$AUTHOR" != "$OWNER" ]; then + echo "::error::Only $OWNER opens pull requests into master (releases). Target develop instead." + exit 1 + fi + if [ "$HEAD_REPO" != "$GITHUB_REPOSITORY" ]; then + echo "::error::A pull request into master must come from this repository, not $HEAD_REPO." + exit 1 + fi + case "$HEAD_REF" in + develop|hotfix/*) echo "Source branch $HEAD_REF is allowed." ;; + *) echo "::error::A pull request into master must come from develop or hotfix/*, not $HEAD_REF. Target develop instead." + exit 1 ;; + esac diff --git a/.gitignore b/.gitignore index 7d792e1e..e41fe9c2 100644 --- a/.gitignore +++ b/.gitignore @@ -97,6 +97,15 @@ $RECYCLE.BIN/ target/ +# Gradle +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.properties +# `*.jar` above would otherwise swallow the wrapper jar, which MUST be committed so that +# `./gradlew` works on a fresh clone. +!gradle/wrapper/gradle-wrapper.jar + +# Maven leftovers (the build migrated to Gradle; the pom.xml files are gone) pom.xml.tag pom.xml.releaseBackup pom.xml.versionsBackup @@ -111,6 +120,7 @@ buildNumber.properties # Common working directory run/ +logs/ /AGENTS.md .classpath .factorypath @@ -120,3 +130,11 @@ run/ .gemini/ gha-creds-*.json /GEMINI.md +agent.yaml +reflection/ +concepts/ +MCBE-Vanilla-RP/ +Minecraft-default-assets-latest/ + +# Local documentation, never committed +docs/ diff --git a/API/build.gradle.kts b/API/build.gradle.kts new file mode 100644 index 00000000..3a1c3dfc --- /dev/null +++ b/API/build.gradle.kts @@ -0,0 +1,20 @@ +plugins { + id("craftengineconverter.java-conventions") +} + +base { + archivesName = "CraftEngineConverter-API" +} + +dependencies { + api(libs.folialib) + + compileOnly(libs.paper.api) + compileOnly(libs.craftengine.core) + compileOnly(libs.craftengine.bukkit) + compileOnly(libs.sarah) + compileOnly(libs.reflections) + compileOnly(libs.message.flow) + compileOnly(libs.yamllibrary) + compileOnly(libs.yamllibrary.core) +} diff --git a/API/pom.xml b/API/pom.xml deleted file mode 100644 index 7c35cf85..00000000 --- a/API/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - 4.0.0 - - fr.robie.craftengineconverter - CraftEngineConverter - 0.0.2 - - - API - - - CraftEngineConverter-API-${project.version} - - - - - io.papermc.paper - paper-api - - - - net.momirealms - craft-engine-core - - - net.momirealms - craft-engine-bukkit - - - - fr.maxlego08.sarah - sarah - provided - - - - com.tcoded - FoliaLib - - - - com.github.1robie.MessageFlow - message-flow - provided - - - \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoModelConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoModelConfigurationLoader.java new file mode 100644 index 00000000..d4b876bd --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoModelConfigurationLoader.java @@ -0,0 +1,14 @@ +package fr.robie.craftengineconverter.api.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface AutoModelConfigurationLoader { + + + String[] value(); +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoRangeDispatchConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoRangeDispatchConfigurationLoader.java new file mode 100644 index 00000000..b31f8927 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoRangeDispatchConfigurationLoader.java @@ -0,0 +1,15 @@ +package fr.robie.craftengineconverter.api.annotations; + +import org.jetbrains.annotations.NotNull; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface AutoRangeDispatchConfigurationLoader { + @NotNull + String[] value(); +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoSelectModelConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoSelectModelConfigurationLoader.java new file mode 100644 index 00000000..22a96f72 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoSelectModelConfigurationLoader.java @@ -0,0 +1,15 @@ +package fr.robie.craftengineconverter.api.annotations; + +import org.jetbrains.annotations.NotNull; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface AutoSelectModelConfigurationLoader { + @NotNull + String[] value(); +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoTintConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoTintConfigurationLoader.java new file mode 100644 index 00000000..5c353a9e --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/AutoTintConfigurationLoader.java @@ -0,0 +1,12 @@ +package fr.robie.craftengineconverter.api.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface AutoTintConfigurationLoader { + String[] value(); +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/annotations/PaperOnly.java b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/PaperOnly.java new file mode 100644 index 00000000..f3c32c90 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/PaperOnly.java @@ -0,0 +1,16 @@ +package fr.robie.craftengineconverter.api.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marks a class as Paper-only. + * Classes annotated with this will only be registered when running on Paper or Paper-based servers. + * Can be combined with {@link SinceVersion} and {@link UntilVersion} for finer-grained control. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface PaperOnly { +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/annotations/RequiresPlugin.java b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/RequiresPlugin.java new file mode 100644 index 00000000..220749e9 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/RequiresPlugin.java @@ -0,0 +1,31 @@ +package fr.robie.craftengineconverter.api.annotations; + +import fr.robie.craftengineconverter.api.utils.Comparison; +import org.jetbrains.annotations.NotNull; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface RequiresPlugin { + @NotNull + String value(); + + @NotNull + String version() default ""; + + @NotNull + Comparison type() default Comparison.GREATER_THAN_OR_EQUAL_TO; + + @NotNull + CheckMode checkMode() default CheckMode.EXISTS; + + enum CheckMode { + EXISTS, + EXISTS_AND_ENABLED + } + +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/annotations/SinceVersion.java b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/SinceVersion.java new file mode 100644 index 00000000..5d1775b3 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/SinceVersion.java @@ -0,0 +1,25 @@ +package fr.robie.craftengineconverter.api.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Declares the minimum Minecraft version (inclusive) for which a class should be registered. + * Classes annotated with this will be skipped on servers running versions older than the declared minimum. + * + *

Example: {@code @SinceVersion("1.21.4")} registers the class only on 1.21.4 and above. + * + *

Can be combined with {@link UntilVersion} to define a closed version range, + * and with {@link PaperOnly} / {@link SpigotOnly} for platform filtering. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface SinceVersion { + + /** + * The minimum Minecraft version string, e.g. {@code "1.21.4"}. + */ + String value(); +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/annotations/SpigotOnly.java b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/SpigotOnly.java new file mode 100644 index 00000000..897ace90 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/SpigotOnly.java @@ -0,0 +1,16 @@ +package fr.robie.craftengineconverter.api.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marks a class as Spigot-only (non-Paper servers). + * Classes annotated with this will only be registered when running on Spigot (not Paper). + * Can be combined with {@link SinceVersion} and {@link UntilVersion} for finer-grained control. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface SpigotOnly { +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/annotations/UntilVersion.java b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/UntilVersion.java new file mode 100644 index 00000000..57719de0 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/annotations/UntilVersion.java @@ -0,0 +1,25 @@ +package fr.robie.craftengineconverter.api.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Declares the maximum Minecraft version (inclusive) for which a class should be registered. + * Classes annotated with this will be skipped on servers running versions newer than the declared maximum. + * + *

Example: {@code @UntilVersion("1.21.3")} registers the class only on 1.21.3 and below. + * + *

Can be combined with {@link SinceVersion} to define a closed version range, + * and with {@link PaperOnly} / {@link SpigotOnly} for platform filtering. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface UntilVersion { + + /** + * The maximum Minecraft version string, e.g. {@code "1.21.3"}. + */ + String value(); +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/builder/TimerBuilder.java b/API/src/main/java/fr/robie/craftengineconverter/api/builder/TimerBuilder.java index 08c4abb8..efbcb413 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/builder/TimerBuilder.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/builder/TimerBuilder.java @@ -69,13 +69,10 @@ public static String formatTime(long milliseconds, TimeUnit maxUnit) { String message = maxUnit.getTimeMessage().firstLine(); - Logger.info("Formatting time: " + milliseconds + " ms with max unit: " + maxUnit.name()); - Logger.info("Calculated values: " + values); Placeholder.Builder placeholderBuilder = new Placeholder.Builder(); for (int i = 0; i < unitsToInclude.size(); i++) { TimeUnit unit = unitsToInclude.get(i); placeholderBuilder.register(unit.name().toLowerCase(Locale.ROOT), unit.getFormat(values.get(i))); - Logger.info("Registered placeholder: " + unit.name().toLowerCase(Locale.ROOT) + " -> " + unit.getFormat(values.get(i))); } Placeholder placeholder = placeholderBuilder.build(); @@ -94,7 +91,6 @@ public static String formatTime(long milliseconds, TimeUnit maxUnit) { */ @Contract(pure = true) public static String formatTimeAuto(long milliseconds) { - Logger.info("Formatting time: " + milliseconds + " ms"); long seconds = milliseconds / 1000L; if (milliseconds < 1000) { diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/cache/FileCache.java b/API/src/main/java/fr/robie/craftengineconverter/api/cache/FileCache.java similarity index 97% rename from Common/src/main/java/fr/robie/craftengineconverter/common/cache/FileCache.java rename to API/src/main/java/fr/robie/craftengineconverter/api/cache/FileCache.java index 5af4cae9..33119335 100644 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/cache/FileCache.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/cache/FileCache.java @@ -1,4 +1,4 @@ -package fr.robie.craftengineconverter.common.cache; +package fr.robie.craftengineconverter.api.cache; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/cache/FileCacheEntry.java b/API/src/main/java/fr/robie/craftengineconverter/api/cache/FileCacheEntry.java similarity index 92% rename from Common/src/main/java/fr/robie/craftengineconverter/common/cache/FileCacheEntry.java rename to API/src/main/java/fr/robie/craftengineconverter/api/cache/FileCacheEntry.java index b430245b..aca08d34 100644 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/cache/FileCacheEntry.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/cache/FileCacheEntry.java @@ -1,4 +1,4 @@ -package fr.robie.craftengineconverter.common.cache; +package fr.robie.craftengineconverter.api.cache; import java.io.File; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/cache/SimpleCache.java b/API/src/main/java/fr/robie/craftengineconverter/api/cache/SimpleCache.java index 295c6d81..78445891 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/cache/SimpleCache.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/cache/SimpleCache.java @@ -1,25 +1,39 @@ package fr.robie.craftengineconverter.api.cache; -import java.util.HashMap; import java.util.Map; - +import java.util.concurrent.ConcurrentHashMap; + +/** + * A small keep-forever cache, safe to read while it is being written. + * + *

Its one user is filled by a conversion running on its own thread and read by chat formatting and placeholder + * resolution on whichever thread asks - so a plain map was being written and read at the same time, which costs + * either a stale answer or a corrupted table. Null keys and values are ignored rather than throwing, since the keys + * come from whatever text a player happened to send. + */ public class SimpleCache { - private final Map cache = new HashMap<>(); + private final Map cache = new ConcurrentHashMap<>(); public V get(K key) { - return this.cache.get(key); + return key == null ? null : this.cache.get(key); } public V getOrDefault(K key, Loader loader) { - return this.cache.computeIfAbsent(key, (k) -> loader.load()); + if (key == null) { + return loader.load(); + } + return this.cache.computeIfAbsent(key, k -> loader.load()); } public void put(K key, V value) { + if (key == null || value == null) { + return; + } this.cache.put(key, value); } public boolean containsKey(K key) { - return this.cache.containsKey(key); + return key != null && this.cache.containsKey(key); } public interface Loader { @@ -29,4 +43,4 @@ public interface Loader { public void clear() { this.cache.clear(); } -} \ No newline at end of file +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/ConfigFile.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/ConfigFile.java new file mode 100644 index 00000000..40bcdaef --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/ConfigFile.java @@ -0,0 +1,35 @@ +package fr.robie.craftengineconverter.api.configuration; + +import org.jetbrains.annotations.NotNull; + +/** + * The configuration files the plugin ships, one per converter plus a general one. + *

+ * Split because a single file grew to 318 lines covering every converter at once: a user had to scroll past + * the Nexo, ItemsAdder and world-converter blocks to reach the handful of settings they came for, and every new + * converter made that worse. One file per converter means a server owner opens exactly the file they mean to edit. + *

+ * {@code database-config.yml} is deliberately absent. It already had its own file and its own loader before this + * split, reads no {@link Key} at all, and folding it in would be a change with no benefit to the person editing it. + */ +public enum ConfigFile { + + /** General settings that belong to no single converter: debug, language, formatting, tags, progress bars. */ + MAIN("config.yml"), + + NEXO("nexo.yml"), + ITEMS_ADDER("itemsadder.yml"), + WORLD("world-converter.yml"); + + private final String fileName; + + ConfigFile(@NotNull String fileName) { + this.fileName = fileName; + } + + /** The name on disk, and equally the resource name inside the jar, so {@code saveResource} can take it. */ + @NotNull + public String fileName() { + return this.fileName; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/Configuration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/Configuration.java index db192b0d..37fc9803 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/Configuration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/Configuration.java @@ -10,15 +10,16 @@ import fr.robie.craftengineconverter.api.progress.ProgressBarUtils; import fr.robie.messageflow.formatter.Placeholder; import fr.robie.messageflow.logger.Logger; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.*; public class Configuration { - private static final Map configValues = new EnumMap<>(ConfigurationKey.class); + private static final Map, Object> configValues = new IdentityHashMap<>(); public static ProgressBarUtils worldConverterProgressBarOptions = ProgressBarOption.of(BukkitProgressBar.ProgressColor.GOLD); @@ -47,11 +48,11 @@ public static Configuration getInstance() { * @return true if the path matches any blacklisted pattern */ public static boolean isPathBlacklisted(String namespacedPath) { - if (namespacedPath == null || (Configuration.>get(ConfigurationKey.BLACKLISTED_PATHS)).isEmpty()) { + if (namespacedPath == null || (Configuration.get(Keys.BLACKLISTED_PATHS)).isEmpty()) { return false; } - for (String pattern : Configuration.>get(ConfigurationKey.BLACKLISTED_PATHS)) { + for (String pattern : Configuration.get(Keys.BLACKLISTED_PATHS)) { if (matchesPattern(namespacedPath, pattern)) { return true; } @@ -100,23 +101,51 @@ private static boolean matchesPattern(String path, String pattern) { return false; } - public void load(YamlConfiguration config, File file) { + /** + * Reads one configuration file, applying only the keys that belong to it. + *

+ * Per file rather than all at once because the settings now live in several: {@code config.yml} for what belongs + * to no converter, and one file per converter beside it. A key names its own file, so this needs no list of its + * own — see {@link Key#in}. + *

+ * A key the file does not mention is written back with its default and the file saved, which is how a setting + * added in a new version reaches an existing install. + */ + public void load(@NotNull ConfigFile configFile, YamlConfiguration config, File file) { + this.load(configFile, config, file, null); + } + + /** + * @param legacy the old single {@code config.yml}, consulted for a setting this file does not have yet, or + * {@code null} when there is none to adopt from + */ + public void load(@NotNull ConfigFile configFile, YamlConfiguration config, File file, + @Nullable YamlConfiguration legacy) { long startTime = System.currentTimeMillis(); - for (ConfigurationKey key : ConfigurationKey.values()) { - Object defaultValue = key.getDefaultValue(); - Object o = config.get(key.getPath()); + for (Key key : Key.in(configFile)) { + Object defaultValue = key.defaultValue(); + Object o = config.get(key.path()); + + // Not here yet, but perhaps under the name it had before the settings were split across files. Adopting + // it is what carries an existing server's configuration across an upgrade, and it needs no version + // marker to decide when to do it: once adopted the old entry is gone, so a later run finds nothing to + // move. The state of the files is the record. if (o == null) { - config.set(key.getPath(), defaultValue); + Adopted adopted = this.adopt(key, config, legacy); + if (adopted != null) { + o = adopted.value(); + this.movedFrom.merge(adopted.source(), 1, Integer::sum); + this.isUpdated = true; + } + } + + if (o == null) { + this.write(config, key, defaultValue); this.isUpdated = true; - if (key.getRawType().isInstance(defaultValue)) { + if (key.rawType().isInstance(defaultValue)) { configValues.put(key, defaultValue); } else { - Placeholder.Builder builder = Placeholder.builder(); - builder.register("expected", key.getRawType().getSimpleName()); - builder.register("got", defaultValue.getClass().getSimpleName()); - builder.register("default", defaultValue.toString()); - builder.register("path", key.getPath()); - Logger.debug(Message.ERROR__PLUGIN__CONFIGURATION__TYPE_MISMATCH, builder.build()); + this.reportTypeMismatch(key, defaultValue.getClass(), defaultValue); } continue; } @@ -124,38 +153,42 @@ public void load(YamlConfiguration config, File file) { try { value = key.deserialize(o); } catch (Exception e) { - Logger.warn("Invalid value for " + key.getPath() + " in configuration, using default value: " + defaultValue); + Logger.warn("Invalid value for " + key.path() + " in " + configFile.fileName() + + ", using default value: " + defaultValue); value = defaultValue; } - if (key.getRawType().isInstance(value)) { + if (key.rawType().isInstance(value)) { configValues.put(key, value); } else { - Placeholder.Builder builder = Placeholder.builder(); - builder.register("expected", key.getRawType().getSimpleName()); - builder.register("got", value.getClass().getSimpleName()); - builder.register("default", defaultValue.toString()); - builder.register("path", key.getPath()); - Logger.debug(Message.ERROR__PLUGIN__CONFIGURATION__TYPE_MISMATCH, builder.build()); + this.reportTypeMismatch(key, value.getClass(), defaultValue); } } - for (ConverterOption options : ConverterOption.values()) { - if (options == ConverterOption.ALL) { - continue; + + // Three settings that were never keys, each mutating something else rather than storing a value. They stay + // as they were; only the file they are read from is now pinned down. + if (configFile == ConfigFile.MAIN) { + for (ConverterOption options : ConverterOption.values()) { + if (options == ConverterOption.ALL) { + continue; + } + String path = "progress-bar-options." + options.name().toLowerCase(Locale.ROOT).replace("_", "-"); + this.loadProgressBarOption(config, options, path); + } + for (CraftEngineBlockState blockStateLimit : CraftEngineBlockState.values()) { + String path = "block-state-limit." + blockStateLimit.name().toLowerCase(Locale.ROOT).replace("_", "-"); + int startLimit = this.getOrAddInt(config, path + ".start-limit", blockStateLimit.getStart()); + try { + blockStateLimit.setStart(startLimit); + } catch (Exception e) { + Logger.debug("Invalid start limit for " + blockStateLimit.name() + " in configuration."); + } } - String path = "progress-bar-options." + options.name().toLowerCase(Locale.ROOT).replace("_", "-"); - this.loadProgressBarOption(config, options, path); - } - ConfigurationSection worldConverterProgressBarSection = config.getConfigurationSection("world-converter.progress-bar-options"); - if (worldConverterProgressBarSection != null) { - this.loadProgressBarOption(config, worldConverterProgressBarOptions, "world-converter.progress-bar-options"); } - for (CraftEngineBlockState blockStateLimit : CraftEngineBlockState.values()) { - String path = "block-state-limit." + blockStateLimit.name().toLowerCase(Locale.ROOT).replace("_", "-"); - int startLimit = this.getOrAddInt(config, path + ".start-limit", blockStateLimit.getStart()); - try { - blockStateLimit.setStart(startLimit); - } catch (Exception e) { - Logger.debug("Invalid start limit for " + blockStateLimit.name() + " in configuration."); + if (configFile == ConfigFile.WORLD) { + ConfigurationSection worldConverterProgressBarSection = + config.getConfigurationSection("progress-bar-options"); + if (worldConverterProgressBarSection != null) { + this.loadProgressBarOption(config, worldConverterProgressBarOptions, "progress-bar-options"); } } if (this.isUpdated) { @@ -170,6 +203,89 @@ public void load(YamlConfiguration config, File file) { Logger.info(Message.MESSAGE__PLUGIN__CONFIGURATION__LOADED, Placeholder.of("time", TimerBuilder.formatTimeAuto(endTime - startTime))); } + /** A value taken from where a setting used to live, and which file it came out of. */ + private record Adopted(@NotNull Object value, @NotNull String source) {} + + /** + * Finds a setting under the name it had before the files were split, and moves it to the new one. + *

+ * Looked for in the key's own file first, then in {@code config.yml}, because a key can have been renamed within + * its file ({@code nexo.enable-hook} to {@code enable-hook}) or moved out of the old shared file entirely — and + * the same {@link Key#legacyPath} describes both. + *

+ * The old entry is removed as part of the move. That is what makes this safe to run on every start: having moved + * a setting once, there is nothing left at the old path for a second run to find. + * + * @return the adopted value, or {@code null} when there is nothing to adopt + */ + @Nullable + private Adopted adopt(@NotNull Key key, @NotNull YamlConfiguration config, + @Nullable YamlConfiguration legacy) { + String legacyPath = key.legacyPath(); + + Object own = config.get(legacyPath); + if (own != null && !legacyPath.equals(key.path())) { + config.set(key.path(), own); + config.set(legacyPath, null); + return new Adopted(own, key.file().fileName()); + } + + if (legacy == null || legacy == config) return null; + Object old = legacy.get(legacyPath); + if (old == null) return null; + + config.set(key.path(), old); + legacy.set(legacyPath, null); + this.legacyChanged = true; + return new Adopted(old, ConfigFile.MAIN.fileName()); + } + + /** + * Writes a default, with the documentation that explains it. + *

+ * Two things the plain {@code set} gets wrong. An enum is serialised as the object, which lands in the + * file as {@code language: !!fr.robie...Languages {}} and reads back as an empty bean rather than {@code EN} — + * silent corruption of every enum setting ever written by default. And a key the file has never held arrives + * with no comment, so a setting added by an upgrade shows up unexplained. + */ + private void write(@NotNull YamlConfiguration config, @NotNull Key key, @NotNull Object value) { + config.set(key.path(), value instanceof Enum constant ? constant.name() : value); + if (!key.doc().isEmpty()) { + config.setComments(key.path(), key.doc()); + } + } + + /** Which file each moved setting came out of, for one summary line rather than one per setting. */ + private final Map movedFrom = new LinkedHashMap<>(); + + /** Whether {@code config.yml} had settings taken out of it and so needs saving too. */ + private boolean legacyChanged; + + /** Whether anything was relocated, so the caller can back the old file up and say what happened. */ + public boolean hasRelocated() { + return !this.movedFrom.isEmpty(); + } + + /** A summary of what moved and from where, or empty when nothing did. */ + @NotNull + public Map relocations() { + return Collections.unmodifiableMap(this.movedFrom); + } + + public boolean legacyNeedsSaving() { + return this.legacyChanged; + } + + /** One place for the "the file said one type and the key wants another" report, which used to be inlined twice. */ + private void reportTypeMismatch(@NotNull Key key, @NotNull Class got, @NotNull Object defaultValue) { + Placeholder.Builder builder = Placeholder.builder(); + builder.register("expected", key.rawType().getSimpleName()); + builder.register("got", got.getSimpleName()); + builder.register("default", defaultValue.toString()); + builder.register("path", key.path()); + Logger.debug(Message.ERROR__PLUGIN__CONFIGURATION__TYPE_MISMATCH, builder.build()); + } + private void loadProgressBarOption(YamlConfiguration config, ProgressBarUtils options, String path) { String progressColor = this.getOrAddString(config, path + ".progress-color", options.getProgressColor().name()); String emptyColor = this.getOrAddString(config, path + ".empty-color", options.getEmptyColor().name()); @@ -224,8 +340,38 @@ private String getOrAddString(YamlConfiguration config, String path, String defa } - public static T get(@NotNull ConfigurationKey key) { - //noinspection unchecked - return (T) configValues.getOrDefault(key, key.getDefaultValue()); + /** + * The configured value, or the key's default when nothing has been loaded for it. + *

+ * The cast is sound now that a {@link Key} carries the type of its own value, so callers no longer need to + * spell it out — a wrong type is a compile error rather than a {@code ClassCastException} on some server. + */ + @SuppressWarnings("unchecked") + public static T get(@NotNull Key key) { + return (T) configValues.getOrDefault(key, key.defaultValue()); + } + + /** + * Forgets everything loaded, so the next {@link #get} falls back to defaults. + *

+ * For tests. The values live in static state, so one test's configuration otherwise leaks into every test that + * runs after it — which is why {@code CreativeGroupRulesTest} had an {@code @AfterEach} that wrote a throwaway + * yml purely to clear this map. + */ + public static void reset() { + configValues.clear(); + getInstance().beginLoad(); + } + + /** + * Clears what the previous load reported, so a reload describes only what it did itself. + *

+ * These counters drive the "settings were moved" log and the one-time backup. Left to accumulate they would make + * a later {@code /cec reload} claim a relocation that happened at startup, and back up a file that no longer + * needs it. + */ + public void beginLoad() { + this.movedFrom.clear(); + this.legacyChanged = false; } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/ConfigurationKey.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/ConfigurationKey.java deleted file mode 100644 index 6a177fea..00000000 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/ConfigurationKey.java +++ /dev/null @@ -1,186 +0,0 @@ -package fr.robie.craftengineconverter.api.configuration; - -import com.google.gson.reflect.TypeToken; -import fr.robie.craftengineconverter.api.enums.ArmorConverter; -import fr.robie.craftengineconverter.api.enums.ConverterOption; -import fr.robie.craftengineconverter.api.enums.Languages; -import fr.robie.craftengineconverter.api.enums.LimitType; -import fr.robie.craftengineconverter.api.utils.ConfigurationDeserializer; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.util.function.Supplier; - -public enum ConfigurationKey { - - // General - ENABLE_DEBUG("enable-debug", new TypeToken<>() { - }, () -> false), - LANGUAGE("language", new TypeToken<>() { - }, () -> Languages.EN), - AUTO_CONVERT_ON_STARTUP("auto-convert-on-startup", new TypeToken<>() { - }, () -> false), - AUTO_CONVERT_ON_STARTUP_TYPES("auto-convert-on-startup-types", new TypeToken>>() { - }, HashMap::new, (o, d) -> { - if (o instanceof ConfigurationSection section) { - Map> map = new HashMap<>(); - for (String key : section.getKeys(false)) { - List stringList = section.getStringList(key); - List options = new ArrayList<>(); - for (String s : stringList) { - try { - options.add(ConverterOption.valueOf(s.toUpperCase(Locale.ROOT))); - } catch (IllegalArgumentException ignored) { - } - } - map.put(key, options); - } - return map; - } - return d.get(); - }), - DEFAULT_MATERIAL("default-material", new TypeToken<>() { - }, () -> Material.PAPER), - DISABLE_DEFAULT_ITALIC("disable-default-italic", new TypeToken<>() { - }, () -> true), - ARMOR_CONVERTER_TYPE("armor-converter-type", new TypeToken<>() { - }, () -> ArmorConverter.COMPONENT), - BLACKLISTED_PATHS("blacklisted-paths", new TypeToken>() { - }, ArrayList::new), - - // Block conversion - ALLOW_BLOCK_CONVERSION_PROPAGATION("allow-block-conversion-propagation", new TypeToken<>() { - }, () -> true), - MAX_BLOCK_CONVERSION_PROPAGATION_DEPTH("max-block-conversion-propagation-depth", new TypeToken<>() { - }, () -> 64), - - // Formatting - PACKET_EVENTS_FORMATTING("formatting.packet-events", new TypeToken<>() { - }, () -> true), - BOSS_BAR_FORMATTING("formatting.boss-bar", new TypeToken<>() { - }, () -> true), - ACTION_BAR_FORMATTING("formatting.action-bar", new TypeToken<>() { - }, () -> true), - PLUGIN_MESSAGE_FORMATTING("formatting.plugin-message", new TypeToken<>() { - }, () -> true), - TITLE_FORMATTING("formatting.title", new TypeToken<>() { - }, () -> true), - MENU_TITLE_FORMATTING("formatting.menu-title", new TypeToken<>() { - }, () -> true), - - // Tags - GLYPH_TAG_ENABLED("tag.nexo-glyph.enabled", new TypeToken<>() { - }, () -> true), - IMAGE_TAG_ENABLED("tag.itemsadder-image.enabled", new TypeToken<>() { - }, () -> true), - PLACEHOLDER_API_TAG_ENABLED("tag.placeholder-api.enabled", new TypeToken<>() { - }, () -> true), - - // Nexo - NEXO_ENABLE_HOOK("nexo.enable-hook", new TypeToken<>() { - }, () -> true), - NEXO_BLOCK_INTERACTION_CONVERSION("nexo.enable-block-interaction-conversion", new TypeToken<>() { - }, () -> true), - NEXO_FURNITURE_INTERACTION_CONVERSION("nexo.enable-furniture-interaction-conversion", new TypeToken<>() { - }, () -> true), - NEXO_CHUNK_LOAD_CONVERSION("nexo.enable-chunk-load-conversion", new TypeToken<>() { - }, () -> false), - - // ItemsAdder - ITEMS_ADDER_ENABLE_HOOK("itemsadder.enable-hook", new TypeToken<>() { - }, () -> true), - ITEMS_ADDER_IMG_PLACEHOLDER_API_SUPPORT("itemsadder.img-placeholderapi-support", new TypeToken<>() { - }, () -> true), - ITEMS_ADDER_BLOCK_INTERACTION_CONVERSION("itemsadder.enable-block-interaction-conversion", new TypeToken<>() { - }, () -> true), - ITEMS_ADDER_FURNITURE_INTERACTION_CONVERSION("itemsadder.enable-furniture-interaction-conversion", new TypeToken<>() { - }, () -> true), - ITEMS_ADDER_CHUNK_LOAD_CONVERSION("itemsadder.enable-chunk-load-conversion", new TypeToken<>() { - }, () -> false), - ITEMS_ADDER_BLACKLISTED_CONTENT_FOLDERS_NAMESPACES("itemsadder.blacklisted-content-folders-namespaces", new TypeToken>() { - }, ArrayList::new), - - // Block state limit - BLOCK_STATE_LIMIT_TYPE("block-state-limit.type", new TypeToken<>() { - }, () -> LimitType.PLUGIN), - - // World converter - WORLD_CONVERTER_ENABLE("world-converter.enable", new TypeToken<>() { - }, () -> false), - WORLD_CONVERTER_NEXO_HOOK("world-converter.nexo.enable", new TypeToken<>() { - }, () -> true), - WORLD_CONVERTER_ITEMS_ADDER_HOOK("world-converter.itemsadder.enable", new TypeToken<>() { - }, () -> true); - - private final String path; - private final TypeToken type; - private final Supplier defaultValueSupplier; - private final Class rawType; - private final ConfigurationDeserializer deserializer; - - ConfigurationKey(@NotNull String path, @NotNull TypeToken type, @NotNull Supplier defaultValueSupplier) { - this(path, type, defaultValueSupplier, buildDeserializer(type)); - } - - ConfigurationKey(@NotNull String path, @NotNull TypeToken type, @NotNull Supplier defaultValueSupplier, @NotNull ConfigurationDeserializer deserializer) { - this.path = path; - this.type = type; - this.defaultValueSupplier = defaultValueSupplier; - this.rawType = type.getRawType(); - this.deserializer = deserializer; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private static ConfigurationDeserializer buildDeserializer(@NotNull TypeToken type) { - Class raw = type.getRawType(); - - if (raw == Boolean.class) return (o, d) -> (T) o; - if (raw == Integer.class) - return (o, d) -> (T) (Integer) (o instanceof Number n ? n.intValue() : Integer.parseInt(o.toString())); - if (raw == Long.class) - return (o, d) -> (T) (Long) (o instanceof Number n ? n.longValue() : Long.parseLong(o.toString())); - if (raw == String.class) return (o, d) -> (T) o.toString(); - if (raw == List.class) return (o, d) -> (T) (o instanceof List l ? new ArrayList<>(l) : new ArrayList<>()); - - if (raw.isEnum()) { - return (o, d) -> { - try { - return (T) Enum.valueOf((Class) raw, o.toString().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException e) { - return d.get(); - } - }; - } - - return (o, d) -> (T) o; - } - - @NotNull - public String getPath() { - return this.path; - } - - @NotNull - public TypeToken getType() { - return this.type; - } - - @NotNull - public Class getRawType() { - return this.rawType; - } - - @NotNull - @SuppressWarnings("unchecked") - public T getDefaultValue() { - return (T) this.defaultValueSupplier.get(); - } - - @NotNull - @SuppressWarnings("unchecked") - public Object deserialize(@NotNull Object rawValue) { - return ((ConfigurationDeserializer) this.deserializer).deserialize(rawValue, (Supplier) this.defaultValueSupplier); - } -} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/CraftEngineItemsConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/CraftEngineItemsConfiguration.java index 127739cf..ec11339f 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/CraftEngineItemsConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/CraftEngineItemsConfiguration.java @@ -2,9 +2,9 @@ import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/Key.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/Key.java new file mode 100644 index 00000000..83c523d3 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/Key.java @@ -0,0 +1,229 @@ +package fr.robie.craftengineconverter.api.configuration; + +import com.google.gson.reflect.TypeToken; +import fr.robie.craftengineconverter.api.utils.ConfigurationDeserializer; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.function.Supplier; + +/** + * One configuration setting: which file holds it, where in that file, what type it is, and what it defaults to. + *

+ * A class rather than the enum this replaces, and the reason is the type parameter. An enum constant cannot carry + * one, so the enum had to declare its type as a {@code TypeToken} and {@code Configuration.get} + * had to return {@code Object} through an unchecked cast — so every call site had to restate the type, some as a + * cast and some as an explicit type argument, and a wrong one was caught only when a server ran it. + * {@code Key} makes {@code get} return {@code T}, and those 43 restatements are gone. + *

+ * Keys register themselves as they are constructed, so {@link Configuration} can ask for the ones belonging to a + * file rather than iterating {@code values()}. That means a key only exists once {@link Keys} has been loaded; + * every caller reaches keys through that class, so the class initialises before anything can ask. + */ +public final class Key { + + // Insertion-ordered, so a file's keys are written in the order they were declared and a generated file stays + // diffable against the last one. + private static final List> REGISTRY = new ArrayList<>(); + + private final ConfigFile file; + private final String path; + private final TypeToken type; + private final Class rawType; + private final Supplier defaultValueSupplier; + private final ConfigurationDeserializer deserializer; + + private Key(@NotNull ConfigFile file, @NotNull String path, @NotNull TypeToken type, + @NotNull Supplier defaultValueSupplier, @NotNull ConfigurationDeserializer deserializer) { + this.file = file; + this.path = path; + this.type = type; + this.rawType = type.getRawType(); + this.defaultValueSupplier = defaultValueSupplier; + this.deserializer = deserializer; + REGISTRY.add(this); + } + + /** A key whose value needs no conversion beyond the standard coercion for its type. */ + @NotNull + public static Key of(@NotNull ConfigFile file, @NotNull String path, @NotNull TypeToken type, + @NotNull Supplier defaultValueSupplier) { + return new Key<>(file, path, type, defaultValueSupplier, buildDeserializer(type)); + } + + /** A key that reads its own shape out of the file — a section, a map, a value with several spellings. */ + @NotNull + public static Key of(@NotNull ConfigFile file, @NotNull String path, @NotNull TypeToken type, + @NotNull Supplier defaultValueSupplier, + @NotNull ConfigurationDeserializer deserializer) { + return new Key<>(file, path, type, defaultValueSupplier, deserializer); + } + + // The three shorthands that cover most of the table, so a plain setting reads as one line. + @NotNull + public static Key bool(@NotNull ConfigFile file, @NotNull String path, boolean defaultValue) { + return of(file, path, new TypeToken<>() {}, () -> defaultValue); + } + + @NotNull + public static Key integer(@NotNull ConfigFile file, @NotNull String path, int defaultValue) { + return of(file, path, new TypeToken<>() {}, () -> defaultValue); + } + + @NotNull + public static Key string(@NotNull ConfigFile file, @NotNull String path, @NotNull String defaultValue) { + return of(file, path, new TypeToken<>() {}, () -> defaultValue); + } + + /** Every key that has been declared, in declaration order. */ + @NotNull + public static List> all() { + ensureDeclarationsLoaded(); + return Collections.unmodifiableList(REGISTRY); + } + + /** The keys belonging to one file, in declaration order. */ + @NotNull + public static List> in(@NotNull ConfigFile file) { + ensureDeclarationsLoaded(); + List> keys = new ArrayList<>(); + for (Key key : REGISTRY) { + if (key.file == file) keys.add(key); + } + return keys; + } + + private static boolean declarationsLoaded; + + /** + * Loads {@link Keys} if it has not been loaded, because a key does not exist until its declaration has run. + *

+ * The registry fills as a side effect of constructing each constant in {@code Keys}, so asking for the keys + * before that class has initialised would quietly return an empty list — a configuration that loads nothing and + * reports no error. Forcing it here means no caller has to know that, which is the whole point: the previous + * shape required every caller to remember to prime the class first, and a forgotten call would have failed + * silently. + *

+ * The flag is set before the call, so a re-entrant path recurses no further than once. + */ + private static void ensureDeclarationsLoaded() { + if (declarationsLoaded) return; + declarationsLoaded = true; + Keys.ensureLoaded(); + } + + @NotNull + public ConfigFile file() { + return this.file; + } + + @NotNull + public String path() { + return this.path; + } + + /** + * Where this setting lived in the old single {@code config.yml}, when that differs from where it lives now. + *

+ * Needed because moving a key into its converter's own file makes its old prefix redundant: {@code nexo.yml} + * should hold {@code enable-hook} at its root, not {@code nexo.enable-hook}. That reads better but stops the + * migration being a straight path lookup, so the old spelling is recorded here instead of being derivable. + * + * @return the old path, or the current one when the move did not rename it + */ + @NotNull + public String legacyPath() { + return this.legacyPath == null ? this.path : this.legacyPath; + } + + /** Declares the old {@code config.yml} path, for {@link #legacyPath()}. Chained at declaration in {@link Keys}. */ + @NotNull + public Key legacy(@NotNull String oldPath) { + this.legacyPath = oldPath; + return this; + } + + private String legacyPath; + + /** + * The comment written above this setting when it is added to a file that lacks it. + *

+ * The YAML library keeps the comments on a key that already exists, but a key it has never seen arrives bare and + * appended to the end of its section — so a setting introduced by an upgrade would show up in a server's file as + * an unexplained line. This is the text that stops that. + * + * @return the lines, without their leading {@code #}, or empty when the key carries none + */ + @NotNull + public List doc() { + return this.doc == null ? List.of() : this.doc; + } + + /** Declares the comment for {@link #doc()}. Chained at declaration in {@link Keys}. */ + @NotNull + public Key doc(@NotNull String... lines) { + this.doc = List.of(lines); + return this; + } + + private List doc; + + @NotNull + public TypeToken type() { + return this.type; + } + + @NotNull + public Class rawType() { + return this.rawType; + } + + @NotNull + public T defaultValue() { + return this.defaultValueSupplier.get(); + } + + @NotNull + public T deserialize(@NotNull Object rawValue) { + return this.deserializer.deserialize(rawValue, this.defaultValueSupplier); + } + + @Override + public String toString() { + return this.file.fileName() + ":" + this.path; + } + + /** + * The coercion a value gets on the way out of YAML, carried over unchanged from the enum this replaces. + *

+ * It exists because the YAML library hands back whatever the file happened to contain — an {@code Integer} for a + * long, a {@code String} for an enum — and a key's declared type is the authority on what that should become. + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + private static ConfigurationDeserializer buildDeserializer(@NotNull TypeToken type) { + Class raw = type.getRawType(); + + if (raw == Boolean.class) return (o, d) -> (T) o; + if (raw == Integer.class) + return (o, d) -> (T) (Integer) (o instanceof Number n ? n.intValue() : Integer.parseInt(o.toString())); + if (raw == Long.class) + return (o, d) -> (T) (Long) (o instanceof Number n ? n.longValue() : Long.parseLong(o.toString())); + if (raw == String.class) return (o, d) -> (T) o.toString(); + if (raw == List.class) return (o, d) -> (T) (o instanceof List l ? new ArrayList<>(l) : new ArrayList<>()); + + if (raw.isEnum()) { + return (o, d) -> { + try { + return (T) Enum.valueOf((Class) raw, o.toString().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return d.get(); + } + }; + } + + return (o, d) -> (T) o; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/Keys.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/Keys.java new file mode 100644 index 00000000..85723b3c --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/Keys.java @@ -0,0 +1,173 @@ +package fr.robie.craftengineconverter.api.configuration; + +import com.google.gson.reflect.TypeToken; +import fr.robie.craftengineconverter.api.configuration.loader.ConfigurationTrees; +import fr.robie.craftengineconverter.api.enums.ArmorConverter; +import fr.robie.craftengineconverter.api.enums.ConverterOption; +import fr.robie.craftengineconverter.api.enums.Languages; +import fr.robie.craftengineconverter.api.enums.LimitType; +import fr.robie.yamllibrary.ConfigurationSection; +import org.bukkit.Material; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import static fr.robie.craftengineconverter.api.configuration.ConfigFile.ITEMS_ADDER; +import static fr.robie.craftengineconverter.api.configuration.ConfigFile.MAIN; +import static fr.robie.craftengineconverter.api.configuration.ConfigFile.NEXO; +import static fr.robie.craftengineconverter.api.configuration.ConfigFile.WORLD; + +/** + * Every configuration setting the plugin reads, grouped by the file that holds it. + *

+ * Replaces the {@code ConfigurationKey} enum. Constants rather than enum members because a key carries the type of + * its own value — see {@link Key} — which an enum constant cannot do. + *

+ * A key that moved into a converter's own file drops the prefix it no longer needs: {@code nexo.enable-hook} became + * {@code enable-hook} in {@code nexo.yml}. The old spelling is recorded with {@link Key#legacy} so the one-shot + * migration can still find it in a pre-split {@code config.yml}. + */ +public final class Keys { + + private Keys() { + throw new UnsupportedOperationException("Keys is a constant holder and cannot be instantiated."); + } + + // ------------------------------------------------------------------ config.yml, general + + public static final Key ENABLE_DEBUG = Key.bool(MAIN, "enable-debug", false); + public static final Key LANGUAGE = + Key.of(MAIN, "language", new TypeToken<>() {}, () -> Languages.EN); + public static final Key AUTO_CONVERT_ON_STARTUP = Key.bool(MAIN, "auto-convert-on-startup", false); + + public static final Key>> AUTO_CONVERT_ON_STARTUP_TYPES = Key.of( + MAIN, "auto-convert-on-startup-types", new TypeToken>>() {}, + HashMap::new, (o, d) -> { + if (o instanceof ConfigurationSection section) { + Map> map = new HashMap<>(); + for (String key : section.getKeys(false)) { + List options = new ArrayList<>(); + for (String s : section.getStringList(key)) { + try { + options.add(ConverterOption.valueOf(s.toUpperCase(Locale.ROOT))); + } catch (IllegalArgumentException ignored) { + } + } + map.put(key, options); + } + return map; + } + return d.get(); + }); + + public static final Key> BLACKLISTED_PATHS = + Key.of(MAIN, "blacklisted-paths", new TypeToken>() {}, ArrayList::new); + + public static final Key BLOCK_STATE_LIMIT_TYPE = + Key.of(MAIN, "block-state-limit.type", new TypeToken<>() {}, () -> LimitType.PLUGIN); + + // Block conversion + public static final Key ALLOW_BLOCK_CONVERSION_PROPAGATION = + Key.bool(MAIN, "allow-block-conversion-propagation", true); + public static final Key MAX_BLOCK_CONVERSION_PROPAGATION_LIMIT = + Key.integer(MAIN, "max-block-conversion-propagation-limit", 64) + .legacy("max-block-conversion-propagation-depth") + .doc("How many blocks or furniture one interaction may convert on top of the one clicked.", + "This is a total, not a distance: propagation spreads outwards until it runs out."); + + // Formatting + public static final Key PACKET_EVENTS_FORMATTING = Key.bool(MAIN, "formatting.packet-events", true); + public static final Key BOSS_BAR_FORMATTING = Key.bool(MAIN, "formatting.boss-bar", true); + public static final Key ACTION_BAR_FORMATTING = Key.bool(MAIN, "formatting.action-bar", true); + public static final Key PLUGIN_MESSAGE_FORMATTING = Key.bool(MAIN, "formatting.plugin-message", true); + public static final Key TITLE_FORMATTING = Key.bool(MAIN, "formatting.title", true); + public static final Key MENU_TITLE_FORMATTING = Key.bool(MAIN, "formatting.menu-title", true); + + // Tags + public static final Key GLYPH_TAG_ENABLED = Key.bool(MAIN, "tag.nexo-glyph.enabled", true); + public static final Key IMAGE_TAG_ENABLED = Key.bool(MAIN, "tag.itemsadder-image.enabled", true); + public static final Key PLACEHOLDER_API_TAG_ENABLED = Key.bool(MAIN, "tag.placeholder-api.enabled", true); + + // ------------------------------------------------------------------ item conversion (config.yml) + + public static final Key DISABLE_DEFAULT_ITALIC = Key.bool(MAIN, "disable-default-italic", true); + + public static final Key ARMOR_CONVERTER_TYPE = + Key.of(MAIN, "armor-converter-type", new TypeToken<>() {}, () -> ArmorConverter.COMPONENT); + + /** + * Object-typed, as it was before: the value is a {@code Material} or the string {@code "auto"} depending on what + * the file says. Narrowing it would change how it parses, which is a separate job. + */ + public static final Key DEFAULT_MATERIAL = Key.of( + MAIN, "default-material", new TypeToken<>() {}, () -> (Object) "auto", (o, d) -> { + if (o instanceof Material material) return material; + if (o instanceof String name) { + if (name.isBlank() || name.equalsIgnoreCase("auto")) return "auto"; + String value = name.contains(":") ? name.substring(name.indexOf(':') + 1) : name; + try { + return Material.valueOf(value.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException ignored) { + return "auto"; + } + } + return d.get(); + }); + + // ------------------------------------------------------------------ nexo.yml + + public static final Key NEXO_ENABLE_HOOK = + Key.bool(NEXO, "enable-hook", true).legacy("nexo.enable-hook"); + public static final Key NEXO_BLOCK_INTERACTION_CONVERSION = + Key.bool(NEXO, "enable-block-interaction-conversion", true) + .legacy("nexo.enable-block-interaction-conversion"); + public static final Key NEXO_FURNITURE_INTERACTION_CONVERSION = + Key.bool(NEXO, "enable-furniture-interaction-conversion", true) + .legacy("nexo.enable-furniture-interaction-conversion"); + public static final Key NEXO_CHUNK_LOAD_CONVERSION = + Key.bool(NEXO, "enable-chunk-load-conversion", false).legacy("nexo.enable-chunk-load-conversion"); + + // ------------------------------------------------------------------ itemsadder.yml + + public static final Key ITEMS_ADDER_ENABLE_HOOK = + Key.bool(ITEMS_ADDER, "enable-hook", true).legacy("itemsadder.enable-hook"); + public static final Key ITEMS_ADDER_IMG_PLACEHOLDER_API_SUPPORT = + Key.bool(ITEMS_ADDER, "img-placeholderapi-support", true) + .legacy("itemsadder.img-placeholderapi-support"); + public static final Key ITEMS_ADDER_BLOCK_INTERACTION_CONVERSION = + Key.bool(ITEMS_ADDER, "enable-block-interaction-conversion", true) + .legacy("itemsadder.enable-block-interaction-conversion"); + public static final Key ITEMS_ADDER_FURNITURE_INTERACTION_CONVERSION = + Key.bool(ITEMS_ADDER, "enable-furniture-interaction-conversion", true) + .legacy("itemsadder.enable-furniture-interaction-conversion"); + public static final Key ITEMS_ADDER_CHUNK_LOAD_CONVERSION = + Key.bool(ITEMS_ADDER, "enable-chunk-load-conversion", false) + .legacy("itemsadder.enable-chunk-load-conversion"); + public static final Key> ITEMS_ADDER_BLACKLISTED_CONTENT_FOLDERS_NAMESPACES = Key.of( + ITEMS_ADDER, "blacklisted-content-folders-namespaces", new TypeToken>() {}, ArrayList::new) + .legacy("itemsadder.blacklisted-content-folders-namespaces"); + + // ------------------------------------------------------------------ world-converter.yml + + public static final Key WORLD_CONVERTER_ENABLE = + Key.bool(WORLD, "enable", false).legacy("world-converter.enable"); + public static final Key WORLD_CONVERTER_NEXO_HOOK = + Key.bool(WORLD, "nexo.enable", true).legacy("world-converter.nexo.enable"); + public static final Key WORLD_CONVERTER_ITEMS_ADDER_HOOK = + Key.bool(WORLD, "itemsadder.enable", true).legacy("world-converter.itemsadder.enable"); + + /** + * Deliberately empty. Calling any static method on a class runs its initialiser, and this class's initialiser is + * what constructs every constant above and registers it with {@link Key}. So invoking this is how {@code Key} + * guarantees the registry is populated before it answers — see {@code Key.ensureDeclarationsLoaded}. + *

+ * An empty body is the honest form. The previous version asserted a field was non-null to force the same effect, + * which read as a no-op to anyone who knows assertions are disabled by default. + */ + static void ensureLoaded() { + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/SectionSerializable.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/SectionSerializable.java index 7e226ffa..6ecd370e 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/SectionSerializable.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/SectionSerializable.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public interface SectionSerializable { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AbstractCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AbstractCondition.java index 94e6a66b..67c94a0f 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AbstractCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AbstractCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public abstract class AbstractCondition implements Condition { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AllOfCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AllOfCondition.java index aca0f32c..e726c8ce 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AllOfCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AllOfCondition.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.conditions; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AnyOfCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AnyOfCondition.java index 63fa08b7..48c4dd0a 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AnyOfCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/AnyOfCondition.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.conditions; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/DistanceCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/DistanceCondition.java index e8d6ea0e..cac78e20 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/DistanceCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/DistanceCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class DistanceCondition extends AbstractCondition { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/EnchantmentCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/EnchantmentCondition.java index 2d7a95f3..4315cf8c 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/EnchantmentCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/EnchantmentCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/ExpressionCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/ExpressionCondition.java index 31b31f67..5e2fcec2 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/ExpressionCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/ExpressionCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/HandCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/HandCondition.java index b6fa0969..a44825a0 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/HandCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/HandCondition.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.conditions; import fr.robie.craftengineconverter.api.enums.Hand; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Locale; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/InventoryHasItemCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/InventoryHasItemCondition.java index 60acad78..08e31057 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/InventoryHasItemCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/InventoryHasItemCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/InvertedCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/InvertedCondition.java index 44da3050..0d99309d 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/InvertedCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/InvertedCondition.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.conditions; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class InvertedCondition extends AbstractCondition { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/IsBedrockPlayerCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/IsBedrockPlayerCondition.java deleted file mode 100644 index ccc47a60..00000000 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/IsBedrockPlayerCondition.java +++ /dev/null @@ -1,7 +0,0 @@ -package fr.robie.craftengineconverter.api.configuration.conditions; - -public class IsBedrockPlayerCondition extends AbstractCondition { - public IsBedrockPlayerCondition() { - super("is_bedrock_player"); - } -} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/IsNullCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/IsNullCondition.java index 4d930a42..93e4c757 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/IsNullCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/IsNullCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchBlockCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchBlockCondition.java index 6b655e3b..9468bf06 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchBlockCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchBlockCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchBlockPropertyCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchBlockPropertyCondition.java index 5fd158ae..2fac6601 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchBlockPropertyCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchBlockPropertyCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Map; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchEntityCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchEntityCondition.java index 3c27bb39..7c7295c7 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchEntityCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchEntityCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchFurnitureVariantCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchFurnitureVariantCondition.java index 0023f698..42d74d71 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchFurnitureVariantCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchFurnitureVariantCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchItemCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchItemCondition.java index 6c642656..a4dc3543 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchItemCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/MatchItemCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/OnCooldownCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/OnCooldownCondition.java index 536d59cd..a470941b 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/OnCooldownCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/OnCooldownCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/PermissionCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/PermissionCondition.java index 4a953890..a70eb0da 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/PermissionCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/PermissionCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/RandomCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/RandomCondition.java index 9ababbeb..078fb300 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/RandomCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/RandomCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class RandomCondition extends AbstractCondition { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/RegexCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/RegexCondition.java index 8a3b8f72..81efc42b 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/RegexCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/RegexCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/StringContainsCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/StringContainsCondition.java index 42822d4d..828c572c 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/StringContainsCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/StringContainsCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/StringEqualsCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/StringEqualsCondition.java index 7f1cb3c1..9114d987 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/StringEqualsCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/StringEqualsCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/TableBonusCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/TableBonusCondition.java index 5c21b162..72803655 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/TableBonusCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/TableBonusCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/WorldGuardRegionCondition.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/WorldGuardRegionCondition.java index 32fa4505..e841c0ed 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/WorldGuardRegionCondition.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/conditions/WorldGuardRegionCondition.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.conditions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/events/Event.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/events/Event.java index 7cc04f53..5db11608 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/events/Event.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/events/Event.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.events; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public interface Event { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/events/EventConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/events/EventConfiguration.java index 69239b6d..98bf8c3a 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/events/EventConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/events/EventConfiguration.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.events; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/functions/internal/DropLootFunction.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/functions/internal/DropLootFunction.java index 30dcb28b..7e4965f4 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/functions/internal/DropLootFunction.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/functions/internal/DropLootFunction.java @@ -2,7 +2,6 @@ import fr.robie.craftengineconverter.api.configuration.item.loottables.LootTable; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.file.YamlConfiguration; import java.util.Map; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/Bitmap.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/Bitmap.java index baa4939e..738dd765 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/Bitmap.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/Bitmap.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.image; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public abstract class Bitmap> implements BitmapConfiguration { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/MultipleCharactersBitmapConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/MultipleCharactersBitmapConfiguration.java index 7d94e418..8dab26b5 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/MultipleCharactersBitmapConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/MultipleCharactersBitmapConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.image; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/ReferenceBitmap.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/ReferenceBitmap.java index fd0f3a9a..a841c839 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/ReferenceBitmap.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/ReferenceBitmap.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.image; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/SingleCharacterBitmapConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/SingleCharacterBitmapConfiguration.java index 05118ef6..42c39c13 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/SingleCharacterBitmapConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/image/SingleCharacterBitmapConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.image; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class SingleCharacterBitmapConfiguration extends Bitmap { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/AbstractEffectsConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/AbstractEffectsConfiguration.java index 2ae9931f..ccfa2eeb 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/AbstractEffectsConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/AbstractEffectsConfiguration.java @@ -1,6 +1,10 @@ package fr.robie.craftengineconverter.api.configuration.item; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import fr.robie.craftengineconverter.api.utils.item.component.ConsumeEffect; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -8,10 +12,6 @@ public abstract class AbstractEffectsConfiguration implements ItemConfigurationSerializable { - public interface ConsumeEffect { - Map serialize(); - } - public record ApplyEffectsConsumeEffect(List effects) implements ConsumeEffect { public record ApplyEffect( @@ -44,6 +44,26 @@ public Map serialize() { result.put("effects", serializedEffects); return result; } + + @Override + public JsonObject serializeToJson() { + JsonArray effectsArray = new JsonArray(); + for (ApplyEffect effect : this.effects) { + JsonObject effectObject = new JsonObject(); + effectObject.addProperty("id", effect.id()); + effectObject.addProperty("amplifier", effect.amplifier()); + effectObject.addProperty("duration", effect.duration()); + effectObject.addProperty("ambient", effect.ambient()); + effectObject.addProperty("show_particles", effect.showParticles()); + effectObject.addProperty("show_icon", effect.showIcon()); + effectObject.addProperty("probability", effect.probability()); + effectsArray.add(effectObject); + } + JsonObject result = new JsonObject(); + result.addProperty("type", "apply_effects"); + result.add("effects", effectsArray); + return result; + } } public record RemoveEffectsConsumeEffect(List effects) implements ConsumeEffect { @@ -54,6 +74,18 @@ public Map serialize() { result.put("effects", this.effects); return result; } + + @Override + public JsonObject serializeToJson() { + JsonArray effectsArray = new JsonArray(); + for (String effect : this.effects) { + effectsArray.add(effect); + } + JsonObject result = new JsonObject(); + result.addProperty("type", "remove_effects"); + result.add("effects", effectsArray); + return result; + } } public record ClearAllEffectsConsumeEffect() implements ConsumeEffect { @@ -63,6 +95,13 @@ public Map serialize() { result.put("type", "clear_all_effects"); return result; } + + @Override + public JsonObject serializeToJson() { + JsonObject result = new JsonObject(); + result.addProperty("type", "clear_all_effects"); + return result; + } } public record TeleportRandomlyConsumeEffect(double diameter) implements ConsumeEffect { @@ -73,6 +112,14 @@ public Map serialize() { result.put("diameter", this.diameter); return result; } + + @Override + public JsonObject serializeToJson() { + JsonObject result = new JsonObject(); + result.addProperty("type", "teleport_randomly"); + result.addProperty("diameter", this.diameter); + return result; + } } public record PlaySoundConsumeEffect(String soundId, double range) implements ConsumeEffect { @@ -86,6 +133,17 @@ public Map serialize() { result.put("sound", soundMap); return result; } + + @Override + public JsonObject serializeToJson() { + JsonObject soundObject = new JsonObject(); + soundObject.addProperty("sound_id", this.soundId); + soundObject.addProperty("range", this.range); + JsonObject result = new JsonObject(); + result.addProperty("type", "play_sound"); + result.add("sound", soundObject); + return result; + } } protected List> serializeEffects(List effects) { @@ -95,4 +153,12 @@ protected List> serializeEffects(List effects } return serialized; } + + protected JsonArray serializeEffectsToJsonArray(List effects) { + JsonArray jsonArray = new JsonArray(); + for (ConsumeEffect effect : effects) { + jsonArray.add(effect.serializeToJson()); + } + return jsonArray; + } } \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/ItemConfigurationSerializable.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/ItemConfigurationSerializable.java index a6853bc4..e4d77026 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/ItemConfigurationSerializable.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/ItemConfigurationSerializable.java @@ -1,11 +1,27 @@ package fr.robie.craftengineconverter.api.configuration.item; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.SectionProvider; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public interface ItemConfigurationSerializable extends SectionProvider { void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId); + + /** + * CraftEngine reads everything that shapes the item stack from a {@code data} section on the item; keys placed + * anywhere else on the item are simply not looked at. + */ + default ConfigurationSection getDataSection(@NotNull ConfigurationSection itemSection) { + return this.getOrCreateSection(itemSection, "data"); + } + + /** + * Raw vanilla data components, which live under {@code data.components}. Anything CraftEngine has no dedicated + * {@code data} entry for - {@code minecraft:food}, {@code minecraft:consumable} and the rest - goes here. + */ + default ConfigurationSection getComponentsSection(@NotNull ConfigurationSection itemSection) { + return this.getOrCreateSection(this.getDataSection(itemSection), "components"); + } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/LoreConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/LoreConfiguration.java index 39d6be39..bc2ef9e6 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/LoreConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/LoreConfiguration.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.item; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -24,7 +24,7 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str if (this.lore == null || this.lore.isEmpty()) { return; } - ConfigurationSection data = this.getOrCreateSection(itemSection, "data"); + ConfigurationSection data = this.getDataSection(itemSection); data.set("lore", this.applyNoItalic(this.lore)); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/OversizedInGuiConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/OversizedInGuiConfiguration.java index ed8dc475..258b5ad7 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/OversizedInGuiConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/OversizedInGuiConfiguration.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.item; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class OversizedInGuiConfiguration implements ItemConfigurationSerializable { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/BlockConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/BlockConfiguration.java index 77ea0c55..569c024f 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/BlockConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/BlockConfiguration.java @@ -4,8 +4,8 @@ import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.StateBlock; import fr.robie.craftengineconverter.api.configuration.item.loottables.LootConfiguration; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/BlockSettings.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/BlockSettings.java index 55730ec4..dc1ef4f6 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/BlockSettings.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/BlockSettings.java @@ -1,10 +1,10 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block; import fr.robie.craftengineconverter.api.common.TrackableSettings; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.block.setting.PushReaction; -import net.momirealms.craftengine.core.util.Instrument; +import org.bukkit.Instrument; import net.momirealms.craftengine.core.util.Tristate; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/ChangeOverTimeBlockBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/ChangeOverTimeBlockBehavior.java index d079f09e..46d5f7a5 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/ChangeOverTimeBlockBehavior.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/ChangeOverTimeBlockBehavior.java @@ -10,7 +10,7 @@ public class ChangeOverTimeBlockBehavior implements BlockBehavior { private Double changeSpeed; private String nextBlock; - private List excludedProperties; + private final List excludedProperties; public ChangeOverTimeBlockBehavior() { this.excludedProperties = new ArrayList<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/DirectionalAttachedBlockBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/DirectionalAttachedBlockBehavior.java index 5fa9b2fc..e3340001 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/DirectionalAttachedBlockBehavior.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/DirectionalAttachedBlockBehavior.java @@ -9,8 +9,8 @@ public class DirectionalAttachedBlockBehavior implements BlockBehavior { private Boolean blacklist; - private List attachedBlocks; - private List attachedBlockTags; + private final List attachedBlocks; + private final List attachedBlockTags; public DirectionalAttachedBlockBehavior() { this.attachedBlocks = new ArrayList<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/FaceAttachedHorizontalDirectionalBlockBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/FaceAttachedHorizontalDirectionalBlockBehavior.java index 7eb8ce17..640ed0b7 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/FaceAttachedHorizontalDirectionalBlockBehavior.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/FaceAttachedHorizontalDirectionalBlockBehavior.java @@ -9,8 +9,8 @@ public class FaceAttachedHorizontalDirectionalBlockBehavior implements BlockBehavior { private Boolean blacklist; - private List attachedBlocks; - private List attachedBlockTags; + private final List attachedBlocks; + private final List attachedBlockTags; public FaceAttachedHorizontalDirectionalBlockBehavior() { this.attachedBlocks = new ArrayList<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/HangingBlockBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/HangingBlockBehavior.java index 7e6da7f0..424e9795 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/HangingBlockBehavior.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/HangingBlockBehavior.java @@ -10,8 +10,8 @@ public class HangingBlockBehavior implements BlockBehavior { private Boolean stackable; private Boolean blacklist; - private List aboveBlockTags; - private List aboveBlocks; + private final List aboveBlockTags; + private final List aboveBlocks; private Integer delay; public HangingBlockBehavior() { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/NearLiquidBlockBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/NearLiquidBlockBehavior.java index a732e13b..9bd94473 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/NearLiquidBlockBehavior.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/NearLiquidBlockBehavior.java @@ -10,7 +10,7 @@ public class NearLiquidBlockBehavior implements BlockBehavior { private String liquidType; private Boolean stackable; - private List positions; + private final List positions; public NearLiquidBlockBehavior() { this.positions = new ArrayList<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/OnLiquidBlockBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/OnLiquidBlockBehavior.java index 6b0fc2d6..0dcf6bca 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/OnLiquidBlockBehavior.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/OnLiquidBlockBehavior.java @@ -9,7 +9,7 @@ public class OnLiquidBlockBehavior implements BlockBehavior { private Boolean stackable; - private List liquidType; + private final List liquidType; public OnLiquidBlockBehavior() { this.liquidType = new ArrayList<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/SeatBlockBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/SeatBlockBehavior.java index ada5afb5..493fe56c 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/SeatBlockBehavior.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/SeatBlockBehavior.java @@ -8,7 +8,7 @@ import java.util.Map; public class SeatBlockBehavior implements BlockBehavior { - private List seats; + private final List seats; public SeatBlockBehavior() { this.seats = new ArrayList<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/StackableBlockBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/StackableBlockBehavior.java index d97893db..4bb5335c 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/StackableBlockBehavior.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/StackableBlockBehavior.java @@ -9,7 +9,7 @@ public class StackableBlockBehavior implements BlockBehavior { private String property; - private List items; + private final List items; public StackableBlockBehavior() { this.items = new ArrayList<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/StrippableBlockBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/StrippableBlockBehavior.java index 0e231414..2499bbf2 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/StrippableBlockBehavior.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/StrippableBlockBehavior.java @@ -9,7 +9,7 @@ public class StrippableBlockBehavior implements BlockBehavior { private String stripped; - private List excludedProperties; + private final List excludedProperties; public StrippableBlockBehavior() { this.excludedProperties = new ArrayList<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/SturdyBaseBlockBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/SturdyBaseBlockBehavior.java index c3951d3b..9cb277dd 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/SturdyBaseBlockBehavior.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/behaviors/SturdyBaseBlockBehavior.java @@ -9,7 +9,7 @@ public class SturdyBaseBlockBehavior implements BlockBehavior { private String direction; - private List supportTypes; + private final List supportTypes; public SturdyBaseBlockBehavior() { this.supportTypes = new ArrayList<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/entities/BlockEntityConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/entities/BlockEntityConfiguration.java index 90919cfc..26ead4ef 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/entities/BlockEntityConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/entities/BlockEntityConfiguration.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.entities; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.SectionProvider; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/BlockAppearance.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/BlockAppearance.java index ed670ff5..5da887ad 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/BlockAppearance.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/BlockAppearance.java @@ -7,7 +7,7 @@ import fr.robie.craftengineconverter.api.enums.CraftEngineBlockState; import fr.robie.craftengineconverter.api.enums.Plugins; import fr.robie.craftengineconverter.api.utils.BlockStateResult; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/BlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/BlockStateProperty.java index 874b1767..b4aa2fa2 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/BlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/BlockStateProperty.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public interface BlockStateProperty extends SectionProvider { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/MultiStateBlock.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/MultiStateBlock.java index 65dc2d6c..d105eaf7 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/MultiStateBlock.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/MultiStateBlock.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/SectionProvider.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/SectionProvider.java index 9cfa30fb..4d9b2eda 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/SectionProvider.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/SectionProvider.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public interface SectionProvider { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/SingleStateBlock.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/SingleStateBlock.java index a10325c5..1f6d3de9 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/SingleStateBlock.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/SingleStateBlock.java @@ -3,7 +3,7 @@ import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; import fr.robie.craftengineconverter.api.enums.CraftEngineBlockState; import fr.robie.craftengineconverter.api.enums.Plugins; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class SingleStateBlock implements StateBlock { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/StateBlock.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/StateBlock.java index fea1c0da..25d2e4c2 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/StateBlock.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/StateBlock.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public interface StateBlock extends SectionProvider { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/AbstractDefaultBlockState.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/AbstractDefaultBlockState.java index c3f9178a..c5f9cb21 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/AbstractDefaultBlockState.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/AbstractDefaultBlockState.java @@ -6,7 +6,7 @@ import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.MultiStateBlock; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties.BooleanBlockStateProperty; import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/DirectionalBlockState.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/DirectionalBlockState.java index b37eae59..f2c735a5 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/DirectionalBlockState.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/DirectionalBlockState.java @@ -6,8 +6,8 @@ import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; import fr.robie.craftengineconverter.api.enums.CraftEngineBlockState; import fr.robie.craftengineconverter.api.enums.Plugins; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.util.Direction; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Locale; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/HorizontalFacingBlockState.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/HorizontalFacingBlockState.java index b36a711b..68d1005f 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/HorizontalFacingBlockState.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/HorizontalFacingBlockState.java @@ -7,7 +7,7 @@ import fr.robie.craftengineconverter.api.configuration.utils.HorizontalDirection; import fr.robie.craftengineconverter.api.enums.CraftEngineBlockState; import fr.robie.craftengineconverter.api.enums.Plugins; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Locale; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/PillarBlockState.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/PillarBlockState.java index 082bdaa3..df420841 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/PillarBlockState.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/defaults/PillarBlockState.java @@ -9,8 +9,8 @@ import fr.robie.craftengineconverter.api.configuration.item.models.model.SimpleModelConfiguration; import fr.robie.craftengineconverter.api.enums.CraftEngineBlockState; import fr.robie.craftengineconverter.api.enums.Plugins; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.util.Direction; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class PillarBlockState extends MultiStateBlock { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/AnchorTypeBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/AnchorTypeBlockStateProperty.java index 6c4335db..090501d3 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/AnchorTypeBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/AnchorTypeBlockStateProperty.java @@ -1,17 +1,13 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.block.property.type.AnchorType; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.Locale; -public class AnchorTypeBlockStateProperty implements BlockStateProperty { - private final String name; - private final AnchorType value; - +public record AnchorTypeBlockStateProperty(String name, AnchorType value) implements BlockStateProperty { public AnchorTypeBlockStateProperty(@NotNull String name, @NotNull AnchorType value) { this.name = name; this.value = value; @@ -22,11 +18,6 @@ public AnchorTypeBlockStateProperty(@NotNull String name, @NotNull AnchorType va return this.name; } - @Override - public @NonNull AnchorType value() { - return this.value; - } - @Override public void serialize(@NotNull ConfigurationSection propertiesSection) { ConfigurationSection section = propertiesSection.createSection(this.name); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/AxisBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/AxisBlockStateProperty.java index 1cff0427..b0109575 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/AxisBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/AxisBlockStateProperty.java @@ -1,17 +1,13 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.util.Direction; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.Locale; -public class AxisBlockStateProperty implements BlockStateProperty { - private final String name; - private final Direction.Axis value; - +public record AxisBlockStateProperty(String name, Direction.Axis value) implements BlockStateProperty { public AxisBlockStateProperty(@NotNull String name, @NotNull Direction.Axis value) { this.name = name; this.value = value; @@ -22,11 +18,6 @@ public AxisBlockStateProperty(@NotNull String name, @NotNull Direction.Axis valu return this.name; } - @Override - public Direction.@NonNull Axis value() { - return this.value; - } - @Override public void serialize(@NotNull ConfigurationSection propertiesSection) { ConfigurationSection section = propertiesSection.createSection(this.name); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/BooleanBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/BooleanBlockStateProperty.java index 1460c499..0dd58217 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/BooleanBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/BooleanBlockStateProperty.java @@ -1,13 +1,10 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; -public class BooleanBlockStateProperty implements BlockStateProperty { - private final String name; - private final Boolean value; - +public record BooleanBlockStateProperty(String name, Boolean value) implements BlockStateProperty { public BooleanBlockStateProperty(@NotNull String name, Boolean value) { this.name = name; this.value = value; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/DirectionBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/DirectionBlockStateProperty.java index 60fed62a..d883c5f9 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/DirectionBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/DirectionBlockStateProperty.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.util.Direction; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Locale; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/DoubleBlockHalfBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/DoubleBlockHalfBlockStateProperty.java index c56e807c..5e63e663 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/DoubleBlockHalfBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/DoubleBlockHalfBlockStateProperty.java @@ -1,17 +1,14 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.block.property.type.DoubleBlockHalf; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.Locale; -public class DoubleBlockHalfBlockStateProperty implements BlockStateProperty { - private final String name; - private final DoubleBlockHalf value; - +public record DoubleBlockHalfBlockStateProperty(String name, + DoubleBlockHalf value) implements BlockStateProperty { public DoubleBlockHalfBlockStateProperty(@NotNull String name, @NotNull DoubleBlockHalf value) { this.name = name; this.value = value; @@ -22,11 +19,6 @@ public DoubleBlockHalfBlockStateProperty(@NotNull String name, @NotNull DoubleBl return this.name; } - @Override - public @NonNull DoubleBlockHalf value() { - return this.value; - } - @Override public void serialize(@NotNull ConfigurationSection propertiesSection) { ConfigurationSection section = propertiesSection.createSection(this.name); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/HingeBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/HingeBlockStateProperty.java index aa0b079f..05511472 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/HingeBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/HingeBlockStateProperty.java @@ -1,17 +1,13 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; +import fr.robie.yamllibrary.ConfigurationSection; import org.bukkit.block.data.type.Door; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.Locale; -public class HingeBlockStateProperty implements BlockStateProperty { - private final String name; - private final Door.Hinge value; - +public record HingeBlockStateProperty(String name, Door.Hinge value) implements BlockStateProperty { public HingeBlockStateProperty(@NotNull String name, @NotNull Door.Hinge value) { this.name = name; this.value = value; @@ -22,11 +18,6 @@ public HingeBlockStateProperty(@NotNull String name, @NotNull Door.Hinge value) return this.name; } - @Override - public Door.@NonNull Hinge value() { - return this.value; - } - @Override public void serialize(@NotNull ConfigurationSection propertiesSection) { ConfigurationSection section = propertiesSection.createSection(this.name); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/HorizontalDirectionBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/HorizontalDirectionBlockStateProperty.java index aa815fcf..911e81da 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/HorizontalDirectionBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/HorizontalDirectionBlockStateProperty.java @@ -2,16 +2,13 @@ import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; import fr.robie.craftengineconverter.api.configuration.utils.HorizontalDirection; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.Locale; -public class HorizontalDirectionBlockStateProperty implements BlockStateProperty { - private final String name; - private final HorizontalDirection value; - +public record HorizontalDirectionBlockStateProperty(String name, + HorizontalDirection value) implements BlockStateProperty { public HorizontalDirectionBlockStateProperty(@NotNull String name, @NotNull HorizontalDirection value) { this.name = name; this.value = value; @@ -22,11 +19,6 @@ public HorizontalDirectionBlockStateProperty(@NotNull String name, @NotNull Hori return this.name; } - @Override - public @NonNull HorizontalDirection value() { - return this.value; - } - @Override public void serialize(@NotNull ConfigurationSection propertiesSection) { ConfigurationSection section = propertiesSection.createSection(this.name); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/IntBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/IntBlockStateProperty.java index 04c5ad44..829ed33d 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/IntBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/IntBlockStateProperty.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NonNull; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SingleBlockHalfBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SingleBlockHalfBlockStateProperty.java index 8aaeba9d..aff20d2e 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SingleBlockHalfBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SingleBlockHalfBlockStateProperty.java @@ -1,17 +1,14 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.block.property.type.SingleBlockHalf; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.Locale; -public class SingleBlockHalfBlockStateProperty implements BlockStateProperty { - private final String name; - private final SingleBlockHalf value; - +public record SingleBlockHalfBlockStateProperty(String name, + SingleBlockHalf value) implements BlockStateProperty { public SingleBlockHalfBlockStateProperty(@NotNull String name, @NotNull SingleBlockHalf value) { this.name = name; this.value = value; @@ -22,11 +19,6 @@ public SingleBlockHalfBlockStateProperty(@NotNull String name, @NotNull SingleBl return this.name; } - @Override - public @NonNull SingleBlockHalf value() { - return this.value; - } - @Override public void serialize(@NotNull ConfigurationSection propertiesSection) { ConfigurationSection section = propertiesSection.createSection(this.name); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SlabTypeBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SlabTypeBlockStateProperty.java index d485a230..1e0811b8 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SlabTypeBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SlabTypeBlockStateProperty.java @@ -1,17 +1,13 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.block.property.type.SlabType; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.Locale; -public class SlabTypeBlockStateProperty implements BlockStateProperty { - private final String name; - private final SlabType value; - +public record SlabTypeBlockStateProperty(String name, SlabType value) implements BlockStateProperty { public SlabTypeBlockStateProperty(@NotNull String name, @NotNull SlabType value) { this.name = name; this.value = value; @@ -22,11 +18,6 @@ public SlabTypeBlockStateProperty(@NotNull String name, @NotNull SlabType value) return this.name; } - @Override - public @NonNull SlabType value() { - return this.value; - } - @Override public void serialize(@NotNull ConfigurationSection propertiesSection) { ConfigurationSection section = propertiesSection.createSection(this.name); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SofaShapeBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SofaShapeBlockStateProperty.java index bf9cb334..a5c93bdb 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SofaShapeBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/SofaShapeBlockStateProperty.java @@ -1,17 +1,13 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.block.property.type.SofaShape; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.Locale; -public class SofaShapeBlockStateProperty implements BlockStateProperty { - private final String name; - private final SofaShape value; - +public record SofaShapeBlockStateProperty(String name, SofaShape value) implements BlockStateProperty { public SofaShapeBlockStateProperty(@NotNull String name, @NotNull SofaShape value) { this.name = name; this.value = value; @@ -22,11 +18,6 @@ public SofaShapeBlockStateProperty(@NotNull String name, @NotNull SofaShape valu return this.name; } - @Override - public @NonNull SofaShape value() { - return this.value; - } - @Override public void serialize(@NotNull ConfigurationSection propertiesSection) { ConfigurationSection section = propertiesSection.createSection(this.name); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/StairsShapeBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/StairsShapeBlockStateProperty.java index 47a43fbf..76247418 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/StairsShapeBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/StairsShapeBlockStateProperty.java @@ -1,17 +1,13 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.block.property.type.StairsShape; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.Locale; -public class StairsShapeBlockStateProperty implements BlockStateProperty { - private final String name; - private final StairsShape value; - +public record StairsShapeBlockStateProperty(String name, StairsShape value) implements BlockStateProperty { public StairsShapeBlockStateProperty(@NotNull String name, @NotNull StairsShape value) { this.name = name; this.value = value; @@ -22,11 +18,6 @@ public StairsShapeBlockStateProperty(@NotNull String name, @NotNull StairsShape return this.name; } - @Override - public @NonNull StairsShape value() { - return this.value; - } - @Override public void serialize(@NotNull ConfigurationSection propertiesSection) { ConfigurationSection section = propertiesSection.createSection(this.name); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/StringBlockStateProperty.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/StringBlockStateProperty.java index bcbd3881..95e0e3cb 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/StringBlockStateProperty.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/block/states/properties/StringBlockStateProperty.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.properties; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.BlockStateProperty; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NonNull; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/FurnitureBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/FurnitureBehavior.java new file mode 100644 index 00000000..a1c44f35 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/FurnitureBehavior.java @@ -0,0 +1,14 @@ +package fr.robie.craftengineconverter.api.configuration.item.behavior.furniture; + +import org.jetbrains.annotations.NotNull; + +import java.util.Map; + +/** + * One entry of a furniture's {@code behavior} list. CraftEngine reads that list as maps keyed by {@code type}, so + * each behaviour describes itself as a map rather than writing into a section of its own. + */ +public interface FurnitureBehavior { + + @NotNull Map serialize(); +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/FurnitureConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/FurnitureConfiguration.java index f146d4df..ca62ab34 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/FurnitureConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/FurnitureConfiguration.java @@ -3,12 +3,14 @@ import fr.robie.craftengineconverter.api.configuration.events.Event; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; import fr.robie.craftengineconverter.api.configuration.item.loottables.LootConfiguration; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; import java.util.EnumMap; +import java.util.List; import java.util.Map; public class FurnitureConfiguration implements ItemConfigurationSerializable { @@ -16,6 +18,7 @@ public class FurnitureConfiguration implements ItemConfigurationSerializable { private final Map placements = new EnumMap<>(FurniturePlacement.class); private LootConfiguration loot; private Event events; + private final List behaviors = new ArrayList<>(); @NotNull public FurnitureSettings getOrCreateSettings(String itemId) { @@ -37,6 +40,10 @@ public void setEvents(@Nullable Event events) { this.events = events; } + public void addBehavior(@NotNull FurnitureBehavior behavior) { + this.behaviors.add(behavior); + } + @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { ConfigurationSection behaviorSection = this.getOrCreateSection(itemSection, "behavior"); @@ -71,6 +78,14 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str this.events.serialize(furnitureSection); } + if (!this.behaviors.isEmpty()) { + List> serializedBehaviors = new ArrayList<>(this.behaviors.size()); + for (FurnitureBehavior behavior : this.behaviors) { + serializedBehaviors.add(behavior.serialize()); + } + furnitureSection.set("behavior", serializedBehaviors); + } + if (!this.placements.isEmpty()) { ConfigurationSection placementSection = this.getOrCreateSection(furnitureSection, "placement"); for (Placement placement : this.placements.values()) { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/Placement.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/Placement.java index 172e41e9..0c48a01f 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/Placement.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/Placement.java @@ -2,7 +2,7 @@ import fr.robie.craftengineconverter.api.configuration.item.behavior.furniture.element.Element; import fr.robie.craftengineconverter.api.configuration.item.behavior.furniture.hitbox.Hitbox; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import java.util.ArrayList; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/Rules.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/Rules.java index 70ca704e..1dff1b43 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/Rules.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/Rules.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.item.behavior.furniture; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.entity.furniture.AlignmentRule; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class Rules { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/SimpleStorageFurnitureBehavior.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/SimpleStorageFurnitureBehavior.java new file mode 100644 index 00000000..f167c7f3 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/behavior/furniture/SimpleStorageFurnitureBehavior.java @@ -0,0 +1,47 @@ +package fr.robie.craftengineconverter.api.configuration.item.behavior.furniture; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * CraftEngine's {@code simple_storage_furniture} behaviour: a container a player opens by interacting with the + * furniture, whose contents belong to the furniture rather than to any block. + */ +public class SimpleStorageFurnitureBehavior implements FurnitureBehavior { + private final int rows; + private final @Nullable String title; + private final @Nullable String openSound; + private final @Nullable String closeSound; + + public SimpleStorageFurnitureBehavior(int rows, @Nullable String title, @Nullable String openSound, @Nullable String closeSound) { + this.rows = rows; + this.title = title; + this.openSound = openSound; + this.closeSound = closeSound; + } + + @Override + public @NotNull Map serialize() { + Map behavior = new LinkedHashMap<>(); + behavior.put("type", "simple_storage_furniture"); + behavior.put("rows", this.rows); + if (this.title != null && !this.title.isBlank()) { + behavior.put("title", this.title); + } + + Map sounds = new LinkedHashMap<>(); + if (this.openSound != null && !this.openSound.isBlank()) { + sounds.put("open", this.openSound); + } + if (this.closeSound != null && !this.closeSound.isBlank()) { + sounds.put("close", this.closeSound); + } + if (!sounds.isEmpty()) { + behavior.put("sounds", sounds); + } + return behavior; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/clientbounddata/OverwritableItemNameConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/clientbounddata/OverwritableItemNameConfiguration.java index f848ba6b..c8ac3475 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/clientbounddata/OverwritableItemNameConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/clientbounddata/OverwritableItemNameConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.clientbounddata; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class OverwritableItemNameConfiguration implements ItemConfigurationSerializable { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/clientbounddata/OverwritableLoreConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/clientbounddata/OverwritableLoreConfiguration.java index 6eec27b7..60a33b88 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/clientbounddata/OverwritableLoreConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/clientbounddata/OverwritableLoreConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.clientbounddata; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/AttackRangeConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/AttackRangeConfiguration.java index 413d627c..8ad429b6 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/AttackRangeConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/AttackRangeConfiguration.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class AttackRangeConfiguration implements ItemConfigurationSerializable { @@ -25,7 +26,7 @@ public AttackRangeConfiguration(double minReach, double maxReach, double minCrea @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection attackRangeSection = this.getOrCreateSection(components, "minecraft:attack_range"); if (this.minReach != 0.0) { @@ -56,4 +57,5 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str private double clamp(double value, double min, double max) { return Math.max(min, Math.min(max, value)); } + } \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/BlocksAttacksConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/BlocksAttacksConfiguration.java index 011de5cb..70fed3c4 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/BlocksAttacksConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/BlocksAttacksConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -35,7 +35,7 @@ public record DamageReduction(double base, double factor, double horizontalBlock @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection blocksAttacksSection = this.getOrCreateSection(components, "minecraft:blocks_attacks"); if (this.blockDelaySeconds != 0) { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/BreakSoundConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/BreakSoundConfiguration.java index 133e4664..71103068 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/BreakSoundConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/BreakSoundConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class BreakSoundConfiguration implements ItemConfigurationSerializable { @@ -16,7 +16,7 @@ public BreakSoundConfiguration(@NotNull String breakSound, float range) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection breakSoundComponent = this.getOrCreateSection(components, "minecraft:break_sound"); breakSoundComponent.set("sound_id", this.breakSound); breakSoundComponent.set("range", this.range); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CanBreakConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CanBreakConfiguration.java index c331effb..c697c834 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CanBreakConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CanBreakConfiguration.java @@ -2,8 +2,8 @@ import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; import fr.robie.craftengineconverter.api.configuration.utils.BlockPredicateConfiguration; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CanPlaceOnConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CanPlaceOnConfiguration.java index 788f436d..a3221597 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CanPlaceOnConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CanPlaceOnConfiguration.java @@ -2,8 +2,8 @@ import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; import fr.robie.craftengineconverter.api.configuration.utils.BlockPredicateConfiguration; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ConsumableConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ConsumableConfiguration.java index f41cd0a7..e7ad87ad 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ConsumableConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ConsumableConfiguration.java @@ -1,22 +1,24 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.AbstractEffectsConfiguration; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.craftengineconverter.api.enums.item.component.ConsumableAnimation; +import fr.robie.craftengineconverter.api.utils.item.component.ConsumeEffect; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.List; -import java.util.Locale; public class ConsumableConfiguration extends AbstractEffectsConfiguration { private final String sound; private final boolean hasConsumeParticles; private final double consumeSeconds; - private final Animation animation; + private final ConsumableAnimation animation; private final List onConsumeEffects; - public ConsumableConfiguration(String sound, boolean hasConsumeParticles, double consumeSeconds, Animation animation, List onConsumeEffects) { + public ConsumableConfiguration(String sound, boolean hasConsumeParticles, double consumeSeconds, ConsumableAnimation animation, List onConsumeEffects) { this.sound = sound; this.hasConsumeParticles = hasConsumeParticles; this.consumeSeconds = consumeSeconds; @@ -24,17 +26,13 @@ public ConsumableConfiguration(String sound, boolean hasConsumeParticles, double this.onConsumeEffects = onConsumeEffects; } - public enum Animation { - NONE, EAT, DRINK, BLOCK, BOW, SPEAR, CROSSBOW, SPYGLASS, TOOT_HORN, BRUSH, BUNDLE, TRIDENT; - - public String toKey() { - return this.name().toLowerCase(Locale.ROOT); - } + public ConsumableConfiguration(double consumeSeconds, ConsumableAnimation animation, List onConsumeEffects) { + this(null, true, consumeSeconds, animation, onConsumeEffects); } @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection consumableSection = this.getOrCreateSection(components, "minecraft:consumable"); if (!this.sound.equals("entity.generic.eat")) { @@ -46,7 +44,7 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str if (this.consumeSeconds != 1.6) { consumableSection.set("consume_seconds", this.consumeSeconds); } - if (this.animation != Animation.EAT) { + if (this.animation != ConsumableAnimation.EAT) { consumableSection.set("animation", this.animation.toKey()); } @@ -54,4 +52,5 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str consumableSection.set("on_consume_effects", this.serializeEffects(this.onConsumeEffects)); } } + } \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CustomDataConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CustomDataConfiguration.java index 80cae095..9236a565 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CustomDataConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/CustomDataConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -17,7 +17,7 @@ public CustomDataConfiguration(@NotNull List customDataEntries) @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection customDataComponent = this.getOrCreateSection(components, "minecraft:custom_data"); for (CustomDataEntry entry : this.customDataEntries) { customDataComponent.set(entry.key(), entry.value()); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DamageResistantConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DamageResistantConfiguration.java index 216d87ff..07352347 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DamageResistantConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DamageResistantConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class DamageResistantConfiguration implements ItemConfigurationSerializable { @@ -14,7 +14,7 @@ public DamageResistantConfiguration(@NotNull String damageResistantType) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection damageResistantComponent = this.getOrCreateSection(components, "minecraft:damage_resistant"); damageResistantComponent.set("types", this.damageResistantType); } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DamageTypeConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DamageTypeConfiguration.java index 9eb5517b..548a9b20 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DamageTypeConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DamageTypeConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class DamageTypeConfiguration implements ItemConfigurationSerializable { @@ -17,7 +17,7 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str if (this.damageType.isEmpty()) { return; } - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); components.set("minecraft:damage_type", this.damageType); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DeathProtectionConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DeathProtectionConfiguration.java index f143b3a7..d57b4a21 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DeathProtectionConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/DeathProtectionConfiguration.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.AbstractEffectsConfiguration; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.craftengineconverter.api.utils.item.component.ConsumeEffect; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -18,7 +19,7 @@ public DeathProtectionConfiguration(List deathEffects) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection deathProtectionSection = this.getOrCreateSection(components, "minecraft:death_protection"); if (this.deathEffects == null || this.deathEffects.isEmpty()) { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/EnchantableConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/EnchantableConfiguration.java index 1b7bb0ef..8d5fef06 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/EnchantableConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/EnchantableConfiguration.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class EnchantableConfiguration implements ItemConfigurationSerializable { @@ -14,8 +15,9 @@ public EnchantableConfiguration(int enchantability) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection enchantableComponent = this.getOrCreateSection(components, "minecraft:enchantable"); enchantableComponent.set("value", this.enchantability); } + } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/EnchantmentGlintOverrideConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/EnchantmentGlintOverrideConfiguration.java index b87d7c14..096b779a 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/EnchantmentGlintOverrideConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/EnchantmentGlintOverrideConfiguration.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class EnchantmentGlintOverrideConfiguration implements ItemConfigurationSerializable { @@ -14,6 +15,7 @@ public EnchantmentGlintOverrideConfiguration(boolean enchantGlintOverride) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - this.getOrCreateSection(itemSection, "components").set("minecraft:enchantment_glint_override", this.enchantGlintOverride); + this.getComponentsSection(itemSection).set("minecraft:enchantment_glint_override", this.enchantGlintOverride); } + } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/FoodConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/FoodConfiguration.java index 42b0b96f..fdac033b 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/FoodConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/FoodConfiguration.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class FoodConfiguration implements ItemConfigurationSerializable { @@ -23,7 +24,7 @@ public FoodConfiguration(int nutrition, float saturation) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection foodComponent = this.getOrCreateSection(components, "minecraft:food"); foodComponent.set("nutrition", this.nutrition); foodComponent.set("saturation", this.saturation); @@ -31,4 +32,5 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str foodComponent.set("can_always_eat", true); } } + } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/GliderConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/GliderConfiguration.java index c134a1f6..70916fdd 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/GliderConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/GliderConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class GliderConfiguration implements ItemConfigurationSerializable { @@ -17,7 +17,7 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str if (!this.hasGlider) { return; } - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); components.set("minecraft:glider", true); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/HideTooltipDisplayConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/HideTooltipDisplayConfiguration.java index 8a41ab8b..5ca88cb3 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/HideTooltipDisplayConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/HideTooltipDisplayConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class HideTooltipDisplayConfiguration implements ItemConfigurationSerializable { @@ -14,7 +14,7 @@ public HideTooltipDisplayConfiguration(boolean hideTooltip) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection tooltipDisplay = this.getOrCreateSection(components, "minecraft:tooltip_display"); tooltipDisplay.set("hide_tooltip", this.hideTooltip); } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ItemModelConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ItemModelConfiguration.java index 0bac9cdb..2c737368 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ItemModelConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ItemModelConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class ItemModelConfiguration implements ItemConfigurationSerializable { @@ -14,6 +14,6 @@ public ItemModelConfiguration(String model) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - this.getOrCreateSection(itemSection, "components").set("minecraft:item_model", this.model); + this.getComponentsSection(itemSection).set("minecraft:item_model", this.model); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/JukeboxPlayableConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/JukeboxPlayableConfiguration.java index 298cd08d..f6a49b6b 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/JukeboxPlayableConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/JukeboxPlayableConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class JukeboxPlayableConfiguration implements ItemConfigurationSerializable { @@ -14,7 +14,7 @@ public JukeboxPlayableConfiguration(@NotNull String song) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection jukeboxPlayableComponent = this.getOrCreateSection(components, "minecraft:jukebox_playable"); jukeboxPlayableComponent.set("song", this.song); } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/KineticWeaponConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/KineticWeaponConfiguration.java index 4b61d261..1e592b60 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/KineticWeaponConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/KineticWeaponConfiguration.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class KineticWeaponConfiguration implements ItemConfigurationSerializable { @@ -43,7 +44,7 @@ public void serialize(@NotNull ConfigurationSection section) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection kineticSection = this.getOrCreateSection(components, "minecraft:kinetic_weapon"); if (this.delayTicks > 0) { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/MaxDamageComponent.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/MaxDamageComponent.java new file mode 100644 index 00000000..865a4ad4 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/MaxDamageComponent.java @@ -0,0 +1,22 @@ +package fr.robie.craftengineconverter.api.configuration.item.components; + +import com.google.gson.JsonObject; +import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; + +public class MaxDamageComponent implements ItemConfigurationSerializable { + private final int maxDamage; + + public MaxDamageComponent(int maxDamage) { + assert maxDamage >= 0 : "Max damage must be non-negative"; + this.maxDamage = maxDamage; + } + + @Override + public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { + ConfigurationSection components = this.getComponentsSection(itemSection); + components.set("minecraft:max_damage", this.maxDamage); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/MaxStackSizeConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/MaxStackSizeConfiguration.java index 15c1571f..ffd282c9 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/MaxStackSizeConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/MaxStackSizeConfiguration.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class MaxStackSizeConfiguration implements ItemConfigurationSerializable { @@ -14,6 +15,7 @@ public MaxStackSizeConfiguration(int maxStackSize) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - this.getOrCreateSection(itemSection, "components").set("minecraft:max_stack_size", this.maxStackSize); + this.getComponentsSection(itemSection).set("minecraft:max_stack_size", this.maxStackSize); } + } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/MinimumAttackChargeConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/MinimumAttackChargeConfiguration.java index b5084bd0..05bbcd07 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/MinimumAttackChargeConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/MinimumAttackChargeConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class MinimumAttackChargeConfiguration implements ItemConfigurationSerializable { @@ -17,7 +17,7 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str if (this.minimumAttackCharge < 0 || this.minimumAttackCharge > 1) { return; } - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection attackChargeComponent = this.getOrCreateSection(components, "minecraft:attack_charge"); attackChargeComponent.set("minimum_attack_charge", this.minimumAttackCharge); } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PaintingVariantConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PaintingVariantConfiguration.java index 68dc5841..0fa84f9d 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PaintingVariantConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PaintingVariantConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class PaintingVariantConfiguration implements ItemConfigurationSerializable { @@ -17,7 +17,7 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str if (this.variant.isEmpty()) { return; } - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); components.set("minecraft:painting/variant", this.variant); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PiercingWeaponConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PiercingWeaponConfiguration.java index 3ffdec08..d0467991 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PiercingWeaponConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PiercingWeaponConfiguration.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class PiercingWeaponConfiguration implements ItemConfigurationSerializable { @@ -21,7 +22,7 @@ public PiercingWeaponConfiguration(boolean dealsKnockback, boolean dismounts, St @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection piercingSection = this.getOrCreateSection(components, "minecraft:piercing_weapon"); if (!this.dealsKnockback) { @@ -40,4 +41,5 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str piercingSection.set("hit_sound", this.hitSound); } } + } \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PlayerProfileConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PlayerProfileConfiguration.java index b6db4343..dae3d991 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PlayerProfileConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PlayerProfileConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -35,7 +35,7 @@ public record Property(String name, String value, String signature) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection profileSection = this.getOrCreateSection(components, "minecraft:profile"); if (this.name != null && !this.name.isBlank()) { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PotionContentsConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PotionContentsConfiguration.java new file mode 100644 index 00000000..1ac4b5d3 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/PotionContentsConfiguration.java @@ -0,0 +1,93 @@ +package fr.robie.craftengineconverter.api.configuration.item.components; + +import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The {@code minecraft:potion_contents} component. CraftEngine has no dedicated processor for it, so it is written as + * a raw component under {@code data.components}. + */ +public class PotionContentsConfiguration implements ItemConfigurationSerializable { + private final List customEffects = new ArrayList<>(); + private @Nullable String potion; + private @Nullable Integer customColor; + + public PotionContentsConfiguration addEffect(@NotNull CustomEffect effect) { + this.customEffects.add(effect); + return this; + } + + /** The base potion this stack is brewed from, e.g. {@code minecraft:swiftness}. */ + public PotionContentsConfiguration setPotion(@Nullable String potion) { + this.potion = potion; + return this; + } + + public PotionContentsConfiguration setCustomColor(@Nullable Integer customColor) { + this.customColor = customColor; + return this; + } + + public boolean hasContents() { + return !this.customEffects.isEmpty() || this.potion != null || this.customColor != null; + } + + @Override + public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { + if (!this.hasContents()) { + return; + } + + ConfigurationSection components = this.getComponentsSection(itemSection); + ConfigurationSection potionContents = this.getOrCreateSection(components, "minecraft:potion_contents"); + + if (this.potion != null) { + potionContents.set("potion", this.potion); + } + if (this.customColor != null) { + potionContents.set("custom_color", this.customColor); + } + if (this.customEffects.isEmpty()) { + return; + } + + List> effects = new ArrayList<>(this.customEffects.size()); + for (CustomEffect effect : this.customEffects) { + effects.add(effect.serialize()); + } + potionContents.set("custom_effects", effects); + } + + /** + * One entry of {@code custom_effects}. Only values that differ from the vanilla defaults are written, so a plain + * effect stays a three-key map rather than carrying every flag. + */ + public record CustomEffect(@NotNull String id, int duration, int amplifier, + @Nullable Boolean ambient, @Nullable Boolean showParticles, @Nullable Boolean showIcon) { + + private Map serialize() { + Map effect = new LinkedHashMap<>(); + effect.put("id", this.id); + effect.put("duration", this.duration); + effect.put("amplifier", this.amplifier); + if (this.ambient != null) { + effect.put("ambient", this.ambient); + } + if (this.showParticles != null) { + effect.put("show_particles", this.showParticles); + } + if (this.showIcon != null) { + effect.put("show_icon", this.showIcon); + } + return effect; + } + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/SwingAnimationConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/SwingAnimationConfiguration.java index a3857f76..872bd87a 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/SwingAnimationConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/SwingAnimationConfiguration.java @@ -1,14 +1,15 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; - import java.util.Locale; public class SwingAnimationConfiguration implements ItemConfigurationSerializable { + private final AnimationType type; private final int duration; @@ -17,6 +18,15 @@ public SwingAnimationConfiguration(AnimationType type, int duration) { this.duration = duration; } + /** + * Animation is hardcoded by the client, so only duration is configurable + * + * @param duration Duration of the swing animation in ticks + */ + public SwingAnimationConfiguration(int duration) { + this(null, duration); + } + public enum AnimationType { NONE, WHACK, STAB; @@ -27,7 +37,7 @@ public String toKey() { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection swingAnimationSection = this.getOrCreateSection(components, "minecraft:swing_animation"); if (this.type != AnimationType.WHACK) { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ToolConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ToolConfiguration.java index 8d12363c..4026113d 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ToolConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/ToolConfiguration.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -25,7 +26,7 @@ public ToolConfiguration(float defaultMiningSpeed, int damagePerBlock, boolean c @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection toolComponent = this.getOrCreateSection(components, "minecraft:tool"); if (this.defaultMiningSpeed != 1.0f) { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/TooltipDisplayConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/TooltipDisplayConfiguration.java index 6bf61291..cf9f1c4c 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/TooltipDisplayConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/TooltipDisplayConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -19,7 +19,7 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str if (this.hiddenComponents.isEmpty()) { return; } - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection tooltipDisplayComponent = this.getOrCreateSection(components, "minecraft:tooltip_display"); tooltipDisplayComponent.set("hidden_components", this.hiddenComponents); } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseCooldownConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseCooldownConfiguration.java index 985e6bf4..f487b74e 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseCooldownConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseCooldownConfiguration.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class UseCooldownConfiguration implements ItemConfigurationSerializable { @@ -16,11 +17,12 @@ public UseCooldownConfiguration(float seconds, String cooldownGroup) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection useCooldownComponent = this.getOrCreateSection(components, "minecraft:use_cooldown"); useCooldownComponent.set("seconds", this.seconds); if (this.cooldownGroup != null) { useCooldownComponent.set("cooldown_group", this.cooldownGroup); } } + } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseEffectsConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseEffectsConfiguration.java index bd4ee45e..f9ab8112 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseEffectsConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseEffectsConfiguration.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.components; +import com.google.gson.JsonObject; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class UseEffectsConfiguration implements ItemConfigurationSerializable { @@ -17,9 +18,19 @@ public UseEffectsConfiguration(boolean canSprint, double speedMultiplier, boolea this.interactVibrations = interactVibrations; } + /** + * Not every client has the can_sprint property, so this is kept off by default. + * + * @param speedMultiplier + * @param interactVibrations + */ + public UseEffectsConfiguration(double speedMultiplier, boolean interactVibrations) { + this(false, speedMultiplier, interactVibrations); + } + @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection useEffectsSection = this.getOrCreateSection(components, "minecraft:use_effects"); if (this.canSprint) { @@ -34,4 +45,5 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str useEffectsSection.set("interact_vibrations", false); } } + } \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseRemainderConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseRemainderConfiguration.java index ed5d40f8..ebc52392 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseRemainderConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/UseRemainderConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class UseRemainderConfiguration implements ItemConfigurationSerializable { @@ -20,7 +20,7 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str return; } - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection useRemainderSection = this.getOrCreateSection(components, "minecraft:use_remainder"); useRemainderSection.set("item", this.remainderItemId); if (this.remainderCount > 1) { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/WeaponConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/WeaponConfiguration.java index d47645b8..448f69b5 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/WeaponConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/components/WeaponConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.components; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class WeaponConfiguration implements ItemConfigurationSerializable { @@ -16,7 +16,7 @@ public WeaponConfiguration(int itemDamagePerAttack, float disableBlockingForSeco @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection weaponComponent = this.getOrCreateSection(components, "minecraft:weapon"); if (this.itemDamagePerAttack != 1) { weaponComponent.set("item_damage_per_attack", this.itemDamagePerAttack); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/AttributeModifier.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/AttributeModifier.java index 61abab5d..0b51ce82 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/AttributeModifier.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/AttributeModifier.java @@ -3,11 +3,11 @@ import net.momirealms.craftengine.core.util.Key; import org.jetbrains.annotations.Nullable; -public record AttributeModifier(String type, net.momirealms.craftengine.core.attribute.AttributeModifier.Slot slot, +public record AttributeModifier(String type, net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot slot, Key id, double amount, - net.momirealms.craftengine.core.attribute.AttributeModifier.Operation operation, + net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation operation, @Nullable Display display) { - public AttributeModifier(String type, net.momirealms.craftengine.core.attribute.AttributeModifier.Slot slot, Key id, double amount, net.momirealms.craftengine.core.attribute.AttributeModifier.Operation operation, @Nullable Display display) { + public AttributeModifier(String type, net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot slot, Key id, double amount, net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation operation, @Nullable Display display) { this.amount = amount; this.display = display; this.id = id; @@ -16,6 +16,6 @@ public AttributeModifier(String type, net.momirealms.craftengine.core.attribute. this.type = type; } - public record Display(net.momirealms.craftengine.core.attribute.AttributeModifier.Display.Type type, String value) { + public record Display(net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Display.Type type, String value) { } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/AttributeModifiersConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/AttributeModifiersConfiguration.java index 045c48ef..39db2786 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/AttributeModifiersConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/AttributeModifiersConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.data; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.*; @@ -16,7 +16,7 @@ public AttributeModifiersConfiguration(List attributeModifier @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection data = this.getOrCreateSection(itemSection, "data"); + ConfigurationSection data = this.getDataSection(itemSection); List> serializedModifiers = new ArrayList<>(); for (AttributeModifier modifier : this.attributeModifiers) { Map serializedModifier = new HashMap<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/BlockStateConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/BlockStateConfiguration.java index 51a3382b..087ca81a 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/BlockStateConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/BlockStateConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.data; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -16,7 +16,7 @@ public BlockStateConfiguration(@NotNull BlockStateEntry blockStateEntry) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection dataSection = this.getOrCreateSection(itemSection, "data"); + ConfigurationSection dataSection = this.getDataSection(itemSection); this.blockStateEntry.serialize(dataSection); } @@ -25,37 +25,22 @@ public interface BlockStateEntry { void serialize(ConfigurationSection dataSection); } - public static class CraftEngineBlockStateEntry implements BlockStateEntry { - private final String blockState; - - public CraftEngineBlockStateEntry(String blockState) { - this.blockState = blockState; - } - - public String getBlockState() { - return this.blockState; - } + public record CraftEngineBlockStateEntry(String blockState) implements BlockStateEntry { @Override - public void serialize(ConfigurationSection dataSection) { - dataSection.set("block-state", this.blockState); + public void serialize(ConfigurationSection dataSection) { + dataSection.set("block-state", this.blockState); + } } - } - public static class VanillaBlockStateEntry implements BlockStateEntry { - private final Map blockStateProperties; + public record VanillaBlockStateEntry(Map blockStateProperties) implements BlockStateEntry { + public VanillaBlockStateEntry(@NotNull Map blockStateProperties) { + this.blockStateProperties = blockStateProperties; + } - public VanillaBlockStateEntry(@NotNull Map blockStateProperties) { - this.blockStateProperties = blockStateProperties; + @Override + public void serialize(ConfigurationSection dataSection) { + dataSection.createSection("block-state", this.blockStateProperties); + } } - - public Map getBlockStateProperties() { - return this.blockStateProperties; - } - - @Override - public void serialize(ConfigurationSection dataSection) { - dataSection.createSection("block-state", this.blockStateProperties); - } - } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/CustomModelDataConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/CustomModelDataConfiguration.java index 56b0fcc4..59c9a260 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/CustomModelDataConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/CustomModelDataConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.data; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class CustomModelDataConfiguration implements ItemConfigurationSerializable { @@ -14,6 +14,6 @@ public CustomModelDataConfiguration(int customModelData) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - this.getOrCreateSection(itemSection, "data").set("custom-model-data", this.customModelData); + this.getDataSection(itemSection).set("custom-model-data", this.customModelData); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/CustomNameConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/CustomNameConfiguration.java index d20ae439..5efea003 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/CustomNameConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/CustomNameConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.data; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class CustomNameConfiguration implements ItemConfigurationSerializable { @@ -14,7 +14,7 @@ public CustomNameConfiguration(@NotNull String customName) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection dataSection = this.getOrCreateSection(itemSection, "data"); + ConfigurationSection dataSection = this.getDataSection(itemSection); dataSection.set("custom-name", this.customName); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/DyedColorConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/DyedColorConfiguration.java index 0113c356..28b2c433 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/DyedColorConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/DyedColorConfiguration.java @@ -1,9 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.data; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; +import fr.robie.yamllibrary.ConfigurationSection; import org.bukkit.DyeColor; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.Locale; @@ -16,17 +16,22 @@ public DyedColorConfiguration(int rgb) { } public static DyedColorConfiguration parse(Object color) throws Exception { + return new DyedColorConfiguration(parseRgb(color)); + } + + /** Accepts a dye name, {@code #rrggbb} or {@code r,g,b}, which is every spelling the source plugins allow. */ + public static int parseRgb(Object color) throws Exception { String colorStr = color.toString().trim(); try { DyeColor dyeColor = DyeColor.valueOf(colorStr.toUpperCase(Locale.ROOT)); - return new DyedColorConfiguration(dyeColor.getColor().asRGB()); + return dyeColor.getColor().asRGB(); } catch (IllegalArgumentException ignored) { } String hex = colorStr.startsWith("#") ? colorStr.substring(1) : colorStr; if (hex.matches("[0-9a-fA-F]{6}")) { - return new DyedColorConfiguration(Integer.parseInt(hex, 16)); + return Integer.parseInt(hex, 16); } String[] parts = colorStr.split(","); @@ -36,12 +41,11 @@ public static DyedColorConfiguration parse(Object color) throws Exception { int r = Integer.parseInt(parts[0].trim()); int g = Integer.parseInt(parts[1].trim()); int b = Integer.parseInt(parts[2].trim()); - int rgb = ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF); - return new DyedColorConfiguration(rgb); + return ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF); } @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - this.getOrCreateSection(itemSection, "data").set("dyed-color", String.format("%d,%d,%d", (this.rgb >> 16) & 0xFF, (this.rgb >> 8) & 0xFF, this.rgb & 0xFF)); + this.getDataSection(itemSection).set("dyed-color", String.format("%d,%d,%d", (this.rgb >> 16) & 0xFF, (this.rgb >> 8) & 0xFF, this.rgb & 0xFF)); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/EnchantmentConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/EnchantmentConfiguration.java index d78789ed..9bb96818 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/EnchantmentConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/EnchantmentConfiguration.java @@ -2,8 +2,8 @@ import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; import fr.robie.craftengineconverter.api.utils.EnchantmentCompatibility; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.HashMap; @@ -33,7 +33,7 @@ public boolean isMerge() { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - ConfigurationSection data = this.getOrCreateSection(itemSection, "data"); + ConfigurationSection data = this.getDataSection(itemSection); ConfigurationSection enchantment = this.getOrCreateSection(data, "enchantment"); if (this.merge) { enchantment.set("merge", true); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/HideTooltipConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/HideTooltipConfiguration.java index db8568cd..00d6f483 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/HideTooltipConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/HideTooltipConfiguration.java @@ -2,8 +2,8 @@ import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; import fr.robie.craftengineconverter.api.enums.ComponentFlag; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.*; @@ -21,6 +21,6 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str for (ComponentFlag flag : this.flags) { flagNames.add(flag.getKey()); } - this.getOrCreateSection(itemSection, "data").set("hide-tooltip", flagNames); + this.getDataSection(itemSection).set("hide-tooltip", flagNames); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/ItemNameConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/ItemNameConfiguration.java index b260dbe8..f4a50e05 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/ItemNameConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/ItemNameConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.data; import fr.robie.craftengineconverter.api.configuration.item.AbstractItemConfiguration; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class ItemNameConfiguration extends AbstractItemConfiguration { @@ -23,7 +23,7 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str if (this.itemName == null || this.itemName.isEmpty()) { return; } - ConfigurationSection data = this.getOrCreateSection(itemSection, "data"); + ConfigurationSection data = this.getDataSection(itemSection); data.set("item-name", this.applyNoItalic(this.itemName)); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/MaxDamageConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/MaxDamageConfiguration.java index 96268b46..9f978240 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/MaxDamageConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/MaxDamageConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.data; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class MaxDamageConfiguration implements ItemConfigurationSerializable { @@ -14,6 +14,6 @@ public MaxDamageConfiguration(int maxDamage) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { - this.getOrCreateSection(itemSection, "data").set("max-damage", this.maxDamage); + this.getDataSection(itemSection).set("max-damage", this.maxDamage); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/TooltipStyleConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/TooltipStyleConfiguration.java index eb9ae99d..47be8e0a 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/TooltipStyleConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/TooltipStyleConfiguration.java @@ -1,9 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.data; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.bukkit.NamespacedKey; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class TooltipStyleConfiguration implements ItemConfigurationSerializable { @@ -20,7 +20,7 @@ public TooltipStyleConfiguration(String styleKey) { @Override public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { if (this.styleKey != null) { - this.getOrCreateSection(itemSection, "data").set("tooltip-style", this.styleKey.asString()); + this.getDataSection(itemSection).set("tooltip-style", this.styleKey.asString()); } } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/TrimConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/TrimConfiguration.java new file mode 100644 index 00000000..535d25f2 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/TrimConfiguration.java @@ -0,0 +1,27 @@ +package fr.robie.craftengineconverter.api.configuration.item.data; + +import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; + +/** + * The armour trim baked onto an item stack. CraftEngine has a dedicated {@code trim} processor for this, so it goes + * straight on {@code data} rather than among the raw components; the processor requires both halves. + */ +public class TrimConfiguration implements ItemConfigurationSerializable { + private final String material; + private final String pattern; + + public TrimConfiguration(@NotNull String material, @NotNull String pattern) { + this.material = material; + this.pattern = pattern; + } + + @Override + public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { + ConfigurationSection trimSection = this.getOrCreateSection(this.getDataSection(itemSection), "trim"); + trimSection.set("material", this.material); + trimSection.set("pattern", this.pattern); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/UnbreakableConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/UnbreakableConfiguration.java index 909d69b5..0c22d428 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/UnbreakableConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/UnbreakableConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.data; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class UnbreakableConfiguration implements ItemConfigurationSerializable { @@ -17,7 +17,7 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str if (!this.unbreakable) { return; } - ConfigurationSection dataSection = this.getOrCreateSection(itemSection, "data"); + ConfigurationSection dataSection = this.getDataSection(itemSection); dataSection.set("unbreakable", true); } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/WrittenBookContentConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/WrittenBookContentConfiguration.java new file mode 100644 index 00000000..f9253e26 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/data/WrittenBookContentConfiguration.java @@ -0,0 +1,52 @@ +package fr.robie.craftengineconverter.api.configuration.item.data; + +import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +/** + * A written book's contents. CraftEngine has a {@code written_book_content} processor, so this goes on {@code data} + * rather than among the raw components. + */ +public class WrittenBookContentConfiguration implements ItemConfigurationSerializable { + /** Matches vanilla's ordering, which is what the component stores. */ + public static final int GENERATION_ORIGINAL = 0; + public static final int GENERATION_COPY_OF_ORIGINAL = 1; + public static final int GENERATION_COPY_OF_COPY = 2; + public static final int GENERATION_TATTERED = 3; + + private final @Nullable String title; + private final @Nullable String author; + private final int generation; + private final List pages; + + public WrittenBookContentConfiguration(@Nullable String title, @Nullable String author, int generation, @NotNull List pages) { + this.title = title; + this.author = author; + this.generation = generation; + this.pages = List.copyOf(pages); + } + + @Override + public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { + ConfigurationSection bookSection = this.getOrCreateSection(this.getDataSection(itemSection), "written_book_content"); + + if (this.title != null && !this.title.isBlank()) { + bookSection.set("title", this.title); + } + if (this.author != null && !this.author.isBlank()) { + bookSection.set("author", this.author); + } + // Vanilla's default is 0, and the processor already assumes it. + if (this.generation != GENERATION_ORIGINAL) { + bookSection.set("generation", this.generation); + } + if (!this.pages.isEmpty()) { + bookSection.set("pages", this.pages); + } + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/LootPool.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/LootPool.java index 991f5516..815c6578 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/LootPool.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/LootPool.java @@ -4,7 +4,7 @@ import fr.robie.craftengineconverter.api.configuration.item.loottables.entries.LootEntry; import fr.robie.craftengineconverter.api.configuration.item.loottables.functions.LootFunction; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/LootTable.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/LootTable.java index d2cdbbd6..8a54a449 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/LootTable.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/LootTable.java @@ -2,7 +2,7 @@ import fr.robie.craftengineconverter.api.configuration.item.loottables.functions.LootFunction; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/AbstractLootEntry.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/AbstractLootEntry.java index fb36fd9c..9d02024b 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/AbstractLootEntry.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/AbstractLootEntry.java @@ -3,7 +3,7 @@ import fr.robie.craftengineconverter.api.configuration.conditions.Condition; import fr.robie.craftengineconverter.api.configuration.item.loottables.functions.LootFunction; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/AlternativesEntry.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/AlternativesEntry.java index e87ccda1..d7778423 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/AlternativesEntry.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/AlternativesEntry.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.item.loottables.entries; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/ExpEntry.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/ExpEntry.java index b77adae1..1a2668d0 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/ExpEntry.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/ExpEntry.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.loottables.entries; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/FurnitureItemEntry.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/FurnitureItemEntry.java index 4e7e462e..2a8f531f 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/FurnitureItemEntry.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/FurnitureItemEntry.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.loottables.entries; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/ItemEntry.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/ItemEntry.java index 795fc179..abfd287c 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/ItemEntry.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/entries/ItemEntry.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.loottables.entries; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/formulas/AbstractLootFormula.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/formulas/AbstractLootFormula.java index 055ce019..80f8550d 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/formulas/AbstractLootFormula.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/formulas/AbstractLootFormula.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.loottables.formulas; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public abstract class AbstractLootFormula implements LootFormula { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/formulas/BinomialWithBonusCountFormula.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/formulas/BinomialWithBonusCountFormula.java index ecfd9f42..ce3cd6fa 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/formulas/BinomialWithBonusCountFormula.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/formulas/BinomialWithBonusCountFormula.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.loottables.formulas; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class BinomialWithBonusCountFormula extends AbstractLootFormula { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/AbstractLootFunction.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/AbstractLootFunction.java index 637f8f0a..2fd73032 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/AbstractLootFunction.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/AbstractLootFunction.java @@ -2,7 +2,7 @@ import fr.robie.craftengineconverter.api.configuration.conditions.Condition; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/ApplyBonusFunction.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/ApplyBonusFunction.java index cfd0bb37..7c9fabd2 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/ApplyBonusFunction.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/ApplyBonusFunction.java @@ -2,7 +2,7 @@ import fr.robie.craftengineconverter.api.configuration.item.loottables.formulas.LootFormula; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/ApplyDataFunction.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/ApplyDataFunction.java index 3f5d59d9..a55fddb1 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/ApplyDataFunction.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/ApplyDataFunction.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.loottables.functions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Map; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/DropExpFunction.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/DropExpFunction.java index 932c488b..d82d7c6e 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/DropExpFunction.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/DropExpFunction.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.loottables.functions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/LimitCountFunction.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/LimitCountFunction.java index 18477cf9..d55da717 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/LimitCountFunction.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/LimitCountFunction.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.loottables.functions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class LimitCountFunction extends AbstractLootFunction { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/SetCountFunction.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/SetCountFunction.java index 5c395859..85921b35 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/SetCountFunction.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/loottables/functions/SetCountFunction.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.loottables.functions; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/ModelConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/ModelConfiguration.java index dab4a16a..5013d155 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/ModelConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/ModelConfiguration.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.item.models; import fr.robie.craftengineconverter.api.configuration.SectionSerializable; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -10,7 +10,7 @@ public interface ModelConfiguration extends SectionSerializable { @Override void serialize(@NotNull ConfigurationSection section); - + @Contract("!null -> !null; null -> null") default @Nullable String namespaced(String path) { return this.namespaced(path, "minecraft"); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/composite/CompositeModelConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/composite/CompositeModelConfiguration.java index 03038c95..e4dd4b55 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/composite/CompositeModelConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/composite/CompositeModelConfiguration.java @@ -2,16 +2,22 @@ import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Objects; public class CompositeModelConfiguration implements ModelConfiguration { private final List models = new ArrayList<>(); + @NotNull + public List getModels() { + return Collections.unmodifiableList(this.models); + } + public CompositeModelConfiguration(@NotNull List models) { this.models.addAll(models); } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/ComponentConditionConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/ComponentConditionConfiguration.java index 80300556..3739513a 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/ComponentConditionConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/ComponentConditionConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.condition; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class ComponentConditionConfiguration extends ConditionModelConfiguration { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/ConditionModelConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/ConditionModelConfiguration.java index a9e5cef4..95fc233c 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/ConditionModelConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/ConditionModelConfiguration.java @@ -2,7 +2,7 @@ import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -15,6 +15,20 @@ public ConditionModelConfiguration(@NotNull String property) { this.property = this.namespaced(property); } + public String getProperty() { + return this.property; + } + + @Nullable + public ModelConfiguration getOnTrue() { + return this.onTrue; + } + + @Nullable + public ModelConfiguration getOnFalse() { + return this.onFalse; + } + public void setOnTrue(@Nullable ModelConfiguration onTrue) { this.onTrue = onTrue; } @@ -36,4 +50,12 @@ public void serialize(@NotNull ConfigurationSection section) { section.set("on-false", ConfigurationSerializationUtils.toMap(this.onFalse)); } } + + public boolean isConditionSupported() { + String propertyName = this.property.contains(":") ? this.property.split(":")[1] : this.property; + return switch (propertyName.toLowerCase(java.util.Locale.ROOT)) { + case "broken", "damaged", "fishing_rod/cast", "custom_model_data", "has_component" -> true; + default -> false; + }; + } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/CustomModelDataConditionConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/CustomModelDataConditionConfiguration.java index 0e93c9fc..a189c1e0 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/CustomModelDataConditionConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/CustomModelDataConditionConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.condition; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class CustomModelDataConditionConfiguration extends ConditionModelConfiguration { @@ -16,4 +16,8 @@ public void serialize(@NotNull ConfigurationSection section) { super.serialize(section); section.set("index", this.index); } + + public int getIndex() { + return this.index; + } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/HasComponentConditionConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/HasComponentConditionConfiguration.java index c36be6b2..013b8528 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/HasComponentConditionConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/HasComponentConditionConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.condition; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class HasComponentConditionConfiguration extends ConditionModelConfiguration { @@ -13,6 +13,11 @@ public HasComponentConditionConfiguration(@NotNull String component, boolean ign this.ignoreDefault = ignoreDefault; } + @NotNull + public String getComponent() { + return this.component; + } + @Override public void serialize(@NotNull ConfigurationSection section) { super.serialize(section); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/KeybindDownConditionConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/KeybindDownConditionConfiguration.java index 26238d18..690b3eec 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/KeybindDownConditionConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/condition/KeybindDownConditionConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.condition; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class KeybindDownConditionConfiguration extends ConditionModelConfiguration { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/model/SimpleModelConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/model/SimpleModelConfiguration.java index 5d90969d..95ae772e 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/model/SimpleModelConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/model/SimpleModelConfiguration.java @@ -3,7 +3,7 @@ import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; import fr.robie.craftengineconverter.api.configuration.item.models.tints.TintConfiguration; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/ChargeType.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/ChargeType.java new file mode 100644 index 00000000..0274c5bd --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/ChargeType.java @@ -0,0 +1,7 @@ +package fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch; + +public enum ChargeType { + NONE, + ROCKET, + ARROW +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CompassRangeDispatchConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CompassRangeDispatchConfiguration.java index fd7669e4..4212fa7a 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CompassRangeDispatchConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CompassRangeDispatchConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class CompassRangeDispatchConfiguration extends RangeDispatchModelConfiguration { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CountRangeDispatchConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CountRangeDispatchConfiguration.java index a3f1a82d..19b6fdd4 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CountRangeDispatchConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CountRangeDispatchConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class CountRangeDispatchConfiguration extends RangeDispatchModelConfiguration { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CrossbowPullRangeDispatchConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CrossbowPullRangeDispatchConfiguration.java new file mode 100644 index 00000000..c69495c7 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CrossbowPullRangeDispatchConfiguration.java @@ -0,0 +1,17 @@ +package fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch; + +/** + * How far a crossbow has been pulled, from 0 to 1. + * + *

Not the same thing as {@code use_duration}

+ * {@link UseDurationRangeDispatchConfiguration} reports ticks, which is why it carries a {@code scale} to turn them + * into a fraction. This property is already a fraction: the Java client divides the elapsed time by the + * crossbow's own charge duration, which Quick Charge shortens, so no scale exists to read and none is meaningful. + * Anything reproducing it has to normalise for itself. + */ +public class CrossbowPullRangeDispatchConfiguration extends RangeDispatchModelConfiguration { + + public CrossbowPullRangeDispatchConfiguration() { + super("minecraft:crossbow/pull"); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CustomModelDataRangeDispatchConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CustomModelDataRangeDispatchConfiguration.java index dfa3d1ef..c73717aa 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CustomModelDataRangeDispatchConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/CustomModelDataRangeDispatchConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class CustomModelDataRangeDispatchConfiguration extends RangeDispatchModelConfiguration { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/DamageRangeDispatchConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/DamageRangeDispatchConfiguration.java index 47966031..1d32c223 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/DamageRangeDispatchConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/DamageRangeDispatchConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class DamageRangeDispatchConfiguration extends RangeDispatchModelConfiguration { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/RangeDispatchModelConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/RangeDispatchModelConfiguration.java index 70c0ac8e..aa9b26a6 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/RangeDispatchModelConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/RangeDispatchModelConfiguration.java @@ -2,7 +2,7 @@ import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -10,7 +10,7 @@ public class RangeDispatchModelConfiguration implements ModelConfiguration { private final String property; - private Double scale; + private Float scale; private final List entries = new ArrayList<>(); private ModelConfiguration fallback; @@ -18,7 +18,27 @@ public RangeDispatchModelConfiguration(@NotNull String property) { this.property = this.namespaced(property); } - public void setScale(@Nullable Double scale) { + @NotNull + public String getProperty() { + return this.property; + } + + @Nullable + public Float getScale() { + return this.scale; + } + + @NotNull + public List getEntries() { + return this.entries; + } + + @Nullable + public ModelConfiguration getFallback() { + return this.fallback; + } + + public void setScale(@Nullable Float scale) { this.scale = scale; } @@ -44,29 +64,18 @@ public void serialize(@NotNull ConfigurationSection section) { List> serializedEntries = new ArrayList<>(); for (Entry entry : this.entries) { Map map = new LinkedHashMap<>(); - map.put("threshold", entry.getThreshold()); - map.put("model", ConfigurationSerializationUtils.toMap(entry.getModel())); + map.put("threshold", entry.threshold()); + map.put("model", ConfigurationSerializationUtils.toMap(entry.model())); serializedEntries.add(map); } section.set("entries", serializedEntries); } } - public static class Entry { - private final double threshold; - private final ModelConfiguration model; - + public record Entry(double threshold, ModelConfiguration model) { public Entry(double threshold, @NotNull ModelConfiguration model) { this.threshold = threshold; this.model = Objects.requireNonNull(model, "model cannot be null"); } - - public double getThreshold() { - return this.threshold; - } - - public ModelConfiguration getModel() { - return this.model; - } } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/TimeRangeDispatchConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/TimeRangeDispatchConfiguration.java index 6d6bd10c..efed6b55 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/TimeRangeDispatchConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/TimeRangeDispatchConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/UseCycleRangeDispatchConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/UseCycleRangeDispatchConfiguration.java index 5098fb82..3c41e615 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/UseCycleRangeDispatchConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/UseCycleRangeDispatchConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class UseCycleRangeDispatchConfiguration extends RangeDispatchModelConfiguration { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/UseDurationRangeDispatchConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/UseDurationRangeDispatchConfiguration.java index b77ad2df..3b7fdf5e 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/UseDurationRangeDispatchConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/range_dispatch/UseDurationRangeDispatchConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class UseDurationRangeDispatchConfiguration extends RangeDispatchModelConfiguration { @@ -15,6 +15,15 @@ public UseDurationRangeDispatchConfiguration() { this(false); } + /** + * Whether the thresholds are compared against the time left rather than the time elapsed. + *

+ * It inverts the direction of every comparison, so anything reproducing this dispatch has to know. + */ + public boolean isRemaining() { + return this.remaining; + } + @Override public void serialize(@NotNull ConfigurationSection section) { super.serialize(section); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/BlockStateSelectConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/BlockStateSelectConfiguration.java index ee3e1a20..21b1aec0 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/BlockStateSelectConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/BlockStateSelectConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.select; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class BlockStateSelectConfiguration extends SelectModelConfiguration { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/ChargeTypeSelectConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/ChargeTypeSelectConfiguration.java index b0f1b00d..345b3900 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/ChargeTypeSelectConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/ChargeTypeSelectConfiguration.java @@ -1,14 +1,10 @@ package fr.robie.craftengineconverter.api.configuration.item.models.select; -public class ChargeTypeSelectConfiguration extends SelectModelConfiguration { +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.ChargeType; + +public class ChargeTypeSelectConfiguration extends SelectModelConfiguration { public ChargeTypeSelectConfiguration() { super("minecraft:charge_type"); } - - public enum ChargeType { - NONE, - ROCKET, - ARROW - } } \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/ComponentSelectConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/ComponentSelectConfiguration.java index c2c9863e..c65ccd72 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/ComponentSelectConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/ComponentSelectConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.select; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.Objects; @@ -13,6 +13,11 @@ public ComponentSelectConfiguration(@NotNull String component) { this.component = this.namespaced(Objects.requireNonNull(component, "component cannot be null")); } + @NotNull + public String getComponent() { + return this.component; + } + @Override public void serialize(@NotNull ConfigurationSection section) { super.serialize(section); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/CustomModelDataSelectConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/CustomModelDataSelectConfiguration.java index 42d2f281..da1777d1 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/CustomModelDataSelectConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/CustomModelDataSelectConfiguration.java @@ -1,9 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.models.select; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; -public class CustomModelDataSelectConfiguration extends SelectModelConfiguration { +public class CustomModelDataSelectConfiguration extends SelectModelConfiguration { private final int index; public CustomModelDataSelectConfiguration(int index) { @@ -11,6 +11,10 @@ public CustomModelDataSelectConfiguration(int index) { this.index = index; } + public int getIndex() { + return this.index; + } + @Override public void serialize(@NotNull ConfigurationSection section) { super.serialize(section); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/DisplayContent.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/DisplayContent.java new file mode 100644 index 00000000..62a69c4e --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/DisplayContent.java @@ -0,0 +1,14 @@ +package fr.robie.craftengineconverter.api.configuration.item.models.select; + +public enum DisplayContent { + NONE, + THIRDPERSON_LEFTHAND, + THIRDPERSON_RIGHTHAND, + FIRSTPERSON_LEFTHAND, + FIRSTPERSON_RIGHTHAND, + HEAD, + GUI, + GROUND, + FIXED, + ON_SHELF +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/DisplayContentSelectConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/DisplayContentSelectConfiguration.java index 7a905ac3..44af9fcc 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/DisplayContentSelectConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/DisplayContentSelectConfiguration.java @@ -1,21 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.models.select; -public class DisplayContentSelectConfiguration extends SelectModelConfiguration{ +public class DisplayContentSelectConfiguration extends SelectModelConfiguration { public DisplayContentSelectConfiguration() { super("minecraft:display_context"); } - public enum DisplayContent { - NONE, - THIRDPERSON_LEFTHAND, - THIRDPERSON_RIGHTHAND, - FIRSTPERSON_LEFTHAND, - FIRSTPERSON_RIGHTHAND, - HEAD, - GUI, - GROUND, - FIXED, - ON_SHELF - } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/LocalTimeSelectConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/LocalTimeSelectConfiguration.java index 30207893..8ec9a688 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/LocalTimeSelectConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/LocalTimeSelectConfiguration.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.configuration.item.models.select; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/MainHand.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/MainHand.java new file mode 100644 index 00000000..603862ce --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/MainHand.java @@ -0,0 +1,6 @@ +package fr.robie.craftengineconverter.api.configuration.item.models.select; + +public enum MainHand { + LEFT, + RIGHT +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/MainHandSelectConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/MainHandSelectConfiguration.java index 07149636..c78f4ccb 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/MainHandSelectConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/MainHandSelectConfiguration.java @@ -1,13 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.models.select; -public class MainHandSelectConfiguration extends SelectModelConfiguration { +public class MainHandSelectConfiguration extends SelectModelConfiguration { public MainHandSelectConfiguration() { super("minecraft:main_hand"); } - public enum MainHand { - LEFT, - RIGHT - } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/SelectModelConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/SelectModelConfiguration.java index fc7f89e4..c8a72cf8 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/SelectModelConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/SelectModelConfiguration.java @@ -2,7 +2,7 @@ import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -17,6 +17,21 @@ public SelectModelConfiguration(@NotNull String property) { this.property = this.namespaced(property); } + @Nullable + public ModelConfiguration getFallback() { + return this.fallback; + } + + @NotNull + public String getProperty() { + return this.property; + } + + @NotNull + public List getCases() { + return this.cases; + } + public void setFallback(@Nullable ModelConfiguration fallback) { this.fallback = fallback; } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/TrimMaterialSelectConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/TrimMaterialSelectConfiguration.java new file mode 100644 index 00000000..df7a618a --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/select/TrimMaterialSelectConfiguration.java @@ -0,0 +1,15 @@ +package fr.robie.craftengineconverter.api.configuration.item.models.select; + +/** + * Selects a model by the armour trim material applied to the item. + *

+ * Case values are resource locations (for example {@code minecraft:gold}) rather than a closed enum, + * so they stay {@link String}s. Geyser can represent this directly as a {@code match} predicate on + * {@code trim_material}. + */ +public class TrimMaterialSelectConfiguration extends SelectModelConfiguration { + + public TrimMaterialSelectConfiguration() { + super("minecraft:trim_material"); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/special/SpecialModelConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/special/SpecialModelConfiguration.java index 3886361a..71308d4b 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/special/SpecialModelConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/special/SpecialModelConfiguration.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.item.models.special; import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class SpecialModelConfiguration implements ModelConfiguration { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/ConstantTintConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/ConstantTintConfiguration.java index 19597828..a9bb873d 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/ConstantTintConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/ConstantTintConfiguration.java @@ -4,14 +4,24 @@ import java.util.LinkedHashMap; import java.util.Map; +import java.util.OptionalInt; -public class ConstantTintConfiguration implements TintConfiguration { - private final Object value; - +public record ConstantTintConfiguration(Object value) implements TintConfiguration { public ConstantTintConfiguration(@NotNull Object value) { this.value = value; } + @Override + @NotNull + public Object value() { + return this.value; + } + + @Override + public OptionalInt constantColor() { + return TintColors.toRgb(this.value); + } + @Override public Map serialize() { Map map = new LinkedHashMap<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/CustomModelDataTintConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/CustomModelDataTintConfiguration.java index 2868ce1e..ce6a56f4 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/CustomModelDataTintConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/CustomModelDataTintConfiguration.java @@ -4,6 +4,7 @@ import java.util.LinkedHashMap; import java.util.Map; +import java.util.OptionalInt; public class CustomModelDataTintConfiguration implements TintConfiguration { private final int index; @@ -14,6 +15,16 @@ public CustomModelDataTintConfiguration(int index, @Nullable Object defaultValue this.defaultValue = defaultValue; } + @Nullable + public Object getDefaultValue() { + return this.defaultValue; + } + + @Override + public OptionalInt constantColor() { + return TintColors.toRgb(this.defaultValue); + } + @Override public Map serialize() { Map map = new LinkedHashMap<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/DyeTintConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/DyeTintConfiguration.java index 42177ed9..91e307ca 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/DyeTintConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/DyeTintConfiguration.java @@ -4,14 +4,24 @@ import java.util.LinkedHashMap; import java.util.Map; +import java.util.OptionalInt; -public class DyeTintConfiguration implements TintConfiguration { - private final Object defaultValue; - +public record DyeTintConfiguration(Object defaultValue) implements TintConfiguration { public DyeTintConfiguration(@Nullable Object defaultValue) { this.defaultValue = defaultValue; } + @Override + @Nullable + public Object defaultValue() { + return this.defaultValue; + } + + @Override + public OptionalInt constantColor() { + return TintColors.toRgb(this.defaultValue); + } + @Override public Map serialize() { Map map = new LinkedHashMap<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/TintColors.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/TintColors.java new file mode 100644 index 00000000..cc60f96b --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/TintColors.java @@ -0,0 +1,58 @@ +package fr.robie.craftengineconverter.api.configuration.item.models.tints; + +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.OptionalInt; + +public final class TintColors { + + private TintColors() { + throw new UnsupportedOperationException("TintColors is a utility class and cannot be instantiated."); + } + + public static OptionalInt toRgb(@Nullable Object value) { + if (value == null) return OptionalInt.empty(); + + if (value instanceof Number number) { + return OptionalInt.of(number.intValue() & 0xFFFFFF); + } + + if (value instanceof Collection collection) { + return fromComponents(collection.stream().map(String::valueOf).toArray(String[]::new)); + } + + if (value instanceof String text) { + String trimmed = text.trim(); + if (trimmed.isEmpty()) return OptionalInt.empty(); + if (trimmed.contains(",")) return fromComponents(trimmed.split(",")); + + try { + if (trimmed.startsWith("#")) { + return OptionalInt.of(Integer.parseInt(trimmed.substring(1), 16) & 0xFFFFFF); + } + return OptionalInt.of(Integer.parseInt(trimmed) & 0xFFFFFF); + } catch (NumberFormatException e) { + return OptionalInt.empty(); + } + } + + return OptionalInt.empty(); + } + + private static OptionalInt fromComponents(String[] parts) { + if (parts.length < 3) return OptionalInt.empty(); + try { + int r = clamp(Integer.parseInt(parts[0].trim())); + int g = clamp(Integer.parseInt(parts[1].trim())); + int b = clamp(Integer.parseInt(parts[2].trim())); + return OptionalInt.of((r << 16) | (g << 8) | b); + } catch (NumberFormatException e) { + return OptionalInt.empty(); + } + } + + private static int clamp(int component) { + return Math.clamp(component, 0, 255); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/TintConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/TintConfiguration.java index b537be97..f97cd568 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/TintConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/models/tints/TintConfiguration.java @@ -1,7 +1,21 @@ package fr.robie.craftengineconverter.api.configuration.item.models.tints; import java.util.Map; +import java.util.OptionalInt; public interface TintConfiguration { Map serialize(); + + /** + * The one RGB colour this tint always resolves to, when it has one. + *

+ * Needed by the pre-rendered inventory icon: the client cannot render a model into a slot, so the sprite is + * drawn at conversion time and the tint has to be multiplied in there — but a sprite is one fixed image, + * so only a tint that does not depend on runtime state can be honoured. A dye or constant tint qualifies; + * {@code grass}, {@code team}, {@code potion} and {@code firework} do not, and return empty so the caller + * can leave the face untinted rather than invent a colour. + */ + default OptionalInt constantColor() { + return OptionalInt.empty(); + } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/AnvilRepairItemConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/AnvilRepairItemConfiguration.java index 21de4ef5..1db14a34 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/AnvilRepairItemConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/AnvilRepairItemConfiguration.java @@ -1,9 +1,10 @@ package fr.robie.craftengineconverter.api.configuration.item.settings; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; +import net.momirealms.craftengine.core.item.ItemSelector; import net.momirealms.craftengine.core.item.setting.value.AnvilRepairItem; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -24,19 +25,33 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str List> repairItemsList = new ArrayList<>(); for (AnvilRepairItem repairItem : this.repairItems) { Map repairItemMap = new HashMap<>(); - if (repairItem.targets().size() == 1) { - repairItemMap.put("target", repairItem.targets().getFirst()); + List targets = new ArrayList<>(); + for (ItemSelector selector : repairItem.targets()) { + targets.add(selectorId(selector)); + } + if (targets.size() == 1) { + repairItemMap.put("target", targets.getFirst()); } else { - repairItemMap.put("target", repairItem.targets()); + repairItemMap.put("target", targets); } - if (repairItem.amount() > 0) { - repairItemMap.put("amount", repairItem.amount()); + if (repairItem.amount().getDouble() > 0) { + repairItemMap.put("amount", repairItem.amount().getInt()); } - if (repairItem.percent() > 0) { - repairItemMap.put("percent", repairItem.percent()); + if (repairItem.percent().getDouble() > 0) { + repairItemMap.put("percent", repairItem.percent().getDouble()); } repairItemsList.add(repairItemMap); } settings.set("anvil-repair-item", repairItemsList); } + + private static String selectorId(ItemSelector selector) { + if (selector instanceof ItemSelector.Tag tag) { + return "#" + tag.tag(); + } + if (selector instanceof ItemSelector.Item item) { + return item.id().toString(); + } + return selector.toString(); + } } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/DropDisplayConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/DropDisplayConfiguration.java index c151b731..0d6ee5db 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/DropDisplayConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/DropDisplayConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.settings; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class DropDisplayConfiguration implements ItemConfigurationSerializable { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/EquippableConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/EquippableConfiguration.java index bca4b9bf..cc48c5cd 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/EquippableConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/EquippableConfiguration.java @@ -1,26 +1,26 @@ package fr.robie.craftengineconverter.api.configuration.item.settings; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.entity.EquipmentSlot; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.Locale; public class EquippableConfiguration implements ItemConfigurationSerializable { - private final EquipmentSlot equipmentSlot; - private final String equipSound; - private final String assetId; - private final Object allowedEntities; - private final boolean dispensable; - private final boolean swappable; - private final boolean damageOnHurt; - private final boolean equipOnInteract; - private final String cameraOverlay; - private final boolean canBeSheared; - private final String shearingSound; - private final String wings; + protected final EquipmentSlot equipmentSlot; + protected final String equipSound; + protected final String assetId; + protected final Object allowedEntities; + protected final boolean dispensable; + protected final boolean swappable; + protected final boolean damageOnHurt; + protected final boolean equipOnInteract; + protected final String cameraOverlay; + protected final boolean canBeSheared; + protected final String shearingSound; + protected final String wings; public EquippableConfiguration(EquipmentSlot equipmentSlot, String equipSound, String assetId, Object allowedEntities, boolean dispensable, boolean swappable, boolean damageOnHurt, boolean equipOnInteract, String cameraOverlay, boolean canBeSheared, String shearingSound, String wings) { this.equipmentSlot = equipmentSlot; @@ -71,7 +71,7 @@ public EquippableConfiguration(String assetId, String wings) { public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull String path, @NotNull ConfigurationSection itemSection, @NotNull String itemId) { ConfigurationSection ceEquippableSection = this.assetId != null && !this.assetId.isBlank() ? this.getOrCreateSection(this.getOrCreateSection(itemSection, "settings"), "equippable") - : this.getOrCreateSection(this.getOrCreateSection(itemSection, "data"), "equippable"); + : this.getOrCreateSection(this.getDataSection(itemSection), "equippable"); if (this.equipmentSlot != null) { ceEquippableSection.set("slot", this.equipmentSlot.name().toLowerCase(Locale.ROOT)); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/FuelTimeSettingConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/FuelTimeSettingConfiguration.java index 8aa7a993..13a6b23c 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/FuelTimeSettingConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/FuelTimeSettingConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.settings; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class FuelTimeSettingConfiguration implements ItemConfigurationSerializable { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/GlowDropColorConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/GlowDropColorConfiguration.java index ad67627b..0f0af1e7 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/GlowDropColorConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/GlowDropColorConfiguration.java @@ -1,9 +1,9 @@ package fr.robie.craftengineconverter.api.configuration.item.settings; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.bukkit.DyeColor; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.Locale; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/InvulnerableSettingConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/InvulnerableSettingConfiguration.java index 08751df7..4e3912fc 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/InvulnerableSettingConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/InvulnerableSettingConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.settings; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/ProjectileSettingConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/ProjectileSettingConfiguration.java index 0678a9e1..7b4ce6cd 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/ProjectileSettingConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/ProjectileSettingConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.settings; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/RepairableSettingConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/RepairableSettingConfiguration.java index 0df581c5..07392046 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/RepairableSettingConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/item/settings/RepairableSettingConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.item.settings; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; public class RepairableSettingConfiguration implements ItemConfigurationSerializable { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/ConfigurationTrees.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/ConfigurationTrees.java new file mode 100644 index 00000000..06fdcfff --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/ConfigurationTrees.java @@ -0,0 +1,67 @@ +package fr.robie.craftengineconverter.api.configuration.loader; + +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.MemoryConfiguration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Converts between {@link ConfigurationSection} and plain {@code Map}/{@code List} trees. + *

+ * The converter passes {@code ConfigurationSection} around, but the template engine and the JSON adapter + * both need to walk and rebuild raw trees. Keeping both directions here means the + * {@code MemoryConfiguration.createSection(path, map)} detail — which recursively turns nested maps into + * child sections — lives in one place. + */ +public final class ConfigurationTrees { + + private ConfigurationTrees() { + throw new UnsupportedOperationException("ConfigurationTrees is a utility class and cannot be instantiated."); + } + + /** + * Wraps a map tree as a detached {@link ConfigurationSection}. + *

+ * The section is parented to a throwaway {@link MemoryConfiguration}; only the returned section is of + * interest, so the path it is created under is arbitrary. + */ + @NotNull + public static ConfigurationSection toSection(@NotNull Map map) { + return new MemoryConfiguration().createSection("root", map); + } + + /** Copies a section into a plain, insertion-ordered map tree. */ + @NotNull + public static Map toMap(@NotNull ConfigurationSection section) { + Map out = new LinkedHashMap<>(); + for (String key : section.getKeys(false)) { + out.put(key, toValue(section.get(key))); + } + return out; + } + + @Nullable + private static Object toValue(@Nullable Object value) { + if (value instanceof ConfigurationSection nested) { + return toMap(nested); + } + if (value instanceof Map map) { + Map out = new LinkedHashMap<>(); + for (Map.Entry entry : map.entrySet()) { + out.put(String.valueOf(entry.getKey()), toValue(entry.getValue())); + } + return out; + } + if (value instanceof List list) { + List out = new ArrayList<>(list.size()); + for (Object element : list) out.add(toValue(element)); + return out; + } + return value; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/JsonConfigurationAdapter.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/JsonConfigurationAdapter.java new file mode 100644 index 00000000..c606e6ea --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/JsonConfigurationAdapter.java @@ -0,0 +1,97 @@ +package fr.robie.craftengineconverter.api.configuration.loader; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Views a {@link JsonObject} as a {@link ConfigurationSection}. + *

+ * Java item model definitions ({@code assets//items/*.json}) describe exactly the same + * structure that CraftEngine expresses in YAML under an item's {@code model:} key, and the + * {@code ModelConfiguration} loaders already read both spellings of every key + * ({@code on-true} / {@code on_true}) and both the bare and {@code minecraft:}-prefixed type names. + * They are therefore already capable of parsing Java's JSON — they just cannot accept it, because they + * take a {@code ConfigurationSection}. + *

+ * Adapting the input here means the whole loader tree works on Java resource packs unchanged, rather + * than every loader needing a parallel JSON overload. + */ +public final class JsonConfigurationAdapter { + + private JsonConfigurationAdapter() { + throw new UnsupportedOperationException("JsonConfigurationAdapter is a utility class and cannot be instantiated."); + } + + /** + * Wraps {@code json} in a detached {@link ConfigurationSection}. + *

+ * See {@link ConfigurationTrees#toSection(Map)} for how the map becomes a section tree. + */ + @NotNull + public static ConfigurationSection toSection(@NotNull JsonObject json) { + return ConfigurationTrees.toSection(toMap(json)); + } + + /** The JSON tree as a plain map, for callers that want to work on it directly. */ + @NotNull + public static Map toMap(@NotNull JsonObject json) { + Map map = new LinkedHashMap<>(); + for (Map.Entry entry : json.entrySet()) { + map.put(entry.getKey(), toValue(entry.getValue())); + } + return map; + } + + @Nullable + private static Object toValue(@NotNull JsonElement element) { + if (element.isJsonObject()) { + // Nested maps are turned into child sections by createSection, so plain maps suffice here. + return toMap(element.getAsJsonObject()); + } + if (element.isJsonArray()) { + JsonArray array = element.getAsJsonArray(); + List list = new ArrayList<>(array.size()); + for (JsonElement child : array) { + list.add(toValue(child)); + } + return list; + } + if (element.isJsonPrimitive()) { + return toPrimitive(element.getAsJsonPrimitive()); + } + return null; + } + + @NotNull + private static Object toPrimitive(@NotNull JsonPrimitive primitive) { + if (primitive.isBoolean()) return primitive.getAsBoolean(); + if (primitive.isString()) return primitive.getAsString(); + + String raw = primitive.getAsString(); + if (raw.indexOf('.') < 0 && raw.indexOf('e') < 0 && raw.indexOf('E') < 0) { + try { + return Integer.valueOf(raw); + } catch (NumberFormatException ignored) { + try { + return Long.valueOf(raw); + } catch (NumberFormatException ignored2) { + } + } + } + try { + return Double.valueOf(raw); + } catch (NumberFormatException ignored) { + return raw; + } + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/AbstractConditionLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/AbstractConditionLoader.java new file mode 100644 index 00000000..32baa311 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/AbstractConditionLoader.java @@ -0,0 +1,18 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models; + +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.condition.ConditionModelConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; + +public abstract class AbstractConditionLoader implements ModelConfigurationLoader { + + protected void loadBranches(ConditionModelConfiguration config, ConfigurationSection section) { + ConfigurationSection trueSection = section.getConfigurationSection("on-true"); + if (trueSection == null) trueSection = section.getConfigurationSection("on_true"); + config.setOnTrue(ModelConfigurationRegistry.load(trueSection)); + + ConfigurationSection falseSection = section.getConfigurationSection("on-false"); + if (falseSection == null) falseSection = section.getConfigurationSection("on_false"); + config.setOnFalse(ModelConfigurationRegistry.load(falseSection)); + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/ModelConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/ModelConfigurationLoader.java new file mode 100644 index 00000000..b39a9ac1 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/ModelConfigurationLoader.java @@ -0,0 +1,11 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models; + +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@FunctionalInterface +public interface ModelConfigurationLoader { + @Nullable T load(@NotNull ConfigurationSection section); +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/ModelConfigurationRegistry.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/ModelConfigurationRegistry.java new file mode 100644 index 00000000..9d5d2fd2 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/ModelConfigurationRegistry.java @@ -0,0 +1,44 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models; + +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.messageflow.logger.Logger; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; + +public class ModelConfigurationRegistry { + private static final Map> LOADERS = new HashMap<>(); + + private static String stripNamespace(String type) { + int colon = type.indexOf(':'); + return colon < 0 ? type : type.substring(colon + 1); + } + + private ModelConfigurationRegistry() { + throw new UnsupportedOperationException("ModelConfigurationRegistry is a utility class and cannot be instantiated."); + } + + public static void register(@NotNull String type, @NotNull ModelConfigurationLoader loader) { + LOADERS.put(type, loader); + } + + @Nullable + public static ModelConfiguration load(@Nullable ConfigurationSection section) { + if (section == null) { + return null; + } + String type = section.getString("type", "model"); + ModelConfigurationLoader loader = LOADERS.get(type); + if (loader == null) { + loader = LOADERS.get(stripNamespace(type)); + } + if (loader == null) { + Logger.warn("Unknown model type '" + type + "', skipping."); + return null; + } + return loader.load(section); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/composite/CompositeModelConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/composite/CompositeModelConfigurationLoader.java new file mode 100644 index 00000000..268069eb --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/composite/CompositeModelConfigurationLoader.java @@ -0,0 +1,30 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.composite; + +import fr.robie.craftengineconverter.api.annotations.AutoModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.composite.CompositeModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationRegistry; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +@AutoModelConfigurationLoader({"composite", "minecraft:composite"}) +public class CompositeModelConfigurationLoader implements ModelConfigurationLoader { + @Override + public @Nullable ModelConfiguration load(@NotNull ConfigurationSection section) { + CompositeModelConfiguration config = new CompositeModelConfiguration(); + + List models = section.getSectionList("models"); + for (ConfigurationSection modelSection : models) { + ModelConfiguration child = ModelConfigurationRegistry.load(modelSection); + if (child != null) { + config.addModel(child); + } + } + + return config; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/ComponentConditionLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/ComponentConditionLoader.java new file mode 100644 index 00000000..154ccf91 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/ComponentConditionLoader.java @@ -0,0 +1,30 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.condition; + +import fr.robie.craftengineconverter.api.annotations.AutoModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.condition.ComponentConditionConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.AbstractConditionLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@AutoModelConfigurationLoader({"component", "minecraft:component"}) +public class ComponentConditionLoader extends AbstractConditionLoader { + + @Override + public @Nullable ModelConfiguration load(@NotNull ConfigurationSection section) { + String predicate = section.getString("predicate"); + if (predicate == null) { + return null; + } + + Object value = section.get("value"); + if (value == null) { + return null; + } + + ComponentConditionConfiguration config = new ComponentConditionConfiguration(predicate, value); + this.loadBranches(config, section); + return config; + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/ConditionModelConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/ConditionModelConfigurationLoader.java new file mode 100644 index 00000000..7bd3ae20 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/ConditionModelConfigurationLoader.java @@ -0,0 +1,25 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.condition; + +import fr.robie.craftengineconverter.api.annotations.AutoModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.condition.ConditionModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.AbstractConditionLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@AutoModelConfigurationLoader({"condition", "minecraft:condition"}) +public class ConditionModelConfigurationLoader extends AbstractConditionLoader { + + @Override + public @Nullable ModelConfiguration load(@NotNull ConfigurationSection section) { + String property = section.getString("property"); + if (property == null) { + return null; + } + + ConditionModelConfiguration config = new ConditionModelConfiguration(property); + this.loadBranches(config, section); + return config; + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/CustomModelDataConditionLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/CustomModelDataConditionLoader.java new file mode 100644 index 00000000..58c7dc9e --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/CustomModelDataConditionLoader.java @@ -0,0 +1,22 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.condition; + +import fr.robie.craftengineconverter.api.annotations.AutoModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.condition.CustomModelDataConditionConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.AbstractConditionLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@AutoModelConfigurationLoader({"custom_model_data", "minecraft:custom_model_data"}) +public class CustomModelDataConditionLoader extends AbstractConditionLoader { + + @Override + public @Nullable ModelConfiguration load(@NotNull ConfigurationSection section) { + int index = section.getInt("index", 0); + + CustomModelDataConditionConfiguration config = new CustomModelDataConditionConfiguration(index); + this.loadBranches(config, section); + return config; + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/HasComponentConditionLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/HasComponentConditionLoader.java new file mode 100644 index 00000000..b29857da --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/HasComponentConditionLoader.java @@ -0,0 +1,27 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.condition; + +import fr.robie.craftengineconverter.api.annotations.AutoModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.condition.HasComponentConditionConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.AbstractConditionLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@AutoModelConfigurationLoader({"has_component", "minecraft:has_component"}) +public class HasComponentConditionLoader extends AbstractConditionLoader { + + @Override + public @Nullable ModelConfiguration load(@NotNull ConfigurationSection section) { + String component = section.getString("component"); + if (component == null) { + return null; + } + + boolean ignoreDefault = section.getBoolean("ignore-default", false); + + HasComponentConditionConfiguration config = new HasComponentConditionConfiguration(component, ignoreDefault); + this.loadBranches(config, section); + return config; + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/KeybindDownConditionLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/KeybindDownConditionLoader.java new file mode 100644 index 00000000..6fd679a6 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/condition/KeybindDownConditionLoader.java @@ -0,0 +1,25 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.condition; + +import fr.robie.craftengineconverter.api.annotations.AutoModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.condition.KeybindDownConditionConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.AbstractConditionLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@AutoModelConfigurationLoader({"keybind_down", "minecraft:keybind_down"}) +public class KeybindDownConditionLoader extends AbstractConditionLoader { + + @Override + public @Nullable ModelConfiguration load(@NotNull ConfigurationSection section) { + String keybind = section.getString("keybind"); + if (keybind == null) { + return null; + } + + KeybindDownConditionConfiguration config = new KeybindDownConditionConfiguration(keybind); + this.loadBranches(config, section); + return config; + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/model/SimpleModelConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/model/SimpleModelConfigurationLoader.java new file mode 100644 index 00000000..abb44e63 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/model/SimpleModelConfigurationLoader.java @@ -0,0 +1,52 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.model; + +import fr.robie.craftengineconverter.api.annotations.AutoModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.model.GenerationConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.model.SimpleModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.tints.TintConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.loader.models.tints.TintConfigurationRegistry; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + + +@AutoModelConfigurationLoader({"model", "minecraft:model"}) +public class SimpleModelConfigurationLoader implements ModelConfigurationLoader { + + @Override + public @Nullable ModelConfiguration load(@NotNull ConfigurationSection section) { + String path = section.getString("path"); + if (path == null) path = section.getString("model"); + if (path == null) { + return null; + } + + SimpleModelConfiguration config = new SimpleModelConfiguration(path); + + ConfigurationSection generationSection = section.getConfigurationSection("generation"); + if (generationSection != null) { + String parent = generationSection.getString("parent"); + GenerationConfiguration generation = new GenerationConfiguration(parent); + + ConfigurationSection texturesSection = generationSection.getConfigurationSection("textures"); + if (texturesSection != null) { + for (String key : texturesSection.getKeys(false)) { + String value = texturesSection.getString(key); + if (value != null) { + generation.addTexture(key, value); + } + } + } + config.setGeneration(generation); + } + + List tints = TintConfigurationRegistry.loadList(section, "tints"); + tints.forEach(config::addTint); + + return config; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/AbstractRangeDispatchConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/AbstractRangeDispatchConfigurationLoader.java new file mode 100644 index 00000000..71af395b --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/AbstractRangeDispatchConfigurationLoader.java @@ -0,0 +1,30 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.range_dispatch; + +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.RangeDispatchModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationRegistry; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public abstract class AbstractRangeDispatchConfigurationLoader implements ModelConfigurationLoader { + + protected void loadCommonProperties(@NotNull T configuration, @NotNull ConfigurationSection section) { + Float scale = (float) section.getDouble("scale", 1.0); + configuration.setScale(scale); + + configuration.setFallback(ModelConfigurationRegistry.load(section.getConfigurationSection("fallback"))); + + List entries = section.getSectionList("entries"); + for (ConfigurationSection entry : entries) { + float threshold = (float) entry.getDouble("threshold"); + ModelConfiguration model = ModelConfigurationRegistry.load(entry.getConfigurationSection("model")); + if (model != null) { + configuration.addEntry(threshold, model); + } + } + } + +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CompassRangeDispatchConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CompassRangeDispatchConfigurationLoader.java new file mode 100644 index 00000000..29766a75 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CompassRangeDispatchConfigurationLoader.java @@ -0,0 +1,25 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.range_dispatch; + +import fr.robie.craftengineconverter.api.annotations.AutoRangeDispatchConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.CompassRangeDispatchConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.Nullable; + +@AutoRangeDispatchConfigurationLoader({"compass", "minecraft:compass"}) +public class CompassRangeDispatchConfigurationLoader extends AbstractRangeDispatchConfigurationLoader { + + @Override + public @Nullable CompassRangeDispatchConfiguration load(@NotNull ConfigurationSection section) { + String target = section.getString("target"); + if (target == null) { + return null; + } + boolean wobble = section.getBoolean("wobble", true); + CompassRangeDispatchConfiguration compassRangeDispatchConfiguration = new CompassRangeDispatchConfiguration(target, wobble); + + this.loadCommonProperties(compassRangeDispatchConfiguration, section); + + return compassRangeDispatchConfiguration; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CountRangeDispatchConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CountRangeDispatchConfigurationLoader.java new file mode 100644 index 00000000..ce523514 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CountRangeDispatchConfigurationLoader.java @@ -0,0 +1,20 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.range_dispatch; + +import fr.robie.craftengineconverter.api.annotations.AutoRangeDispatchConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.CountRangeDispatchConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.Nullable; + +@AutoRangeDispatchConfigurationLoader({"count", "minecraft:count"}) +public class CountRangeDispatchConfigurationLoader extends AbstractRangeDispatchConfigurationLoader { + @Override + public @Nullable CountRangeDispatchConfiguration load(@NotNull ConfigurationSection section) { + boolean normalize = section.getBoolean("normalize", true); + CountRangeDispatchConfiguration countRangeDispatchConfiguration = new CountRangeDispatchConfiguration(normalize); + + this.loadCommonProperties(countRangeDispatchConfiguration, section); + + return countRangeDispatchConfiguration; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CrossbowPullRangeDispatchConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CrossbowPullRangeDispatchConfigurationLoader.java new file mode 100644 index 00000000..29b25129 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CrossbowPullRangeDispatchConfigurationLoader.java @@ -0,0 +1,24 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.range_dispatch; + +import fr.robie.craftengineconverter.api.annotations.AutoRangeDispatchConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.CrossbowPullRangeDispatchConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.Nullable; + +/** + * Without this, {@link RangeDispatchConfigurationRegistry#load} finds no loader for {@code crossbow/pull} and + * returns {@code null} — which the callers treat as "no model here", so a crossbow's entire pull sub-tree was + * discarded during parsing, before anything downstream could have a view on it. + */ +@AutoRangeDispatchConfigurationLoader({"crossbow/pull", "minecraft:crossbow/pull"}) +public class CrossbowPullRangeDispatchConfigurationLoader + extends AbstractRangeDispatchConfigurationLoader { + + @Override + public @Nullable CrossbowPullRangeDispatchConfiguration load(@NotNull ConfigurationSection section) { + CrossbowPullRangeDispatchConfiguration configuration = new CrossbowPullRangeDispatchConfiguration(); + this.loadCommonProperties(configuration, section); + return configuration; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CustomModelDataRangeDispatchConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CustomModelDataRangeDispatchConfigurationLoader.java new file mode 100644 index 00000000..0c9bde78 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/CustomModelDataRangeDispatchConfigurationLoader.java @@ -0,0 +1,21 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.range_dispatch; + +import fr.robie.craftengineconverter.api.annotations.AutoRangeDispatchConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.CustomModelDataRangeDispatchConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.Nullable; + +@AutoRangeDispatchConfigurationLoader({"custom_model_data", "minecraft:custom_model_data"}) +public class CustomModelDataRangeDispatchConfigurationLoader extends AbstractRangeDispatchConfigurationLoader { + @Override + public @Nullable CustomModelDataRangeDispatchConfiguration load(@NotNull ConfigurationSection section) { + int index = section.getInt("index", 0); + + CustomModelDataRangeDispatchConfiguration customModelDataRangeDispatchConfiguration = new CustomModelDataRangeDispatchConfiguration(index); + + this.loadCommonProperties(customModelDataRangeDispatchConfiguration, section); + + return customModelDataRangeDispatchConfiguration; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/DamageRangeDispatchConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/DamageRangeDispatchConfigurationLoader.java new file mode 100644 index 00000000..5a192823 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/DamageRangeDispatchConfigurationLoader.java @@ -0,0 +1,20 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.range_dispatch; + +import fr.robie.craftengineconverter.api.annotations.AutoRangeDispatchConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.DamageRangeDispatchConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.Nullable; + +@AutoRangeDispatchConfigurationLoader({"damage", "minecraft:damage"}) +public class DamageRangeDispatchConfigurationLoader extends AbstractRangeDispatchConfigurationLoader { + @Override + public @Nullable DamageRangeDispatchConfiguration load(@NotNull ConfigurationSection section) { + boolean normalize = section.getBoolean("normalize", true); + DamageRangeDispatchConfiguration damageRangeDispatchConfiguration = new DamageRangeDispatchConfiguration(normalize); + + this.loadCommonProperties(damageRangeDispatchConfiguration, section); + + return damageRangeDispatchConfiguration; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/RangeDispatchConfigurationRegistry.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/RangeDispatchConfigurationRegistry.java new file mode 100644 index 00000000..321bd054 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/RangeDispatchConfigurationRegistry.java @@ -0,0 +1,35 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.range_dispatch; + +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.RangeDispatchModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; + +public class RangeDispatchConfigurationRegistry { + private static final Map> LOADERS = new HashMap<>(); + + public static void register(@NotNull String property, @NotNull ModelConfigurationLoader loader) { + LOADERS.put(property, loader); + } + + @Nullable + public static RangeDispatchModelConfiguration load(@Nullable ConfigurationSection section) { + if (section == null) { + return null; + } + String property = section.getString("property"); + if (property == null) { + return null; + } + + ModelConfigurationLoader loader = LOADERS.get(property); + if (loader == null) { + return null; + } + return loader.load(section); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/TimeRangeDispatchConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/TimeRangeDispatchConfigurationLoader.java new file mode 100644 index 00000000..a40b039b --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/TimeRangeDispatchConfigurationLoader.java @@ -0,0 +1,24 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.range_dispatch; + +import fr.robie.craftengineconverter.api.annotations.AutoRangeDispatchConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.TimeRangeDispatchConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.Nullable; + +@AutoRangeDispatchConfigurationLoader({"time", "minecraft:time"}) +public class TimeRangeDispatchConfigurationLoader extends AbstractRangeDispatchConfigurationLoader { + @Override + public @Nullable TimeRangeDispatchConfiguration load(@NotNull ConfigurationSection section) { + String source = section.getString("source"); + if (source == null) { + return null; + } + boolean wobble = section.getBoolean("wobble", true); + TimeRangeDispatchConfiguration timeRangeDispatchConfiguration = new TimeRangeDispatchConfiguration(source, wobble); + + this.loadCommonProperties(timeRangeDispatchConfiguration, section); + + return timeRangeDispatchConfiguration; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/UseCycleRangeDispatchConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/UseCycleRangeDispatchConfigurationLoader.java new file mode 100644 index 00000000..32d79fe3 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/UseCycleRangeDispatchConfigurationLoader.java @@ -0,0 +1,21 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.range_dispatch; + +import fr.robie.craftengineconverter.api.annotations.AutoRangeDispatchConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.UseCycleRangeDispatchConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.Nullable; + +@AutoRangeDispatchConfigurationLoader({"use_cycle", "minecraft:use_cycle"}) +public class UseCycleRangeDispatchConfigurationLoader extends AbstractRangeDispatchConfigurationLoader { + @Override + public @Nullable UseCycleRangeDispatchConfiguration load(@NotNull ConfigurationSection section) { + float period = (float) section.getDouble("period", 1.0); + if (period < 0) { + return null; + } + UseCycleRangeDispatchConfiguration configuration = new UseCycleRangeDispatchConfiguration(period); + this.loadCommonProperties(configuration, section); + return configuration; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/UseDurationRangeDispatchConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/UseDurationRangeDispatchConfigurationLoader.java new file mode 100644 index 00000000..679b3f48 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/range_dispatch/UseDurationRangeDispatchConfigurationLoader.java @@ -0,0 +1,18 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.range_dispatch; + +import fr.robie.craftengineconverter.api.annotations.AutoRangeDispatchConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.UseDurationRangeDispatchConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.Nullable; + +@AutoRangeDispatchConfigurationLoader({"use_duration", "minecraft:use_duration"}) +public class UseDurationRangeDispatchConfigurationLoader extends AbstractRangeDispatchConfigurationLoader { + @Override + public @Nullable UseDurationRangeDispatchConfiguration load(@NotNull ConfigurationSection section) { + boolean remaining = section.getBoolean("remaining", false); + UseDurationRangeDispatchConfiguration configuration = new UseDurationRangeDispatchConfiguration(remaining); + this.loadCommonProperties(configuration, section); + return configuration; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/AbstractSelectModelConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/AbstractSelectModelConfigurationLoader.java new file mode 100644 index 00000000..09b72795 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/AbstractSelectModelConfigurationLoader.java @@ -0,0 +1,69 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.select; + +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.select.SelectModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationRegistry; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.BiConsumer; +import java.util.function.Function; + +public abstract class AbstractSelectModelConfigurationLoader implements ModelConfigurationLoader> { + + public AbstractSelectModelConfigurationLoader() { + } + + @Nullable + protected ModelConfiguration loadFallback(@NotNull ConfigurationSection section) { + ConfigurationSection fallbackSection = section.getConfigurationSection("fallback"); + return fallbackSection != null ? this.loadModel(fallbackSection) : null; + } + + /** + * Reads the {@code cases} list, registering one case per value. + *

+ * Java lets a single case name several values at once — {@code "when": ["gui","ground","fixed","on_shelf"]} + * is how every vanilla trident, spear and shield is written. Passing that list to {@code valueParser} + * stringifies it to {@code [gui, ground, fixed]}, which no enum accepts, and the + * {@link IllegalArgumentException} below then discarded the case and its model in silence. Splitting + * the list first is what lets those items convert at all; a case that names four contexts simply becomes + * four cases sharing a model, which is what it means. + *

+ * The catch stays, but per value: one unrecognised member of a list no longer costs the whole case. + */ + protected void loadCases( + @NotNull ConfigurationSection section, + BiConsumer caseConsumer, + Function valueParser) { + for (ConfigurationSection caseSection : section.getSectionList("cases")) { + Object when = caseSection.get("when"); + if (when == null) { + continue; + } + + // Loaded lazily: an unparseable "when" must not cost the work of resolving a model tree. + ModelConfiguration model = null; + for (Object value : when instanceof Iterable values ? values : java.util.List.of(when)) { + if (value == null) continue; + T parsedValue; + try { + parsedValue = valueParser.apply(value); + } catch (IllegalArgumentException ignored) { + continue; + } + if (model == null) { + model = this.loadModel(caseSection.getConfigurationSection("model")); + if (model == null) break; + } + caseConsumer.accept(parsedValue, model); + } + } + } + + protected ModelConfiguration loadModel(ConfigurationSection modelSection) { + return ModelConfigurationRegistry.load(modelSection); + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/BlockStateSelectConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/BlockStateSelectConfigurationLoader.java new file mode 100644 index 00000000..b53b70e5 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/BlockStateSelectConfigurationLoader.java @@ -0,0 +1,28 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.select; + +import fr.robie.craftengineconverter.api.annotations.AutoSelectModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.select.BlockStateSelectConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; + +@AutoSelectModelConfigurationLoader({"block_state", "minecraft:block_state"}) +public class BlockStateSelectConfigurationLoader extends AbstractSelectModelConfigurationLoader { + + public BlockStateSelectConfigurationLoader() { + super(); + } + + @Override + public BlockStateSelectConfiguration load(@NotNull ConfigurationSection section) { + String blockStateProperty = section.getString("block_state_property"); + if (blockStateProperty == null || blockStateProperty.isEmpty()) { + throw new IllegalArgumentException("Missing required field 'block_state_property'"); + } + + BlockStateSelectConfiguration config = new BlockStateSelectConfiguration(blockStateProperty); + config.setFallback(this.loadFallback(section)); + this.loadCases(section, config::addCase, when -> when); + return config; + } + +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/ChargeTypeSelectConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/ChargeTypeSelectConfigurationLoader.java new file mode 100644 index 00000000..9063baa5 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/ChargeTypeSelectConfigurationLoader.java @@ -0,0 +1,24 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.select; + +import fr.robie.craftengineconverter.api.annotations.AutoSelectModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.ChargeType; +import fr.robie.craftengineconverter.api.configuration.item.models.select.ChargeTypeSelectConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.select.SelectModelConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; + +@AutoSelectModelConfigurationLoader({"charge_type", "minecraft:charge_type"}) +public class ChargeTypeSelectConfigurationLoader extends AbstractSelectModelConfigurationLoader { + + public ChargeTypeSelectConfigurationLoader() { + super(); + } + + @Override + public SelectModelConfiguration load(@NotNull ConfigurationSection section) { + ChargeTypeSelectConfiguration chargeTypeSelectConfiguration = new ChargeTypeSelectConfiguration(); + chargeTypeSelectConfiguration.setFallback(this.loadFallback(section)); + this.loadCases(section, chargeTypeSelectConfiguration::addCase, when -> ChargeType.valueOf(when.toString().toUpperCase())); + return chargeTypeSelectConfiguration; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/ComponentSelectConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/ComponentSelectConfigurationLoader.java new file mode 100644 index 00000000..58fe2c3f --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/ComponentSelectConfigurationLoader.java @@ -0,0 +1,28 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.select; + +import fr.robie.craftengineconverter.api.annotations.AutoSelectModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.select.ComponentSelectConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.select.SelectModelConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; + +@AutoSelectModelConfigurationLoader({"component", "minecraft:component"}) +public class ComponentSelectConfigurationLoader extends AbstractSelectModelConfigurationLoader { + + public ComponentSelectConfigurationLoader() { + super(); + } + + @Override + public SelectModelConfiguration load(@NotNull ConfigurationSection section) { + String component = section.getString("component"); + if (component == null || component.isEmpty()) { + throw new IllegalArgumentException("Missing required field 'component'"); + } + + SelectModelConfiguration config = new ComponentSelectConfiguration(component); + config.setFallback(this.loadFallback(section)); + this.loadCases(section, config::addCase, when -> when); + return config; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/CustomModelDataSelectConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/CustomModelDataSelectConfigurationLoader.java new file mode 100644 index 00000000..e5f8ea1c --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/CustomModelDataSelectConfigurationLoader.java @@ -0,0 +1,24 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.select; + +import fr.robie.craftengineconverter.api.annotations.AutoSelectModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.select.CustomModelDataSelectConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.select.SelectModelConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; + +@AutoSelectModelConfigurationLoader({"custom_model_data", "minecraft:custom_model_data"}) +public class CustomModelDataSelectConfigurationLoader extends AbstractSelectModelConfigurationLoader { + + public CustomModelDataSelectConfigurationLoader() { + super(); + } + + @Override + public SelectModelConfiguration load(@NotNull ConfigurationSection section) { + int index = section.getInt("index", 0); + SelectModelConfiguration config = new CustomModelDataSelectConfiguration(index); + config.setFallback(this.loadFallback(section)); + this.loadCases(section, config::addCase, Object::toString); + return config; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/DisplayContextSelectConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/DisplayContextSelectConfigurationLoader.java new file mode 100644 index 00000000..a89d1736 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/DisplayContextSelectConfigurationLoader.java @@ -0,0 +1,24 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.select; + +import fr.robie.craftengineconverter.api.annotations.AutoSelectModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.select.DisplayContent; +import fr.robie.craftengineconverter.api.configuration.item.models.select.DisplayContentSelectConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.select.SelectModelConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; + +@AutoSelectModelConfigurationLoader({"display_context", "minecraft:display_context"}) +public class DisplayContextSelectConfigurationLoader extends AbstractSelectModelConfigurationLoader { + + public DisplayContextSelectConfigurationLoader() { + super(); + } + + @Override + public SelectModelConfiguration load(@NotNull ConfigurationSection section) { + SelectModelConfiguration config = new DisplayContentSelectConfiguration(); + config.setFallback(this.loadFallback(section)); + this.loadCases(section, config::addCase, when -> DisplayContent.valueOf(when.toString().toUpperCase())); + return config; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/LocalTimeSelectConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/LocalTimeSelectConfigurationLoader.java new file mode 100644 index 00000000..6cc8caf7 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/LocalTimeSelectConfigurationLoader.java @@ -0,0 +1,29 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.select; + +import fr.robie.craftengineconverter.api.annotations.AutoSelectModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.select.LocalTimeSelectConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.select.SelectModelConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; + +@AutoSelectModelConfigurationLoader({"local_time", "minecraft:local_time"}) +public class LocalTimeSelectConfigurationLoader extends AbstractSelectModelConfigurationLoader { + + public LocalTimeSelectConfigurationLoader() { + super(); + } + + @Override + public SelectModelConfiguration load(@NotNull ConfigurationSection section) { + String locale = section.getString("locale"); + String timeZone = section.getString("time_zone"); + String pattern = section.getString("pattern"); + if (pattern == null || pattern.isEmpty()) { + throw new IllegalArgumentException("Missing required field 'pattern'"); + } + LocalTimeSelectConfiguration config = new LocalTimeSelectConfiguration(locale, timeZone, pattern); + config.setFallback(this.loadFallback(section)); + this.loadCases(section, config::addCase, when -> when); + return config; + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/MainHandSelectConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/MainHandSelectConfigurationLoader.java new file mode 100644 index 00000000..7ab7b38d --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/MainHandSelectConfigurationLoader.java @@ -0,0 +1,24 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.select; + +import fr.robie.craftengineconverter.api.annotations.AutoSelectModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.select.MainHand; +import fr.robie.craftengineconverter.api.configuration.item.models.select.MainHandSelectConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.select.SelectModelConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; + +@AutoSelectModelConfigurationLoader({"main_hand", "minecraft:main_hand"}) +public class MainHandSelectConfigurationLoader extends AbstractSelectModelConfigurationLoader { + + public MainHandSelectConfigurationLoader() { + super(); + } + + @Override + public SelectModelConfiguration load(@NotNull ConfigurationSection section) { + SelectModelConfiguration config = new MainHandSelectConfiguration(); + config.setFallback(this.loadFallback(section)); + this.loadCases(section, config::addCase, when -> MainHand.valueOf(when.toString().toUpperCase())); + return config; + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/SelectModelConfigurationRegistry.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/SelectModelConfigurationRegistry.java new file mode 100644 index 00000000..d7343e52 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/SelectModelConfigurationRegistry.java @@ -0,0 +1,35 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.select; + +import fr.robie.craftengineconverter.api.configuration.item.models.select.SelectModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; + +public class SelectModelConfigurationRegistry { + private static final Map>> LOADERS = new HashMap<>(); + + public static void register(@NotNull String property, @NotNull ModelConfigurationLoader> loader) { + LOADERS.put(property, loader); + } + + @Nullable + public static SelectModelConfiguration load(@Nullable ConfigurationSection section) { + if (section == null) { + return null; + } + String property = section.getString("property"); + if (property == null) { + return null; + } + + ModelConfigurationLoader> loader = LOADERS.get(property); + if (loader == null) { + return null; + } + return loader.load(section); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/TrimMaterialSelectConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/TrimMaterialSelectConfigurationLoader.java new file mode 100644 index 00000000..9c54939e --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/select/TrimMaterialSelectConfigurationLoader.java @@ -0,0 +1,23 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.select; + +import fr.robie.craftengineconverter.api.annotations.AutoSelectModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.select.SelectModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.select.TrimMaterialSelectConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; + +@AutoSelectModelConfigurationLoader({"trim_material", "minecraft:trim_material"}) +public class TrimMaterialSelectConfigurationLoader extends AbstractSelectModelConfigurationLoader { + + public TrimMaterialSelectConfigurationLoader() { + super(); + } + + @Override + public SelectModelConfiguration load(@NotNull ConfigurationSection section) { + TrimMaterialSelectConfiguration configuration = new TrimMaterialSelectConfiguration(); + configuration.setFallback(this.loadFallback(section)); + this.loadCases(section, configuration::addCase, Object::toString); + return configuration; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/special/SpecialModelConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/special/SpecialModelConfigurationLoader.java new file mode 100644 index 00000000..0e70750a --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/special/SpecialModelConfigurationLoader.java @@ -0,0 +1,50 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.special; + +import fr.robie.craftengineconverter.api.annotations.AutoModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.model.SimpleModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationLoader; +import fr.robie.messageflow.logger.Logger; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Reduces a {@code minecraft:special} node to the ordinary model underneath it. + * + *

What special is

+ * Java uses it where the client draws something no model file can describe — a shield's banner patterns, a + * trident's spin, a conduit, a decorated pot: + *
+ * {"type":"minecraft:special","base":"minecraft:item/shield_blocking","model":{"type":"minecraft:shield"}}
+ * 
+ * The {@code model} names a hard-coded renderer. The {@code base} is a real model file, and it is what carries the + * display transforms the client poses that renderer with. + * + *

Why the base is worth taking

+ * The node used to be dropped outright, which took the whole branch with it — so a vanilla-shaped shield or + * trident converted to nothing at all. Keeping the base recovers the poses, and for a custom pack it usually + * recovers everything: an author who wants a custom shield replaces the renderer with real geometry anyway, and + * a pack that leaves the vanilla base in place gets an extruded sprite in the right position rather than a hole. + *

+ * The renderer itself is not reproducible under any circumstances, which is what the warning says. + */ +@AutoModelConfigurationLoader({"special", "minecraft:special"}) +public class SpecialModelConfigurationLoader implements ModelConfigurationLoader { + + @Override + public @Nullable ModelConfiguration load(@NotNull ConfigurationSection section) { + String base = section.getString("base"); + if (base == null) { + Logger.debug("A 'special' model names no base, so there is nothing to fall back to - skipping"); + return null; + } + + ConfigurationSection renderer = section.getConfigurationSection("model"); + String rendererType = renderer == null ? "unknown" : renderer.getString("type", "unknown"); + Logger.debug("Using '" + base + "' in place of the '" + rendererType + "' special renderer," + + " which has no equivalent."); + + return new SimpleModelConfiguration(base); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/tints/TintConfigurationLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/tints/TintConfigurationLoader.java new file mode 100644 index 00000000..486f974d --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/tints/TintConfigurationLoader.java @@ -0,0 +1,13 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.tints; + +import fr.robie.craftengineconverter.api.configuration.item.models.tints.TintConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@FunctionalInterface +public interface TintConfigurationLoader { + @Nullable + TintConfiguration load(@NotNull ConfigurationSection section); +} + \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/tints/TintConfigurationRegistry.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/tints/TintConfigurationRegistry.java new file mode 100644 index 00000000..2d05af13 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/models/tints/TintConfigurationRegistry.java @@ -0,0 +1,57 @@ +package fr.robie.craftengineconverter.api.configuration.loader.models.tints; + +import fr.robie.craftengineconverter.api.configuration.item.models.tints.TintConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.messageflow.logger.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TintConfigurationRegistry { + private static final Map LOADERS = new HashMap<>(); + + private TintConfigurationRegistry() { + } + + public static void register(@NotNull String type, @NotNull TintConfigurationLoader loader) { + LOADERS.put(type, loader); + } + + @Nullable + public static TintConfiguration load(@Nullable ConfigurationSection section) { + if (section == null) { + return null; + } + String type = section.getString("type"); + if (type == null) { + Logger.warn("Tint section is missing 'type' field, skipping."); + return null; + } + if (type.startsWith("minecraft:")) { + type = type.substring("minecraft:".length()); + } + TintConfigurationLoader loader = LOADERS.get(type); + if (loader == null) { + Logger.info("Unknown tint type '" + type + "', skipping."); + return null; + } + return loader.load(section); + } + + @NotNull + public static List loadList(@NotNull ConfigurationSection parent, @NotNull String key) { + List result = new ArrayList<>(); + List sections = parent.getSectionList(key); + for (ConfigurationSection section : sections) { + TintConfiguration tint = load(section); + if (tint != null) { + result.add(tint); + } + } + return result; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/ConstantTintLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/ConstantTintLoader.java new file mode 100644 index 00000000..5366caf9 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/ConstantTintLoader.java @@ -0,0 +1,17 @@ +package fr.robie.craftengineconverter.api.configuration.loader.tints; + +import fr.robie.craftengineconverter.api.annotations.AutoTintConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.tints.ConstantTintConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.tints.TintConfigurationLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jspecify.annotations.NonNull; + +@AutoTintConfigurationLoader({"constant", "minecraft:constant"}) +public class ConstantTintLoader implements TintConfigurationLoader { + + @Override + public ConstantTintConfiguration load(@NonNull ConfigurationSection section) { + Object value = section.get("value"); + return value == null ? null : new ConstantTintConfiguration(value); + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/CustomModelDataTintLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/CustomModelDataTintLoader.java new file mode 100644 index 00000000..15fce618 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/CustomModelDataTintLoader.java @@ -0,0 +1,18 @@ +package fr.robie.craftengineconverter.api.configuration.loader.tints; + +import fr.robie.craftengineconverter.api.annotations.AutoTintConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.tints.CustomModelDataTintConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.tints.TintConfigurationLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jspecify.annotations.NonNull; + +@AutoTintConfigurationLoader({"custom_model_data", "minecraft:custom_model_data"}) +public class CustomModelDataTintLoader implements TintConfigurationLoader { + + @Override + public CustomModelDataTintConfiguration load(@NonNull ConfigurationSection section) { + int index = section.getInt("index", 0); + Object defaultValue = section.get("default"); + return new CustomModelDataTintConfiguration(index, defaultValue); + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/DyeTintLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/DyeTintLoader.java new file mode 100644 index 00000000..48bc03ff --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/DyeTintLoader.java @@ -0,0 +1,17 @@ +package fr.robie.craftengineconverter.api.configuration.loader.tints; + +import fr.robie.craftengineconverter.api.annotations.AutoTintConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.tints.DyeTintConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.tints.TintConfigurationLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jspecify.annotations.NonNull; + +@AutoTintConfigurationLoader({"dye", "minecraft:dye"}) +public class DyeTintLoader implements TintConfigurationLoader { + + @Override + public DyeTintConfiguration load(@NonNull ConfigurationSection section) { + Object o = section.get("default"); + return o == null ? null : new DyeTintConfiguration(o); + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/FireworkTintLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/FireworkTintLoader.java new file mode 100644 index 00000000..e45274f2 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/FireworkTintLoader.java @@ -0,0 +1,17 @@ +package fr.robie.craftengineconverter.api.configuration.loader.tints; + +import fr.robie.craftengineconverter.api.annotations.AutoTintConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.tints.FireworkTintConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.tints.TintConfigurationLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jspecify.annotations.NonNull; + +@AutoTintConfigurationLoader({"firework", "minecraft:firework"}) +public class FireworkTintLoader implements TintConfigurationLoader { + + @Override + public FireworkTintConfiguration load(@NonNull ConfigurationSection section) { + Object o = section.get("default"); + return o == null ? null : new FireworkTintConfiguration(o); + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/GrassTintLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/GrassTintLoader.java new file mode 100644 index 00000000..52068c70 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/GrassTintLoader.java @@ -0,0 +1,18 @@ +package fr.robie.craftengineconverter.api.configuration.loader.tints; + +import fr.robie.craftengineconverter.api.annotations.AutoTintConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.tints.GrassTintConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.tints.TintConfigurationLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jspecify.annotations.NonNull; + +@AutoTintConfigurationLoader({"grass", "minecraft:grass"}) +public class GrassTintLoader implements TintConfigurationLoader { + + @Override + public GrassTintConfiguration load(@NonNull ConfigurationSection section) { + float temperature = (float) section.getDouble("temperature", 0.0); + float downfall = (float) section.getDouble("downfall", 0.0); + return new GrassTintConfiguration(temperature, downfall); + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/MapColorTintLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/MapColorTintLoader.java new file mode 100644 index 00000000..2f48f5a0 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/MapColorTintLoader.java @@ -0,0 +1,17 @@ +package fr.robie.craftengineconverter.api.configuration.loader.tints; + +import fr.robie.craftengineconverter.api.annotations.AutoTintConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.tints.MapColorTintConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.tints.TintConfigurationLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jspecify.annotations.NonNull; + +@AutoTintConfigurationLoader({"map_color", "minecraft:map_color"}) +public class MapColorTintLoader implements TintConfigurationLoader { + + @Override + public MapColorTintConfiguration load(@NonNull ConfigurationSection section) { + Object defaultValue = section.get("default"); + return defaultValue == null ? null : new MapColorTintConfiguration(defaultValue); + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/PotionTintLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/PotionTintLoader.java new file mode 100644 index 00000000..7b333b6c --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/PotionTintLoader.java @@ -0,0 +1,17 @@ +package fr.robie.craftengineconverter.api.configuration.loader.tints; + +import fr.robie.craftengineconverter.api.annotations.AutoTintConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.tints.PotionTintConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.tints.TintConfigurationLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jspecify.annotations.NonNull; + +@AutoTintConfigurationLoader({"potion", "minecraft:potion"}) +public class PotionTintLoader implements TintConfigurationLoader { + + @Override + public PotionTintConfiguration load(@NonNull ConfigurationSection section) { + Object o = section.get("default"); + return o == null ? null : new PotionTintConfiguration(o); + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/TeamTintLoader.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/TeamTintLoader.java new file mode 100644 index 00000000..0c18c948 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/loader/tints/TeamTintLoader.java @@ -0,0 +1,17 @@ +package fr.robie.craftengineconverter.api.configuration.loader.tints; + +import fr.robie.craftengineconverter.api.annotations.AutoTintConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.tints.TeamTintConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.tints.TintConfigurationLoader; +import fr.robie.yamllibrary.ConfigurationSection; +import org.jspecify.annotations.NonNull; + +@AutoTintConfigurationLoader({"team", "minecraft:team"}) +public class TeamTintLoader implements TintConfigurationLoader { + + @Override + public TeamTintConfiguration load(@NonNull ConfigurationSection section) { + Object o = section.get("default"); + return o == null ? null : new TeamTintConfiguration(o); + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/AbstractRecipe.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/AbstractRecipe.java index bd1c8ab3..f29e3edc 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/AbstractRecipe.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/AbstractRecipe.java @@ -7,7 +7,7 @@ import fr.robie.craftengineconverter.api.configuration.recipe.ingredient.RecipeResult; import fr.robie.craftengineconverter.api.enums.RecipeType; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/BrewingRecipe.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/BrewingRecipe.java index aa87bbce..bfa9cceb 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/BrewingRecipe.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/BrewingRecipe.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.recipe; import fr.robie.craftengineconverter.api.enums.RecipeType; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class BrewingRecipe extends AbstractRecipe { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/CookingRecipe.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/CookingRecipe.java index c620efb1..b19e7eae 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/CookingRecipe.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/CookingRecipe.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.recipe; import fr.robie.craftengineconverter.api.enums.RecipeType; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.item.recipe.CookingRecipeCategory; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class CookingRecipe extends CraftingAbstractRecipe { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/CraftingAbstractRecipe.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/CraftingAbstractRecipe.java index 6bf668b2..f8079366 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/CraftingAbstractRecipe.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/CraftingAbstractRecipe.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.recipe; import fr.robie.craftengineconverter.api.enums.RecipeType; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ShapedRecipe.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ShapedRecipe.java index 5e378393..4f413f4f 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ShapedRecipe.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ShapedRecipe.java @@ -2,8 +2,8 @@ import fr.robie.craftengineconverter.api.configuration.recipe.ingredient.CraftingIngredient; import fr.robie.craftengineconverter.api.enums.RecipeType; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.item.recipe.CraftingRecipeCategory; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.*; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ShapelessRecipe.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ShapelessRecipe.java index a172247e..96b60d7b 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ShapelessRecipe.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ShapelessRecipe.java @@ -3,8 +3,8 @@ import fr.robie.craftengineconverter.api.configuration.recipe.ingredient.CraftingIngredient; import fr.robie.craftengineconverter.api.enums.RecipeType; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.item.recipe.CraftingRecipeCategory; -import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/StonecuttingRecipe.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/StonecuttingRecipe.java index c57b56e7..01624999 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/StonecuttingRecipe.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/StonecuttingRecipe.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.recipe; import fr.robie.craftengineconverter.api.enums.RecipeType; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class StonecuttingRecipe extends AbstractRecipe { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ingredient/CraftingIngredient.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ingredient/CraftingIngredient.java index 214befde..0cb11e28 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ingredient/CraftingIngredient.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ingredient/CraftingIngredient.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.recipe.ingredient; import fr.robie.craftengineconverter.api.configuration.SectionSerializable; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ingredient/RecipeResult.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ingredient/RecipeResult.java index 0eed27f3..7ed56b11 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ingredient/RecipeResult.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/ingredient/RecipeResult.java @@ -3,7 +3,7 @@ import fr.robie.craftengineconverter.api.configuration.SectionSerializable; import fr.robie.craftengineconverter.api.configuration.recipe.postprocessor.PostProcessor; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/AbstractSmithingRecipe.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/AbstractSmithingRecipe.java index 6bfcd975..e58ef89b 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/AbstractSmithingRecipe.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/AbstractSmithingRecipe.java @@ -2,7 +2,7 @@ import fr.robie.craftengineconverter.api.configuration.recipe.AbstractRecipe; import fr.robie.craftengineconverter.api.enums.RecipeType; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/SmithingTransformRecipe.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/SmithingTransformRecipe.java index 84a21a86..b0aa276a 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/SmithingTransformRecipe.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/SmithingTransformRecipe.java @@ -3,7 +3,7 @@ import fr.robie.craftengineconverter.api.configuration.recipe.postprocessor.PostProcessor; import fr.robie.craftengineconverter.api.enums.RecipeType; import fr.robie.craftengineconverter.api.utils.ConfigurationSerializationUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/SmithingTrimRecipe.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/SmithingTrimRecipe.java index d528c60b..ffd7aeaf 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/SmithingTrimRecipe.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/recipe/smithing/SmithingTrimRecipe.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.recipe.smithing; import fr.robie.craftengineconverter.api.enums.RecipeType; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/sound/JukeboxSongConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/sound/JukeboxSongConfiguration.java index 60ebefbd..ee907ee0 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/sound/JukeboxSongConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/sound/JukeboxSongConfiguration.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.sound; import fr.robie.craftengineconverter.api.configuration.SectionSerializable; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; public class JukeboxSongConfiguration implements SectionSerializable { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/sound/SoundConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/sound/SoundConfiguration.java index adff8b5e..159a6e0a 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/sound/SoundConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/sound/SoundConfiguration.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.configuration.sound; import fr.robie.craftengineconverter.api.configuration.SectionSerializable; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/ArgumentString.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/ArgumentString.java new file mode 100644 index 00000000..0d060a6f --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/ArgumentString.java @@ -0,0 +1,357 @@ +package fr.robie.craftengineconverter.api.configuration.template; + +import fr.robie.messageflow.logger.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * A config string with its {@code ${placeholder}} positions already located. + *

+ * CraftEngine templates are parameterised with {@code ${name}} placeholders, and a single value can mix + * literal text with several of them ({@code minecraft:item/custom/${material}_${part}}). Parsing is done + * once, up front, so that resolving a template is a walk over pre-split parts rather than a regex pass over + * every string every time — which matters because a template is re-resolved for every item that uses it. + *

+ * Keys are parsed too, not just values: a template may name a key by placeholder, and a placeholder that + * resolves to {@code null} drops its entry — that is how CraftEngine omits a key conditionally. + * + *

Syntax

+ *
    + *
  • {@code ${name}} — an unbound argument resolves to nothing and drops its entry, with a warning
  • + *
  • {@code ${name:-fallback}} — used when the argument is unbound
  • + *
  • {@code ${name^}} — capitalise; {@code ${name^^}} — upper-case
  • + *
  • {@code \$} — a literal dollar
  • + *
  • {@code \{} and {@code \}} — literal braces inside a placeholder
  • + *
+ * Brace depth is tracked, so braces nested inside a placeholder do not end it early. An unclosed + * {@code ${} is treated as ordinary text rather than raising — a malformed string should not abort a + * conversion. + */ +public interface ArgumentString { + + /** The string as authored, used for error messages. */ + String rawValue(); + + /** + * Resolves against {@code arguments}. + * + * @return the resolved value, or {@code null} to signal that the owning entry should be dropped + */ + @Nullable + Object resolve(@NotNull String node, @NotNull Map arguments); + + /** Text with no placeholders. */ + final class Literal implements ArgumentString { + private final String value; + + private Literal(String value) { + this.value = value; + } + + public static Literal of(String value) { + return new Literal(value); + } + + @Override + public String rawValue() { + return this.value; + } + + @Override + public Object resolve(@NotNull String node, @NotNull Map arguments) { + return this.value; + } + + @Override + public boolean equals(Object o) { + return o instanceof Literal other && this.value.equals(other.value); + } + + @Override + public int hashCode() { + return this.value.hashCode(); + } + + @Override + public String toString() { + return "Literal(" + this.value + ")"; + } + } + + /** A single {@code ${...}} reference. */ + final class Placeholder implements ArgumentString { + private final String name; + private final String rawText; + private final String fallback; + private final boolean hasFallback; + private final boolean capitalize; + private final boolean upperCase; + + /** + * Strips one layer of matching quotes from a fallback. + *

+ * A config writes {@code ${fence_type:-"oak"}_fence} and means the block {@code oak_fence}. The quotes are + * ordinary characters inside a YAML plain scalar, so keeping them produced the id {@code "oak"_fence}, + * which matches no block — the fence's host state, and so the whole fence, resolved to nothing. + */ + private static String unquote(String fallback) { + if (fallback.length() < 2) return fallback; + char first = fallback.charAt(0); + char last = fallback.charAt(fallback.length() - 1); + boolean quoted = (first == '"' || first == '\'') && first == last; + return quoted ? fallback.substring(1, fallback.length() - 1) : fallback; + } + + private Placeholder(String content) { + this.rawText = "${" + content + "}"; + + int separator = content.indexOf(":-"); + String namePart; + if (separator < 0) { + namePart = content; + this.fallback = null; + this.hasFallback = false; + } else { + namePart = content.substring(0, separator); + this.fallback = unquote(content.substring(separator + 2)); + this.hasFallback = true; + } + + // "^^" must be tested before "^", since both end with a caret. + if (namePart.endsWith("^^")) { + this.capitalize = false; + this.upperCase = true; + this.name = namePart.substring(0, namePart.length() - 2); + } else if (namePart.endsWith("^")) { + this.capitalize = true; + this.upperCase = false; + this.name = namePart.substring(0, namePart.length() - 1); + } else { + this.capitalize = false; + this.upperCase = false; + this.name = namePart; + } + } + + public static Placeholder of(String content) { + return new Placeholder(content); + } + + public String name() { + return this.name; + } + + @Override + public String rawValue() { + return this.rawText; + } + + @Override + public Object resolve(@NotNull String node, @NotNull Map arguments) { + Object value; + TemplateArgument argument = arguments.get(this.name); + if (argument != null) { + value = argument.resolve(node, arguments); + } else if (this.hasFallback) { + // The fallback is itself a config string, so it may reference further placeholders. + value = parse(this.fallback).resolve(node, arguments); + } else { + // Unbound resolves to null, dropping the entry, rather than failing. + // + // CraftEngine errors here, but it can tell "bound to null" from "absent"; this converter + // cannot. Its YAML layer follows Bukkit semantics, where a null value removes the key — + // so a deliberate "lore: null", which CraftEngine uses precisely to drop a templated key, + // reaches us indistinguishable from a missing argument. Failing would discard the whole + // item over config that is actually correct, so the lenient reading wins and the warning + // keeps a genuine typo discoverable. + // + // Only worth a warning for a *resolved* item, though. Inside a template body the arguments + // legitimately arrive later, from whichever item uses it, so an unbound placeholder there says + // nothing — and it said it about ninety times per conversion, which buried the warnings that + // matter. Both signals mean "still inside a template": a node path that itself contains an + // unresolved placeholder, or one that passes through a template reference. + boolean insideTemplateBody = node.contains("${") || node.contains("template["); + if (insideTemplateBody) { + Logger.debug("Template argument " + this.rawText + " at " + node + + " is unbound while resolving a template body; omitting that entry"); + } else { + Logger.warn("Template argument " + this.rawText + " at " + node + + " is unbound; omitting that entry"); + } + return null; + } + + if (value == null) return null; + if (this.upperCase) return String.valueOf(value).toUpperCase(Locale.ROOT); + if (this.capitalize) return capitalise(String.valueOf(value)); + return value; + } + + private static String capitalise(String value) { + if (value.isEmpty()) return value; + return Character.toUpperCase(value.charAt(0)) + value.substring(1); + } + + @Override + public boolean equals(Object o) { + return o instanceof Placeholder other && this.rawText.equals(other.rawText); + } + + @Override + public int hashCode() { + return this.rawText.hashCode(); + } + + @Override + public String toString() { + return "Placeholder(" + this.name + ")"; + } + } + + /** Literal text and placeholders interleaved; the parts are concatenated on resolve. */ + final class Composite implements ArgumentString { + private final ArgumentString[] parts; + private final String rawText; + + private Composite(String rawText, ArgumentString[] parts) { + this.rawText = rawText; + this.parts = parts; + } + + public static Composite of(String rawText, List parts) { + return new Composite(rawText, parts.toArray(new ArgumentString[0])); + } + + @Override + public String rawValue() { + return this.rawText; + } + + @Override + public Object resolve(@NotNull String node, @NotNull Map arguments) { + StringBuilder result = new StringBuilder(); + boolean any = false; + for (ArgumentString part : this.parts) { + Object resolved = part.resolve(node, arguments); + if (resolved != null) { + result.append(resolved); + any = true; + } + } + // Every part resolving away means the whole value is absent, not the empty string. + return any ? result.toString() : null; + } + + @Override + public boolean equals(Object o) { + return o instanceof Composite other && this.rawText.equals(other.rawText); + } + + @Override + public int hashCode() { + return this.rawText.hashCode(); + } + + @Override + public String toString() { + return "Composite(" + this.rawText + ")"; + } + } + + /** + * Splits {@code input} into literal and placeholder parts. + *

+ * A string with no {@code ${} returns a {@link Literal}, which is the overwhelmingly common case and + * costs one scan. + */ + @NotNull + static ArgumentString parse(@Nullable String input) { + if (input == null || input.isEmpty()) { + return Literal.of(""); + } + + List parts = new ArrayList<>(); + StringBuilder literal = new StringBuilder(); + int length = input.length(); + int i = 0; + + while (i < length) { + char c = input.charAt(i); + + if (c == '$' && i + 1 < length && input.charAt(i + 1) == '{') { + Scanned scanned = scanPlaceholder(input, i + 2); + if (scanned == null) { + // Unclosed: treat the '$' as ordinary text and carry on. + literal.append(c); + i++; + continue; + } + if (!literal.isEmpty()) { + parts.add(Literal.of(literal.toString())); + literal.setLength(0); + } + parts.add(Placeholder.of(scanned.content())); + i = scanned.closeIndex() + 1; + } else if (c == '\\' && i + 1 < length && input.charAt(i + 1) == '$') { + // Only the placeholder trigger is escapable; a lone backslash stays literal. + literal.append('$'); + i += 2; + } else { + literal.append(c); + i++; + } + } + + if (!literal.isEmpty()) { + parts.add(Literal.of(literal.toString())); + } + + return switch (parts.size()) { + case 0 -> Literal.of(""); + case 1 -> parts.getFirst(); + default -> Composite.of(input, parts); + }; + } + + /** A placeholder body and the index of the brace that closed it. */ + record Scanned(String content, int closeIndex) {} + + /** + * Scans the body of a placeholder opened just before {@code start}. + * + * @return the body and closing index, or {@code null} if unterminated + */ + @Nullable + private static Scanned scanPlaceholder(String input, int start) { + StringBuilder content = new StringBuilder(); + int depth = 1; + int length = input.length(); + + for (int j = start; j < length; ) { + char c = input.charAt(j); + if (c == '\\' && j + 1 < length && (input.charAt(j + 1) == '{' || input.charAt(j + 1) == '}')) { + content.append(input.charAt(j + 1)); + j += 2; + } else if (c == '{') { + depth++; + content.append(c); + j++; + } else if (c == '}') { + if (--depth == 0) { + return new Scanned(content.toString(), j); + } + content.append(c); + j++; + } else { + content.append(c); + j++; + } + } + return null; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/TemplateArgument.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/TemplateArgument.java new file mode 100644 index 00000000..dd04ffba --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/TemplateArgument.java @@ -0,0 +1,121 @@ +package fr.robie.craftengineconverter.api.configuration.template; + +import fr.robie.messageflow.logger.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * A value bound to a template placeholder. + *

+ * Most arguments are plain scalars, lists or maps. A map argument carrying a {@code type:} key is + * instead a computed argument, dispatched by {@link #fromValue}. + */ +public interface TemplateArgument { + + /** Resolves this argument. May return {@code null}, which drops the entry that referenced it. */ + @Nullable + Object resolve(@NotNull String node, @NotNull Map arguments); + + /** An argument that resolves to nothing, dropping whatever entry referenced it. */ + TemplateArgument NULL = (node, arguments) -> null; + + /** + * Wraps an already-resolved config value as an argument. + *

+ * A map with a {@code type:} key selects a computed argument. CraftEngine registers twelve such types, + * but its own shipped templates use exactly one ({@code condition}), so only the structural kinds and + * {@code condition} are implemented; the rest warn once and fall back to being treated as plain data, + * which is correct for anything that does not actually need computing. + */ + @NotNull + static TemplateArgument fromValue(@Nullable Object value) { + if (value == null) return NULL; + + if (value instanceof Map map) { + Object type = map.get("type"); + if (type instanceof String typeName) { + return computed(stripNamespace(typeName), map); + } + return new Structural(map); + } + if (value instanceof List list) { + return new Structural(list); + } + return new Structural(value); + } + + private static String stripNamespace(String type) { + int colon = type.indexOf(':'); + return (colon < 0 ? type : type.substring(colon + 1)).toLowerCase(Locale.ROOT); + } + + private static TemplateArgument computed(String type, Map map) { + return switch (type) { + case "condition" -> new Condition(map); + case "plain", "object", "map", "list" -> new Structural(map); + case "null" -> NULL; + default -> { + Logger.warn("Unsupported template argument type '" + type + "' - treating it as plain data, which may leave a placeholder unresolved"); + yield new Structural(map); + } + }; + } + + /** A plain scalar, list or map, resolved as-is. */ + final class Structural implements TemplateArgument { + private final Object value; + + Structural(Object value) { + this.value = value; + } + + @Override + public Object resolve(@NotNull String node, @NotNull Map arguments) { + return this.value; + } + + @Override + public String toString() { + return "Structural(" + this.value + ")"; + } + } + + /** + * Picks between two values on a boolean. + *

+ * {@code {type: condition, condition: ${flag:-false}, on_true: a, on_false: b}} — the one computed + * argument type CraftEngine's own templates use. The condition has already had its placeholders + * resolved by the time it arrives here, so this is a string-truthiness test. + */ + final class Condition implements TemplateArgument { + private final Object condition; + private final Object onTrue; + private final Object onFalse; + + Condition(Map map) { + this.condition = map.get("condition"); + this.onTrue = map.containsKey("on_true") ? map.get("on_true") : map.get("on-true"); + this.onFalse = map.containsKey("on_false") ? map.get("on_false") : map.get("on-false"); + } + + @Override + public Object resolve(@NotNull String node, @NotNull Map arguments) { + return isTrue(this.condition) ? this.onTrue : this.onFalse; + } + + private static boolean isTrue(Object value) { + if (value == null) return false; + if (value instanceof Boolean bool) return bool; + return Boolean.parseBoolean(String.valueOf(value).trim()); + } + + @Override + public String toString() { + return "Condition(" + this.condition + ")"; + } + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/TemplateEngine.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/TemplateEngine.java new file mode 100644 index 00000000..a17cecaf --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/TemplateEngine.java @@ -0,0 +1,327 @@ +package fr.robie.craftengineconverter.api.configuration.template; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; + +/** + * Resolves CraftEngine config templates. + *

+ * A CraftEngine item can inherit most of its definition from a reusable template, parameterised by + * arguments: + *

+ * items:
+ *   default:topaz_boots:
+ *     template: default:armor/topaz
+ *     arguments: { equipment_part: boots, equipment_material: topaz }
+ * templates:
+ *   default:armor/topaz:
+ *     material: chainmail_${equipment_part}
+ * 
+ * Without resolution, {@code material:} is simply absent from the item and it converts against the wrong + * base Java item. This is a port of CraftEngine's {@code TemplateManagerImpl}, keeping its merge semantics + * exactly, because packs are authored against those semantics. + * + *

Recognised keys

+ *
    + *
  • {@code template} / {@code templates} — one id or a list; multiple are deep-merged in order
  • + *
  • {@code arguments} — bound values; a parent's argument wins over a child's re-declaration
  • + *
  • {@code overrides} — replaces: {@code putAll} for maps, whole-list replacement for lists
  • + *
  • {@code merges} — deep-merges for maps, appends for lists
  • + *
+ * Keys left alongside {@code template} are folded in as merges — CraftEngine tolerates that mistake, so + * mirroring it avoids silently dropping such config. When a template resolves to something that is not a + * map or list, precedence is {@code overrides} then {@code merges} then the last template. + *

+ * Two arguments are always available: {@code __NAMESPACE__} and {@code __ID__}, taken from the id of the + * object being resolved. + *

+ * Pre-parsing. {@link #preprocess} converts every string in the tree — keys included — into an + * {@link ArgumentString} once. A key or value whose placeholder resolves to {@code null} is dropped, + * which is how CraftEngine omits config conditionally. + */ +public final class TemplateEngine { + + private static final String TEMPLATE = "template"; + private static final String TEMPLATES = "templates"; + private static final String ARGUMENTS = "arguments"; + private static final String OVERRIDES = "overrides"; + private static final String MERGES = "merges"; + private static final Set RESERVED = Set.of(TEMPLATE, TEMPLATES, ARGUMENTS, OVERRIDES, MERGES); + + private final Map templates = new LinkedHashMap<>(); + + /** + * Registers a template body. Templates are collected from every config file before any item is + * resolved, because a template may live in a different file from the items using it. + */ + public void register(@NotNull String id, @Nullable Object rawBody) { + this.templates.put(id, preprocess(rawBody)); + } + + public boolean isEmpty() { + return this.templates.isEmpty(); + } + + public int size() { + return this.templates.size(); + } + + public boolean has(@NotNull String id) { + return this.templates.containsKey(id); + } + + /** + * Resolves {@code input} for the object identified by {@code id}, which supplies + * {@code __NAMESPACE__} and {@code __ID__}. + * + * @param id a namespaced id such as {@code default:topaz_boots} + */ + @Nullable + public Object resolve(@NotNull String id, @Nullable Object input) { + int colon = id.indexOf(':'); + String namespace = colon < 0 ? "minecraft" : id.substring(0, colon); + String value = colon < 0 ? id : id.substring(colon + 1); + return this.resolve(input, Map.of( + "__NAMESPACE__", TemplateArgument.fromValue(namespace), + "__ID__", TemplateArgument.fromValue(value))); + } + + /** Resolves {@code input} against explicit arguments. */ + @Nullable + public Object resolve(@Nullable Object input, @NotNull Map arguments) { + return this.process("", preprocess(input), arguments); + } + + /** + * Converts a raw config tree into one where every string has been parsed into an + * {@link ArgumentString}. Idempotent, so already-preprocessed trees pass through unchanged. + */ + @Nullable + public static Object preprocess(@Nullable Object value) { + return switch (value) { + case null -> null; + case ArgumentString ignored -> value; + case Map map -> { + Map out = new LinkedHashMap<>(); + for (Map.Entry entry : map.entrySet()) { + out.put(ArgumentString.parse(String.valueOf(entry.getKey())), preprocess(entry.getValue())); + } + yield out; + } + case List list -> { + List out = new ArrayList<>(list.size()); + for (Object element : list) out.add(preprocess(element)); + yield out; + } + case String string -> ArgumentString.parse(string); + default -> value; + }; + } + + @SuppressWarnings("unchecked") + @Nullable + private Object process(String node, @Nullable Object value, Map arguments) { + return switch (value) { + case null -> null; + case Map map -> this.processMap(node, (Map) map, arguments); + case List list -> { + List out = new ArrayList<>(list.size()); + for (int i = 0; i < list.size(); i++) { + out.add(this.process(node + "[" + i + "]", list.get(i), arguments)); + } + yield out; + } + case ArgumentString argument -> argument.resolve(node, arguments); + default -> value; + }; + } + + @Nullable + private Object processMap(String node, Map input, + Map arguments) { + Object templateRef = lookup(input, TEMPLATE); + if (templateRef == null) templateRef = lookup(input, TEMPLATES); + + if (templateRef == null) { + Map out = new LinkedHashMap<>(); + for (Map.Entry entry : input.entrySet()) { + ArgumentString rawKey = entry.getKey(); + String childNode = node.isEmpty() ? rawKey.rawValue() : node + "." + rawKey.rawValue(); + Object key = rawKey.resolve(childNode, arguments); + if (key == null) continue; + out.put(key.toString(), this.process(childNode, entry.getValue(), arguments)); + } + return out; + } + return this.applyTemplates(node, templateRef, input, arguments); + } + + private Object applyTemplates(String node, Object templateRef, Map input, + Map parentArguments) { + Object rawArguments = lookup(input, ARGUMENTS); + Map arguments = rawArguments instanceof Map argumentMap + ? this.mergeArguments(node + "." + ARGUMENTS, castKeys(argumentMap), parentArguments) + : parentArguments; + + List resolvedTemplates = new ArrayList<>(); + List ids = templateRef instanceof List list ? new ArrayList<>(list) : List.of(templateRef); + for (int i = 0; i < ids.size(); i++) { + String childNode = node + "." + TEMPLATE + "[" + i + "]"; + Object rawId = this.process(childNode, ids.get(i), arguments); + if (rawId == null) continue; // A null id skips that template. + String id = rawId.toString(); + if (!this.templates.containsKey(id)) { + throw new TemplateException("Unknown template '" + id + "' referenced at " + childNode); + } + Object resolved = this.process(childNode, this.templates.get(id), arguments); + if (resolved != null) resolvedTemplates.add(resolved); + } + + Object overrides = null; + Object rawOverrides = lookup(input, OVERRIDES); + if (rawOverrides != null) { + overrides = this.process(node + "." + OVERRIDES, rawOverrides, arguments); + } + + Object merges = null; + Object rawMerges = lookup(input, MERGES); + if (rawMerges != null) { + merges = this.process(node + "." + MERGES, rawMerges, arguments); + } + + Map strays = new LinkedHashMap<>(); + for (Map.Entry entry : input.entrySet()) { + ArgumentString rawKey = entry.getKey(); + if (RESERVED.contains(rawKey.rawValue())) continue; + String childNode = node + "." + rawKey.rawValue(); + Object key = rawKey.resolve(childNode, parentArguments); + if (key == null) continue; + strays.put(key.toString(), this.process(childNode, entry.getValue(), arguments)); + } + if (!strays.isEmpty()) { + if (merges instanceof Map existing) strays.putAll(castToStringMap(existing)); + merges = strays; + } + + return combine(resolvedTemplates, overrides, merges); + } + + /** Folds the resolved templates together with the overrides and merges. */ + @Nullable + private static Object combine(List templates, @Nullable Object overrides, @Nullable Object merges) { + if (templates.isEmpty()) { + if (overrides instanceof Map map) { + Map out = new LinkedHashMap<>(castToStringMap(map)); + if (merges instanceof Map mergeMap) deepMerge(out, castToStringMap(mergeMap)); + return out; + } + if (overrides instanceof List list) { + List out = new ArrayList<>(list); + if (merges instanceof List mergeList) out.addAll(mergeList); + return out; + } + if (overrides != null) return overrides; + return merges; + } + + Object first = templates.getFirst(); + if (first instanceof Map) { + Map out = new LinkedHashMap<>(); + for (Object template : templates) { + if (template instanceof Map map) deepMerge(out, castToStringMap(map)); + } + if (overrides instanceof Map map) out.putAll(castToStringMap(map)); + if (merges instanceof Map map) deepMerge(out, castToStringMap(map)); + return out; + } + if (first instanceof List) { + List out = new ArrayList<>(); + for (Object template : templates) { + if (template instanceof List list) out.addAll(list); + } + if (overrides instanceof List list) { + out.clear(); + out.addAll(list); + } + if (merges instanceof List list) out.addAll(list); + return out; + } + if (overrides != null) return overrides; + if (merges != null) return merges; + return templates.getLast(); + } + + /** + * Merges a child's arguments over its parent's, with the parent winning. + *

+ * That direction is deliberate and matches CraftEngine: a template declares defaults, and the item + * using it passes the values that must take effect, so an inner template cannot clobber what the + * caller supplied. + */ + private Map mergeArguments(String node, Map childArguments, + Map parentArguments) { + Map result = new LinkedHashMap<>(parentArguments); + for (Map.Entry entry : childArguments.entrySet()) { + Object key = entry.getKey().resolve(node, result); + if (key == null) continue; + String name = key.toString(); + if (result.containsKey(name)) continue; // Parent wins. + result.put(name, TemplateArgument.fromValue(this.process(node + "." + name, entry.getValue(), result))); + } + return result; + } + + /** + * Recursively merges {@code source} into {@code target}. + *

+ * Nested maps merge, lists concatenate, scalars replace. A {@code $$}-prefixed key forces replacement + * instead of merging, with one {@code $} stripped — CraftEngine's escape hatch for a template that must + * discard what it inherited rather than add to it. + */ + @SuppressWarnings("unchecked") + private static void deepMerge(Map target, Map source) { + for (Map.Entry entry : source.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if (key.length() > 2 && key.charAt(0) == '$' && key.charAt(1) == '$') { + target.put(key.substring(2), value); + continue; + } + + Object existing = target.get(key); + if (existing instanceof Map existingMap && value instanceof Map valueMap) { + Map merged = new LinkedHashMap<>(castToStringMap(existingMap)); + deepMerge(merged, castToStringMap(valueMap)); + target.put(key, merged); + } else if (existing instanceof List existingList && value instanceof List valueList) { + List merged = new ArrayList<>(existingList); + merged.addAll(valueList); + target.put(key, merged); + } else { + target.put(key, value); + } + } + } + + /** Finds a reserved key in a pre-parsed map, whose keys are {@link ArgumentString}s. */ + @Nullable + private static Object lookup(Map input, String key) { + for (Map.Entry entry : input.entrySet()) { + if (key.equals(entry.getKey().rawValue())) return entry.getValue(); + } + return null; + } + + @SuppressWarnings("unchecked") + private static Map castKeys(Map map) { + return (Map) map; + } + + @SuppressWarnings("unchecked") + private static Map castToStringMap(Map map) { + return (Map) map; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/TemplateException.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/TemplateException.java new file mode 100644 index 00000000..7abf4e5f --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/template/TemplateException.java @@ -0,0 +1,16 @@ +package fr.robie.craftengineconverter.api.configuration.template; + +/** + * A template could not be resolved — an unknown template id, or a {@code ${placeholder}} with neither a + * bound argument nor a fallback. + *

+ * Thrown rather than skipped because a half-resolved template would emit an item with a + * {@code ${...}} still in its material or texture path, which fails later and much less legibly. Callers + * catch this per item so one bad template does not abort the whole conversion. + */ +public class TemplateException extends RuntimeException { + + public TemplateException(String message) { + super(message); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/utils/BlockPredicateConfiguration.java b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/utils/BlockPredicateConfiguration.java index 89078b64..3f5e81fb 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/configuration/utils/BlockPredicateConfiguration.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/configuration/utils/BlockPredicateConfiguration.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.configuration.utils; import fr.robie.craftengineconverter.api.configuration.item.ItemConfigurationSerializable; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -44,7 +44,7 @@ public void serialize(@NotNull YamlConfiguration yamlConfiguration, @NotNull Str return; } - ConfigurationSection components = this.getOrCreateSection(itemSection, "components"); + ConfigurationSection components = this.getComponentsSection(itemSection); ConfigurationSection predicateSection = this.getOrCreateSection(components, this.type.getComponentKey()); List> serialized = new ArrayList<>(); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/database/ActiveConversionReader.java b/API/src/main/java/fr/robie/craftengineconverter/api/database/ActiveConversionReader.java new file mode 100644 index 00000000..fdcec9c5 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/database/ActiveConversionReader.java @@ -0,0 +1,28 @@ +package fr.robie.craftengineconverter.api.database; + +import org.jetbrains.annotations.NotNull; + +import java.util.function.Consumer; + +/** + * Reads the set of conversions still in effect without building objects for them. + * + *

Only the coordinates are needed to answer "has this already been converted?", and there can be millions of rows. + * Handing back a list of records - each carrying a world name, an id and the block state it replaced - costs a couple + * of hundred bytes per row for data that is thrown away immediately, so these push the few columns that matter at a + * consumer instead and never hold more than one row at a time. + */ +public interface ActiveConversionReader { + + /** Visits the position of every block conversion that has not been reverted. */ + void forEachActiveBlockPosition(@NotNull BlockPositionConsumer consumer); + + /** Visits the serialised location of every entity conversion that has not been reverted. */ + void forEachActiveEntityLocation(@NotNull Consumer consumer); + + @FunctionalInterface + interface BlockPositionConsumer { + + void accept(@NotNull String worldName, int blockX, int blockY, int blockZ); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/database/StorageManager.java b/API/src/main/java/fr/robie/craftengineconverter/api/database/StorageManager.java index 4ef3a061..9b9f5715 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/database/StorageManager.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/database/StorageManager.java @@ -11,10 +11,43 @@ import java.util.Optional; -public interface StorageManager { +public interface StorageManager extends ActiveConversionReader { void loadDatabase(); + /** + * Marks every block conversion still in effect as reverted, in one statement. + *

+ * The alternative is an update per row, which for a world-sized conversion is a million round trips. + */ + void markAllBlocksAsReverted(); + + /** As {@link #markAllBlocksAsReverted()}, for entity conversions. */ + void markAllEntitiesAsReverted(); + + /** + * The next page of block conversions still in effect, ordered by id and starting after {@code afterId}. + *

+ * Paging by id rather than by offset means the walk stays correct while it is marking rows reverted underneath + * itself, which an OFFSET would not: every page it had already passed would shift. + * + * @param afterId the id the previous page ended on, or 0 to start + * @param limit how many rows to read + * @return the page, empty once there is nothing left + */ + @NotNull + java.util.List nextActiveBlockPage(long afterId, int limit); + + /** As {@link #nextActiveBlockPage}, for entity conversions. */ + @NotNull + java.util.List nextActiveEntityPage(long afterId, int limit); + + /** Marks the given block conversions reverted in one statement. */ + void markBlocksAsReverted(@NotNull java.util.Collection ids); + + /** Marks the given entity conversions reverted in one statement. */ + void markEntitiesAsReverted(@NotNull java.util.Collection ids); + /** * Insert or update a block history record in persistent storage. * @param blockHistory Block history record (not null). diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/enums/ArmorConverter.java b/API/src/main/java/fr/robie/craftengineconverter/api/enums/ArmorConverter.java index 4098c24c..ec2dee27 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/enums/ArmorConverter.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/enums/ArmorConverter.java @@ -1,8 +1,8 @@ package fr.robie.craftengineconverter.api.enums; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.craftengineconverter.api.configuration.Keys; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.NotNull; import java.util.*; @@ -55,14 +55,14 @@ public static Map createArmorConverterSect Map converterSections = new HashMap<>(); - if (Configuration.get(ConfigurationKey.ARMOR_CONVERTER_TYPE) == ArmorConverter.BOTH) { + if (Configuration.get(Keys.ARMOR_CONVERTER_TYPE) == ArmorConverter.BOTH) { ConfigurationSection componentSection = getOrCreateSection(fileEquipementsSection, "$$>=1.21.2"); ConfigurationSection trimSection = getOrCreateSection(fileEquipementsSection, "$$<1.21.2"); converterSections.put(ArmorConverter.COMPONENT, getOrCreateSection(componentSection, assetId)); converterSections.put(ArmorConverter.TRIM, getOrCreateSection(trimSection, assetId)); } else { ConfigurationSection assetIdSection = getOrCreateSection(fileEquipementsSection, assetId); - converterSections.put(Configuration.get(ConfigurationKey.ARMOR_CONVERTER_TYPE), assetIdSection); + converterSections.put(Configuration.get(Keys.ARMOR_CONVERTER_TYPE), assetIdSection); } for (Map.Entry entry : converterSections.entrySet()) { diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/enums/CraftEngineBlockState.java b/API/src/main/java/fr/robie/craftengineconverter/api/enums/CraftEngineBlockState.java index 5b8d255e..ae1d0ec9 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/enums/CraftEngineBlockState.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/enums/CraftEngineBlockState.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.enums; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.utils.BlockStateResult; import org.jetbrains.annotations.NotNull; @@ -250,7 +250,7 @@ private CraftEngineBlockState getCountTarget() { * @return The current count/index */ private int getCurrentCount(Plugins plugin) { - if (Configuration.get(ConfigurationKey.BLOCK_STATE_LIMIT_TYPE) == fr.robie.craftengineconverter.api.enums.LimitType.PLUGIN) { + if (Configuration.get(Keys.BLOCK_STATE_LIMIT_TYPE) == fr.robie.craftengineconverter.api.enums.LimitType.PLUGIN) { return this.getMaxIndexRecursive(this, plugin); } else { return this.getTotalMaxIndexRecursive(this); diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/enums/ItemDisplayType.java b/API/src/main/java/fr/robie/craftengineconverter/api/enums/ItemDisplayType.java index 6484373f..6cc67727 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/enums/ItemDisplayType.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/enums/ItemDisplayType.java @@ -9,5 +9,5 @@ public enum ItemDisplayType { HEAD, GUI, GROUND, - FIXED; + FIXED } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/enums/Languages.java b/API/src/main/java/fr/robie/craftengineconverter/api/enums/Languages.java index f281bcb9..3129ea81 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/enums/Languages.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/enums/Languages.java @@ -3,6 +3,6 @@ public enum Languages { EN, FR, - DE; + DE } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/enums/item/component/ConsumableAnimation.java b/API/src/main/java/fr/robie/craftengineconverter/api/enums/item/component/ConsumableAnimation.java new file mode 100644 index 00000000..61860ee1 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/enums/item/component/ConsumableAnimation.java @@ -0,0 +1,9 @@ +package fr.robie.craftengineconverter.api.enums.item.component; + +public enum ConsumableAnimation { + NONE, EAT, DRINK, BLOCK, BOW, SPEAR, CROSSBOW, SPYGLASS, TOOT_HORN, BRUSH, BUNDLE, TRIDENT; + + public String toKey() { + return this.name().toLowerCase(); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/format/Message.java b/API/src/main/java/fr/robie/craftengineconverter/api/format/Message.java index de3289c3..8103d222 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/format/Message.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/format/Message.java @@ -126,6 +126,8 @@ public enum Message implements fr.robie.messageflow.model.Message { WARNING__CONVERTER__NEXO__CUSTOM_BLOCK__UNKNOWN_BEST_TOOL("warning.converter.nexo.custom-block.unknown-best-tool", "Unknown best_tool §e%tool%§c for custom block item §e%item%§c. Skipping best_tool conversion."), WARNING__CONVERTER__NEXO__RECIPE__NO_MAPPING_INGREDIENT("warning.converter.nexo.recipe.no-mapping-ingredient", "§cNo mapping found for ingredient §e%item%§c in recipe §e%recipe%§c."), WARNING__CONVERTER__NEXO__RECIPE__NO_MAPPING_RESULT("warning.converter.nexo.recipe.no-mapping-result", "§cNo mapping found for result item §e%item%§c in recipe §e%recipe%§c."), + WARNING__CONVERTER__NEXO__TEMPLATE__NOT_FOUND("warning.converter.nexo.template.not-found", "§eItem §6%item%§e references the template §6%template%§e, which no item file defines; it is ignored."), + WARNING__CONVERTER__NEXO__TEMPLATE__CIRCULAR("warning.converter.nexo.template.circular", "§eTemplate §6%template%§e is part of a cycle reached from §6%item%§e; the repeated reference is ignored."), WARNING__CONVERTER__NEXO__RECIPE__NO_MAPPING_INPUT("warning.converter.nexo.recipe.no-mapping-input", "§cNo mapping found for input item §e%item%§c in recipe §e%recipe%§c."), WARNING__CONVERTER__NEXO__RECIPE__NO_MAPPING_CONTAINER("warning.converter.nexo.recipe.no-mapping-container", "§cNo mapping found for container item §e%item%§c in recipe §e%recipe%§c."), WARNING__CONVERTER__NEXO__RECIPE__COULD_NOT_DETERMINE_RECIPE_TYPE("warning.converter.nexo.recipe.could-not-determine-recipe-type", "§cCould not determine recipe type for file §e%file%§c. Skipping file conversion."), @@ -165,10 +167,15 @@ public enum Message implements fr.robie.messageflow.model.Message { WARNING__FURNITURE__NON_NUMERIC_BARRIER_RANGE_BOUNDS("warning.furniture.non-numeric-barrier-range-bounds", "§cNon-numeric range bounds §e%range%§c in barrier entry §e%entry%§c."), WARNING__FURNITURE__NON_NUMERIC_BARRIER_VALUE("warning.furniture.non-numeric-barrier-value", "§cNon-numeric value §e%value%§c in barrier entry §e%entry%§c."), + WARNING__CONVERTER__UNSUPPORTED_SUMMARY_HEADER("warning.converter.unsupported-summary-header", "§eSome configuration has no CraftEngine equivalent and was left out:"), + WARNING__CONVERTER__UNSUPPORTED_SUMMARY_LINE("warning.converter.unsupported-summary-line", "§e - §6%feature%§e on §6%count%§e item(s), e.g. §6%examples%"), + WARNING__CONVERTER__DUPLICATE_ITEM_ID("warning.converter.duplicate-item-id", "§eTwo items resolve to the same id §6%item%§e (§6%first-file%§e and §6%second-file%§e); keeping the first one."), + WARNING__CONVERTER__AMBIGUOUS_DEPENDENCY("warning.converter.ambiguous-dependency", "§eItem id §6%raw-item%§e is defined in more than one namespace (§6%first%§e, §6%second%§e); dependencies on it resolve to the first."), WARNING__CONVERTER__CIRCULAR_DEPENDENCY("warning.converter.circular-dependency", "§eCircular dependency detected, falling back to original order for unresolved items."), WARNING__CONVERTER__IA__FURNITURE__UNKNOWN_DISPLAY_TRANSFORM("warning.converter.ia.furniture.unknown-display-transform", "§cUnknown furniture display transform type §e%transform%§c for item §e%item%§c."), WARNING__CONVERTER__IA__ITEMS__NO_SECTION("warning.converter.ia.items.no-section", "No 'items' section found in: §e%file%§c"), WARNING__CONVERTER__IA__ITEMS__SKIPPED_NO_SECTION("warning.converter.ia.items.skipped-no-section", "Skipped item (no section): §e%item%§c in file: §e%file%§c"), + WARNING__CONVERTER__IA__EMOJIS__NOT_APPLICABLE("warning.converter.ia.emojis.not-applicable", "ItemsAdder has no dedicated emoji configuration; its emojis are declared as font images and are converted by the images converter."), WARNING__CONVERTER__IA__IMAGES__NONE_FOUND("warning.converter.ia.images.none-found", "No ItemsAdder font images found to convert"), WARNING__CONVERTER__IA__LANGUAGES__NONE_FOUND("warning.converter.ia.languages.none-found", "No ItemsAdder language files found to convert"), WARNING__CONVERTER__IA__SOUNDS__NO_SECTION("warning.converter.ia.sounds.no-section", "No 'sounds' section found in: §e%file%§c"), @@ -179,6 +186,7 @@ public enum Message implements fr.robie.messageflow.model.Message { WARNING__CONVERTER__IA__RECIPES__ANVIL_REPAIR_NOT_IMPLEMENTED("warning.converter.ia.recipes.anvil-repair-not-implemented", "Anvil Repair recipe conversion not implemented yet for recipe: §e%recipe%§c"), WARNING__CONVERTER__IA__RECIPES__UNSUPPORTED_TYPE("warning.converter.ia.recipes.unsupported-type", "Unsupported recipe type: §e%type%§c for recipe: §e%recipe%§c"), WARNING__CONVERTER__IA__RECIPES__UNKNOWN_MACHINE_TYPE("warning.converter.ia.recipes.unknown-machine-type", "Unknown machine type: §e%machine%§c for recipe: §e%recipe%§c"), + WARNING__CONVERTER__IA__RECIPES__SKIPPED_NO_RESULT("warning.converter.ia.recipes.skipped-no-result", "Skipped recipe (its result could not be resolved): §e%recipe%§c in file: §e%file%§c"), WARNING__CONVERTER__IA__RECIPES__SMITHING_MISSING_BASE("warning.converter.ia.recipes.smithing-missing-base", "Missing required 'base' for smithing recipe: §e%recipe%§c in file: §e%file%§c"), WARNING__CONVERTER__IA__RECIPES__UNKNOWN_ITEM_REFERENCE("warning.converter.ia.recipes.unknown-item-reference", "Unknown ItemsAdder item: §e%item%§c for recipe: §e%recipe%§c in file: §e%file%§c"), WARNING__CONVERTER__IA__RECIPES__ITEM_REFERENCE_CONVERSION_FAILURE("warning.converter.ia.recipes.item-reference-conversion-failure", "Could not convert item reference: §e%item%§c for recipe: §e%recipe%§c in file: §e%file%§c"), @@ -236,6 +244,7 @@ public enum Message implements fr.robie.messageflow.model.Message { ERROR__FILE_OPERATIONS__FORCE_SHUTDOWN("error.file-operations.force-shutdown", "Forcing shutdown of file operation threads"), ERROR__JSON__MALFORMED_AUTO_FIXED("error.json.malformed-auto-fixed", "Malformed JSON detected in §e%file%§c, auto-fixed."), ERROR__JSON__LOAD_FAILURE("error.json.load-failure", "Unable to load JSON file '%file%': file not found or invalid JSON format"), + ERROR__JSON__SAVE_FAILURE("error.json.save-failure", "Unable to save JSON file '%file%': §e%message%§c"), ERROR__PACK_CONVERSION__EXCEPTION("error.pack-conversion.exception", "An error occurred during pack conversion for plugin §e%plugin%§c"), ERROR__PLUGIN__CONFIGURATION__TYPE_MISMATCH("error.plugin.configuration.type-mismatch", "§cType mismatch for §e%path%§c in configuration, expected §e%expected%§c but got §e%got%§c, using default value: §e%default%§c"), diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/loader/ClassRegistry.java b/API/src/main/java/fr/robie/craftengineconverter/api/loader/ClassRegistry.java new file mode 100644 index 00000000..9578786d --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/loader/ClassRegistry.java @@ -0,0 +1,69 @@ +package fr.robie.craftengineconverter.api.loader; + +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +public class ClassRegistry { + + private final List> strategies = new ArrayList<>(); + private final Consumer registrar; + private final Class expectedType; + private Consumer errorLogger; + + private ClassRegistry(Class expectedType, Consumer registrar) { + this.expectedType = expectedType; + this.registrar = registrar; + } + + public static ClassRegistry of(Class type, Consumer registrar) { + return new ClassRegistry<>(type, registrar); + } + + public ClassRegistry tryConstructor(ConstructorStrategy

strategy) { + this.strategies.add(strategy); + return this; + } + + public ClassRegistry errorLogger(Consumer errorLogger) { + this.errorLogger = errorLogger; + return this; + } + + public ClassRegistry tryNoArgsConstructor() { + return this.tryConstructor((clazz, plugin) -> clazz.getDeclaredConstructor().newInstance()); + } + + public boolean load(P plugin, Class clazz) { + for (ConstructorStrategy

strategy : this.strategies) { + try { + Object instance = strategy.instantiate(clazz, plugin); + if (this.expectedType.isInstance(instance)) { + this.registrar.accept(this.expectedType.cast(instance)); + return true; + } + } catch (Exception ignored) { + } + } + + if (this.errorLogger != null) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("Could not find a valid constructor for ").append(clazz.getName()).append(". Available constructors: "); + for (int i = 0; i < clazz.getDeclaredConstructors().length; i++) { + stringBuilder.append(clazz.getDeclaredConstructors()[i]); + if (i < clazz.getDeclaredConstructors().length - 1) { + stringBuilder.append(", "); + } + } + this.errorLogger.accept(stringBuilder.toString()); + } + + return false; + } + + public Class getExpectedType() { + return this.expectedType; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/loader/ConstructorStrategy.java b/API/src/main/java/fr/robie/craftengineconverter/api/loader/ConstructorStrategy.java new file mode 100644 index 00000000..61a968d9 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/loader/ConstructorStrategy.java @@ -0,0 +1,8 @@ +package fr.robie.craftengineconverter.api.loader; + +import org.bukkit.plugin.Plugin; + +@FunctionalInterface +public interface ConstructorStrategy

{ + Object instantiate(Class clazz, P plugin) throws Exception; +} diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/manager/FileCacheManager.java b/API/src/main/java/fr/robie/craftengineconverter/api/manager/FileCacheManager.java similarity index 67% rename from Common/src/main/java/fr/robie/craftengineconverter/common/manager/FileCacheManager.java rename to API/src/main/java/fr/robie/craftengineconverter/api/manager/FileCacheManager.java index a063a696..7695cdae 100644 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/manager/FileCacheManager.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/manager/FileCacheManager.java @@ -1,21 +1,20 @@ -package fr.robie.craftengineconverter.common.manager; +package fr.robie.craftengineconverter.api.manager; import com.google.gson.*; import com.google.gson.stream.JsonReader; +import fr.robie.craftengineconverter.api.cache.FileCache; import fr.robie.craftengineconverter.api.format.Message; - -import fr.robie.craftengineconverter.common.cache.FileCache; import fr.robie.messageflow.formatter.Placeholder; import fr.robie.messageflow.logger.Logger; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; import java.nio.file.Files; +import java.nio.file.Path; public class FileCacheManager { - private static final Gson GSON = new GsonBuilder() - .setPrettyPrinting() - .serializeNulls() - .create(); + private static final Gson GSON = createGsonBuilder(true).create(); + private static final Gson COMPACT_GSON = createGsonBuilder(false).create(); private static final FileCache yamlCache = new FileCache<>(100, 30, YamlConfiguration::loadConfiguration); private static final FileCache jsonCache = new FileCache<>(100, 30, file -> { @@ -65,4 +64,22 @@ public static FileCache getYamlCache() { public static FileCache getJsonCache() { return jsonCache; } + + public static void saveJsonToFile(@NotNull Path path, @NotNull JsonElement jsonElement) { + try (var writer = Files.newBufferedWriter(path)) { + COMPACT_GSON.toJson(jsonElement, writer); + } catch (Exception e) { + Logger.error(Message.ERROR__JSON__LOAD_FAILURE, e, Placeholder.of("file", path.toAbsolutePath().toString(), "message", e.getMessage())); + } + } + + private static GsonBuilder createGsonBuilder(boolean prettyPrint) { + GsonBuilder builder = new GsonBuilder() + .disableHtmlEscaping(); + if (prettyPrint) { + builder.setPrettyPrinting(); + } + return builder; + } + } \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/manager/FoliaCompatibilityManager.java b/API/src/main/java/fr/robie/craftengineconverter/api/manager/FoliaCompatibilityManager.java index 48d8f9a1..e6f05104 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/manager/FoliaCompatibilityManager.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/manager/FoliaCompatibilityManager.java @@ -2,6 +2,7 @@ import com.tcoded.folialib.FoliaLib; import com.tcoded.folialib.wrapper.task.WrappedTask; +import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; @@ -12,17 +13,26 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; -public class FoliaCompatibilityManager { - private final FoliaLib foliaLib; +public record FoliaCompatibilityManager(FoliaLib foliaLib) { + private static FoliaCompatibilityManager instance; public FoliaCompatibilityManager(Plugin plugin) { - this.foliaLib = new FoliaLib(plugin); + this(new FoliaLib(plugin)); + instance = this; + } + + public static FoliaCompatibilityManager getInstance() { + if (instance == null) { + throw new IllegalStateException("FoliaCompatibilityManager has not been initialized yet."); + } + return instance; } /** * Get the FoliaLib instance for direct access if needed. */ - public FoliaLib getFoliaLib() { + @Override + public FoliaLib foliaLib() { return this.foliaLib; } @@ -260,7 +270,7 @@ public boolean isOwnedByCurrentRegion(Location location) { if (this.foliaLib.isFolia()) { // Use Bukkit.isOwnedByCurrentRegion() on Folia try { - return org.bukkit.Bukkit.isOwnedByCurrentRegion(location); + return Bukkit.isOwnedByCurrentRegion(location); } catch (Exception e) { // Fallback if method doesn't exist in current version return true; @@ -280,7 +290,7 @@ public boolean isOwnedByCurrentRegion(Entity entity) { if (this.foliaLib.isFolia()) { // Use Bukkit.isOwnedByCurrentRegion() on Folia try { - return org.bukkit.Bukkit.isOwnedByCurrentRegion(entity); + return Bukkit.isOwnedByCurrentRegion(entity); } catch (Exception e) { // Fallback if method doesn't exist in current version return true; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/profile/ServerProfile.java b/API/src/main/java/fr/robie/craftengineconverter/api/profile/ServerProfile.java index 663fa0d7..c67e0d5a 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/profile/ServerProfile.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/profile/ServerProfile.java @@ -8,7 +8,6 @@ import fr.robie.craftengineconverter.api.history.EntityHistory; import org.jetbrains.annotations.NotNull; -import java.util.Collection; public interface ServerProfile { @@ -52,14 +51,14 @@ public interface ServerProfile { void markEntityAsReverted(@NotNull EntityHistory history); /** - * Gets all active (non-reverted) block conversions from the cache. - * - * @return Collection of all active BlockHistory records (never null, may be empty). + * Drops a block from the index without touching the database. + *

+ * For callers that revert a whole page in one statement: {@link #markBlockAsReverted} would issue a second + * update for the same row. */ - @NotNull - Collection getAllActiveConversions(); + void forgetBlock(@NotNull BlockHistory history); - @NotNull - Collection getAllActiveEntityConversions(); + /** As {@link #forgetBlock}, for an entity conversion. */ + void forgetEntity(@NotNull EntityHistory history); } diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/reflections/ReflectionsCache.java b/API/src/main/java/fr/robie/craftengineconverter/api/reflections/ReflectionsCache.java new file mode 100644 index 00000000..64b278b2 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/reflections/ReflectionsCache.java @@ -0,0 +1,59 @@ +package fr.robie.craftengineconverter.api.reflections; + +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; +import org.reflections.Reflections; +import org.reflections.scanners.Scanners; +import org.reflections.util.ConfigurationBuilder; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class ReflectionsCache { + private static ReflectionsCache instance; + + private final Map cache; + + private ReflectionsCache() { + this.cache = new ConcurrentHashMap<>(); + } + + public static synchronized ReflectionsCache getInstance() { + if (instance == null) { + instance = new ReflectionsCache(); + } + return instance; + } + + public Reflections getOrCreate(@NotNull Plugin plugin, @NotNull String packageName) { + if (packageName.trim().isEmpty()) { + throw new IllegalArgumentException("Package name cannot be empty"); + } + + ClassLoader classLoader = plugin.getClass().getClassLoader(); + CacheKey key = new CacheKey(packageName, classLoader); + + return this.cache.computeIfAbsent(key, k -> this.createReflections(classLoader, packageName)); + } + + public Reflections getOrCreate(@NotNull ClassLoader classLoader, @NotNull String packageName) { + if (packageName.trim().isEmpty()) { + throw new IllegalArgumentException("Package name cannot be empty"); + } + CacheKey key = new CacheKey(packageName, classLoader); + return this.cache.computeIfAbsent(key, k -> this.createReflections(classLoader, packageName)); + } + + private Reflections createReflections(ClassLoader classLoader, String packageName) { + return new Reflections(new ConfigurationBuilder() + .forPackage(packageName, classLoader) + .addClassLoaders(classLoader) + .setScanners(Scanners.TypesAnnotated, Scanners.SubTypes)); + } + + private record CacheKey(String packageName, int classLoaderHash) { + CacheKey(String packageName, ClassLoader classLoader) { + this(packageName, System.identityHashCode(classLoader)); + } + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/utils/Comparison.java b/API/src/main/java/fr/robie/craftengineconverter/api/utils/Comparison.java new file mode 100644 index 00000000..349b6518 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/utils/Comparison.java @@ -0,0 +1,21 @@ +package fr.robie.craftengineconverter.api.utils; + +public enum Comparison { + GREATER_THAN, + GREATER_THAN_OR_EQUAL_TO, + LESS_THAN, + LESS_THAN_OR_EQUAL_TO, + EQUAL, + NOT_EQUAL; + + public boolean compare(int result) { + return switch (this) { + case GREATER_THAN -> result > 0; + case GREATER_THAN_OR_EQUAL_TO -> result >= 0; + case LESS_THAN -> result < 0; + case LESS_THAN_OR_EQUAL_TO -> result <= 0; + case EQUAL -> result == 0; + case NOT_EQUAL -> result != 0; + }; + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/utils/ConfigurationSerializationUtils.java b/API/src/main/java/fr/robie/craftengineconverter/api/utils/ConfigurationSerializationUtils.java index 3810a45e..63c7f417 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/utils/ConfigurationSerializationUtils.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/utils/ConfigurationSerializationUtils.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.api.utils; import fr.robie.craftengineconverter.api.configuration.SectionSerializable; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import java.util.Collection; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/utils/FileUtils.java b/API/src/main/java/fr/robie/craftengineconverter/api/utils/FileUtils.java new file mode 100644 index 00000000..3d20c737 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/utils/FileUtils.java @@ -0,0 +1,102 @@ +package fr.robie.craftengineconverter.api.utils; + +import fr.robie.craftengineconverter.api.format.Message; +import fr.robie.messageflow.formatter.Placeholder; +import fr.robie.messageflow.logger.Logger; +import org.jetbrains.annotations.NotNull; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; + +public class FileUtils { + + public static void deleteDirectory(@NotNull File directory) { + File[] files = directory.listFiles(); + if (files != null) { + for (File file : files) { + if (file.isDirectory()) { + deleteDirectory(file); + } else if (!file.delete()) { + Logger.error(Message.WARNING__FILE__DELETE_FAILURE, Placeholder.of("file", file.getName(), "path", file.getAbsolutePath())); + } + } + } + if (!directory.delete()) { + Logger.error(Message.WARNING__FOLDER__DELETE_FAILURE, Placeholder.of("folder", directory.getName(), "path", directory.getAbsolutePath())); + } + } + + public static boolean mkdirs(@NotNull File directory) { + if (directory.exists()) { + return true; + } + if (directory.mkdirs()) { + return true; + } + Logger.info(Message.ERROR__MKDIR_FAILURE, Placeholder.of("directory", directory.getName(), "path", directory.getAbsolutePath())); + return false; + } + + public static String getFileNameWithoutExtension(@NotNull File file) { + String name = file.getName(); + int lastDotIndex = name.lastIndexOf('.'); + if (lastDotIndex > 0) { + return name.substring(0, lastDotIndex); + } + return name; + } + + public static String getFileExtension(@NotNull File file) { + String name = file.getName(); + int lastDotIndex = name.lastIndexOf('.'); + if (lastDotIndex > 0 && lastDotIndex < name.length() - 1) { + return name.substring(lastDotIndex + 1); + } + return ""; + } + + public static void copyDirectory(@NotNull File source, @NotNull File destination) { + if (!mkdirs(destination)) { + return; + } + + File[] files = source.listFiles(); + if (files == null) { + return; + } + + for (File file : files) { + File dest = new File(destination, file.getName()); + if (file.isDirectory()) { + copyDirectory(file, dest); + } else { + copyFile(file, dest); + } + } + } + + public static boolean isYmlFile(@NotNull File file) { + String extension = getFileExtension(file); + return extension.equalsIgnoreCase("yml") || extension.equalsIgnoreCase("yaml"); + } + + public static boolean isJsonFile(File file) { + String extension = getFileExtension(file); + return extension.equalsIgnoreCase("json"); + } + + public static void copyFile(@NotNull File source, @NotNull File destination) { + try { + mkdirs(destination.getParentFile()); + Files.copy( + source.toPath(), + destination.toPath(), + StandardCopyOption.REPLACE_EXISTING + ); + } catch (IOException e) { + Logger.error(Message.ERROR__FILE__COPY_EXCEPTION, Placeholder.of("file", destination.getName(), "message", e.getMessage())); + } + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/utils/MinecraftVersion.java b/API/src/main/java/fr/robie/craftengineconverter/api/utils/MinecraftVersion.java new file mode 100644 index 00000000..edbb8a2c --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/utils/MinecraftVersion.java @@ -0,0 +1,120 @@ +package fr.robie.craftengineconverter.api.utils; + +import fr.robie.messageflow.logger.Logger; +import org.bukkit.Bukkit; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public final class MinecraftVersion implements Comparable { + private static final Map PARSE_CACHE = new ConcurrentHashMap<>(); + + private static MinecraftVersion currentVersion; + + private final int major; + private final int minor; + private final int patch; + + private MinecraftVersion(int major, int minor, int patch) { + this.major = major; + this.minor = minor; + this.patch = patch; + } + + public static MinecraftVersion getCurrentVersion() { + if (currentVersion == null) { + String bukkitVersion; + try { + bukkitVersion = Bukkit.getBukkitVersion(); + } catch (NoClassDefFoundError | Exception e) { // In case we're running in an environment without Bukkit (e.g., during testing), we can't get the version, so we default to (0, 0, 0). + bukkitVersion = null; + } + currentVersion = parse(bukkitVersion); + } + return currentVersion; + } + + @NotNull + public static MinecraftVersion parse(@Nullable String rawVersion) { + if (rawVersion == null || rawVersion.isBlank()) { + return new MinecraftVersion(0, 0, 0); + } + return PARSE_CACHE.computeIfAbsent(rawVersion, raw -> { + String clean = raw.contains("-") ? raw.substring(0, raw.indexOf('-')) : raw; + String[] parts = clean.split("\\."); + try { + int major = parts.length > 0 ? Integer.parseInt(parts[0]) : 0; + int minor = parts.length > 1 ? Integer.parseInt(parts[1]) : 0; + int patch = parts.length > 2 ? Integer.parseInt(parts[2]) : 0; + return new MinecraftVersion(major, minor, patch); + } catch (NumberFormatException e) { + Logger.error("Could not parse Minecraft value '" + raw + "'. Version-gated classes will be skipped. (" + e.getMessage() + ")", e); + return new MinecraftVersion(0, 0, 0); + } + }); + } + + /** + * Returns {@code true} if this value is greater than or equal to {@code other}. + */ + public boolean isAtLeast(MinecraftVersion other) { + return this.compareTo(other) >= 0; + } + + /** + * Returns {@code true} if this value is less than or equal to {@code other}. + */ + public boolean isAtMost(MinecraftVersion other) { + return this.compareTo(other) <= 0; + } + + public boolean isBefore(MinecraftVersion other) { + return this.compareTo(other) < 0; + } + + public boolean isAfter(MinecraftVersion other) { + return this.compareTo(other) > 0; + } + + public int getMajor() { + return this.major; + } + + public int getMinor() { + return this.minor; + } + + public int getPatch() { + return this.patch; + } + + @Override + public int compareTo(MinecraftVersion other) { + if (this.major != other.major) { + return Integer.compare(this.major, other.major); + } + if (this.minor != other.minor) { + return Integer.compare(this.minor, other.minor); + } + return Integer.compare(this.patch, other.patch); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (!(obj instanceof MinecraftVersion other)) return false; + return this.major == other.major && this.minor == other.minor && this.patch == other.patch; + } + + @Override + public int hashCode() { + return 31 * (31 * this.major + this.minor) + this.patch; + } + + @Override + public String toString() { + return this.major + "." + this.minor + (this.patch != 0 ? "." + this.patch : ""); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/utils/ObjectUtils.java b/API/src/main/java/fr/robie/craftengineconverter/api/utils/ObjectUtils.java index 063a3ead..c3053fe3 100644 --- a/API/src/main/java/fr/robie/craftengineconverter/api/utils/ObjectUtils.java +++ b/API/src/main/java/fr/robie/craftengineconverter/api/utils/ObjectUtils.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.api.utils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/utils/PluginVersion.java b/API/src/main/java/fr/robie/craftengineconverter/api/utils/PluginVersion.java new file mode 100644 index 00000000..a7893940 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/utils/PluginVersion.java @@ -0,0 +1,90 @@ +package fr.robie.craftengineconverter.api.utils; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public final class PluginVersion implements Comparable { + private static final Map PARSE_CACHE = new ConcurrentHashMap<>(); + + private final int[] segments; + + private PluginVersion(int[] segments) { + this.segments = stripLeadingZeros(segments); + } + + /** + * Strips leading zero segments: [0, 61, 2] → [61, 2]. + * Keeps at least one segment to represent version "0". + */ + private static int[] stripLeadingZeros(int[] segments) { + int start = 0; + while (start < segments.length - 1 && segments[start] == 0) { + start++; + } + return start == 0 ? segments : Arrays.copyOfRange(segments, start, segments.length); + } + + @NotNull + public static PluginVersion parse(@Nullable String rawVersion) { + if (rawVersion == null || rawVersion.isBlank()) { + return new PluginVersion(new int[]{0}); + } + return PARSE_CACHE.computeIfAbsent(rawVersion, raw -> { + String clean = raw.contains("-") ? raw.substring(0, raw.indexOf('-')) : raw; + String[] parts = clean.split("\\."); + int[] segments = new int[parts.length]; + for (int i = 0; i < parts.length; i++) { + String part = parts[i].replaceAll("[^0-9]", ""); + try { + segments[i] = part.isEmpty() ? 0 : Integer.parseInt(part); + } catch (NumberFormatException e) { + segments[i] = 0; + } + } + return new PluginVersion(segments); + }); + } + + @Override + public int compareTo(@NotNull PluginVersion other) { + int length = Math.max(this.segments.length, other.segments.length); + for (int i = 0; i < length; i++) { + if (i >= this.segments.length) return -1; + if (i >= other.segments.length) return 1; + if (this.segments[i] != other.segments[i]) { + return Integer.compare(this.segments[i], other.segments[i]); + } + } + return 0; + } + + public boolean isNewerThan(@NotNull PluginVersion other) { return this.compareTo(other) > 0; } + public boolean isOlderThan(@NotNull PluginVersion other) { return this.compareTo(other) < 0; } + public boolean isSameAs(@NotNull PluginVersion other) { return this.compareTo(other) == 0; } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (!(obj instanceof PluginVersion other)) return false; + return Arrays.equals(this.segments, other.segments); + } + + @Override + public int hashCode() { + return Arrays.hashCode(this.segments); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < this.segments.length; i++) { + if (i > 0) builder.append('.'); + builder.append(this.segments[i]); + } + return builder.toString(); + } +} diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/utils/VersionFilter.java b/API/src/main/java/fr/robie/craftengineconverter/api/utils/VersionFilter.java new file mode 100644 index 00000000..114707c0 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/utils/VersionFilter.java @@ -0,0 +1,81 @@ +package fr.robie.craftengineconverter.api.utils; + +import fr.robie.craftengineconverter.api.annotations.*; +import fr.robie.craftengineconverter.api.loader.ClassRegistry; +import fr.robie.craftengineconverter.api.manager.FoliaCompatibilityManager; +import fr.robie.craftengineconverter.api.reflections.ReflectionsCache; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; +import org.reflections.Reflections; + +import java.lang.annotation.Annotation; + +public final class VersionFilter { + + private VersionFilter() { + } + + public static boolean passes(Class clazz) { + if (clazz.isAnnotationPresent(PaperOnly.class) && !FoliaCompatibilityManager.getInstance().isPaperOrFolia()) { + return false; + } + if (clazz.isAnnotationPresent(SpigotOnly.class) && FoliaCompatibilityManager.getInstance().isPaperOrFolia()) { + return false; + } + + RequiresPlugin requiresPlugin = clazz.getAnnotation(RequiresPlugin.class); + if (requiresPlugin != null) { + Plugin plugin = Bukkit.getPluginManager().getPlugin(requiresPlugin.value()); + + if (plugin == null) return false; + + if (requiresPlugin.checkMode() == RequiresPlugin.CheckMode.EXISTS_AND_ENABLED && !plugin.isEnabled()) return false; + + String requiredVersionStr = requiresPlugin.version(); + if (!requiredVersionStr.isEmpty()) { + PluginVersion pluginVersion = PluginVersion.parse(plugin.getDescription().getVersion()); + PluginVersion requiredVersion = PluginVersion.parse(requiredVersionStr); + if (!requiresPlugin.type().compare(pluginVersion.compareTo(requiredVersion))) { + return false; + } + } + } + + MinecraftVersion serverVersion = MinecraftVersion.getCurrentVersion(); + + SinceVersion since = clazz.getAnnotation(SinceVersion.class); + if (since != null) { + MinecraftVersion minimum = MinecraftVersion.parse(since.value()); + if (!serverVersion.isAtLeast(minimum)) { + return false; + } + } + + UntilVersion until = clazz.getAnnotation(UntilVersion.class); + if (until != null) { + MinecraftVersion maximum = MinecraftVersion.parse(until.value()); + return serverVersion.isAtMost(maximum); + } + + return true; + } + + public static int scanAndRegister( + @NotNull String packageName, + @NotNull P plugin, + @NotNull Class annotation, + @NotNull ClassRegistry registry) { + + Reflections reflection = ReflectionsCache.getInstance().getOrCreate(plugin, packageName); + int count = 0; + + for (Class clazz : reflection.getTypesAnnotatedWith(annotation)) { + if (!registry.getExpectedType().isAssignableFrom(clazz)) continue; + if (!passes(clazz)) continue; + if (registry.load(plugin, clazz)) count++; + } + + return count; + } +} \ No newline at end of file diff --git a/API/src/main/java/fr/robie/craftengineconverter/api/utils/item/component/ConsumeEffect.java b/API/src/main/java/fr/robie/craftengineconverter/api/utils/item/component/ConsumeEffect.java new file mode 100644 index 00000000..c0329228 --- /dev/null +++ b/API/src/main/java/fr/robie/craftengineconverter/api/utils/item/component/ConsumeEffect.java @@ -0,0 +1,11 @@ +package fr.robie.craftengineconverter.api.utils.item.component; + +import com.google.gson.JsonObject; + +import java.util.Map; + +public interface ConsumeEffect { + Map serialize(); + + JsonObject serializeToJson(); +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0b9a9806..eb898e2d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -107,7 +107,6 @@ CraftEngineConverter/ │ ├── packet/ # Packet handling │ └── tag/ # Tag processing system ├── Hooks/ # Plugin hook implementations -│ ├── BOM/ # Bill of Materials │ ├── PacketEvent/ # Packet event integration │ └── PlaceholderAPI/ # PlaceholderAPI integration └── Plugin/ # Main plugin implementation @@ -325,10 +324,12 @@ void testConvertItemWithValidInput() { ### Adding a New Hook 1. Create module in `Hooks/` directory -2. Add dependency in `pom.xml` -3. Implement hook interface -4. Add to BOM required to load the hook into `Plugin` module -5. Test integration +2. Add an `include(":Hooks:")` entry in `settings.gradle.kts` +3. Apply `craftengineconverter.hook-conventions` in the module's `build.gradle.kts` +4. Implement hook interface + +The hook is picked up by `:Plugin` automatically - it no longer needs to be listed anywhere, the +old `Hooks/BOM` aggregator is gone. ## Reporting Bugs diff --git a/Common/build.gradle.kts b/Common/build.gradle.kts new file mode 100644 index 00000000..580fc18b --- /dev/null +++ b/Common/build.gradle.kts @@ -0,0 +1,19 @@ +plugins { + id("craftengineconverter.java-conventions") +} + +dependencies { + api(project(":API")) + api(libs.sarah) + + compileOnly(libs.paper.api) + compileOnly(libs.craftengine.core) + compileOnly(libs.craftengine.bukkit) + compileOnly(libs.message.flow) + compileOnly(libs.yamllibrary) + compileOnly(libs.yamllibrary.core) + + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testRuntimeOnly(libs.junit.platform.launcher) +} diff --git a/Common/pom.xml b/Common/pom.xml deleted file mode 100644 index 7df456a7..00000000 --- a/Common/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - 4.0.0 - - fr.robie.craftengineconverter - CraftEngineConverter - 0.0.2 - - - Common - - - - org.junit.jupiter - junit-jupiter - - - io.papermc.paper - paper-api - - - fr.robie.craftengineconverter - API - - - - net.momirealms - craft-engine-core - - - net.momirealms - craft-engine-bukkit - - - - fr.maxlego08.sarah - sarah - compile - - - - com.github.1robie.MessageFlow - message-flow - provided - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*Test.java - - - - - - - \ No newline at end of file diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/PluginNameMapper.java b/Common/src/main/java/fr/robie/craftengineconverter/common/PluginNameMapper.java index cd8e57fc..3fb8d258 100644 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/PluginNameMapper.java +++ b/Common/src/main/java/fr/robie/craftengineconverter/common/PluginNameMapper.java @@ -13,18 +13,31 @@ public class PluginNameMapper { private PluginNameMapper() { } - public boolean hasMapping(Plugins plugin, String oldName) { + public boolean hasMapping(Plugins plugin, @Nullable String oldName) { + if (oldName == null) { + return false; + } Map pluginMappings = this.mappings.get(plugin.name()); return pluginMappings != null && pluginMappings.containsKey(oldName); } + /** + * The name an old id converts to, or null if it has none. A null id answers null rather than throwing: ids read + * back out of a persistent data container are only as trustworthy as whatever wrote them. + */ @Nullable - public String getNewName(Plugins plugin, String oldName) { + public String getNewName(Plugins plugin, @Nullable String oldName) { + if (oldName == null) { + return null; + } Map pluginMappings = this.mappings.get(plugin.name()); return pluginMappings != null ? pluginMappings.get(oldName) : null; } - public void storeMapping(Plugins plugin, String oldName, String newName) { + public void storeMapping(Plugins plugin, @Nullable String oldName, @Nullable String newName) { + if (oldName == null || newName == null) { + return; + } this.mappings.computeIfAbsent(plugin.name(), k -> new ConcurrentHashMap<>()) .put(oldName, newName); } diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/converter/BlockConverter.java b/Common/src/main/java/fr/robie/craftengineconverter/common/converter/BlockConverter.java index 894c21a3..d96896db 100644 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/converter/BlockConverter.java +++ b/Common/src/main/java/fr/robie/craftengineconverter/common/converter/BlockConverter.java @@ -1,11 +1,14 @@ package fr.robie.craftengineconverter.common.converter; import fr.robie.craftengineconverter.api.enums.Plugins; +import fr.robie.craftengineconverter.api.history.BlockHistory; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; +import org.jetbrains.annotations.Nullable; import net.momirealms.craftengine.bukkit.api.CraftEngineBlocks; import net.momirealms.craftengine.core.util.Key; import org.bukkit.Location; +import java.util.HashSet; import java.util.Set; public abstract class BlockConverter extends ObjectConverter { @@ -13,7 +16,19 @@ public BlockConverter(CraftEngineConverterPlugin plugin, Plugins pluginType) { super(plugin, pluginType); } - protected void executeBlockConversion(Location blockLoc, Set processed, ConversionCounter counter) { + /** Converts whatever adjoins a block that was just converted, within the configured budget. */ + protected void propagateFrom(Location origin) { + ConversionCounter counter = this.propagationCounter(); + if (counter == null) { + return; + } + + Set processed = new HashSet<>(); + processed.add(BlockKey.of(origin)); + this.executeBlockConversion(origin, processed, counter); + } + + protected void executeBlockConversion(Location blockLoc, Set processed, ConversionCounter counter) { for (int[] offset : this.ADJACENT_OFFSETS) { if (counter.hasReachedLimit()) { return; @@ -21,7 +36,7 @@ protected void executeBlockConversion(Location blockLoc, Set processed Location adjacentLoc = blockLoc.clone().add(offset[0], offset[1], offset[2]); - if (!processed.add(adjacentLoc)) { + if (!processed.add(BlockKey.of(adjacentLoc))) { continue; } @@ -54,7 +69,20 @@ public boolean isRegistered(String itemId) { public abstract boolean removeBlockAt(Location location); - public void placeBlock(String itemId, Location location, String oldBlockState) { + public void placeBlock(String itemId, Location location, @Nullable String oldBlockState) { this.plugin.getPlacementTracker().placeBlock(itemId, location); + if (oldBlockState == null) { + return; + } + + this.serverProfile.addBlockHistory(new BlockHistory(null, + location.getWorld().getName(), + location.getBlockX() >> 4, + location.getBlockZ() >> 4, + location.getBlockX(), + location.getBlockY(), + location.getBlockZ(), + oldBlockState, + false)); } } diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/converter/FurnitureConverter.java b/Common/src/main/java/fr/robie/craftengineconverter/common/converter/FurnitureConverter.java index 6efc6a5d..4c7d242d 100644 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/converter/FurnitureConverter.java +++ b/Common/src/main/java/fr/robie/craftengineconverter/common/converter/FurnitureConverter.java @@ -1,6 +1,8 @@ package fr.robie.craftengineconverter.common.converter; +import com.google.gson.Gson; import fr.robie.craftengineconverter.api.enums.Plugins; +import fr.robie.craftengineconverter.api.history.EntityHistory; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import net.momirealms.craftengine.bukkit.api.CraftEngineFurniture; import net.momirealms.craftengine.core.util.Key; @@ -8,21 +10,36 @@ import org.bukkit.entity.Entity; import org.jetbrains.annotations.Nullable; +import java.util.Collection; +import java.util.HashSet; import java.util.Set; +import java.util.function.Predicate; public abstract class FurnitureConverter extends ObjectConverter { public FurnitureConverter(CraftEngineConverterPlugin plugin, Plugins pluginType) { super(plugin, pluginType); } - protected void executeFurnitureConversion(Location entityLoc, Set processed, ConversionCounter counter) { + /** Converts whatever adjoins furniture that was just converted, within the configured budget. */ + protected void propagateFrom(Location origin) { + ConversionCounter counter = this.propagationCounter(); + if (counter == null) { + return; + } + + Set processed = new HashSet<>(); + processed.add(BlockKey.of(origin)); + this.executeFurnitureConversion(origin, processed, counter); + } + + protected void executeFurnitureConversion(Location entityLoc, Set processed, ConversionCounter counter) { for (int[] offset : this.ADJACENT_OFFSETS) { if (counter.hasReachedLimit()) { return; } Entity furnitureEntityAt = this.getFurnitureEntityAt(entityLoc.clone().add(offset[0], offset[1], offset[2])); Location adjacentLoc = (furnitureEntityAt == null ? entityLoc.clone().add(offset[0], offset[1], offset[2]) : furnitureEntityAt.getLocation()).add(0, -0.5, 0); - if (!adjacentLoc.isChunkLoaded() || !processed.add(adjacentLoc)) { + if (!adjacentLoc.isChunkLoaded() || !processed.add(BlockKey.of(adjacentLoc))) { continue; } if (!this.isFurnitureAt(adjacentLoc)) { @@ -32,7 +49,10 @@ protected void executeFurnitureConversion(Location entityLoc, Set proc if (newName == null || !this.isRegistered(newName)) { continue; } - String entityNBT = furnitureEntityAt.getAsString(); + // isFurnitureAt can be true where no entity was found - Nexo answers it from the barrier blocks, and + // the probe happens half a block above adjacentLoc - so the furniture is still converted, just without + // the snapshot that would let it be restored. + String entityNBT = furnitureEntityAt == null ? null : furnitureEntityAt.getAsString(); if (this.removeFurnitureAt(adjacentLoc)) { this.placeFurniture(newName, adjacentLoc, entityNBT); counter.increment(); @@ -46,6 +66,32 @@ public boolean isRegistered(String itemId) { return CraftEngineFurniture.byId(Key.from(itemId)) != null; } + /** How far around a probe point the hooks look for the entity that carries a piece of furniture. */ + protected static final double FURNITURE_SEARCH_RADIUS = 1.0; + + /** + * The candidate closest to {@code location}, rather than whichever the world happened to return first. + *

+ * The search box is a block wide in every direction, so a neighbouring piece of furniture is just as likely to + * be inside it as the one actually being asked about - and picking the wrong one converts the wrong furniture. + */ + @Nullable + protected static Entity nearest(Location location, Collection candidates, Predicate accepted) { + Entity nearest = null; + double nearestDistance = Double.MAX_VALUE; + for (Entity candidate : candidates) { + if (!accepted.test(candidate)) { + continue; + } + double distance = candidate.getLocation().distanceSquared(location); + if (distance < nearestDistance) { + nearestDistance = distance; + nearest = candidate; + } + } + return nearest; + } + public abstract Entity getFurnitureEntityAt(Location location); public abstract boolean isFurnitureAt(Location location); @@ -56,6 +102,14 @@ public boolean isRegistered(String itemId) { public void placeFurniture(String itemId, Location location, @Nullable String entityNBT) { this.plugin.getPlacementTracker().placeFurniture(itemId, location); + if (entityNBT == null) { + return; + } + + // Callers place furniture half a block below the entity it replaces; history stores where the entity was. + Location entityLocation = location.clone().add(0, 0.5, 0); + this.serverProfile.addEntityHistory( + new EntityHistory(null, new Gson().toJson(entityLocation.serialize()), entityNBT, false)); } public static boolean isRegisteredStatic(String itemId) { diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/converter/ObjectConverter.java b/Common/src/main/java/fr/robie/craftengineconverter/common/converter/ObjectConverter.java index d5905fc5..bcd556d5 100644 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/converter/ObjectConverter.java +++ b/Common/src/main/java/fr/robie/craftengineconverter/common/converter/ObjectConverter.java @@ -1,9 +1,14 @@ package fr.robie.craftengineconverter.common.converter; +import fr.robie.craftengineconverter.api.configuration.Configuration; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.enums.Plugins; import fr.robie.craftengineconverter.api.profile.ServerProfile; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.PluginNameMapper; +import org.bukkit.Location; +import org.bukkit.World; +import org.jetbrains.annotations.Nullable; public abstract class ObjectConverter { protected final CraftEngineConverterPlugin plugin; @@ -32,6 +37,36 @@ public String getNewName(String oldName) { public abstract boolean isRegistered(String itemId); + /** + * A budget for one interaction's propagation, or null when it should not propagate at all. The clicked object is + * already converted by the time this is asked for, which is why the budget is one less than the configured limit. + */ + @Nullable + protected ConversionCounter propagationCounter() { + if (!Configuration.get(Keys.ALLOW_BLOCK_CONVERSION_PROPAGATION)) { + return null; + } + int limit = Configuration.get(Keys.MAX_BLOCK_CONVERSION_PROPAGATION_LIMIT); + return limit > 1 ? new ConversionCounter(limit - 1) : null; + } + + /** + * Identifies a position by the block it falls in. + *

+ * Propagation has to remember where it has been, and {@link Location} cannot do that job: it compares exact + * coordinates, and the same piece of furniture is reached both through its entity's own fractional position and + * through a whole-block offset from a neighbour. Those two never compare equal, so a Location-keyed set lets the + * walk revisit the same furniture over and over until the conversion budget runs out. + */ + protected record BlockKey(String world, int x, int y, int z) { + + protected static BlockKey of(Location location) { + World world = location.getWorld(); + return new BlockKey(world == null ? "" : world.getName(), + location.getBlockX(), location.getBlockY(), location.getBlockZ()); + } + } + protected static class ConversionCounter { private final int maxConversions; private int conversions = 0; diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/permission/Permission.java b/Common/src/main/java/fr/robie/craftengineconverter/common/permission/Permission.java index a42397e1..7f29714b 100644 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/permission/Permission.java +++ b/Common/src/main/java/fr/robie/craftengineconverter/common/permission/Permission.java @@ -17,6 +17,7 @@ public enum Permission { ITEMSADDER_BLOCK_INTERACT_CONVERSION("Allows the user to convert ItemsAdder blocks on interaction"), ITEMSADDER_FURNITURE_INTERACT_CONVERSION("Allows the user to convert ItemsAdder furniture on interaction"); + private final String description; private final String[] args; diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/records/ChunkPosition.java b/Common/src/main/java/fr/robie/craftengineconverter/common/records/ChunkPosition.java deleted file mode 100644 index 9ac9839e..00000000 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/records/ChunkPosition.java +++ /dev/null @@ -1,20 +0,0 @@ -package fr.robie.craftengineconverter.common.records; - -public record ChunkPosition(String worldName, int x, int z) { - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || this.getClass() != o.getClass()) { - return false; - } - ChunkPosition that = (ChunkPosition) o; - return this.x == that.x && this.z == that.z && this.worldName.equals(that.worldName); - } - - @Override - public int hashCode() { - return this.worldName.hashCode() * 31 * 31 + this.x * 31 + this.z; - } -} \ No newline at end of file diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/scanner/BlockStateMappingScanner.java b/Common/src/main/java/fr/robie/craftengineconverter/common/scanner/BlockStateMappingScanner.java index 230e33a4..3e3f3799 100644 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/scanner/BlockStateMappingScanner.java +++ b/Common/src/main/java/fr/robie/craftengineconverter/common/scanner/BlockStateMappingScanner.java @@ -1,7 +1,8 @@ package fr.robie.craftengineconverter.common.scanner; import fr.robie.craftengineconverter.api.enums.CraftEngineBlockState; -import fr.robie.craftengineconverter.common.utils.SnakeUtils; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.data.BlockData; @@ -89,17 +90,14 @@ private void scanDirectory(File dir) { } private void processFile(File file) { - SnakeUtils yaml = SnakeUtils.loadSmart(file); - if (yaml == null) { - return; - } + YamlConfiguration configuration = YamlConfiguration.loadConfiguration(file); for (String mappingKey : MAPPING_KEYS) { - Map mappings = yaml.getMap(mappingKey); - if (mappings == null) { - continue; + ConfigurationSection configurationSection = configuration.getConfigurationSection(mappingKey); + if (configurationSection != null) { + Map mappings = configurationSection.getValues(true); + this.processMappings(mappings); } - this.processMappings(mappings); } } diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/SnakeUtils.java b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/SnakeUtils.java deleted file mode 100644 index e91cdbe7..00000000 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/SnakeUtils.java +++ /dev/null @@ -1,1075 +0,0 @@ -package fr.robie.craftengineconverter.common.utils; - - -import fr.robie.craftengineconverter.common.utils.directive.SmartConstructor; -import fr.robie.messageflow.logger.Logger; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.LoaderOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.representer.Representer; - -import java.io.*; -import java.util.*; -import java.util.regex.Pattern; - -/** - * SnakeUtils - A utility class for managing YAML files with convenient access methods. - *

- * This class provides a fluent API for reading, writing, and manipulating YAML data - * with support for nested keys using dot notation (e.g., "section.subsection.key"). - *

- * Features: - * - Load and save YAML files - * - Navigate nested structures with dot notation - * - Type-safe getters for common data types (String, int, double, boolean) - * - Section management (get, create, update sections) - * - Data manipulation (add, remove, merge, clone) - * - Auto-save capability - * - Implements AutoCloseable for try-with-resources support - *

- * Example usage: - *

- * try (SnakeUtils yaml = new SnakeUtils(new File("config.yml"), true)) {
- *     yaml.addData("server.port", 8080);
- *     String host = yaml.getString("server.host", "localhost");
- *     SnakeUtils dbSection = yaml.getOrCreateSection("database");
- *     // Auto-saved on close
- * }
- * 
- * - * @author Robie - * @version 1.0 - */ -public class SnakeUtils implements AutoCloseable { - private final File targetFile; - private final Map data; - private final boolean autoSave; - - /** - * Creates a new SnakeUtils instance from a YAML file. - * - * @param targetFile The YAML file to load. If the file doesn't exist or is empty, - * an empty data structure will be initialized - * @param autoSave If true, changes will be automatically saved when close() is called. - * Useful with try-with-resources pattern - * @throws IOException If the file cannot be read - */ - public SnakeUtils(@NotNull File targetFile, boolean autoSave) throws IOException { - this.targetFile = targetFile; - Yaml yaml = new Yaml(); - Map loadedData; - try (FileInputStream fis = new FileInputStream(targetFile)) { - loadedData = yaml.load(fis); - } - this.data = (loadedData != null) ? loadedData : new LinkedHashMap<>(); - this.autoSave = autoSave; - } - - /** - * Creates a new SnakeUtils instance from a YAML file with auto-save disabled. - * - * @param targetFile The YAML file to load. If the file doesn't exist or is empty, - * an empty data structure will be initialized - * @throws IOException If the file cannot be read - */ - public SnakeUtils(@NotNull File targetFile) throws IOException { - this(targetFile, false); - } - - public SnakeUtils(@NotNull InputStream inputStream) throws IOException { - Yaml yaml = new Yaml(); - Map loadedData = yaml.load(inputStream); - this.data = (loadedData != null) ? loadedData : new LinkedHashMap<>(); - this.targetFile = File.createTempFile("snakeutils_temp_" + System.currentTimeMillis(), ".yml"); - this.autoSave = false; - } - - /** - * Creates a SnakeUtils from a file using the SmartConstructor, - * so all $$ directives are resolved transparently. - * - * @param file the YAML file to load - * @return a SnakeUtils instance with directives applied, or null on error - */ - @Nullable - public static SnakeUtils loadSmart(@NotNull File file) { - try { - LoaderOptions options = new LoaderOptions(); - SmartConstructor constructor = new SmartConstructor(options); - DumperOptions dumper = new DumperOptions(); - dumper.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(constructor, new Representer(dumper), dumper); - try (FileInputStream fis = new FileInputStream(file)) { - Map data = yaml.load(fis); - SnakeUtils su = SnakeUtils.createEmpty(file); - su.getData().clear(); - if (data != null) { - su.getData().putAll(data); - } - return su; - } - } catch (IOException e) { - Logger.error("Failed to load smart YAML: " + file, e); - return null; - } - } - - /** - * Adds or updates data at the specified key path using dot notation. - * Creates nested sections as needed. - *

- * Example: - *

-     * addData("server.database.host", "localhost");
-     * // Creates: server -> database -> host: "localhost"
-     * 
- * - * @param key The key path with dot notation (e.g., "section.subsection.key") - * @param value The value to store (can be any object, Map, List, etc.) - */ - public void addData(@NotNull String key, @NotNull Object value) { - this.addData(key, value, "."); - } - - /** - * Adds or updates data at the specified key path using a custom delimiter. - * Creates nested sections as needed. - * - * @param key The key path with custom delimiter - * @param value The value to store (can be any object, Map, List, etc.) - * @param delimiter The delimiter to use for splitting the key path (e.g., ".", "/", ":") - */ - public void addData(@NotNull String key, @NotNull Object value, @NotNull String delimiter) { - if (key.isEmpty()) { - return; - } - - String[] keys = key.split(Pattern.quote(delimiter)); - - if (keys.length == 0) { - return; - } - - Map currentMap = this.data; - for (int i = 0; i < keys.length - 1; i++) { - String k = keys[i]; - if (!currentMap.containsKey(k) || !(currentMap.get(k) instanceof Map)) { - currentMap.put(k, new java.util.LinkedHashMap()); - } - //noinspection unchecked - currentMap = (Map) currentMap.get(k); - } - currentMap.put(keys[keys.length - 1], value); - } - - /** - * Gets the raw data Map containing all YAML data. - * Modifications to this map will affect the underlying data. - * - * @return The data Map (never null, but may be empty) - */ - public Map getData() { - return this.data; - } - - /** - * Gets the target file associated with this SnakeUtils instance. - * - * @return The target file for save operations - */ - public File getTargetFile() { - return this.targetFile; - } - - /** - * Retrieves a value from the data using a delimited key path. - * Internal method supporting custom delimiters. - * - * @param key The key path with delimiter (e.g., "section.subsection.key") - * @param delimiter The delimiter to use for splitting the key path - * @return The value found, or null if absent or path is invalid - */ - @Nullable - private Object getValue(@NotNull String key, @NotNull String delimiter) { - if (key.isEmpty() || this.data == null) { - return null; - } - - String[] keys = key.split(Pattern.quote(delimiter)); - - if (keys.length == 0) { - return null; - } - - Map currentMap = this.data; - - for (int i = 0; i < keys.length - 1; i++) { - String k = keys[i]; - if (!currentMap.containsKey(k) || !(currentMap.get(k) instanceof Map)) { - return null; - } - //noinspection unchecked - currentMap = (Map) currentMap.get(k); - } - - return currentMap.get(keys[keys.length - 1]); - } - - /** - * Retrieves a value from the data using dot notation. - * - * @param key The key path with dot notation (e.g., "section.subsection.key") - * @return The value found, or null if absent or path is invalid - */ - @Nullable - private Object getValue(@NotNull String key) { - return this.getValue(key, "."); - } - - @NotNull - public Object getObject(@NotNull String key) { - return this.getValue(key); - } - - /** - * Retrieves an integer value from the specified key path. - * Returns 0 if the value is absent or cannot be parsed as an integer. - * - * @param key The key path with dot notation - * @return The integer value, or 0 if absent/invalid - */ - public int getInt(@NotNull String key) { - return this.getInt(key, 0); - } - - /** - * Retrieves an integer value from the specified key path with a default value. - * Attempts to parse the value as an integer if it's not a Number type. - * - * @param key The key path with dot notation - * @param defaultValue The value to return if the key doesn't exist or cannot be parsed - * @return The integer value, or defaultValue if absent/invalid - */ - public int getInt(@NotNull String key, int defaultValue) { - Object value = this.getValue(key); - if (value == null) { - return defaultValue; - } - - if (value instanceof Number) { - return ((Number) value).intValue(); - } - - try { - return Integer.parseInt(value.toString()); - } catch (NumberFormatException e) { - return defaultValue; - } - } - - /** - * Retrieves a double value from the specified key path. - * Returns 0.0 if the value is absent or cannot be parsed as a double. - * - * @param key The key path with dot notation - * @return The double value, or 0.0 if absent/invalid - */ - public double getDouble(@NotNull String key) { - return this.getDouble(key, 0.0); - } - - /** - * Retrieves a double value from the specified key path with a default value. - * Attempts to parse the value as a double if it's not a Number type. - * - * @param key The key path with dot notation - * @param defaultValue The value to return if the key doesn't exist or cannot be parsed - * @return The double value, or defaultValue if absent/invalid - */ - public double getDouble(@NotNull String key, double defaultValue) { - Object value = this.getValue(key); - if (value == null) { - return defaultValue; - } - - if (value instanceof Number) { - return ((Number) value).doubleValue(); - } - - try { - return Double.parseDouble(value.toString()); - } catch (NumberFormatException e) { - return defaultValue; - } - } - - /** - * Retrieves a String value from the specified key path. - * Returns null if the value is absent. Converts any non-null value to String. - * - * @param key The key path with dot notation - * @return The String value, or null if absent - */ - @Nullable - public String getString(@NotNull String key) { - return this.getString(key, null); - } - - /** - * Retrieves a String value from the specified key path with a default value. - * Converts any non-null value to String using toString(). - * - * @param key The key path with dot notation - * @param defaultValue The value to return if the key doesn't exist - * @return The String value, or defaultValue if absent - */ - @Nullable - public String getString(@NotNull String key, @Nullable String defaultValue) { - Object value = this.getValue(key); - return (value != null) ? value.toString() : defaultValue; - } - - /** - * Retrieves a boolean value from the specified key path. - * Returns false if the value is absent or cannot be parsed as a boolean. - * - * @param key The key path with dot notation - * @return The boolean value, or false if absent/invalid - */ - public boolean getBoolean(@NotNull String key) { - return this.getBoolean(key, false); - } - - /** - * Retrieves a boolean value from the specified key path with a default value. - * Attempts to parse the value as a boolean using Boolean.parseBoolean() if not a Boolean type. - * - * @param key The key path with dot notation - * @param defaultValue The value to return if the key doesn't exist - * @return The boolean value, or defaultValue if absent - */ - public boolean getBoolean(@NotNull String key, boolean defaultValue) { - Object value = this.getValue(key); - if (value == null) { - return defaultValue; - } - - if (value instanceof Boolean) { - return (Boolean) value; - } - - return Boolean.parseBoolean(value.toString()); - } - - /** - * Retrieves a Map value from the specified key path. - * This is useful for accessing nested sections as raw Map objects. - * - * @param key The key path with dot notation - * @return The Map value, or null if absent or not a Map type - */ - @SuppressWarnings("unchecked") - @Nullable - public Map getMap(@NotNull String key) { - Object value = this.getValue(key); - return (value instanceof Map) ? (Map) value : null; - } - - /** - * Retrieves a List of Maps from the specified key path. - * This is useful for accessing lists of complex objects stored as maps. - *

- * Example YAML: - *

-     * players:
-     *   - name: John
-     *     score: 100
-     *   - name: Jane
-     *     score: 200
-     * 
- *

- * Usage: - *

-     * List<Map<String, Object>> players = config.getListMap("players");
-     * if (players != null) {
-     *     for (Map<String, Object> player : players) {
-     *         String name = (String) player.get("name");
-     *         Integer score = (Integer) player.get("score");
-     *     }
-     * }
-     * 
- * - * @param key The key path with dot notation - * @return The List of Maps, or null if absent, not a List, or contains non-Map elements - */ - @SuppressWarnings("unchecked") - @NotNull - public List> getListMap(@NotNull String key) { - Object value = this.getValue(key); - if (!(value instanceof List list)) { - return new ArrayList<>(); - } - - List> result = new ArrayList<>(); - - for (Object item : list) { - if (!(item instanceof Map)) { - return new ArrayList<>(); - } - result.add((Map) item); - } - - return result; - } - - /** - * Retrieves a subsection as a new SnakeUtils instance. - * This allows you to work directly with a nested section as if it were a separate YAML file. - * The returned SnakeUtils is independent and backed by a temporary file. - *

- * Example: - *

-     * SnakeUtils config = new SnakeUtils(new File("config.yml"));
-     * SnakeUtils dbSection = config.getSection("database");
-     * if (dbSection != null) {
-     *     String host = dbSection.getString("host");
-     * }
-     * 
- * - * @param key The key path to the section (e.g., "database" or "server.database") - * @return A new SnakeUtils instance for the section, or null if the section doesn't exist or isn't a Map - */ - @Nullable - public SnakeUtils getSection(@NotNull String key) { - Map sectionData = this.getMap(key); - if (sectionData == null) { - return null; - } - - try { - File tempFile = File.createTempFile("snakeutils_section_" + key.replace(".", "_"), ".yml"); - - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - - try (FileWriter writer = new FileWriter(tempFile)) { - yaml.dump(sectionData, writer); - } - - SnakeUtils sectionUtils = new SnakeUtils(tempFile); - - tempFile.deleteOnExit(); - - return sectionUtils; - } catch (IOException e) { - Logger.error("Failed to create section SnakeUtils for key: " + key, e); - return null; - } - } - - /** - * Retrieves a subsection as a SnakeUtils instance, creating it if it doesn't exist. - * This is useful when you want to ensure a section exists before working with it. - *

- * Example: - *

-     * SnakeUtils config = new SnakeUtils(new File("config.yml"));
-     * SnakeUtils dbSection = config.getOrCreateSection("database");
-     * dbSection.addData("host", "localhost");
-     * dbSection.addData("port", 3306);
-     * config.setSection("database", dbSection); // Sync changes back
-     * 
- * - * @param key The key path to the section (e.g., "database" or "config.database") - * @return A SnakeUtils instance for the section (never null) - * @throws RuntimeException if the section cannot be created - */ - @NotNull - public SnakeUtils getOrCreateSection(@NotNull String key) { - SnakeUtils section = this.getSection(key); - if (section != null) { - return section; - } - - this.addData(key, new java.util.LinkedHashMap()); - - section = this.getSection(key); - if (section == null) { - throw new RuntimeException("Failed to create section: " + key); - } - - return section; - } - - /** - * Updates a section with data from another SnakeUtils instance. - * This completely replaces the existing section with the new data. - *

- * Use this to sync changes made to a section obtained via getSection() or getOrCreateSection(). - *

- * Example: - *

-     * SnakeUtils section = config.getOrCreateSection("player");
-     * section.addData("name", "John");
-     * config.setSection("player", section); // Apply changes to parent
-     * 
- * - * @param key The key path to the section (e.g., "database" or "config.database") - * @param section The SnakeUtils instance containing the new data - */ - public void setSection(@NotNull String key, @NotNull SnakeUtils section) { - this.addData(key, section.getData()); - } - - /** - * Updates a section with data from a Map. - * This completely replaces the existing section with the new data. - * - * @param key The key path to the section (e.g., "database" or "config.database") - * @param sectionData The Map containing the new data - */ - public void setSection(@NotNull String key, @NotNull Map sectionData) { - this.addData(key, sectionData); - } - - /** - * Retrieves a List value from the specified key path. - * Useful for accessing YAML arrays/lists. - *

- * Example: - *

-     * List<Object> items = yaml.getList("server.allowed-ips");
-     * if (items != null) {
-     *     for (Object item : items) {
-     *         System.out.println(item);
-     *     }
-     * }
-     * 
- * - * @param key The key path with dot notation - * @return The List value, or null if absent or not a List type - */ - @SuppressWarnings("unchecked") - @Nullable - public List getList(@NotNull String key) { - Object value = this.getValue(key); - return (value instanceof List) ? (List) value : null; - } - - @NotNull - public List getStringList(@NotNull String key) { - List rawList = this.getList(key); - List stringList = new ArrayList<>(); - if (rawList != null) { - for (Object item : rawList) { - if (item != null) { - stringList.add(item.toString()); - } - } - } - return stringList; - } - - /** - * Checks if a key exists in the data. - * Supports nested keys with dot notation. - * - * @param key The key path with dot notation (e.g., "section.subsection.key") - * @return true if the key exists, false otherwise - */ - public boolean contains(@NotNull String key) { - return this.getValue(key) != null; - } - - /** - * Checks if a key exists in the data (alias of contains). - * Supports nested keys with dot notation. - * - * @param key The key path with dot notation (e.g., "section.subsection.key") - * @return true if the key exists, false otherwise - */ - public boolean containsKey(@NotNull String key) { - return this.contains(key); - } - - /** - * Checks if the data structure is empty (no root-level keys). - * - * @return true if no data is present, false otherwise - */ - public boolean isEmpty() { - return this.data == null || this.data.isEmpty(); - } - - /** - * Returns the number of keys at the root level. - * Does not count nested keys. - * - * @return The number of root-level keys - */ - public int size() { - return (this.data != null) ? this.data.size() : 0; - } - - /** - * Clears all data from this SnakeUtils instance. - * After calling this, the data structure will be empty. - */ - public void clear() { - if (this.data != null) { - this.data.clear(); - } - } - - /** - * Retrieves all keys at the root level. - *

- * Example: - *

-     * Set<String> keys = yaml.getKeys();
-     * for (String key : keys) {
-     *     System.out.println(key);
-     * }
-     * 
- * - * @return Set of root-level keys (never null, but may be empty) - */ - @NotNull - public Set getKeys() { - return (this.data != null) ? this.data.keySet() : Collections.emptySet(); - } - - /** - * Retrieves all keys from a specific section. - * Useful for iterating over nested sections. - *

- * Example: - *

-     * Set<String> dbKeys = yaml.getKeys("database");
-     * for (String key : dbKeys) {
-     *     System.out.println(key + ": " + yaml.getString("database." + key));
-     * }
-     * 
- * - * @param key The key path to the section (e.g., "database" or "config.database") - * @return Set of keys in the section (never null, but may be empty if section doesn't exist) - */ - @NotNull - public Set getKeys(@NotNull String key) { - Map section = this.getMap(key); - return (section != null) ? section.keySet() : Collections.emptySet(); - } - - /** - * Removes a key and its value from the data. - * Supports nested keys with dot notation. - *

- * Example: - *

-     * yaml.removeData("database.password"); // Removes only the password key
-     * yaml.removeData("database"); // Removes the entire database section
-     * 
- * - * @param key The key path with dot notation (e.g., "section.subsection.key") - * @return true if the key was removed, false if it didn't exist - */ - public boolean removeData(@NotNull String key) { - return this.removeData(key, "."); - } - - /** - * Removes a key and its value from the data using a custom delimiter. - * - * @param key The key path with custom delimiter - * @param delimiter The delimiter to use for splitting the key path - * @return true if the key was removed, false if it didn't exist - */ - public boolean removeData(@NotNull String key, @NotNull String delimiter) { - if (key.isEmpty() || this.data == null) { - return false; - } - - String[] keys = key.split(Pattern.quote(delimiter)); - - if (keys.length == 0) { - return false; - } - - Map currentMap = this.data; - - for (int i = 0; i < keys.length - 1; i++) { - String k = keys[i]; - if (!currentMap.containsKey(k) || !(currentMap.get(k) instanceof Map)) { - return false; - } - //noinspection unchecked - currentMap = (Map) currentMap.get(k); - } - - return currentMap.remove(keys[keys.length - 1]) != null; - } - - /** - * Saves the current data to the target file. - * Creates parent directories if they don't exist. - * - * @throws IOException If the file cannot be written - */ - public void save() throws IOException { - this.save(this.targetFile); - } - - /** - * Saves the current data to a specific file. - * Creates parent directories if they don't exist. - * Useful for saving to a different location than the original file. - * - * @param file The destination file for saving - * @throws IOException If the file cannot be written - */ - public void save(@NotNull File file) throws IOException { - File parentDir = file.getParentFile(); - if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs()) { - throw new IOException("Failed to create parent directories for file: " + file); - } - - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - - try (FileWriter writer = new FileWriter(file)) { - yaml.dump(this.data, writer); - } - } - - /** - * Reloads the data from the target file. - * Discards any unsaved changes and reloads from disk. - * Useful for detecting external changes to the file. - * - * @throws IOException If the file cannot be read - */ - public void reload() throws IOException { - Yaml yaml = new Yaml(); - try (FileInputStream fis = new FileInputStream(this.targetFile)) { - Map newData = yaml.load(fis); - this.data.clear(); - if (newData != null) { - this.data.putAll(newData); - } - } - } - - /** - * Merges data from another SnakeUtils instance into this one. - * Existing values are overwritten by the new values. - * Nested Maps are merged recursively. - *

- * Example: - *

-     * SnakeUtils defaults = SnakeUtils.load("defaults.yml");
-     * SnakeUtils user = SnakeUtils.load("user.yml");
-     * defaults.merge(user); // User settings override defaults
-     * 
- * - * @param other The SnakeUtils instance to merge from - */ - public void merge(@NotNull SnakeUtils other) { - if (other.data != null) { - this.mergeMap(this.data, other.data); - } - } - - /** - * Merges a Map into the current data. - * Existing values are overwritten by the new values. - * Nested Maps are merged recursively. - * - * @param dataToMerge The Map to merge into the current data - */ - public void merge(@NotNull Map dataToMerge) { - this.mergeMap(this.data, dataToMerge); - } - - /** - * Recursively merges two Maps. - * When both target and source contain a Map at the same key, they are merged recursively. - * Otherwise, the source value overwrites the target value. - * - * @param target The target Map to merge into - * @param source The source Map to merge from - */ - @SuppressWarnings("unchecked") - private void mergeMap(Map target, Map source) { - for (Map.Entry entry : source.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - - if (value instanceof Map && target.get(key) instanceof Map) { - this.mergeMap((Map) target.get(key), (Map) value); - } else { - target.put(key, value); - } - } - } - - /** - * Copies all data to another SnakeUtils instance. - * Clears the target's data first, then copies all data from this instance. - * - * @param target The destination SnakeUtils instance - */ - public void copyTo(@NotNull SnakeUtils target) { - target.data.clear(); - target.data.putAll(this.data); - } - - /** - * Creates a deep clone of the data Map. - * All nested Maps and Lists are recursively cloned. - * Modifications to the clone will not affect the original data. - * - * @return A new Map containing a deep copy of all data - */ - @NotNull - public Map clone() { - return this.deepClone(this.data); - } - - /** - * Recursively clones a Map and all its nested structures. - * Creates new instances of Maps and Lists to ensure deep copying. - * - * @param original The original Map to clone - * @return A deep copy of the original Map - */ - @SuppressWarnings("unchecked") - private Map deepClone(Map original) { - Map copy = new java.util.LinkedHashMap<>(); - for (Map.Entry entry : original.entrySet()) { - Object value = entry.getValue(); - if (value instanceof Map) { - copy.put(entry.getKey(), this.deepClone((Map) value)); - } else if (value instanceof List) { - copy.put(entry.getKey(), new java.util.ArrayList<>((List) value)); - } else { - copy.put(entry.getKey(), value); - } - } - return copy; - } - - /** - * Converts the current data to a YAML-formatted string. - * Useful for debugging or displaying the data without writing to a file. - *

- * Example: - *

-     * SnakeUtils yaml = new SnakeUtils(new File("config.yml"));
-     * System.out.println(yaml.toYamlString());
-     * 
- * - * @return A YAML-formatted string representation of the data - */ - @NotNull - public String toYamlString() { - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - return yaml.dump(this.data); - } - - // =============== STATIC METHODS =============== - - /** - * Creates a new SnakeUtils instance from a YAML file. - * This is a convenient static factory method that handles IOExceptions gracefully. - *

- * Example: - *

-     * SnakeUtils yaml = SnakeUtils.load(new File("config.yml"));
-     * if (yaml != null) {
-     *     // File loaded successfully
-     * }
-     * 
- * - * @param file The YAML file to load - * @return A new SnakeUtils instance, or null if an IOException occurs - */ - @Nullable - public static SnakeUtils load(@NotNull File file) { - try { - return new SnakeUtils(file); - } catch (IOException e) { - Logger.error("Failed to load YAML file: " + file, e); - return null; - } - } - - /** - * Creates a new SnakeUtils instance from a file path string. - * Convenient overload that accepts a String path instead of a File object. - *

- * Example: - *

-     * SnakeUtils yaml = SnakeUtils.load("config.yml");
-     * SnakeUtils yaml2 = SnakeUtils.load("C:/configs/database.yml");
-     * 
- * - * @param filePath The path to the YAML file to load - * @return A new SnakeUtils instance, or null if an IOException occurs - */ - @Nullable - public static SnakeUtils load(@NotNull String filePath) { - return load(new File(filePath)); - } - - @NotNull - public static SnakeUtils createEmpty() { - try { - File tempFile = File.createTempFile("snakeutils_empty_", ".yml"); - try (FileWriter writer = new FileWriter(tempFile)) { - writer.write("{}"); - } - SnakeUtils utils = new SnakeUtils(tempFile); - utils.clear(); - tempFile.deleteOnExit(); - return utils; - } catch (IOException e) { - throw new RuntimeException("Failed to create empty SnakeUtils", e); - } - } - - /** - * Creates an empty SnakeUtils instance with a target file. - * The instance starts with no data, but has a file associated for future saves. - *

- * Example: - *

-     * SnakeUtils yaml = SnakeUtils.createEmpty(new File("new-config.yml"));
-     * yaml.addData("version", "1.0");
-     * yaml.save(); // Saves to new-config.yml
-     * 
- * - * @param targetFile The target file for save operations - * @return A new empty SnakeUtils instance (never null) - * @throws RuntimeException if the empty instance cannot be created - */ - @NotNull - public static SnakeUtils createEmpty(@NotNull File targetFile) { - try { - File parentDir = targetFile.getParentFile(); - if (parentDir != null && !parentDir.exists()) { - if (!parentDir.mkdirs()) { - throw new IOException("Failed to create parent directories for: " + targetFile); - } - } - - if (!targetFile.exists()) { - try (FileWriter writer = new FileWriter(targetFile)) { - writer.write("{}"); - } - } - - SnakeUtils utils = new SnakeUtils(targetFile); - utils.clear(); - return utils; - } catch (IOException e) { - throw new RuntimeException("Failed to create empty SnakeUtils for file: " + targetFile, e); - } - } - - /** - * Saves a Map directly to a YAML file without creating a SnakeUtils instance. - * Useful for one-off saves when you already have a Map of data. - * Creates parent directories if they don't exist. - *

- * Example: - *

-     * Map<String, Object> data = new LinkedHashMap<>();
-     * data.put("key", "value");
-     * boolean success = SnakeUtils.saveToFile(data, new File("output.yml"));
-     * 
- * - * @param data The data Map to save - * @param file The destination file - * @return true if the save was successful, false if an IOException occurred - */ - public static boolean saveToFile(@NotNull Map data, @NotNull File file) { - try { - File parentDir = file.getParentFile(); - if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs()) { - Logger.debug("Failed to create parent directories for file: " + file); - return false; - } - - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - - try (FileWriter writer = new FileWriter(file)) { - yaml.dump(data, writer); - } - return true; - } catch (IOException e) { - Logger.error("Failed to save YAML file: " + file, e); - return false; - } - } - - /** - * Loads a Map directly from a YAML file without creating a SnakeUtils instance. - * Useful for quick reads when you don't need the full SnakeUtils functionality. - *

- * Example: - *

-     * Map<String, Object> data = SnakeUtils.loadFromFile(new File("config.yml"));
-     * if (data != null) {
-     *     String value = (String) data.get("key");
-     * }
-     * 
- * - * @param file The YAML file to load - * @return A Map containing the YAML data, or null if the file doesn't exist or an error occurs - */ - @Nullable - public static Map loadFromFile(@NotNull File file) { - if (!file.exists() || !file.isFile()) { - return null; - } - - try (FileInputStream fis = new FileInputStream(file)) { - Yaml yaml = new Yaml(); - return yaml.load(fis); - } catch (IOException e) { - Logger.error("Failed to load YAML file: " + file, e); - return null; - } - } - - /** - * Closes this SnakeUtils instance and automatically saves if auto-save is enabled. - * This method is called automatically when used with try-with-resources. - *

- * Example: - *

-     * try (SnakeUtils yaml = new SnakeUtils(new File("config.yml"), true)) {
-     *     yaml.addData("key", "value");
-     *     // Auto-saved on close
-     * } catch (Exception e) {
-     *     e.printStackTrace();
-     * }
-     * 
- * - * @throws Exception if save() fails when auto-save is enabled - */ - @Override - public void close() throws Exception { - if (this.autoSave) { - this.save(); - } - } -} diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/KeyDirective.java b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/KeyDirective.java deleted file mode 100644 index 99e1e72f..00000000 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/KeyDirective.java +++ /dev/null @@ -1,17 +0,0 @@ -package fr.robie.craftengineconverter.common.utils.directive; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.yaml.snakeyaml.nodes.Node; - -import java.util.Map; - -public interface KeyDirective { - - boolean matches(@NotNull String key); - - void handleBlockMerge(@NotNull Map targetMap, @NotNull String key, @NotNull Node valueNode, @NotNull SmartConstructor constructor); - - @Nullable - Object handleValueSelect(@NotNull String key, @NotNull Node valueNode, @NotNull SmartConstructor constructor); -} \ No newline at end of file diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/KeyDirectiveRegistry.java b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/KeyDirectiveRegistry.java deleted file mode 100644 index a6d685f6..00000000 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/KeyDirectiveRegistry.java +++ /dev/null @@ -1,35 +0,0 @@ -package fr.robie.craftengineconverter.common.utils.directive; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public final class KeyDirectiveRegistry { - private static final List DIRECTIVES = new ArrayList<>(); - - static { - register(new VersionKeyDirective()); - } - - private KeyDirectiveRegistry() {} - - public static void register(@NotNull KeyDirective directive) { - DIRECTIVES.add(directive); - } - - @NotNull - public static List getAll() { - return Collections.unmodifiableList(DIRECTIVES); - } - - @Nullable - public static KeyDirective findMatch(@NotNull String key) { - for (KeyDirective d : DIRECTIVES) { - if (d.matches(key)) return d; - } - return null; - } -} \ No newline at end of file diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/SmartConstructor.java b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/SmartConstructor.java deleted file mode 100644 index a2078ed8..00000000 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/SmartConstructor.java +++ /dev/null @@ -1,152 +0,0 @@ -package fr.robie.craftengineconverter.common.utils.directive; - -import org.jetbrains.annotations.NotNull; -import org.yaml.snakeyaml.LoaderOptions; -import org.yaml.snakeyaml.constructor.SafeConstructor; -import org.yaml.snakeyaml.nodes.MappingNode; -import org.yaml.snakeyaml.nodes.Node; -import org.yaml.snakeyaml.nodes.NodeTuple; -import org.yaml.snakeyaml.nodes.ScalarNode; - -import java.util.LinkedHashMap; -import java.util.Map; - -public class SmartConstructor extends SafeConstructor { - - private static final String PREFIX = "$$"; - private static final String FALLBACK = "$$fallback"; - - public SmartConstructor(@NotNull LoaderOptions options) { - super(options); - } - - - @Override - public Object constructObject(Node node) { - if (node instanceof MappingNode mn && this.isValueSelectorNode(mn)) { - return this.constructValueSelector(mn); - } - return super.constructObject(node); - } - - @Override - protected Map constructMapping(MappingNode node) { - Map map = new LinkedHashMap<>(); - - for (NodeTuple tuple : node.getValue()) { - if (!(tuple.getKeyNode() instanceof ScalarNode scalarNode)) { - continue; - } - - String key = this.constructScalar(scalarNode); - Node valueNode = tuple.getValueNode(); - - if (key.startsWith(PREFIX)) { - KeyDirective directive = KeyDirectiveRegistry.findMatch(key); - if (directive != null) { - directive.handleBlockMerge(map, key, valueNode, this); - } - } else if (key.contains("::")) { - this.processDeepKey(map, key, valueNode); - } else { - Object value = this.constructObjectPublic(valueNode); - this.setWithMerge(map, key, value, key); - } - } - - return map; - } - - private boolean isValueSelectorNode(MappingNode node) { - if (node.getValue().isEmpty()) { - return false; - } - for (NodeTuple t : node.getValue()) { - if (!(t.getKeyNode() instanceof ScalarNode sn)) { - return false; - } - if (!sn.getValue().startsWith(PREFIX)) { - return false; - } - } - return true; - } - - @SuppressWarnings("unchecked") - private void processDeepKey(Map map, String fullKey, Node valueNode) { - String[] parts = fullKey.split("::"); - Map current = map; - - for (int i = 0; i < parts.length - 1; i++) { - Object existing = current.get(parts[i]); - if (existing instanceof Map) { - current = (Map) existing; - } else { - Map nested = new LinkedHashMap<>(); - current.put(parts[i], nested); - current = nested; - } - } - - String finalKey = parts[parts.length - 1]; - Object value = this.constructObjectPublic(valueNode); - this.setWithMerge(current, finalKey, value, fullKey); - } - - private Object constructValueSelector(MappingNode node) { - Object fallback = null; - Object matched = null; - - for (NodeTuple tuple : node.getValue()) { - String key = this.constructScalar((ScalarNode) tuple.getKeyNode()); - - if (FALLBACK.equals(key)) { - fallback = this.constructObjectPublic(tuple.getValueNode()); - continue; - } - - KeyDirective directive = KeyDirectiveRegistry.findMatch(key); - if (directive != null) { - Object candidate = directive.handleValueSelect(key, tuple.getValueNode(), this); - if (candidate != null) { - matched = candidate; - } - } - } - - return matched != null ? matched : fallback; - } - - public Object constructObjectPublic(@NotNull Node node) { - return this.constructObject(node); - } - - @SuppressWarnings("unchecked") - public void mergeInto(@NotNull Map target, @NotNull Map source, @NotNull String parentPath) { - for (Map.Entry e : source.entrySet()) { - String key = e.getKey().toString(); - Object srcVal = e.getValue(); - Object tgtVal = target.get(key); - - String path = parentPath.isEmpty() ? key : parentPath + "." + key; - - if (tgtVal == null) { - target.put(key, srcVal); - } else if (tgtVal instanceof Map && srcVal instanceof Map) { - this.mergeInto((Map) tgtVal, (Map) srcVal, path); - } else { - target.put(key, srcVal); - } - } - } - - @SuppressWarnings("unchecked") - private void setWithMerge(Map map, String key, Object value, String path) { - Object existing = map.get(key); - if (existing instanceof Map && value instanceof Map) { - this.mergeInto((Map) existing, (Map) value, path); - } else { - map.put(key, value); - } - } -} \ No newline at end of file diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/VersionKeyDirective.java b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/VersionKeyDirective.java deleted file mode 100644 index 6c054f7b..00000000 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/directive/VersionKeyDirective.java +++ /dev/null @@ -1,110 +0,0 @@ -package fr.robie.craftengineconverter.common.utils.directive; - -import fr.robie.craftengineconverter.common.enums.NmsVersion; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.yaml.snakeyaml.nodes.MappingNode; -import org.yaml.snakeyaml.nodes.Node; - -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class VersionKeyDirective implements KeyDirective { - private static final Pattern VERSION_PATTERN = Pattern.compile("^\\$\\$(>=|<=|>|<|!=|==)?([\\d][\\d.]*)(?:~([\\d][\\d.]*))?(?:#.*)?$"); - - @Override - public boolean matches(@NotNull String key) { - return VERSION_PATTERN.matcher(key).matches(); - } - - @Override - public void handleBlockMerge(@NotNull Map targetMap, @NotNull String key, @NotNull Node valueNode, @NotNull SmartConstructor constructor) { - if (!evaluate(key)) return; - - if (!(valueNode instanceof MappingNode mappingNode)) { - return; - } - - @SuppressWarnings("unchecked") - Map child = (Map) constructor.constructObjectPublic(mappingNode); - constructor.mergeInto(targetMap, child, key); - } - - @Override - @Nullable - public Object handleValueSelect(@NotNull String key, @NotNull Node valueNode, @NotNull SmartConstructor constructor) { - if (!evaluate(key)) return null; - return constructor.constructObjectPublic(valueNode); - } - - private static boolean evaluate(@NotNull String key) { - Matcher m = VERSION_PATTERN.matcher(key); - if (!m.matches()) return false; - - String operator = m.group(1); - String verA = m.group(2); - String verB = m.group(3); - - NmsVersion current = NmsVersion.nmsVersion; - - if (verB != null) { - NmsVersion min = resolve(verA); - NmsVersion max = resolve(verB); - return current.isAtLeast(min) && current.isAtMost(max); - } - - NmsVersion target = resolve(verA); - - if (operator == null || operator.isEmpty()) return current == target; - return switch (operator) { - case ">=" -> current.isAtLeast(target); - case ">" -> current.isNewerThan(target); - case "<=" -> current.isAtMost(target); - case "<" -> current.isOlderThan(target); - case "==" -> current == target; - case "!=" -> current != target; - default -> false; - }; - } - - private static NmsVersion resolve(@NotNull String versionStr) { - Matcher m = Pattern.compile("(\\d+\\.\\d+)(\\.\\d+)?").matcher(versionStr); - if (!m.find()) return NmsVersion.UNKNOWN; - - String base = m.group(1).replace(".", ""); - String patch = m.group(2) != null ? m.group(2).replace(".", "") : "0"; - int target; - try { - target = Integer.parseInt(base + patch); - } catch (NumberFormatException e) { - return NmsVersion.UNKNOWN; - } - - NmsVersion best = NmsVersion.UNKNOWN; - int bestDiff = Integer.MAX_VALUE; - for (NmsVersion v : NmsVersion.values()) { - if (v == NmsVersion.UNKNOWN) continue; - int diff = Math.abs(versionInt(v) - target); - if (diff < bestDiff) { - bestDiff = diff; best = v; - if (diff == 0) - break; - } - } - return best; - } - - private static int versionInt(@NotNull NmsVersion v) { - String name = v.name(); - if (!name.startsWith("V_")) return Integer.MAX_VALUE; - String[] p = name.substring(2).split("_"); - try { - return switch (p.length) { - case 2 -> Integer.parseInt(p[0] + p[1] + "0"); - case 3 -> Integer.parseInt(p[0] + p[1] + p[2]); - default -> Integer.MAX_VALUE; - }; - } catch (NumberFormatException e) { return Integer.MAX_VALUE; } - } -} \ No newline at end of file diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/enums/Billboard.java b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/enums/Billboard.java index 5608d14b..0f239c9f 100644 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/enums/Billboard.java +++ b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/enums/Billboard.java @@ -4,5 +4,5 @@ public enum Billboard { FIXED, VERTICAL, HORIZONTAL, - CENTER; + CENTER } diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/enums/ia/IAModelsKeys.java b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/enums/ia/IAModelsKeys.java index 9b9861d8..f999b110 100644 --- a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/enums/ia/IAModelsKeys.java +++ b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/enums/ia/IAModelsKeys.java @@ -14,22 +14,31 @@ public enum IAModelsKeys { this.keys = keys; } - public String[] getKeys() { - return this.keys; + /** + * Whether the given keys are exactly this model type's key set. + * + *

Several types share the {@code normal} key and have the same key count + * (fishing rod, trident and shield all have two), so a partial match is not + * enough to tell them apart - every key has to be present. + */ + public boolean matches(Collection keysToCheck) { + if (keysToCheck.size() != this.keys.length) { + return false; + } + for (String key : this.keys) { + if (!this.contains(keysToCheck, key)) { + return false; + } + } + return true; } - public boolean containsAny(Collection keysToCheck) { + private boolean contains(Collection keysToCheck, String key) { for (String keyToCheck : keysToCheck) { - for (String key : this.keys) { - if (key.equalsIgnoreCase(keyToCheck)) { - return true; - } + if (key.equalsIgnoreCase(keyToCheck)) { + return true; } } return false; } - - public int getKeysCount() { - return this.keys.length; - } } diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/yaml/directive/PluginKeyDirective.java b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/yaml/directive/PluginKeyDirective.java new file mode 100644 index 00000000..29b36eb8 --- /dev/null +++ b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/yaml/directive/PluginKeyDirective.java @@ -0,0 +1,61 @@ +package fr.robie.craftengineconverter.common.utils.yaml.directive; + +import fr.robie.yamllibrary.constructor.SmartConstructor; +import fr.robie.yamllibrary.directive.KeyDirective; +import org.bukkit.Bukkit; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.Node; + +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class PluginKeyDirective implements KeyDirective { + + private static final Pattern PLUGIN_PATTERN = Pattern.compile("^plugin:(!)?([A-Za-z0-9_]+)(?:#.*)?$"); + + @Override + public boolean matches(@NotNull String key) { + return PLUGIN_PATTERN.matcher(key).matches(); + } + + @Override + public void handleBlockMerge(@NotNull Map targetMap, @NotNull String key, @NotNull Node valueNode, @NotNull SmartConstructor constructor) { + if (!this.evaluate(key)) { + return; + } + + if (!(valueNode instanceof MappingNode mappingNode)) { + return; + } + + @SuppressWarnings("unchecked") + Map child = (Map) constructor.constructObjectPublic(mappingNode); + constructor.mergeInto(targetMap, child, key); + } + + @Override + @Nullable + public Object handleValueSelect(@NotNull String key, @NotNull Node valueNode, @NotNull SmartConstructor constructor) { + if (!this.evaluate(key)) { + return null; + } + return constructor.constructObjectPublic(valueNode); + } + + private boolean evaluate(@NotNull String key) { + Matcher m = PLUGIN_PATTERN.matcher(key); + if (!m.matches()) { + return false; + } + + boolean negate = m.group(1) != null; + String pluginName = m.group(2); + + boolean isEnabled = Bukkit.getPluginManager().isPluginEnabled(pluginName); + + return negate != isEnabled; + } +} diff --git a/Common/src/main/java/fr/robie/craftengineconverter/common/utils/yaml/directive/VersionKeyDirective.java b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/yaml/directive/VersionKeyDirective.java new file mode 100644 index 00000000..cb7c5fc2 --- /dev/null +++ b/Common/src/main/java/fr/robie/craftengineconverter/common/utils/yaml/directive/VersionKeyDirective.java @@ -0,0 +1,80 @@ +package fr.robie.craftengineconverter.common.utils.yaml.directive; + +import fr.robie.craftengineconverter.api.utils.MinecraftVersion; +import fr.robie.yamllibrary.constructor.SmartConstructor; +import fr.robie.yamllibrary.directive.KeyDirective; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.Node; + +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class VersionKeyDirective implements KeyDirective { + private static final Pattern VERSION_PATTERN = Pattern.compile("^(>=|<=|>|<|!=|==)?(\\d[\\d.]*)(?:~(\\d[\\d.]*))?(?:#.*)?$"); + + @Override + public boolean matches(@NotNull String key) { + return VERSION_PATTERN.matcher(key).matches(); + } + + @Override + public void handleBlockMerge(@NotNull Map targetMap, @NotNull String key, @NotNull Node valueNode, @NotNull SmartConstructor constructor) { + if (!evaluate(key)) { + return; + } + + if (!(valueNode instanceof MappingNode mappingNode)) { + return; + } + + @SuppressWarnings("unchecked") + Map child = (Map) constructor.constructObjectPublic(mappingNode); + constructor.mergeInto(targetMap, child, key); + } + + @Override + @Nullable + public Object handleValueSelect(@NotNull String key, @NotNull Node valueNode, @NotNull SmartConstructor constructor) { + if (!evaluate(key)) { + return null; + } + return constructor.constructObjectPublic(valueNode); + } + + private static boolean evaluate(@NotNull String key) { + Matcher m = VERSION_PATTERN.matcher(key); + if (!m.matches()) { + return false; + } + + String operator = m.group(1); + String verA = m.group(2); + String verB = m.group(3); + + MinecraftVersion current = MinecraftVersion.getCurrentVersion(); + + if (verB != null) { + MinecraftVersion min = MinecraftVersion.parse(verA); + MinecraftVersion max = MinecraftVersion.parse(verB); + return current.isAtLeast(min) && current.isAtMost(max); + } + + MinecraftVersion target = MinecraftVersion.parse(verA); + + if (operator == null || operator.isEmpty()) { + return current.equals(target); + } + return switch (operator) { + case ">=" -> current.isAtLeast(target); + case ">" -> current.compareTo(target) > 0; + case "<=" -> current.isAtMost(target); + case "<" -> current.compareTo(target) < 0; + case "==" -> current.equals(target); + case "!=" -> !current.equals(target); + default -> false; + }; + } +} \ No newline at end of file diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md new file mode 100644 index 00000000..b57b11b7 --- /dev/null +++ b/DEVELOPMENT.md @@ -0,0 +1,265 @@ +# Development guide + +The build is Gradle (Kotlin DSL) with a version catalog and convention plugins. Everything below +assumes the wrapper, so no Gradle installation is required. + +``` +CraftEngineConverter/ +├─ settings.gradle.kts module list, plugin repositories, toolchain auto-provisioning +├─ build.gradle.kts root (intentionally almost empty) +├─ gradle.properties group/version, plugin metadata, runServer knobs +├─ gradle/libs.versions.toml every dependency and plugin version +├─ gradle/gradle-daemon-jvm.properties pins the Gradle daemon to Java 21 +├─ build-logic/ convention plugins (included build) +│ └─ src/main/kotlin/ +│ ├─ catalog.kt version-catalog access helper +│ ├─ craftengineconverter.java-conventions.gradle.kts toolchain, encoding, tests, REPOSITORIES +│ └─ craftengineconverter.hook-conventions.gradle.kts shared deps for Hooks/* +├─ API/ Common/ Hooks/{BOM,PacketEvent,PlaceholderAPI,Nexo,ItemsAdder}/ Plugin/ +``` + +## Everyday commands + +| Command | What it does | +| --- | --- | +| `./gradlew build` | Compiles everything, runs the tests, produces `Plugin/build/libs/CraftEngineConverter-.jar` | +| `./gradlew :Plugin:shadowJar` | Just the shaded plugin jar | +| `./gradlew runServer` | Downloads Paper, creates `run/`, installs the plugin, starts the server | +| `./gradlew test` | Tests only | +| `./gradlew build -PdevBuild` | Same as the old `-P dev-build` Maven profile: appends `-Dev` to the jar version | +| `./gradlew build -PdevSuffix=-RC1` | Arbitrary version suffix | +| `./gradlew cleanPaperCache` | Drops run-paper's cached Paper jars | + +## The development server + +`./gradlew runServer` needs nothing installed: + +1. run-paper resolves the latest Paper build for the Minecraft version of the paperweight dev + bundle, so the test server can never drift away from the API the plugin compiles against. +2. It creates `run/` (git-ignored) and starts the server with `--nogui`. +3. The freshly built shaded jar is handed to Paper via `-add-plugin=...`, so nothing is copied into + a plugins directory and there is no stale-jar problem. +4. `-Ddisable.watchdog=true` is set for you, so sitting on a breakpoint does not kill the server. + +### Manual steps, once + +Two things are still manual, once: + +- **EULA.** The first run stops and writes `run/eula.txt`. Read it and set `eula=true` yourself - + the build will not accept Mojang's licence on your behalf. +- **CraftEngine.** It is a hard dependency (`required: true` in `paper-plugin.yml`) and is not + publicly downloadable, so drop its jar into `run/plugins/` once. Optional soft dependencies + (PlaceholderAPI, packetevents) can be fetched automatically - see the commented `downloadPlugins` + block at the bottom of [Plugin/build.gradle.kts](Plugin/build.gradle.kts). + +### JVM arguments + +All configured from `gradle.properties`, or per invocation: + +```bash +./gradlew runServer -PrunServer.jvmArgs="-Xms4G -Xmx4G -XX:+UseZGC" +``` + +| Property | Purpose | +| --- | --- | +| `runServer.jvmArgs` | Full JVM argument list for the dev server | +| `runServer.javaAgent` | Path to a `-javaagent:` jar (HotswapAgent, profiler, ...) | +| `runServer.javaVersion` | Run the server on a different JDK than the compile toolchain | +| `runServer.javaVendor` | Toolchain vendor filter, e.g. `JETBRAINS` | + +## Debugging in IntelliJ IDEA + +1. Open the project directory. IntelliJ detects `settings.gradle.kts` and imports the Gradle build, + including `build-logic` as a separate module. +2. In the Gradle tool window, open **CraftEngineConverter → Tasks → run paper → runServer**, + right-click and choose **Debug 'runServer'**. IntelliJ attaches the debugger to the forked server + JVM automatically - there is no remote-debug configuration or `-agentlib` flag to set up. +3. In **Settings → Build, Execution, Deployment → Compiler**, enable **Build project automatically**. + +The intended loop: + +``` +Debug runServer → server starts → edit Java → Ctrl+F9 (Build) → changes are live +``` + +`Ctrl+F9` recompiles into `Plugin/build/classes`, and IntelliJ hot-swaps the changed classes into +the running server. + +### Toolchains and the daemon JVM + +`gradle/gradle-daemon-jvm.properties` pins the **Gradle daemon itself** to Java 21, and Gradle +downloads that JDK if it is missing. This makes the daemon JVM independent of IntelliJ's +"Gradle JVM" setting, so it does not matter what that is set to. + +That file is not cosmetic. Without it the daemon runs on whatever JVM launched it, and on a JDK +newer than the embedded Kotlin compiler supports (JDK 26 at the time of writing) Kotlin silently +falls back to an older JVM target and warns `Inconsistent JVM-target compatibility ... 'compileJava' +(26) and 'compileKotlin' (25)`. Regenerate it with: + +```bash +./gradlew updateDaemonJvm --jvm-version=21 +``` + +The build then compiles with Java 21 (`java = "21"` in `libs.versions.toml`), independently of the +JDK running Gradle. If no JDK 21 is installed, the foojay resolver applied in `settings.gradle.kts` +downloads one - that path is verified: on a machine with only JDK 25, the first build provisioned +Temurin 21 and `runServer` reported `Running Java 21 (... Temurin-21.0.8+9)`. Point IntelliJ at the +Gradle JVM of your choice; it does not have to be 21. + +## HotSwap + +### Level 1 - method bodies, nothing to install + +Start the server with **Debug 'runServer'**, not Run. Edit a method body, press `Ctrl+F9`, and the +JVM's standard HotSwap replaces the code in the running server. This is plain JDK functionality and +needs no extra JVM, no agent and no configuration. + +Its limit: **method bodies only**. Adding or removing a method or field, or changing a class +hierarchy, fails with "operation not supported by VM". + +### Level 2 - structural changes, still nothing to install + +IntelliJ bundles a JetBrains Runtime, and JBR has DCEVM built in. It sits outside the directories +Gradle scans, so `gradle.properties` registers it via `org.gradle.java.installations.paths` +(adjust the path if your IDE lives elsewhere). Then: + +```bash +./gradlew runServer -PrunServer.javaVersion=25 -PrunServer.javaVendor=JetBrains \ + "-PrunServer.jvmArgs=-Xms2G -Xmx2G -XX:+AllowEnhancedClassRedefinition" +``` + +or make it permanent in `gradle.properties`: + +```properties +runServer.javaVersion = 25 +runServer.javaVendor = JetBrains +runServer.jvmArgs = -Xms2G -Xmx2G -Dfile.encoding=UTF-8 -XX:+AllowEnhancedClassRedefinition +``` + +Verified on this machine: the server reports +`Running Java 25 (... JetBrains s.r.o. JBR-25.0.3+1-329.124-jcef)` and the plugin initializes. Now +`Ctrl+F9` also handles added/removed methods and fields. + +The dev server runs on 25 while the plugin still **compiles** against Java 21 - the toolchain is +unchanged, and Java 21 bytecode runs fine on a 25 JVM. + +`-XX:+AllowEnhancedClassRedefinition` is **only valid on a JBR/DCEVM JVM**; a stock JDK refuses to +start with it. That is why it is not in the default `runServer.jvmArgs`. + +### Level 3 - HotswapAgent (optional, rarely worth it here) + +HotswapAgent adds *framework* reloading - Spring beans, Hibernate mappings, resource files. A Paper +plugin uses none of that, and DCEVM already covers the structural changes. Get `hotswap-agent.jar` +from (the HotSwapHelper IntelliJ plugin +also downloads one, to `~/.hotswap/hotswap-agent.jar`) and set: + +```properties +runServer.javaVersion = 25 +runServer.javaVendor = JetBrains +runServer.javaAgent = C:/Users/you/.hotswap/hotswap-agent.jar +runServer.javaAgentArgs = disablePlugin=Log4j2 +runServer.jvmArgs = -Xms2G -Xmx2G -XX:+AllowEnhancedClassRedefinition -XX:HotswapAgent=external +``` + +`runServer.javaAgent` contributes the `-javaagent:` flag and `runServer.javaAgentArgs` is appended +after it as `-javaagent:=`; `-XX:HotswapAgent=external` stays in `runServer.jvmArgs` +because it too is JBR-only. + +**`disablePlugin=Log4j2` is not optional.** HotswapAgent's Log4j2 plugin tries to instrument +`org.apache.logging.log4j.core.LoggerContext`, but Paper loads log4j2 in a separate `URLClassLoader` +that cannot see `org.hotswap.agent.config.PluginManager`, so every startup prints +`CannotCompileException: no such class` stack traces. The server still boots, but the noise is +constant. Note the key is `disablePlugin` (singular) - `disabledPlugins` is the +`hotswap-agent.properties` key and is ignored as an agent argument. + +Verified end to end: agent loads (`Loading Hotswap agent {2.0.2} - unlimited runtime class +redefinition`), zero HotswapAgent errors, plugin initializes. + +### About the HotSwapHelper IntelliJ plugin + +HotSwapHelper works by cloning a **run configuration** and relaunching it on a DCEVM JVM with the +agent attached. `runServer` is a Gradle task whose server JVM is forked by the Gradle daemon, not a +process IntelliJ launches, so HotSwapHelper cannot inject into it. That is fine - this build does +the same job through `runServer.javaVersion` / `javaVendor` / `javaAgent` / `jvmArgs`. The plugin is +still useful for the `hotswap-agent.jar` it downloads. + +### What HotSwap can never do + +Redefinition swaps bytecode. It does not re-run anything or rebuild existing objects, so a restart +is still required for: + +- `onEnable` / `onDisable` / bootstrapper / loader changes - they already ran +- registering or unregistering event listeners, commands or bStats charts +- `paper-plugin.yml` changes (dependencies, api-version, main class) +- new fields on objects that already exist - they get default values, not your initialiser +- anything already cached or held by CraftEngine through `join-classpath: true` + +### Where it pays off in this project + +The converter code (`converter/**`, mappers, geometry, textures) is pure logic triggered by a +command, which is the ideal shape for HotSwap: edit a mapper, `Ctrl+F9`, re-run the convert command. + +For that same code the *fastest* loop is often no server at all. The suite is pure unit tests and runs in about a +second: + +```bash +./gradlew :Plugin:test --tests '*KeyRegistryTest*' +``` + +The suite runs the same way: one test class at a time is the fastest feedback loop. + +## Migration notes (Maven → Gradle) + +- The ten `pom.xml` files have been deleted; Gradle is the only build system. They remain in git + history if you ever need to compare - `git show 84ce318:pom.xml` for the old root POM. + If IntelliJ still shows the project as Maven, unlink it in the Maven tool window and re-import + from `settings.gradle.kts`. +- Maven's `provided` scope maps to Gradle's `compileOnly`, but Maven also puts `provided` + dependencies on the test classpath. `craftengineconverter.java-conventions` restores that with + `testImplementation.extendsFrom(compileOnly)`. +- Resource filtering is applied only to `paper-plugin.yml` and `translations/**/messages.yml` - the + only resources that ever contained `${...}` tokens. The resource files themselves are unchanged. +- Repositories live in `craftengineconverter.java-conventions`, not in `settings.gradle.kts`. + paperweight-userdev registers extra repositories on `:Plugin` (mache, the plugin remapper, and + whichever decompiler/param-mapping repos the dev bundle's metadata names). Gradle never *merges* + settings repositories with project repositories - one side always wins - so a settings-level block + would break paperweight's setup pipeline. It is still a single declaration site. +- `fr.robie:yamllibrary:1.0-SNAPSHOT` is published to no remote repository; it is `mvn install`ed + into `~/.m2` by hand. Maven resolved it implicitly, Gradle cannot, so the convention plugin has a + `mavenLocal()` entry **restricted to that one module**. Publishing yamllibrary somewhere real is + the only thing standing between this build and a clean-machine CI run - see + `craftengineconverter.java-conventions.gradle.kts`. +- "Deprecated Gradle features were used in this build" comes from paperweight-userdev itself + (`val reobfJar by tasks.registering`), not from these scripts. Verify with + `./gradlew help --warning-mode all`. + +## Known upstream defect: JitPack parent-POM case collision + +`MessageFlow` and `Paper-Dispatch` are published to JitPack with **both** the root aggregator and +the child module, whose artifactIds differ only in case: + +| module | declared parent | +| --- | --- | +| `com.github.1robie.MessageFlow:message-flow` | `com.github.1robie.MessageFlow:Message-Flow` | +| `com.github.1robie.paper-dispatch:paper-dispatch` | `com.github.1robie.paper-dispatch:Paper-Dispatch` | + +On a case-insensitive filesystem (Windows, default macOS) the parent resolves back to the child, so +Gradle walks an infinite parent chain and dies with a bare `java.lang.StackOverflowError` deep in +`GradlePomModuleDescriptorParser`. It is order-dependent: a warm metadata cache hides it, which is +why a CLI build can pass while an IntelliJ sync fails. + +The workaround lives in `craftengineconverter.java-conventions.gradle.kts`: the jitpack repository +(already scoped to `com.github.1robie.*`) declares `metadataSources { artifact() }`, so Gradle takes +the jars and never reads those POMs. Nothing is lost - both are shaded fat jars, and the only +dependency either POM declares is `paper-api` at `provided` scope. + +**The real fix is upstream.** In the `MessageFlow` and `Paper-Dispatch` repos, rename the root +aggregator's `artifactId` so it no longer collides case-insensitively with its child module (e.g. +`message-flow-parent`). Once republished, delete the `metadataSources` block. + +To check whether any dependency has a cyclic parent chain, look for two POMs in the same cache +directory whose names differ only in case: + +```bash +find ~/.gradle/caches/modules-2/files-2.1 -name '*.pom' -printf '%f\n' | sort -f | uniq -Di +``` diff --git a/Hooks/BOM/pom.xml b/Hooks/BOM/pom.xml deleted file mode 100644 index 66262c3a..00000000 --- a/Hooks/BOM/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - 4.0.0 - - fr.robie.craftengineconverter - Hooks - 0.0.2 - - - BOM - - - - fr.robie.craftengineconverter - PacketEvent - ${project.version} - compile - - - - fr.robie.craftengineconverter - PlaceholderAPI - ${project.version} - compile - - - - fr.robie.craftengineconverter - Nexo - ${project.version} - compile - - - - fr.robie.craftengineconverter - ItemsAdder - ${project.version} - compile - - - - \ No newline at end of file diff --git a/Hooks/ItemsAdder/build.gradle.kts b/Hooks/ItemsAdder/build.gradle.kts new file mode 100644 index 00000000..69fdd053 --- /dev/null +++ b/Hooks/ItemsAdder/build.gradle.kts @@ -0,0 +1,7 @@ +plugins { + id("craftengineconverter.hook-conventions") +} + +dependencies { + compileOnly(libs.itemsadder) +} diff --git a/Hooks/ItemsAdder/pom.xml b/Hooks/ItemsAdder/pom.xml deleted file mode 100644 index 79730773..00000000 --- a/Hooks/ItemsAdder/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - 4.0.0 - - fr.robie.craftengineconverter - Hooks - 0.0.2 - - - ItemsAdder - - - - dev.lone - api-itemsadder - - - net.kyori - adventure-api - - - \ No newline at end of file diff --git a/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderBlockConverter.java b/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderBlockConverter.java index ef607c39..609f8918 100644 --- a/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderBlockConverter.java +++ b/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderBlockConverter.java @@ -3,7 +3,7 @@ import dev.lone.itemsadder.api.CustomBlock; import dev.lone.itemsadder.api.Events.CustomBlockInteractEvent; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.enums.Plugins; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.converter.BlockConverter; @@ -13,8 +13,6 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; -import java.util.HashSet; -import java.util.Set; public class ItemsAdderBlockConverter extends BlockConverter implements Listener { public ItemsAdderBlockConverter(CraftEngineConverterPlugin plugin) { @@ -23,7 +21,7 @@ public ItemsAdderBlockConverter(CraftEngineConverterPlugin plugin) { @EventHandler public void onItemsAdderBlockInteract(CustomBlockInteractEvent event) { - if (!Configuration.get(ConfigurationKey.ITEMS_ADDER_BLOCK_INTERACTION_CONVERSION) || !event.getPlayer().hasPermission(Permission.ITEMSADDER_BLOCK_INTERACT_CONVERSION.asPermission())) { + if (!Configuration.get(Keys.ITEMS_ADDER_BLOCK_INTERACTION_CONVERSION) || !event.getPlayer().hasPermission(Permission.ITEMSADDER_BLOCK_INTERACT_CONVERSION.asPermission())) { return; } @@ -36,19 +34,16 @@ public void onItemsAdderBlockInteract(CustomBlockInteractEvent event) { Block block = event.getBlockClicked(); Location location = block.getLocation(); + // Read before the block is removed, so the conversion can be restored. + String oldBlockState = block.getBlockData().getAsString(); if (!this.removeBlockAt(location)) { return; } - this.placeBlock(newName, location, null); + this.placeBlock(newName, location, oldBlockState); event.setCancelled(true); - if (Configuration.get(ConfigurationKey.ALLOW_BLOCK_CONVERSION_PROPAGATION) && Configuration.get(ConfigurationKey.MAX_BLOCK_CONVERSION_PROPAGATION_DEPTH) > 1) { - Set processed = new HashSet<>(); - processed.add(location); - ConversionCounter counter = new ConversionCounter(Configuration.get(ConfigurationKey.MAX_BLOCK_CONVERSION_PROPAGATION_DEPTH) - 1); - this.executeBlockConversion(block.getLocation(), processed, counter); - } + this.propagateFrom(location); } diff --git a/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderFurnitureConverter.java b/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderFurnitureConverter.java index 6a9e7a13..4b0c5d5b 100644 --- a/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderFurnitureConverter.java +++ b/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderFurnitureConverter.java @@ -3,7 +3,7 @@ import dev.lone.itemsadder.api.CustomFurniture; import dev.lone.itemsadder.api.Events.FurnitureInteractEvent; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.enums.Plugins; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.converter.FurnitureConverter; @@ -18,8 +18,6 @@ import org.jetbrains.annotations.Nullable; import java.util.Collection; -import java.util.HashSet; -import java.util.Set; public class ItemsAdderFurnitureConverter extends FurnitureConverter implements Listener { @@ -29,7 +27,7 @@ public ItemsAdderFurnitureConverter(CraftEngineConverterPlugin plugin) { @EventHandler public void onItemsAdderFurnitureInteract(FurnitureInteractEvent event) { - if (!Configuration.get(ConfigurationKey.ITEMS_ADDER_FURNITURE_INTERACTION_CONVERSION) || !event.getPlayer().hasPermission(Permission.ITEMSADDER_FURNITURE_INTERACT_CONVERSION.asPermission())) { + if (!Configuration.get(Keys.ITEMS_ADDER_FURNITURE_INTERACTION_CONVERSION) || !event.getPlayer().hasPermission(Permission.ITEMSADDER_FURNITURE_INTERACT_CONVERSION.asPermission())) { return; } String namespacedID = event.getNamespacedID(); @@ -38,17 +36,13 @@ public void onItemsAdderFurnitureInteract(FurnitureInteractEvent event) { return; } Entity bukkitEntity = event.getBukkitEntity(); - CustomFurniture.remove(bukkitEntity, false); + // Both have to be read before the entity goes away: the snapshot is what makes the conversion restorable. Location location = bukkitEntity.getLocation(); - this.placeFurniture(newName, location.add(0, -0.5, 0), null); + String entityNBT = bukkitEntity.getAsString(); + CustomFurniture.remove(bukkitEntity, false); + this.placeFurniture(newName, location.add(0, -0.5, 0), entityNBT); event.setCancelled(true); - - if (Configuration.get(ConfigurationKey.ALLOW_BLOCK_CONVERSION_PROPAGATION) && Configuration.get(ConfigurationKey.MAX_BLOCK_CONVERSION_PROPAGATION_DEPTH) > 1) { - Set processed = new HashSet<>(); - processed.add(location); - ConversionCounter counter = new ConversionCounter(Configuration.get(ConfigurationKey.MAX_BLOCK_CONVERSION_PROPAGATION_DEPTH) - 1); - this.executeFurnitureConversion(location, processed, counter); - } + this.propagateFrom(location); } @Override @@ -62,23 +56,20 @@ public String getNewNameForFurniture(Location location) { if (furnitureEntity != null) { CustomFurniture customFurniture = CustomFurniture.byAlreadySpawned(furnitureEntity); if (customFurniture != null) { - return customFurniture.getNamespacedID(); + return this.getNewName(customFurniture.getNamespacedID()); } } return null; } + @Override @Nullable public Entity getFurnitureEntityAt(Location location) { - Collection entities = location.getNearbyEntities(1, 1, 1); - for (Entity entity : entities) { - if (entity instanceof ItemFrame || entity instanceof ItemDisplay || entity instanceof ArmorStand) { - if (CustomFurniture.byAlreadySpawned(entity) != null) { - return entity; - } - } - } - return null; + Collection entities = location.getNearbyEntities( + FURNITURE_SEARCH_RADIUS, FURNITURE_SEARCH_RADIUS, FURNITURE_SEARCH_RADIUS); + return nearest(location, entities, entity -> + (entity instanceof ItemFrame || entity instanceof ItemDisplay || entity instanceof ArmorStand) + && CustomFurniture.byAlreadySpawned(entity) != null); } @Override diff --git a/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderWorldConverter.java b/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderWorldConverter.java index 42c76f8f..e4451778 100644 --- a/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderWorldConverter.java +++ b/Hooks/ItemsAdder/src/main/java/fr/robie/craftengineconverter/hooks/itemsadder/ItemsAdderWorldConverter.java @@ -1,12 +1,14 @@ package fr.robie.craftengineconverter.hooks.itemsadder; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.enums.Plugins; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.CraftEnginePlacementTracker; import fr.robie.craftengineconverter.common.PluginNameMapper; +import fr.robie.craftengineconverter.common.converter.FurnitureConverter; import fr.robie.craftengineconverter.common.converter.WorldConverter; +import org.bukkit.Location; import org.bukkit.NamespacedKey; import org.bukkit.entity.Entity; import org.bukkit.persistence.PersistentDataContainer; @@ -24,22 +26,26 @@ public ItemsAdderWorldConverter(CraftEngineConverterPlugin plugin) { @Override public boolean convertEntity(@NotNull Entity entity) { - if (Configuration.get(ConfigurationKey.ITEMS_ADDER_CHUNK_LOAD_CONVERSION)) { + if (Configuration.get(Keys.ITEMS_ADDER_CHUNK_LOAD_CONVERSION)) { PersistentDataContainer persistentDataContainer = entity.getPersistentDataContainer(); for (NamespacedKey key : persistentDataContainer.getKeys()) { if (key.asString().equalsIgnoreCase("itemsadder:placeable_entity_item")){ - String itemID = persistentDataContainer.get(key, PersistentDataType.STRING); + String itemID = persistentDataContainer.get(key, PersistentDataType.STRING); String newName = this.nameMapper.getNewName(Plugins.ITEMS_ADDER, itemID); - if (newName == null) { + // Without the registration check the entity would be removed and nothing would replace it. + if (newName == null || !FurnitureConverter.isRegisteredStatic(newName)) { return false; } - this.placementTracker.placeFurniture(newName, entity.getLocation()); + Location location = entity.getLocation(); entity.remove(); + // CraftEngine furniture is placed half a block below the entity it stands in for, as everywhere else. + this.placementTracker.placeFurniture(newName, location.add(0, -0.5, 0)); return true; } } } - return false; } + return false; + } @Override public @NotNull Plugins getPlugin() { diff --git a/Hooks/Nexo/build.gradle.kts b/Hooks/Nexo/build.gradle.kts new file mode 100644 index 00000000..da7ccecc --- /dev/null +++ b/Hooks/Nexo/build.gradle.kts @@ -0,0 +1,9 @@ +plugins { + id("craftengineconverter.hook-conventions") +} + +dependencies { + compileOnly(libs.nexo) { + exclude(group = "dev.triumphteam", module = "triumph-gui") + } +} diff --git a/Hooks/Nexo/pom.xml b/Hooks/Nexo/pom.xml deleted file mode 100644 index 714cafbc..00000000 --- a/Hooks/Nexo/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - 4.0.0 - - fr.robie.craftengineconverter - Hooks - 0.0.2 - - - Nexo - - - - com.nexomc - nexo - - - \ No newline at end of file diff --git a/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoBlockConverter.java b/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoBlockConverter.java index 83711a99..de6025ce 100644 --- a/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoBlockConverter.java +++ b/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoBlockConverter.java @@ -5,9 +5,8 @@ import com.nexomc.nexo.mechanics.custom_block.CustomBlockMechanic; import com.nexomc.nexo.utils.drops.Drop; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.enums.Plugins; -import fr.robie.craftengineconverter.api.history.BlockHistory; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.converter.BlockConverter; import fr.robie.craftengineconverter.common.permission.Permission; @@ -16,8 +15,6 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; -import java.util.HashSet; -import java.util.Set; public class NexoBlockConverter extends BlockConverter implements Listener { @@ -27,7 +24,7 @@ public NexoBlockConverter(CraftEngineConverterPlugin plugin) { @EventHandler public void onNexoBlockInteract(NexoBlockInteractEvent event) { - if (!Configuration.get(ConfigurationKey.NEXO_BLOCK_INTERACTION_CONVERSION) || !event.getPlayer().hasPermission(Permission.NEXO_BLOCK_INTERACT_CONVERSION.asPermission())) { + if (!Configuration.get(Keys.NEXO_BLOCK_INTERACTION_CONVERSION) || !event.getPlayer().hasPermission(Permission.NEXO_BLOCK_INTERACT_CONVERSION.asPermission())) { return; } String itemID = event.getMechanic().getItemID(); @@ -47,13 +44,7 @@ public void onNexoBlockInteract(NexoBlockInteractEvent event) { this.placeBlock(newName, location, blockState); event.setCancelled(true); - - if (Configuration.get(ConfigurationKey.ALLOW_BLOCK_CONVERSION_PROPAGATION) && Configuration.get(ConfigurationKey.MAX_BLOCK_CONVERSION_PROPAGATION_DEPTH) > 1) { - Set processed = new HashSet<>(); - processed.add(location); - ConversionCounter counter = new ConversionCounter(Configuration.get(ConfigurationKey.MAX_BLOCK_CONVERSION_PROPAGATION_DEPTH) - 1); - this.executeBlockConversion(block.getLocation(), processed, counter); - } + this.propagateFrom(location); } @@ -71,21 +62,6 @@ public String getNewNameForCustomBlock(Location location) { return this.getNewName(mechanic.getItemID()); } - @Override - public void placeBlock(String itemId, Location location, String oldBlockState) { - BlockHistory blockHistory = new BlockHistory(null, - location.getWorld().getName(), - location.getBlockX() >> 4, - location.getBlockZ() >> 4, - location.getBlockX(), - location.getBlockY(), - location.getBlockZ(), - oldBlockState, - false); - super.placeBlock(itemId, location, oldBlockState); - this.serverProfile.addBlockHistory(blockHistory); - } - @Override public boolean removeBlockAt(Location location) { return NexoBlocks.remove(location, null, Drop.emptyDrop()); diff --git a/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoFurnitureConverter.java b/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoFurnitureConverter.java index 5ad3a90d..3c36a939 100644 --- a/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoFurnitureConverter.java +++ b/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoFurnitureConverter.java @@ -1,13 +1,11 @@ package fr.robie.craftengineconverter.hooks.nexo; -import com.google.gson.Gson; import com.nexomc.nexo.api.NexoFurniture; import com.nexomc.nexo.api.events.furniture.NexoFurnitureInteractEvent; import com.nexomc.nexo.mechanics.furniture.FurnitureMechanic; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.enums.Plugins; -import fr.robie.craftengineconverter.api.history.EntityHistory; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.converter.FurnitureConverter; import fr.robie.craftengineconverter.common.permission.Permission; @@ -16,11 +14,7 @@ import org.bukkit.entity.ItemDisplay; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; -import org.jetbrains.annotations.Nullable; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; public class NexoFurnitureConverter extends FurnitureConverter implements Listener { @@ -30,7 +24,7 @@ public NexoFurnitureConverter(CraftEngineConverterPlugin plugin) { @EventHandler public void onNexoFurnitureInteract(NexoFurnitureInteractEvent event) { - if (!Configuration.get(ConfigurationKey.NEXO_FURNITURE_INTERACTION_CONVERSION) || !event.getPlayer().hasPermission(Permission.NEXO_FURNITURE_INTERACT_CONVERSION.asPermission())) { + if (!Configuration.get(Keys.NEXO_FURNITURE_INTERACTION_CONVERSION) || !event.getPlayer().hasPermission(Permission.NEXO_FURNITURE_INTERACT_CONVERSION.asPermission())) { return; } String itemID = event.getMechanic().getItemID(); @@ -39,42 +33,20 @@ public void onNexoFurnitureInteract(NexoFurnitureInteractEvent event) { return; } ItemDisplay baseEntity = event.getBaseEntity(); + // Both have to be read before the entity goes away. + Location location = baseEntity.getLocation(); String entityNBT = baseEntity.getAsString(); NexoFurniture.remove(baseEntity); - Location location = baseEntity.getLocation(); this.placeFurniture(newName, location.add(0, -0.5, 0), entityNBT); event.setCancelled(true); - - if (Configuration.get(ConfigurationKey.ALLOW_BLOCK_CONVERSION_PROPAGATION) && Configuration.get(ConfigurationKey.MAX_BLOCK_CONVERSION_PROPAGATION_DEPTH) > 1) { - Set processed = new HashSet<>(); - processed.add(location); - ConversionCounter counter = new ConversionCounter(Configuration.get(ConfigurationKey.MAX_BLOCK_CONVERSION_PROPAGATION_DEPTH) - 1); - this.executeFurnitureConversion(location, processed, counter); - } + this.propagateFrom(location); } @Override public Entity getFurnitureEntityAt(Location location) { - Collection nearbyEntitiesByType = location.getNearbyEntitiesByType(ItemDisplay.class, 1); - for (ItemDisplay entity : nearbyEntitiesByType) { - if (NexoFurniture.isFurniture(entity)) { - return entity; - } - } - return null; - } - - public void placeFurniture(String itemId, Location location, @Nullable String entityNBT) { - EntityHistory entityHistory = null; - if (entityNBT != null) { - Location duplicateLocation = location.clone().add(0, 0.5, 0); - String locationJson = new Gson().toJson(duplicateLocation.serialize()); - entityHistory = new EntityHistory(null, locationJson, entityNBT, false); - } - this.plugin.getPlacementTracker().placeFurniture(itemId, location); - if (entityHistory != null) { - this.serverProfile.addEntityHistory(entityHistory); - } + return nearest(location, + location.getNearbyEntitiesByType(ItemDisplay.class, FURNITURE_SEARCH_RADIUS), + entity -> NexoFurniture.isFurniture((ItemDisplay) entity)); } @Override diff --git a/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoWorldConverter.java b/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoWorldConverter.java index 9be7c455..521be1ae 100644 --- a/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoWorldConverter.java +++ b/Hooks/Nexo/src/main/java/fr/robie/craftengineconverter/hooks/nexo/NexoWorldConverter.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.hooks.nexo; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.enums.Plugins; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.CraftEnginePlacementTracker; @@ -27,7 +27,7 @@ public NexoWorldConverter(CraftEngineConverterPlugin plugin) { @Override public boolean convertEntity(@NotNull Entity entity) { - if (Configuration.get(ConfigurationKey.NEXO_CHUNK_LOAD_CONVERSION)) { + if (Configuration.get(Keys.NEXO_CHUNK_LOAD_CONVERSION)) { PersistentDataContainer persistentDataContainer = entity.getPersistentDataContainer(); for (NamespacedKey key : persistentDataContainer.getKeys()) { if (key.asString().equalsIgnoreCase("nexo:furniture")){ diff --git a/Hooks/PacketEvent/build.gradle.kts b/Hooks/PacketEvent/build.gradle.kts new file mode 100644 index 00000000..92eeb8ed --- /dev/null +++ b/Hooks/PacketEvent/build.gradle.kts @@ -0,0 +1,7 @@ +plugins { + id("craftengineconverter.hook-conventions") +} + +dependencies { + compileOnly(libs.packetevents.spigot) +} diff --git a/Hooks/PacketEvent/pom.xml b/Hooks/PacketEvent/pom.xml deleted file mode 100644 index 4a3f433f..00000000 --- a/Hooks/PacketEvent/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - 4.0.0 - - fr.robie.craftengineconverter - Hooks - 0.0.2 - - - PacketEvent - - - - com.github.retrooper - packetevents-spigot - - - \ No newline at end of file diff --git a/Hooks/PacketEvent/src/main/java/fr/robie/craftengineconverter/hooks/packetevent/PacketEventsListener.java b/Hooks/PacketEvent/src/main/java/fr/robie/craftengineconverter/hooks/packetevent/PacketEventsListener.java index 0512c0b0..ad479d5f 100644 --- a/Hooks/PacketEvent/src/main/java/fr/robie/craftengineconverter/hooks/packetevent/PacketEventsListener.java +++ b/Hooks/PacketEvent/src/main/java/fr/robie/craftengineconverter/hooks/packetevent/PacketEventsListener.java @@ -7,7 +7,7 @@ import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon; import com.github.retrooper.packetevents.wrapper.play.server.*; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.tag.ITagResolver; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.packet.PacketContent; @@ -29,20 +29,20 @@ public class PacketEventsListener extends PacketListenerAbstract { public PacketEventsListener(CraftEngineConverterPlugin plugin, AdventureMessageFormatter messageFormatter) { super(PacketListenerPriority.LOW); - if (Configuration.get(ConfigurationKey.PLUGIN_MESSAGE_FORMATTING)) { + if (Configuration.get(Keys.PLUGIN_MESSAGE_FORMATTING)) { this.packetTypeProcessors.put(PacketType.Play.Server.SYSTEM_CHAT_MESSAGE, PacketEventsProcessor.SYSTEM_CHAT_MESSAGE); } - if (Configuration.get(ConfigurationKey.TITLE_FORMATTING)) { + if (Configuration.get(Keys.TITLE_FORMATTING)) { this.packetTypeProcessors.put(PacketType.Play.Server.SET_TITLE_TEXT, PacketEventsProcessor.SET_TITLE_TEXT); this.packetTypeProcessors.put(PacketType.Play.Server.SET_TITLE_SUBTITLE, PacketEventsProcessor.SET_TITLE_SUBTITLE); } - if (Configuration.get(ConfigurationKey.ACTION_BAR_FORMATTING)) { + if (Configuration.get(Keys.ACTION_BAR_FORMATTING)) { this.packetTypeProcessors.put(PacketType.Play.Server.ACTION_BAR, PacketEventsProcessor.ACTION_BAR); } - if (Configuration.get(ConfigurationKey.BOSS_BAR_FORMATTING)) { + if (Configuration.get(Keys.BOSS_BAR_FORMATTING)) { this.packetTypeProcessors.put(PacketType.Play.Server.BOSS_BAR, PacketEventsProcessor.BOSS_BAR); } - if (Configuration.get(ConfigurationKey.MENU_TITLE_FORMATTING)) { + if (Configuration.get(Keys.MENU_TITLE_FORMATTING)) { this.packetTypeProcessors.put(PacketType.Play.Server.OPEN_WINDOW, PacketEventsProcessor.OPEN_WINDOW); } diff --git a/Hooks/PlaceholderAPI/build.gradle.kts b/Hooks/PlaceholderAPI/build.gradle.kts new file mode 100644 index 00000000..e8609853 --- /dev/null +++ b/Hooks/PlaceholderAPI/build.gradle.kts @@ -0,0 +1,7 @@ +plugins { + id("craftengineconverter.hook-conventions") +} + +dependencies { + compileOnly(libs.placeholderapi) +} diff --git a/Hooks/PlaceholderAPI/pom.xml b/Hooks/PlaceholderAPI/pom.xml deleted file mode 100644 index b68be7de..00000000 --- a/Hooks/PlaceholderAPI/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - 4.0.0 - - fr.robie.craftengineconverter - Hooks - 0.0.2 - - - PlaceholderAPI - - - - me.clip - placeholderapi - - - \ No newline at end of file diff --git a/Hooks/PlaceholderAPI/src/main/java/fr/robie/craftengineconverter/hooks/placeholderapi/PlaceholderAPIUtils.java b/Hooks/PlaceholderAPI/src/main/java/fr/robie/craftengineconverter/hooks/placeholderapi/PlaceholderAPIUtils.java index 9a106d87..47cab879 100644 --- a/Hooks/PlaceholderAPI/src/main/java/fr/robie/craftengineconverter/hooks/placeholderapi/PlaceholderAPIUtils.java +++ b/Hooks/PlaceholderAPI/src/main/java/fr/robie/craftengineconverter/hooks/placeholderapi/PlaceholderAPIUtils.java @@ -1,14 +1,14 @@ package fr.robie.craftengineconverter.hooks.placeholderapi; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.hooks.placeholderapi.itemsadder.ImgExpansion; public class PlaceholderAPIUtils { public static void registerExpansions(CraftEngineConverterPlugin plugin) { - if (Configuration.get(ConfigurationKey.ITEMS_ADDER_IMG_PLACEHOLDER_API_SUPPORT)){ + if (Configuration.get(Keys.ITEMS_ADDER_IMG_PLACEHOLDER_API_SUPPORT)){ new ImgExpansion(plugin).register(); } } diff --git a/docs/troubleshooting/common-issues.md b/Hooks/build.gradle.kts similarity index 100% rename from docs/troubleshooting/common-issues.md rename to Hooks/build.gradle.kts diff --git a/Hooks/pom.xml b/Hooks/pom.xml deleted file mode 100644 index aad70f03..00000000 --- a/Hooks/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - - fr.robie.craftengineconverter - CraftEngineConverter - 0.0.2 - - - Hooks - pom - - - BOM - PacketEvent - PlaceholderAPI - Nexo - ItemsAdder - - - - - io.papermc.paper - paper-api - - - fr.robie.craftengineconverter - Common - - - - com.github.1robie.MessageFlow - message-flow - provided - - - \ No newline at end of file diff --git a/Plugin/build.gradle.kts b/Plugin/build.gradle.kts new file mode 100644 index 00000000..8814bdb4 --- /dev/null +++ b/Plugin/build.gradle.kts @@ -0,0 +1,149 @@ +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar +import io.papermc.paperweight.userdev.ReobfArtifactConfiguration +import org.gradle.jvm.toolchain.JavaLanguageVersion +import org.gradle.jvm.toolchain.JvmVendorSpec +import xyz.jpenilla.runpaper.task.RunServer + +plugins { + id("craftengineconverter.java-conventions") + alias(libs.plugins.shadow) + alias(libs.plugins.paperweight.userdev) + alias(libs.plugins.run.paper) +} + +val pluginVersion: String = project.version.toString() + +paperweight { + injectPaperRepository = false + reobfArtifactConfiguration = ReobfArtifactConfiguration.MOJANG_PRODUCTION +} + +dependencies { + paperweight.paperDevBundle(libs.versions.paper.get()) + + rootProject.subprojects + .filter { it.path.startsWith(":Hooks:") } + .sortedBy { it.path } + .forEach { implementation(project(it.path)) } + + implementation(libs.message.flow) { isTransitive = false } + + implementation(libs.bstats.bukkit) + implementation(libs.bstats.base) + implementation(libs.yamllibrary) + implementation(libs.yamllibrary.core) + implementation(libs.paper.dispatch) + + compileOnly(libs.craftengine.core) + compileOnly(libs.craftengine.bukkit) + compileOnly(libs.reflections) + compileOnly(libs.snakeyaml) + + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testRuntimeOnly(libs.junit.platform.launcher) +} + +val resourceTokens: Map = mapOf( + "version" to project.version.toString(), + "project" to mapOf( + "version" to project.version.toString(), + "artifactId" to project.name, + "parent" to mapOf("artifactId" to rootProject.name), + ), + "plugin" to mapOf( + "finalVersion" to pluginVersion, + "author" to providers.gradleProperty("plugin.author").get(), + "description" to providers.gradleProperty("plugin.description").get(), + "apiVersion" to providers.gradleProperty("plugin.apiVersion").get(), + "mainClass" to providers.gradleProperty("plugin.mainClass").get(), + "bootstrapper" to providers.gradleProperty("plugin.bootstrapper").get(), + "loader" to providers.gradleProperty("plugin.loader").get(), + ), +) + +tasks.processResources { + val tokens = resourceTokens + + inputs.property("resourceTokens", tokens.toString()) + + filesMatching(listOf("paper-plugin.yml", "translations/**/messages.yml")) { + expand(tokens) + } +} + +tasks.named("shadowJar") { + archiveBaseName = "CraftEngineConverter" + archiveVersion = pluginVersion + archiveClassifier = "" + + dependencies { + include(dependency("fr.robie.craftengineconverter:.*")) + include(dependency("com.tcoded:FoliaLib")) + include(dependency("org.bstats:bstats-bukkit")) + include(dependency("org.bstats:bstats-base")) + include(dependency("fr.maxlego08.sarah:sarah")) + include(dependency("com.github.1robie.MessageFlow:message-flow")) + include(dependency("com.github.1robie.YamlLibrary:yamllibrary-core")) + include(dependency("com.github.1robie.YamlLibrary:yamllibrary-paper")) + include(dependency("com.github.1robie.paper-dispatch:paper-dispatch")) + } + + relocate("com.tcoded.folialib", "fr.robie.craftengineconverter.lib.folialib") + relocate("org.bstats", "fr.robie.craftengineconverter.lib.bstats") + relocate("fr.maxlego08.sarah", "fr.robie.craftengineconverter.lib.sarah") + relocate("fr.robie.messageflow", "fr.robie.craftengineconverter.lib.messageflow") + relocate("fr.robie.paperdispatch", "fr.robie.craftengineconverter.lib.paperdispatch") + relocate("fr.robie.yamllibrary", "fr.robie.craftengineconverter.lib.yamllibrary") + + duplicatesStrategy = DuplicatesStrategy.INCLUDE + mergeServiceFiles() + + exclude("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA") + + exclude("org/slf4j/**") +} + +tasks.assemble { + dependsOn(tasks.named("shadowJar")) +} + +val runServerJvmArgs: Provider> = providers.gradleProperty("runServer.jvmArgs") + .map { args -> args.split(' ').filter(String::isNotBlank) } + .orElse(emptyList()) + +val runServerJvmArgsExtra: Provider> = providers.gradleProperty("runServer.jvmArgsExtra") + .map { args -> args.split(' ').filter(String::isNotBlank) } + .orElse(emptyList()) + +val runServerJavaAgent: Provider = providers.gradleProperty("runServer.javaAgent") + +val runServerJavaAgentArgs: Provider = providers.gradleProperty("runServer.javaAgentArgs") + +val runServerJavaVersion: Provider = providers.gradleProperty("runServer.javaVersion") + .map(String::toInt) + .orElse(libs.versions.java.map(String::toInt)) + +val runServerJavaVendor: Provider = providers.gradleProperty("runServer.javaVendor") + +tasks.withType().configureEach { + // Lets the dev server run on a different JDK than the compilation toolchain - useful for + // pointing it at a JetBrains Runtime / DCEVM install for HotSwap. + javaLauncher = javaToolchains.launcherFor { + languageVersion = runServerJavaVersion.map(JavaLanguageVersion::of) + if (runServerJavaVendor.isPresent) { + vendor = JvmVendorSpec.matching(runServerJavaVendor.get()) + } + } + + jvmArgs(runServerJvmArgs.get() + runServerJvmArgsExtra.get()) + runServerJavaAgent.orNull?.let { agent -> + val agentArgs = runServerJavaAgentArgs.orNull?.takeIf(String::isNotBlank) + jvmArgs(if (agentArgs == null) "-javaagent:$agent" else "-javaagent:$agent=$agentArgs") + } + + // downloadPlugins { + // hangar("PlaceholderAPI", "2.11.6") + // modrinth("packetevents", "2.9.1") + // } +} diff --git a/Plugin/pom.xml b/Plugin/pom.xml deleted file mode 100644 index af99cda2..00000000 --- a/Plugin/pom.xml +++ /dev/null @@ -1,122 +0,0 @@ - - - 4.0.0 - - fr.robie.craftengineconverter - CraftEngineConverter - 0.0.2 - - - Plugin - - - CraftEngineConverter-${plugin.finalVersion} - - - org.apache.maven.plugins - maven-shade-plugin - - - package - - shade - - - false - false - ${project.build.directory}/${project.build.finalName}.jar - - - fr.robie.craftengineconverter:* - com.tcoded:FoliaLib - org.bstats:bstats-bukkit - org.bstats:bstats-base - fr.maxlego08.sarah:sarah - com.github.1robie.MessageFlow:message-flow - - - - - com.tcoded.folialib - fr.robie.craftengineconverter.lib.folialib - - - org.bstats - fr.robie.craftengineconverter.lib.bstats - - - fr.maxlego08.sarah - fr.robie.craftengineconverter.lib.sarah - - - fr.robie.messageflow - fr.robie.craftengineconverter.lib.messageflow - - - - - *:* - - META-INF/MANIFEST.MF - - - - - - - - - - - - - fr.robie.craftengineconverter - BOM - - - - com.github.1robie.MessageFlow - message-flow - - - - io.papermc.paper - paper-api - - - - net.momirealms - craft-engine-core - - - net.momirealms - craft-engine-bukkit - - - - org.bstats - bstats-bukkit - compile - - - - org.bstats - bstats-base - compile - - - - - org.junit.jupiter - junit-jupiter - - - - org.yaml - snakeyaml - - - - \ No newline at end of file diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/CraftEngineConverter.java b/Plugin/src/main/java/fr/robie/craftengineconverter/CraftEngineConverter.java index 0496313c..60040a45 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/CraftEngineConverter.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/CraftEngineConverter.java @@ -1,13 +1,15 @@ package fr.robie.craftengineconverter; import fr.robie.craftengineconverter.api.builder.TimerBuilder; +import fr.robie.craftengineconverter.api.configuration.ConfigFile; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.database.StorageManager; import fr.robie.craftengineconverter.api.enums.ConverterOption; import fr.robie.craftengineconverter.api.enums.Languages; import fr.robie.craftengineconverter.api.enums.Plugins; import fr.robie.craftengineconverter.api.format.Message; +import fr.robie.craftengineconverter.api.manager.FileCacheManager; import fr.robie.craftengineconverter.api.manager.FoliaCompatibilityManager; import fr.robie.craftengineconverter.api.packet.PacketLoader; import fr.robie.craftengineconverter.api.profile.ServerProfile; @@ -15,9 +17,10 @@ import fr.robie.craftengineconverter.behavior.BehaviorRegister; import fr.robie.craftengineconverter.command.CraftEngineConverterCommand; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; -import fr.robie.craftengineconverter.common.manager.FileCacheManager; import fr.robie.craftengineconverter.common.scanner.BlockStateMappingScanner; import fr.robie.craftengineconverter.common.utils.CraftEngineImageUtils; +import fr.robie.craftengineconverter.common.utils.yaml.directive.PluginKeyDirective; +import fr.robie.craftengineconverter.common.utils.yaml.directive.VersionKeyDirective; import fr.robie.craftengineconverter.converter.Converter; import fr.robie.craftengineconverter.converter.itemsadder.IAConverter; import fr.robie.craftengineconverter.converter.nexo.NexoConverter; @@ -33,13 +36,14 @@ import fr.robie.craftengineconverter.hooks.placeholderapi.PlaceholderAPIUtils; import fr.robie.craftengineconverter.listener.WorldConverterManager; import fr.robie.craftengineconverter.utils.TagResolver; -import fr.robie.craftengineconverter.utils.command.CommandManager; import fr.robie.messageflow.configuration.ConfigurationManager; import fr.robie.messageflow.configuration.lang.EnumLanguageConfiguration; import fr.robie.messageflow.formatter.MessageFormatter; import fr.robie.messageflow.formatter.Placeholder; import fr.robie.messageflow.impl.MessageManager; import fr.robie.messageflow.logger.Logger; +import fr.robie.paperdispatch.manager.ICommandManager; +import fr.robie.yamllibrary.directive.KeyDirectiveRegistry; import org.bstats.bukkit.Metrics; import org.bukkit.event.Listener; @@ -60,7 +64,7 @@ public final class CraftEngineConverter extends CraftEngineConverterPlugin { private final StorageManager storageManager = new DataBaseManager(this); private final ServerProfile serverProfile = new ServerProfileManager(this); private final FoliaCompatibilityManager foliaCompatibilityManager = new FoliaCompatibilityManager(this); - private final CommandManager commandManager = new CommandManager(this); + private final ICommandManager commandManager = new fr.robie.paperdispatch.manager.CommandManager<>(this); private final WorldConverterManager worldConverterManager = new WorldConverterManager(this); private final ITagResolver tagResolver = new TagResolver(); private final MessageManager messageManager; @@ -84,11 +88,13 @@ public void onLoad() { this.getServer().getPluginManager().disablePlugin(this); return; } + KeyDirectiveRegistry.register(new VersionKeyDirective()); + KeyDirectiveRegistry.register(new PluginKeyDirective()); this.reloadBlockStateMappings(); this.reloadConfig(); if (Plugins.PACKET_EVENTS.isPresent()) { Logger.info("[Hook] PacketEvents"); - if (Configuration.get(ConfigurationKey.PACKET_EVENTS_FORMATTING)) { + if (Configuration.get(Keys.PACKET_EVENTS_FORMATTING)) { this.packetLoader = new PacketEventHook(this); } } @@ -96,7 +102,7 @@ public void onLoad() { this.packetLoader.onLoad(); } - this.commandManager.loadCommands(); + this.commandManager.registerCommands(); BehaviorRegister.init(); } @@ -119,11 +125,9 @@ public void onEnable() { this.storageManager.loadDatabase(); this.serverProfile.load(); - this.commandManager.registerCommand("craftengineconverter", new CraftEngineConverterCommand(this), "cengineconverter", "cec"); + new RegistryHelper(this).loadRegistries(); - this.commandManager.validCommands(); - - this.commandManager.enableCommands(); + this.commandManager.registerCommand(new CraftEngineConverterCommand(this)); this.registerConverter(new NexoConverter(this)); this.registerConverter(new IAConverter(this)); @@ -142,11 +146,11 @@ public void onEnable() { this.getServer().getServicesManager().register(ITagResolver.class, this.tagResolver, this, ServicePriority.Normal); - if (Configuration.get(ConfigurationKey.AUTO_CONVERT_ON_STARTUP)) { + if (Configuration.get(Keys.AUTO_CONVERT_ON_STARTUP)) { Logger.info(Message.MESSAGE__AUTO_CONVERTER__STARTUP__START); long startTimeAutoConverter = System.currentTimeMillis(); - Map> autoConvertOptions = Configuration.get(ConfigurationKey.AUTO_CONVERT_ON_STARTUP_TYPES); + Map> autoConvertOptions = Configuration.get(Keys.AUTO_CONVERT_ON_STARTUP_TYPES); List> futures = new ArrayList<>(); if (autoConvertOptions.isEmpty()) { @@ -181,21 +185,21 @@ public void onEnable() { Logger.info(Message.MESSAGE__AUTO_CONVERTER__STARTUP__DISABLED); } - if (Configuration.get(ConfigurationKey.WORLD_CONVERTER_ENABLE)) { + if (Configuration.get(Keys.WORLD_CONVERTER_ENABLE)) { this.registerListener(this.worldConverterManager); } - if (Plugins.NEXO.isEnabled() && Configuration.get(ConfigurationKey.NEXO_ENABLE_HOOK)) { + if (Plugins.NEXO.isEnabled() && Configuration.get(Keys.NEXO_ENABLE_HOOK)) { this.registerListener(new NexoBlockConverter(this)); this.registerListener(new NexoFurnitureConverter(this)); - if (Configuration.get(ConfigurationKey.WORLD_CONVERTER_ENABLE) && Configuration.get(ConfigurationKey.WORLD_CONVERTER_NEXO_HOOK)) { + if (Configuration.get(Keys.WORLD_CONVERTER_ENABLE) && Configuration.get(Keys.WORLD_CONVERTER_NEXO_HOOK)) { this.worldConverterManager.registerConverter(new NexoWorldConverter(this)); } } - if (Plugins.ITEMS_ADDER.isEnabled() && Configuration.get(ConfigurationKey.ITEMS_ADDER_ENABLE_HOOK)) { + if (Plugins.ITEMS_ADDER.isEnabled() && Configuration.get(Keys.ITEMS_ADDER_ENABLE_HOOK)) { this.registerListener(new ItemsAdderBlockConverter(this)); this.registerListener(new ItemsAdderFurnitureConverter(this)); - if (Configuration.get(ConfigurationKey.WORLD_CONVERTER_ENABLE) && Configuration.get(ConfigurationKey.WORLD_CONVERTER_ITEMS_ADDER_HOOK)) { + if (Configuration.get(Keys.WORLD_CONVERTER_ENABLE) && Configuration.get(Keys.WORLD_CONVERTER_ITEMS_ADDER_HOOK)) { this.worldConverterManager.registerConverter(new ItemsAdderWorldConverter(this)); } } @@ -224,8 +228,6 @@ public void onDisable() { this.metrics.shutdown(); - this.commandManager.disableCommands(); - if (this.placementTracker != null) { Logger.info("Conversion stats :"); Logger.info("Total blocks converted : " + this.placementTracker.getBlocksConverted() + " (Failed : " + this.placementTracker.getBlocksFailed() + ", Success rate : " + String.format("%.2f", this.placementTracker.getBlocksSuccessRate()) + "%)"); @@ -237,17 +239,13 @@ public void onDisable() { } public void reloadMessages() { - this.messageManager.loadLanguage(Configuration.get(ConfigurationKey.LANGUAGE)); + this.messageManager.loadLanguage(Configuration.get(Keys.LANGUAGE)); } private void registerListener(@NotNull Listener listener) { this.getServer().getPluginManager().registerEvents(listener, this); } - public CommandManager getCommandManager() { - return this.commandManager; - } - @Override public MessageFormatter getMessageFormatter() { return this.messageFormatter; @@ -297,10 +295,71 @@ public ServerProfile getServerProfile() { return this.serverProfile; } + /** + * Loads every configuration file, one per converter plus the general one. + *

+ * Each file is written out from the jar if it is not there yet, so a new converter's file appears on upgrade + * without anyone having to create it. + */ public void reloadConfig() { - this.saveDefaultConfig(); - File configFile = new File(this.getDataFolder(), "config.yml"); - FileCacheManager.getYamlCache().getEntryFile(configFile.toPath()).ifPresent(entry -> Configuration.getInstance().load(entry.getData(), configFile)); + // Only what this reload does should be reported or backed up. + Configuration.getInstance().beginLoad(); + File mainFile = new File(this.getDataFolder(), ConfigFile.MAIN.fileName()); + // Read before anything is written, so a setting still living in the old single file can be adopted by + // whichever file now owns it. Captured up front because ConfigFile.MAIN is loaded first and would otherwise + // have been saved before the other files got the chance to look in it. + boolean hadMain = mainFile.exists(); + fr.robie.yamllibrary.file.YamlConfiguration legacy = hadMain + ? fr.robie.yamllibrary.file.YamlConfiguration.loadConfiguration(mainFile) + : null; + + for (ConfigFile configFile : ConfigFile.values()) { + File file = new File(this.getDataFolder(), configFile.fileName()); + if (!file.exists()) { + this.saveResource(configFile.fileName(), false); + } + FileCacheManager.getYamlCache().getEntryFile(file.toPath()) + .ifPresent(entry -> Configuration.getInstance() + .load(configFile, entry.getData(), file, legacy)); + } + + this.reportConfigurationMoves(mainFile, legacy); + } + + /** + * Keeps a copy of the old configuration and says what moved, once, the first time anything is relocated. + *

+ * Silent when nothing moved, which is every start after the first — the relocation is driven by what the files + * contain rather than by a version marker, so a settled installation simply finds nothing to do. + */ + private void reportConfigurationMoves(File mainFile, fr.robie.yamllibrary.file.YamlConfiguration legacy) { + Configuration configuration = Configuration.getInstance(); + if (!configuration.hasRelocated() || legacy == null) return; + + // Written before config.yml is, so a move that goes wrong is always recoverable. Never overwritten: the + // existing copy is the pre-split original and is worth more than a later one. + File backup = new File(mainFile.getParentFile(), ConfigFile.MAIN.fileName() + ".bak"); + if (!backup.exists()) { + try { + java.nio.file.Files.copy(mainFile.toPath(), backup.toPath()); + Logger.info("Saved the previous configuration as " + backup.getName()); + } catch (Exception e) { + Logger.warn("Could not back up " + mainFile.getName() + ": " + e.getMessage()); + } + } + + StringBuilder moved = new StringBuilder(); + configuration.relocations().forEach((fileName, count) -> + moved.append(moved.isEmpty() ? "" : ", ").append(count).append(" from ").append(fileName)); + Logger.info("Configuration updated: moved " + moved + " into the file that now owns them"); + + if (configuration.legacyNeedsSaving()) { + try { + legacy.save(mainFile); + } catch (Exception e) { + Logger.warn("Could not tidy " + mainFile.getName() + ": " + e.getMessage()); + } + } } public void reloadBlockStateMappings() { diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/CraftEngineConverterBootstrapper.java b/Plugin/src/main/java/fr/robie/craftengineconverter/CraftEngineConverterBootstrapper.java new file mode 100644 index 00000000..0c39de12 --- /dev/null +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/CraftEngineConverterBootstrapper.java @@ -0,0 +1,20 @@ +package fr.robie.craftengineconverter; + +import io.papermc.paper.plugin.bootstrap.BootstrapContext; +import io.papermc.paper.plugin.bootstrap.PluginBootstrap; +import io.papermc.paper.plugin.bootstrap.PluginProviderContext; +import org.bukkit.plugin.java.JavaPlugin; + +public class CraftEngineConverterBootstrapper implements PluginBootstrap { + + @Override + public void bootstrap(BootstrapContext context) { + + } + + @Override + public JavaPlugin createPlugin(PluginProviderContext context) { + return new CraftEngineConverter(); + } + +} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/CraftEngineConverterLoader.java b/Plugin/src/main/java/fr/robie/craftengineconverter/CraftEngineConverterLoader.java new file mode 100644 index 00000000..378f6f2d --- /dev/null +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/CraftEngineConverterLoader.java @@ -0,0 +1,26 @@ +package fr.robie.craftengineconverter; + +import io.papermc.paper.plugin.loader.PluginClasspathBuilder; +import io.papermc.paper.plugin.loader.PluginLoader; +import io.papermc.paper.plugin.loader.library.impl.MavenLibraryResolver; +import org.eclipse.aether.artifact.DefaultArtifact; +import org.eclipse.aether.graph.Dependency; +import org.eclipse.aether.repository.RemoteRepository; + +public class CraftEngineConverterLoader implements PluginLoader { + + @Override + public void classloader(PluginClasspathBuilder classpathBuilder) { + final MavenLibraryResolver resolver = new MavenLibraryResolver(); + resolver.addRepository(new RemoteRepository.Builder( + "central", "default", MavenLibraryResolver.MAVEN_CENTRAL_DEFAULT_MIRROR + ).build()); + + resolver.addDependency(new Dependency( + new DefaultArtifact("org.reflections:reflections:0.10.2"), + null + )); + + classpathBuilder.addLibrary(resolver); + } +} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/RegistryHelper.java b/Plugin/src/main/java/fr/robie/craftengineconverter/RegistryHelper.java new file mode 100644 index 00000000..453a4672 --- /dev/null +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/RegistryHelper.java @@ -0,0 +1,175 @@ +package fr.robie.craftengineconverter; + +import fr.robie.craftengineconverter.api.annotations.AutoModelConfigurationLoader; +import fr.robie.craftengineconverter.api.annotations.AutoRangeDispatchConfigurationLoader; +import fr.robie.craftengineconverter.api.annotations.AutoSelectModelConfigurationLoader; +import fr.robie.craftengineconverter.api.annotations.AutoTintConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.item.models.ModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.RangeDispatchModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.select.SelectModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.loader.models.ModelConfigurationRegistry; +import fr.robie.craftengineconverter.api.configuration.loader.models.range_dispatch.RangeDispatchConfigurationRegistry; +import fr.robie.craftengineconverter.api.configuration.loader.models.select.SelectModelConfigurationRegistry; +import fr.robie.craftengineconverter.api.configuration.loader.models.tints.TintConfigurationLoader; +import fr.robie.craftengineconverter.api.configuration.loader.models.tints.TintConfigurationRegistry; +import fr.robie.craftengineconverter.api.reflections.ReflectionsCache; +import fr.robie.craftengineconverter.api.utils.VersionFilter; +import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; +import fr.robie.messageflow.logger.Logger; +import org.jetbrains.annotations.NotNull; +import org.reflections.Reflections; + +import java.util.Arrays; +import java.util.Set; + +public class RegistryHelper { + private final ClassLoader classLoader; + + public RegistryHelper(CraftEngineConverterPlugin plugin) { + this.classLoader = plugin.getClass().getClassLoader(); + } + + public RegistryHelper(@NotNull ClassLoader classLoader) { + this.classLoader = classLoader; + } + + public void loadRegistries() { + this.loadModelConfigurationRegistry(); + this.loadTintConfigurationRegistry(); + this.loadSelectModelConfigurationRegistry(); + this.loadRangeDispatchModelConfigurationRegistry(); + } + + private void loadModelConfigurationRegistry() { + Reflections reflections = ReflectionsCache.getInstance().getOrCreate(this.classLoader, "fr.robie.craftengineconverter"); + Set> candidates = reflections.getTypesAnnotatedWith(AutoModelConfigurationLoader.class); + int count = 0; + for (Class clazz : candidates) { + if (!ModelConfigurationLoader.class.isAssignableFrom(clazz)) { + continue; + } + if (!VersionFilter.passes(clazz)) { + continue; + } + AutoModelConfigurationLoader annotation = clazz.getAnnotation(AutoModelConfigurationLoader.class); + if (annotation.value().length == 0) { + continue; + } + try { + @SuppressWarnings("rawtypes") + Class typedClass = clazz.asSubclass(ModelConfigurationLoader.class); + @SuppressWarnings("unchecked") + ModelConfigurationLoader loader = (ModelConfigurationLoader) typedClass.getDeclaredConstructor().newInstance(); + for (String name : annotation.value()) { + ModelConfigurationRegistry.register(name, loader); + } + count++; + } catch (ClassCastException e) { + Logger.error("Class " + clazz.getName() + " cannot be cast to ModelConfigurationLoader", e); + } catch (Exception e) { + Logger.error("Failed to load ModelConfigurationLoader " + clazz.getName() + " for names " + Arrays.toString(annotation.value()), e); + } + } + + ModelConfigurationRegistry.register("select", SelectModelConfigurationRegistry::load); + ModelConfigurationRegistry.register("minecraft:select", SelectModelConfigurationRegistry::load); + count++; + ModelConfigurationRegistry.register("range_dispatch", RangeDispatchConfigurationRegistry::load); + ModelConfigurationRegistry.register("minecraft:range_dispatch", RangeDispatchConfigurationRegistry::load); + count++; + + Logger.info("Loaded " + count + " ModelConfigurationLoaders"); + } + + private void loadTintConfigurationRegistry() { + Reflections reflections = ReflectionsCache.getInstance().getOrCreate(this.classLoader, "fr.robie.craftengineconverter"); + Set> candidates = reflections.getTypesAnnotatedWith(AutoTintConfigurationLoader.class); + int count = 0; + for (Class clazz : candidates) { + if (!TintConfigurationLoader.class.isAssignableFrom(clazz)) { + continue; + } + if (!fr.robie.craftengineconverter.api.utils.VersionFilter.passes(clazz)) { + continue; + } + AutoTintConfigurationLoader annotation = clazz.getAnnotation(AutoTintConfigurationLoader.class); + try { + TintConfigurationLoader loader = (TintConfigurationLoader) clazz.getDeclaredConstructor().newInstance(); + for (String name : annotation.value()) { + TintConfigurationRegistry.register(name, loader); + } + count++; + } catch (Exception e) { + Logger.error("Failed to load TintConfigurationLoader " + clazz.getName() + " for names " + java.util.Arrays.toString(annotation.value()), e); + } + } + Logger.info("Loaded " + count + " TintConfigurationLoaders"); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private void loadSelectModelConfigurationRegistry() { + Reflections reflections = ReflectionsCache.getInstance().getOrCreate(this.classLoader, "fr.robie.craftengineconverter"); + Set> candidates = reflections.getTypesAnnotatedWith(AutoSelectModelConfigurationLoader.class); + int count = 0; + for (Class clazz : candidates) { + if (!ModelConfigurationLoader.class.isAssignableFrom(clazz)) { + continue; + } + if (!VersionFilter.passes(clazz)) { + continue; + } + AutoSelectModelConfigurationLoader annotation = clazz.getAnnotation(AutoSelectModelConfigurationLoader.class); + if (annotation.value().length == 0) { + Logger.debug("Skipping " + clazz.getName() + " — no names specified in @AutoSelectModelConfigurationLoader"); + continue; + } + try { + Class typedClass = clazz.asSubclass(ModelConfigurationLoader.class); + ModelConfigurationLoader> loader = (ModelConfigurationLoader>) typedClass.getDeclaredConstructor().newInstance(); + for (String name : annotation.value()) { + SelectModelConfigurationRegistry.register(name, loader); + } + count++; + } catch (ClassCastException e) { + Logger.error("Class " + clazz.getName() + " cannot be cast to ModelConfigurationLoader", e); + } catch (Exception e) { + Logger.error("Failed to load SelectModelConfigurationLoader " + clazz.getName() + " for names " + Arrays.toString(annotation.value()), e); + } + } + Logger.info("Loaded " + count + " SelectModelConfigurationLoaders"); + } + + private void loadRangeDispatchModelConfigurationRegistry() { + Reflections reflections = ReflectionsCache.getInstance().getOrCreate(this.classLoader, "fr.robie.craftengineconverter"); + Set> candidates = reflections.getTypesAnnotatedWith(AutoRangeDispatchConfigurationLoader.class); + int count = 0; + for (Class clazz : candidates) { + if (!ModelConfigurationLoader.class.isAssignableFrom(clazz)) { + continue; + } + if (!VersionFilter.passes(clazz)) { + continue; + } + AutoRangeDispatchConfigurationLoader annotation = clazz.getAnnotation(AutoRangeDispatchConfigurationLoader.class); + if (annotation.value().length == 0) { + Logger.debug("Skipping " + clazz.getName() + " — no names specified in @AutoRangeDispatchConfigurationLoader"); + continue; + } + try { + Class typedClass = clazz.asSubclass(ModelConfigurationLoader.class); + ModelConfigurationLoader loader = (ModelConfigurationLoader) typedClass.getDeclaredConstructor().newInstance(); + for (String name : annotation.value()) { + RangeDispatchConfigurationRegistry.register(name, loader); + } + count++; + } catch (ClassCastException e) { + Logger.error("Class " + clazz.getName() + " cannot be cast to ModelConfigurationLoader", e); + } catch (Exception e) { + Logger.error("Failed to load RangeDispatchModelConfigurationLoader " + clazz.getName() + " for names " + Arrays.toString(annotation.value()), e); + } + } + + Logger.info("Loaded " + count + " RangeDispatchModelConfigurationLoaders"); + } +} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommand.java b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommand.java index 548ca446..6def2a6e 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommand.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommand.java @@ -2,13 +2,16 @@ import fr.robie.craftengineconverter.CraftEngineConverter; import fr.robie.craftengineconverter.common.permission.Permission; -import fr.robie.craftengineconverter.utils.command.CommandType; -import fr.robie.craftengineconverter.utils.command.VCommand; +import fr.robie.paperdispatch.command.BaseCommand; +import fr.robie.paperdispatch.command.CommandDispatch; +import fr.robie.paperdispatch.command.CommandResultType; +import org.jetbrains.annotations.NotNull; + +public class CraftEngineConverterCommand extends BaseCommand { -public class CraftEngineConverterCommand extends VCommand { public CraftEngineConverterCommand(CraftEngineConverter craftEngineConverter) { - super(craftEngineConverter); - this.setPermission(Permission.COMMAND_USE); + super(craftEngineConverter, "craftengineconverter", "cengineconverter", "cec"); + this.setPermission(Permission.COMMAND_USE.asPermission()); this.addSubCommand(new CraftEngineConverterCommandReload(craftEngineConverter)); this.addSubCommand(new CraftEngineConverterCommandConvert(craftEngineConverter)); this.addSubCommand(new CraftEngineConverterCommandClearFilesCache(craftEngineConverter)); @@ -16,8 +19,7 @@ public CraftEngineConverterCommand(CraftEngineConverter craftEngineConverter) { } @Override - protected CommandType perform(CraftEngineConverter plugin) { - this.syntaxMessage(); - return CommandType.SUCCESS; + protected @NotNull CommandResultType perform(@NotNull CommandDispatch commandDispatch) { + return CommandResultType.SUCCESS; } } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandClearFilesCache.java b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandClearFilesCache.java index 11cd1662..76b0417b 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandClearFilesCache.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandClearFilesCache.java @@ -3,33 +3,37 @@ import fr.robie.craftengineconverter.CraftEngineConverter; import fr.robie.craftengineconverter.api.builder.TimerBuilder; import fr.robie.craftengineconverter.api.format.Message; -import fr.robie.craftengineconverter.common.manager.FileCacheManager; +import fr.robie.craftengineconverter.api.manager.FileCacheManager; +import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.permission.Permission; -import fr.robie.craftengineconverter.utils.command.CommandType; -import fr.robie.craftengineconverter.utils.command.VCommand; +import fr.robie.messageflow.formatter.MessageFormatter; import fr.robie.messageflow.formatter.Placeholder; +import fr.robie.paperdispatch.command.CommandDispatch; +import fr.robie.paperdispatch.command.CommandResultType; +import fr.robie.paperdispatch.command.SubCommand; +import org.jetbrains.annotations.NotNull; + +public class CraftEngineConverterCommandClearFilesCache extends SubCommand { + private final MessageFormatter messageFormatter; -public class CraftEngineConverterCommandClearFilesCache extends VCommand { public CraftEngineConverterCommandClearFilesCache(CraftEngineConverter plugin) { - super(plugin); - this.setPermission(Permission.COMMAND_CLEARFILESCACHE); - this.setDescription(Message.COMMAND__CLEAR_FILES_CACHE__DESCRIPTION); - this.addSubCommand("clearfilescache"); - this.addFlag("--all"); + super(plugin, "clearfilescache", "cfc"); + this.messageFormatter = plugin.getMessageFormatter(); + this.setPermission(Permission.COMMAND_CLEARFILESCACHE.asPermission()); + this.addFlag("all"); } @Override - protected CommandType perform(CraftEngineConverter plugin) { - boolean clearAll = this.containFlag("--all"); + protected @NotNull CommandResultType perform(@NotNull CommandDispatch commandDispatch) { long startTime = System.currentTimeMillis(); long clearedFiles; - if (clearAll) { + if (commandDispatch.hasFlag("all")) { clearedFiles = FileCacheManager.getTotalSize(); FileCacheManager.invalidateAllCaches(); } else { clearedFiles = FileCacheManager.cleanStaleEntries(); } - this.messageFormatter.sendMessage(Message.COMMAND__CLEAR_FILES_CACHE__COMPLETE,this.sender, Placeholder.of("cleared_files", String.valueOf(clearedFiles), "time", TimerBuilder.formatTimeAuto(System.currentTimeMillis() - startTime))); - return CommandType.SUCCESS; + this.messageFormatter.sendMessage(Message.COMMAND__CLEAR_FILES_CACHE__COMPLETE, commandDispatch.getSender(), Placeholder.of("cleared_files", String.valueOf(clearedFiles), "time", TimerBuilder.formatTimeAuto(System.currentTimeMillis() - startTime))); + return CommandResultType.SUCCESS; } } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandConvert.java b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandConvert.java index 7907e804..4294e5e9 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandConvert.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandConvert.java @@ -1,119 +1,119 @@ package fr.robie.craftengineconverter.command; +import com.mojang.brigadier.arguments.StringArgumentType; import fr.robie.craftengineconverter.CraftEngineConverter; import fr.robie.craftengineconverter.api.builder.TimerBuilder; import fr.robie.craftengineconverter.api.enums.ConverterOption; import fr.robie.craftengineconverter.api.enums.CraftEngineBlockState; import fr.robie.craftengineconverter.api.format.Message; +import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.permission.Permission; import fr.robie.craftengineconverter.converter.Converter; -import fr.robie.craftengineconverter.utils.command.CommandType; -import fr.robie.craftengineconverter.utils.command.VCommand; +import fr.robie.messageflow.formatter.MessageFormatter; import fr.robie.messageflow.formatter.Placeholder; +import fr.robie.paperdispatch.argument.EnumArgument; +import fr.robie.paperdispatch.command.CommandDispatch; +import fr.robie.paperdispatch.command.CommandResultType; +import fr.robie.paperdispatch.command.SubCommand; +import fr.robie.paperdispatch.flag.Flags; +import io.papermc.paper.command.brigadier.Commands; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; -public class CraftEngineConverterCommandConvert extends VCommand { +public class CraftEngineConverterCommandConvert extends SubCommand { private final List> conversionTasks = new ArrayList<>(); + private final MessageFormatter messageFormatter; public CraftEngineConverterCommandConvert(CraftEngineConverter plugin) { - super(plugin); - this.setPermission(Permission.COMMAND_CONVERT); - this.setDescription(Message.COMMAND__CONVERTER__DESCRIPTION); - this.addSubCommand("convert"); - this.addOptionalArg("plugin", (sender, args) -> this.plugin.getConverterNames()); - this.addOptionalArg("type", (sender, args) -> { - Set options = new HashSet<>(); - for (ConverterOption o : ConverterOption.values()) { - options.add(o.name()); + super(plugin, "convert"); + this.messageFormatter = plugin.getMessageFormatter(); + this.setPermission(Permission.COMMAND_CONVERT.asPermission()); + + this.addOptionalArgument(Commands.argument("plugin", StringArgumentType.word()).suggests(((context, builder) -> { + this.plugin.getConverterNames().stream().filter(name -> name.toLowerCase(Locale.ROOT).startsWith(builder.getRemaining())).forEach(builder::suggest); + return builder.buildFuture(); + }))); + this.addOptionalArgument(Commands.argument("type", new EnumArgument<>(ConverterOption.class))); + + this.addFlag("dryrun"); + this.addFlag("force"); + this.addFlag(Flags.intFlag("threads").defaultTo(1)); + } + + private void disableAllConversions() { + if (!this.conversionTasks.isEmpty()) { + for (CompletableFuture task : new ArrayList<>(this.conversionTasks)) { + task.cancel(true); } - return options; - }); - this.addFlag("--dryrun"); - this.addFlag("--force"); - this.addFlag("--threads", Integer.class, 1); - this.setTabCompletor(); + this.conversionTasks.clear(); + } } @Override - protected CommandType perform(CraftEngineConverter plugin) { - boolean forceConversion = this.containFlag("--force"); + protected @NotNull CommandResultType perform(@NotNull CommandDispatch commandDispatch) { + CommandSender sender = commandDispatch.getSender(); + boolean forceConversion = commandDispatch.hasFlag("force"); if (!this.conversionTasks.isEmpty() && !forceConversion) { - this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__ALREADY_RUNNING, this.sender); - return CommandType.SUCCESS; + this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__ALREADY_RUNNING, sender); + return CommandResultType.SUCCESS; } if (forceConversion) { - this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__FORCE_STOPPING, this.sender); + this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__FORCE_STOPPING, sender); this.disableAllConversions(); } - String targetPlugin = this.argAsString(0); - ConverterOption converterOption = this.argAsEnum(1, ConverterOption.class, ConverterOption.ALL); - boolean dryRun = this.containFlag("--dryrun"); - if (dryRun) { - this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__DRY_RUN_NOTE, this.sender); - } - int threads = this.getFlagValueAsInteger("--threads"); + ConverterOption converterOption = commandDispatch.getArgument("type", ConverterOption.class, ConverterOption.ALL); + int threads = commandDispatch.getFlagValue("threads", Integer.class); if (threads < 1) { threads = 1; } else if (threads > Runtime.getRuntime().availableProcessors()) { int availableProcessors = Runtime.getRuntime().availableProcessors(); threads = availableProcessors; - this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__THREADS__ERROR_TOO_MANY, this.sender, Placeholder.of("max", String.valueOf(availableProcessors))); + this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__THREADS__ERROR_TOO_MANY, sender, Placeholder.of("max", String.valueOf(availableProcessors))); } - this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__THREADS__INFO, this.sender, Placeholder.of("threads", String.valueOf(threads))); + this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__THREADS__INFO, sender, Placeholder.of("threads", String.valueOf(threads))); CraftEngineBlockState.resetAllLimits(); - if (targetPlugin == null) { + Optional optionalPlugin = commandDispatch.getOptionalArgument("plugin", String.class); + if (optionalPlugin.isPresent()) { + String targetPlugin = optionalPlugin.get(); + Optional optionalConverter = this.plugin.getConverter(targetPlugin); + if (optionalConverter.isPresent()) { + long startTime = System.currentTimeMillis(); + this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__START__SINGLE, sender, Placeholder.of("plugin", targetPlugin)); + Converter converter = optionalConverter.get(); + CompletableFuture voidCompletableFuture = converter.convert(converterOption, Optional.ofNullable(commandDispatch.getPlayer()), commandDispatch.hasFlag("dryrun"), threads); + voidCompletableFuture.thenRun(() -> { + long endTime = System.currentTimeMillis(); + this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__COMPLETE__SINGLE, sender, Placeholder.of("plugin", targetPlugin, "time", TimerBuilder.formatTimeAuto(endTime - startTime))); + this.conversionTasks.remove(voidCompletableFuture); + }); + this.conversionTasks.add(voidCompletableFuture); + } else { + this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__NOT_SUPPORTED, sender, Placeholder.of("plugin", targetPlugin)); + } + } else { long startTime = System.currentTimeMillis(); - this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__START__ALL,this.sender); - Collection converters = plugin.getConverters(); + this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__START__ALL,sender); + Collection converters = this.plugin.getConverters(); AtomicInteger counter = new AtomicInteger(converters.size()); for (Converter converter : converters) { - CompletableFuture voidCompletableFuture = converter.convert(converterOption, Optional.ofNullable(this.player), dryRun, threads); + CompletableFuture voidCompletableFuture = converter.convert(converterOption, Optional.ofNullable(commandDispatch.getPlayer()), commandDispatch.hasFlag("dryrun"), threads); voidCompletableFuture.thenRun(() -> { int remaining = counter.decrementAndGet(); if (remaining == 0) { long endTime = System.currentTimeMillis(); - this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__COMPLETE__ALL, this.sender, Placeholder.of("time", TimerBuilder.formatTimeAuto(endTime - startTime))); + this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__COMPLETE__ALL, sender, Placeholder.of("time", TimerBuilder.formatTimeAuto(endTime - startTime))); } this.conversionTasks.remove(voidCompletableFuture); }); this.conversionTasks.add(voidCompletableFuture); } - } else { - Optional optionalConverter = plugin.getConverter(targetPlugin); - if (optionalConverter.isPresent()) { - long startTime = System.currentTimeMillis(); - this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__START__SINGLE, this.sender, Placeholder.of("plugin", targetPlugin)); - Converter converter = optionalConverter.get(); - CompletableFuture voidCompletableFuture = converter.convert(converterOption, Optional.ofNullable(this.player), dryRun, threads); - voidCompletableFuture.thenRun(() -> { - long endTime = System.currentTimeMillis(); - this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__COMPLETE__SINGLE, this.sender, Placeholder.of("plugin", targetPlugin, "time", TimerBuilder.formatTimeAuto(endTime - startTime))); - this.conversionTasks.remove(voidCompletableFuture); - }); - this.conversionTasks.add(voidCompletableFuture); - } else { - this.messageFormatter.sendMessage(Message.COMMAND__CONVERTER__NOT_SUPPORTED, this.sender, Placeholder.of("plugin", targetPlugin)); - } - } - return CommandType.SUCCESS; - } - - private void disableAllConversions() { - if (!this.conversionTasks.isEmpty()) { - for (CompletableFuture task : new ArrayList<>(this.conversionTasks)) { - task.cancel(true); - } - this.conversionTasks.clear(); } - } - - @Override - public void onDisable() { - this.disableAllConversions(); + return CommandResultType.SUCCESS; } } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandReload.java b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandReload.java index 8102eb2c..78bcf3a3 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandReload.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandReload.java @@ -3,34 +3,41 @@ import fr.robie.craftengineconverter.CraftEngineConverter; import fr.robie.craftengineconverter.api.builder.TimerBuilder; import fr.robie.craftengineconverter.api.format.Message; - +import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.permission.Permission; -import fr.robie.craftengineconverter.utils.command.CommandType; -import fr.robie.craftengineconverter.utils.command.VCommand; +import fr.robie.messageflow.formatter.MessageFormatter; import fr.robie.messageflow.formatter.Placeholder; import fr.robie.messageflow.logger.Logger; +import fr.robie.paperdispatch.command.CommandDispatch; +import fr.robie.paperdispatch.command.CommandResultType; +import fr.robie.paperdispatch.command.SubCommand; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; + +public class CraftEngineConverterCommandReload extends SubCommand { + private final MessageFormatter messageFormatter; -public class CraftEngineConverterCommandReload extends VCommand { public CraftEngineConverterCommandReload(CraftEngineConverter plugin) { - super(plugin); - this.addSubCommand("reload", "rl"); - this.setPermission(Permission.COMMAND_RELOAD); - this.setDescription(Message.COMMAND__RELOAD__DESCRIPTION); + super(plugin, "reload", "rl"); + this.messageFormatter = plugin.getMessageFormatter(); + this.setPermission(Permission.COMMAND_RELOAD.asPermission()); } @Override - protected CommandType perform(CraftEngineConverter plugin) { + protected fr.robie.paperdispatch.command.@NotNull CommandResultType perform(@NotNull CommandDispatch commandDispatch) { + CommandSender sender = commandDispatch.getSender(); try { long startTime = System.currentTimeMillis(); - plugin.reloadBlockStateMappings(); - plugin.reloadConfig(); - plugin.reloadMessages(); + commandDispatch.getPlugin().reloadBlockStateMappings(); + commandDispatch.getPlugin().reloadConfig(); + commandDispatch.getPlugin().reloadMessages(); long endTime = System.currentTimeMillis(); - this.messageFormatter.sendMessage(Message.COMMAND__RELOAD__SUCCESS, this.sender, Placeholder.of("time", TimerBuilder.formatTimeAuto(endTime - startTime))); + this.messageFormatter.sendMessage(Message.COMMAND__RELOAD__SUCCESS, sender, Placeholder.of("time", TimerBuilder.formatTimeAuto(endTime - startTime))); + return CommandResultType.SUCCESS; } catch (Exception e) { Logger.error("An error occurred while reloading the plugin.", e); - this.messageFormatter.sendMessage(Message.COMMAND__RELOAD__FAILURE, this.sender); + this.messageFormatter.sendMessage(Message.COMMAND__RELOAD__FAILURE, sender); + return CommandResultType.FAILURE; } - return CommandType.SUCCESS; } } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverter.java b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverter.java index 598e3450..0a47df9a 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverter.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverter.java @@ -1,26 +1,24 @@ package fr.robie.craftengineconverter.command; import fr.robie.craftengineconverter.CraftEngineConverter; -import fr.robie.craftengineconverter.api.format.Message; import fr.robie.craftengineconverter.common.permission.Permission; -import fr.robie.craftengineconverter.utils.command.CommandType; -import fr.robie.craftengineconverter.utils.command.VCommand; +import fr.robie.paperdispatch.command.CommandDispatch; +import fr.robie.paperdispatch.command.CommandResultType; +import fr.robie.paperdispatch.command.SubCommand; +import org.jetbrains.annotations.NotNull; -public class CraftEngineConverterCommandWorldConverter extends VCommand { +public class CraftEngineConverterCommandWorldConverter extends SubCommand { public CraftEngineConverterCommandWorldConverter(CraftEngineConverter plugin) { - super(plugin); - this.setPermission(Permission.COMMAND_WORLDCONVERTER); - this.setDescription(Message.COMMAND__WORLD_CONVERTER__DESCRIPTION); - this.addSubCommand("worldconverter", "wc"); + super(plugin, "worldconverter", "wc"); + this.setPermission(Permission.COMMAND_WORLDCONVERTER.asPermission()); this.addSubCommand(new CraftEngineConverterCommandWorldConverterClearCachedChunks(plugin)); this.addSubCommand(new CraftEngineConverterCommandWorldConverterStart(plugin)); this.addSubCommand(new CraftEngineConverterCommandWorldConverterRestore(plugin)); } @Override - protected CommandType perform(CraftEngineConverter plugin) { - this.syntaxMessage(); - return CommandType.SUCCESS; + protected @NotNull CommandResultType perform(@NotNull CommandDispatch commandDispatch) { + return CommandResultType.SUCCESS; } } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterClearCachedChunks.java b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterClearCachedChunks.java index d6d29bc0..32334c34 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterClearCachedChunks.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterClearCachedChunks.java @@ -3,34 +3,39 @@ import fr.robie.craftengineconverter.CraftEngineConverter; import fr.robie.craftengineconverter.api.builder.TimerBuilder; import fr.robie.craftengineconverter.api.format.Message; +import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.permission.Permission; import fr.robie.craftengineconverter.listener.WorldConverterManager; -import fr.robie.craftengineconverter.utils.command.CommandType; -import fr.robie.craftengineconverter.utils.command.VCommand; +import fr.robie.messageflow.formatter.MessageFormatter; import fr.robie.messageflow.formatter.Placeholder; +import fr.robie.paperdispatch.command.CommandDispatch; +import fr.robie.paperdispatch.command.CommandResultType; +import fr.robie.paperdispatch.command.SubCommand; +import org.jetbrains.annotations.NotNull; + +public class CraftEngineConverterCommandWorldConverterClearCachedChunks extends SubCommand { + private final MessageFormatter messageFormatter; -public class CraftEngineConverterCommandWorldConverterClearCachedChunks extends VCommand { public CraftEngineConverterCommandWorldConverterClearCachedChunks(CraftEngineConverter plugin) { - super(plugin); - this.setPermission(Permission.COMMAND_WORLDCONVERTER_CLEAR_CACHED_CHUNKS); - this.setDescription(Message.COMMAND__WORLD_CONVERTER__CLEAR_CACHED_CHUNKS__DESCRIPTION); - this.addSubCommand("clear-cached-chunks"); + super(plugin, "clear-cached-chunks"); + this.messageFormatter = plugin.getMessageFormatter(); + this.setPermission(Permission.COMMAND_WORLDCONVERTER_CLEAR_CACHED_CHUNKS.asPermission()); } @Override - protected CommandType perform(CraftEngineConverter plugin) { + protected @NotNull CommandResultType perform(@NotNull CommandDispatch commandDispatch) { long startTime = System.currentTimeMillis(); - WorldConverterManager worldConverterManager = plugin.getWorldConverterManager(); + WorldConverterManager worldConverterManager = this.plugin.getWorldConverterManager(); int clearedChunks = worldConverterManager.getProcessedChunksCount(); worldConverterManager.clearProcessedChunks(); long endTime = System.currentTimeMillis(); - this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__CLEAR_CACHED_CHUNKS__COMPLETE, this.sender, + this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__CLEAR_CACHED_CHUNKS__COMPLETE, commandDispatch.getSender(), Placeholder.of("chunks", String.valueOf(clearedChunks), "time", TimerBuilder.formatTimeAuto(endTime - startTime))); - return CommandType.SUCCESS; + return CommandResultType.SUCCESS; } } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterRestore.java b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterRestore.java index a2b61ad0..688bacdb 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterRestore.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterRestore.java @@ -6,13 +6,15 @@ import fr.robie.craftengineconverter.api.format.Message; import fr.robie.craftengineconverter.api.history.BlockHistory; import fr.robie.craftengineconverter.api.history.EntityHistory; - import fr.robie.craftengineconverter.api.profile.ServerProfile; +import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.permission.Permission; -import fr.robie.craftengineconverter.utils.command.CommandType; -import fr.robie.craftengineconverter.utils.command.VCommand; +import fr.robie.messageflow.formatter.MessageFormatter; import fr.robie.messageflow.formatter.Placeholder; import fr.robie.messageflow.logger.Logger; +import fr.robie.paperdispatch.command.CommandDispatch; +import fr.robie.paperdispatch.command.CommandResultType; +import fr.robie.paperdispatch.command.SubCommand; import net.momirealms.craftengine.bukkit.api.CraftEngineBlocks; import net.momirealms.craftengine.bukkit.api.CraftEngineFurniture; import org.bukkit.Bukkit; @@ -20,41 +22,79 @@ import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; +import org.bukkit.command.CommandSender; import org.bukkit.entity.EntitySnapshot; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -public class CraftEngineConverterCommandWorldConverterRestore extends VCommand { +public class CraftEngineConverterCommandWorldConverterRestore extends SubCommand { + /** Rows restored per scheduled tick. */ + private static final int PAGE_SIZE = 50; + + private final MessageFormatter messageFormatter; public CraftEngineConverterCommandWorldConverterRestore(CraftEngineConverter plugin) { - super(plugin); - this.setPermission(Permission.COMMAND_WORLDCONVERTER_RESTORE); - this.setDescription(Message.COMMAND__WORLD_CONVERTER__RESTORE__DESCRIPTION); - this.addSubCommand("restore"); - this.addFlag("--confirm"); + super(plugin, "restore", "r"); + this.messageFormatter = plugin.getMessageFormatter(); + this.setPermission(Permission.COMMAND_WORLDCONVERTER_RESTORE.asPermission()); + this.addFlag("confirm"); + } + + /** + * Restores a block to its original state. + * + * @param location The location of the block + * @param history The block history containing the original block data + */ + private void restoreBlock(Location location, BlockHistory history) { + Block block = location.getBlock(); + + if (CraftEngineBlocks.isCustomBlock(block)) { + CraftEngineBlocks.remove(block); + + } + + try { + org.bukkit.block.data.BlockData blockData = Bukkit.createBlockData(history.getOriginalBlock()); + block.setBlockData(blockData, false); + } catch (Exception e) { + Logger.error("Failed to parse block data: " + history.getOriginalBlock(), e); + try { + String materialName = history.getOriginalBlock().split("\\[")[0]; + Material material = Material.matchMaterial(materialName); + if (material != null) { + block.setType(material, false); + } + } catch (Exception ex) { + Logger.error("Failed to restore block, setting to AIR", ex); + block.setType(Material.AIR, false); + } + } } @Override - protected CommandType perform(CraftEngineConverter plugin) { + protected @NotNull CommandResultType perform(@NotNull CommandDispatch commandDispatch) { StorageManager dataBaseManager = this.plugin.getStorageManager(); ServerProfile serverProfile = this.plugin.getServerProfile(); + CommandSender sender = commandDispatch.getSender(); if (!dataBaseManager.isEnabled()) { - this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__RESTORE__DATABASE_DISABLED, this.sender); - return CommandType.SUCCESS; + this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__RESTORE__DATABASE_DISABLED, sender); + return CommandResultType.SUCCESS; } - boolean confirm = this.containFlag("--confirm"); + boolean confirm = commandDispatch.hasFlag("confirm"); int activeBlockConversions = serverProfile.getActiveBlockCount(); int activeEntityConversions = serverProfile.getActiveEntityCount(); int totalActiveConversions = activeBlockConversions + activeEntityConversions; if (totalActiveConversions == 0) { - this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__RESTORE__ALL__NONE, this.sender); - return CommandType.SUCCESS; + this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__RESTORE__ALL__NONE, sender); + return CommandResultType.SUCCESS; } Placeholder.Builder builder = Placeholder.builder(); @@ -62,31 +102,56 @@ protected CommandType perform(CraftEngineConverter plugin) { .register("blocks", String.valueOf(activeBlockConversions)) .register("entities", String.valueOf(activeEntityConversions)); if (!confirm) { - this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__RESTORE__ALL__CONFIRM, this.sender, builder.build()); - return CommandType.SUCCESS; + this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__RESTORE__ALL__CONFIRM, sender, builder.build()); + return CommandResultType.SUCCESS; } - this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__RESTORE__ALL__START, this.sender, builder.build()); + this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__RESTORE__ALL__START, sender, builder.build()); - long startTime = System.currentTimeMillis(); - AtomicInteger restoredBlockCount = new AtomicInteger(0); - AtomicInteger restoredEntityCount = new AtomicInteger(0); - AtomicInteger totalBlockCount = new AtomicInteger(0); - AtomicInteger totalEntityCount = new AtomicInteger(0); + Progress progress = new Progress(System.currentTimeMillis()); + this.restoreBlockPage(sender, builder, progress, 0L); - // Restore blocks - List allHistory = new ArrayList<>(serverProfile.getAllActiveConversions()); + return CommandResultType.SUCCESS; + } - final int BATCH_SIZE = 50; + /** Counters shared by the pages of one restore. */ + private record Progress(long startTime, AtomicInteger restoredBlocks, AtomicInteger restoredEntities, + AtomicInteger seenBlocks, AtomicInteger seenEntities) { - for (int i = 0; i < allHistory.size(); i += BATCH_SIZE) { - final int end = Math.min(i + BATCH_SIZE, allHistory.size()); - final List batch = allHistory.subList(i, end); - final long tickDelay = i / BATCH_SIZE; + private Progress(long startTime) { + this(startTime, new AtomicInteger(), new AtomicInteger(), new AtomicInteger(), new AtomicInteger()); + } + } - plugin.getFoliaCompatibilityManager().runLater(() -> { - for (BlockHistory history : batch) { - totalBlockCount.incrementAndGet(); + /** + * Restores one page of blocks and schedules the next. + *

+ * The pages are read as the restore goes rather than up front. Reading them all first meant holding every record + * in memory at once - on a world-sized conversion, more than the index it replaced - and scheduling one task per + * fifty rows before any work began, which for a million blocks is twenty thousand tasks queued in advance. + */ + private void restoreBlockPage(CommandSender sender, Placeholder.Builder builder, Progress progress, long afterId) { + StorageManager storage = this.plugin.getStorageManager(); + ServerProfile serverProfile = this.plugin.getServerProfile(); + + // Read off the main thread: a page per tick against a remote database would otherwise stall the server for + // a round trip every tick, for as long as the restore runs. + this.plugin.getFoliaCompatibilityManager().runAsync(() -> { + List page = storage.nextActiveBlockPage(afterId, PAGE_SIZE); + if (page.isEmpty()) { + this.restoreEntityPage(sender, builder, progress, 0L); + return; + } + + this.plugin.getFoliaCompatibilityManager().runLater(() -> { + List restoredIds = new ArrayList<>(page.size()); + long lastId = afterId; + + for (BlockHistory history : page) { + progress.seenBlocks().incrementAndGet(); + if (history.getId() != null) { + lastId = history.getId(); + } World world = Bukkit.getWorld(history.getWorldName()); if (world == null) { @@ -98,46 +163,56 @@ protected CommandType perform(CraftEngineConverter plugin) { chunk.load(); } - Location location = new Location( - world, - history.getBlockX(), - history.getBlockY(), - history.getBlockZ() - ); - + Location location = new Location(world, history.getBlockX(), history.getBlockY(), history.getBlockZ()); try { this.restoreBlock(location, history); - serverProfile.markBlockAsReverted(history); - restoredBlockCount.incrementAndGet(); + serverProfile.forgetBlock(history); + if (history.getId() != null) { + restoredIds.add(history.getId()); + } + progress.restoredBlocks().incrementAndGet(); } catch (Exception e) { Logger.error("Failed to restore block at " + location, e); } } - }, tickDelay); - } - List allEntityHistory = new ArrayList<>(serverProfile.getAllActiveEntityConversions()); + // A page that restored nothing would otherwise be read for ever, since nothing was marked reverted. + long nextId = lastId > afterId ? lastId : afterId + PAGE_SIZE; + this.plugin.getFoliaCompatibilityManager().runAsync(() -> { + storage.markBlocksAsReverted(restoredIds); + this.restoreBlockPage(sender, builder, progress, nextId); + }); + }, 1L); + }); + } - for (int i = 0; i < allEntityHistory.size(); i += BATCH_SIZE) { - final int end = Math.min(i + BATCH_SIZE, allEntityHistory.size()); - final List batch = allEntityHistory.subList(i, end); - final long tickDelay = (allHistory.size() / BATCH_SIZE) + (i / BATCH_SIZE); + private void restoreEntityPage(CommandSender sender, Placeholder.Builder builder, Progress progress, long afterId) { + StorageManager storage = this.plugin.getStorageManager(); + ServerProfile serverProfile = this.plugin.getServerProfile(); - plugin.getFoliaCompatibilityManager().runLater(() -> { - for (EntityHistory entityHistory : batch) { - totalEntityCount.incrementAndGet(); + this.plugin.getFoliaCompatibilityManager().runAsync(() -> { + List page = storage.nextActiveEntityPage(afterId, PAGE_SIZE); + if (page.isEmpty()) { + this.plugin.getFoliaCompatibilityManager().runNextTick(() -> this.reportComplete(sender, builder, progress)); + return; + } - Location location = entityHistory.getLocation(); - if (location == null) { - continue; + this.plugin.getFoliaCompatibilityManager().runLater(() -> { + List restoredIds = new ArrayList<>(page.size()); + long lastId = afterId; + + for (EntityHistory entityHistory : page) { + progress.seenEntities().incrementAndGet(); + if (entityHistory.getId() != null) { + lastId = entityHistory.getId(); } - World world = location.getWorld(); - if (world == null) { + Location location = entityHistory.getLocation(); + if (location == null || location.getWorld() == null) { continue; } - world.getNearbyEntities(location, 1, 1, 1).forEach(entity -> { + location.getWorld().getNearbyEntities(location, 1, 1, 1).forEach(entity -> { if (CraftEngineFurniture.isFurniture(entity)) { CraftEngineFurniture.remove(entity); } @@ -147,63 +222,35 @@ protected CommandType perform(CraftEngineConverter plugin) { EntitySnapshot entitySnapshot = Bukkit.getEntityFactory().createEntitySnapshot(entityHistory.getNbt()); entitySnapshot.createEntity(location); - serverProfile.markEntityAsReverted(entityHistory); - restoredEntityCount.incrementAndGet(); + serverProfile.forgetEntity(entityHistory); + if (entityHistory.getId() != null) { + restoredIds.add(entityHistory.getId()); + } + progress.restoredEntities().incrementAndGet(); } catch (Exception e) { Logger.error("Failed to restore entity at " + location, e); } } - }, tickDelay); - } - long totalDelayTicks = (long) Math.ceil((double) (allHistory.size() + allEntityHistory.size()) / BATCH_SIZE); - - plugin.getFoliaCompatibilityManager().runLater(() -> { - - long endTime = System.currentTimeMillis(); - - builder.register("restored", String.valueOf(restoredBlockCount.get() + restoredEntityCount.get())) - .register("restored_blocks", String.valueOf(restoredBlockCount.get())) - .register("restored_entities", String.valueOf(restoredEntityCount.get())) - .register("total", String.valueOf(totalBlockCount.get() + totalEntityCount.get())) - .register("total_blocks", String.valueOf(totalBlockCount.get())) - .register("total_entities", String.valueOf(totalEntityCount.get())) - .register("time", TimerBuilder.formatTimeAuto(endTime - startTime)); - this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__RESTORE__ALL__COMPLETE, this.sender, builder.build()); - }, totalDelayTicks + 1); - - return CommandType.SUCCESS; + long nextId = lastId > afterId ? lastId : afterId + PAGE_SIZE; + this.plugin.getFoliaCompatibilityManager().runAsync(() -> { + storage.markEntitiesAsReverted(restoredIds); + this.restoreEntityPage(sender, builder, progress, nextId); + }); + }, 1L); + }); } - /** - * Restores a block to its original state. - * - * @param location The location of the block - * @param history The block history containing the original block data - */ - private void restoreBlock(Location location, BlockHistory history) { - Block block = location.getBlock(); - - if (CraftEngineBlocks.isCustomBlock(block)) { - CraftEngineBlocks.remove(block); - - } - - try { - org.bukkit.block.data.BlockData blockData = Bukkit.createBlockData(history.getOriginalBlock()); - block.setBlockData(blockData, false); - } catch (Exception e) { - Logger.error("Failed to parse block data: " + history.getOriginalBlock(), e); - try { - String materialName = history.getOriginalBlock().split("\\[")[0]; - Material material = Material.matchMaterial(materialName); - if (material != null) { - block.setType(material, false); - } - } catch (Exception ex) { - Logger.error("Failed to restore block, setting to AIR", ex); - block.setType(Material.AIR, false); - } - } + private void reportComplete(CommandSender sender, Placeholder.Builder builder, Progress progress) { + long endTime = System.currentTimeMillis(); + + builder.register("restored", String.valueOf(progress.restoredBlocks().get() + progress.restoredEntities().get())) + .register("restored_blocks", String.valueOf(progress.restoredBlocks().get())) + .register("restored_entities", String.valueOf(progress.restoredEntities().get())) + .register("total", String.valueOf(progress.seenBlocks().get() + progress.seenEntities().get())) + .register("total_blocks", String.valueOf(progress.seenBlocks().get())) + .register("total_entities", String.valueOf(progress.seenEntities().get())) + .register("time", TimerBuilder.formatTimeAuto(endTime - progress.startTime())); + this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__RESTORE__ALL__COMPLETE, sender, builder.build()); } -} +} \ No newline at end of file diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterStart.java b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterStart.java index 810c155d..d7348dbe 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterStart.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/command/CraftEngineConverterCommandWorldConverterStart.java @@ -5,51 +5,61 @@ import fr.robie.craftengineconverter.api.configuration.Configuration; import fr.robie.craftengineconverter.api.format.Message; import fr.robie.craftengineconverter.api.progress.BukkitProgressBar; +import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; import fr.robie.craftengineconverter.common.permission.Permission; import fr.robie.craftengineconverter.listener.WorldConverterManager; -import fr.robie.craftengineconverter.utils.command.CommandType; -import fr.robie.craftengineconverter.utils.command.VCommand; +import fr.robie.messageflow.formatter.MessageFormatter; import fr.robie.messageflow.formatter.Placeholder; +import fr.robie.paperdispatch.command.CommandDispatch; +import fr.robie.paperdispatch.command.CommandResultType; +import fr.robie.paperdispatch.command.SubCommand; +import fr.robie.paperdispatch.flag.Flags; import org.bukkit.Bukkit; import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.concurrent.CompletableFuture; -public class CraftEngineConverterCommandWorldConverterStart extends VCommand { +public class CraftEngineConverterCommandWorldConverterStart extends SubCommand { + private final MessageFormatter messageFormatter; private CompletableFuture currentConversion = null; public CraftEngineConverterCommandWorldConverterStart(CraftEngineConverter plugin) { - super(plugin); - this.setPermission(Permission.COMMAND_WORLDCONVERTER_START); - this.addSubCommand("start"); - this.addFlag("--force"); - this.addFlag("--chunks-per-tick", Integer.class, 10); + super(plugin, "start"); + this.messageFormatter = plugin.getMessageFormatter(); + this.setPermission(Permission.COMMAND_WORLDCONVERTER_START.asPermission()); + this.addFlag("force"); + this.addFlag(Flags.intFlag("chunks-per-tick", 1, 100).defaultTo(10)); + } + + public void onDisable() { + if (this.currentConversion != null && !this.currentConversion.isDone()) { + this.currentConversion.cancel(true); + } } @Override - protected CommandType perform(CraftEngineConverter plugin) { - WorldConverterManager worldConverterManager = plugin.getWorldConverterManager(); + protected @NotNull CommandResultType perform(@NotNull CommandDispatch commandDispatch) { + WorldConverterManager worldConverterManager = this.plugin.getWorldConverterManager(); - boolean forceConversion = this.containFlag("--force"); + boolean forceConversion = commandDispatch.hasFlag("force"); + CommandSender sender = commandDispatch.getSender(); if (this.currentConversion != null && !this.currentConversion.isDone() && !forceConversion) { - this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__ALREADY_RUNNING, this.sender); - return CommandType.SUCCESS; + this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__ALREADY_RUNNING, sender); + return CommandResultType.SUCCESS; } if (forceConversion && this.currentConversion != null && !this.currentConversion.isDone()) { - this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__FORCE_STOPPING, this.sender); + this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__FORCE_STOPPING, sender); worldConverterManager.cancelAllConversions(); this.currentConversion.cancel(true); } - int chunksPerTick = this.getFlagValueAsInteger("--chunks-per-tick"); - if (chunksPerTick < 1) { - chunksPerTick = 1; - } else if (chunksPerTick > 100) { - chunksPerTick = 100; - } + int chunksPerTick = commandDispatch.getFlagValue("chunks-per-tick", Integer.class); List worlds = Bukkit.getServer().getWorlds(); int totalChunks = 0; @@ -58,13 +68,14 @@ protected CommandType perform(CraftEngineConverter plugin) { } BukkitProgressBar.Builder builder = new BukkitProgressBar.Builder(totalChunks).options(Configuration.worldConverterProgressBarOptions).prefix("World Converter:").suffix("chunks").updateInterval(5000); - if (this.player != null) { - builder.player(this.player); + Player player = commandDispatch.getPlayer(); + if (player != null) { + builder.player(player); builder.showBar(false); } BukkitProgressBar progressBar = builder.build(this.plugin); - this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__START, this.sender, Placeholder.of("chunks", String.valueOf(totalChunks))); + this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__START, sender, Placeholder.of("chunks", String.valueOf(totalChunks))); int oldConvertedBlocks = worldConverterManager.getPlacementTracker().getBlocksConverted(); int oldConvertedFurniture = worldConverterManager.getPlacementTracker().getFurnitureConverted(); @@ -90,16 +101,8 @@ protected CommandType perform(CraftEngineConverter plugin) { .register("furniture", String.valueOf(convertedFurniture - oldConvertedFurniture)) .register("time", TimerBuilder.formatTimeAuto(endTime - startTime)); - this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__COMPLETE, this.sender, placeholderBuilder.build()); + this.messageFormatter.sendMessage(Message.COMMAND__WORLD_CONVERTER__COMPLETE, sender, placeholderBuilder.build()); }); - - return CommandType.SUCCESS; - } - - @Override - public void onDisable() { - if (this.currentConversion != null && !this.currentConversion.isDone()) { - this.currentConversion.cancel(true); - } + return CommandResultType.SUCCESS; } } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/Converter.java b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/Converter.java index ff15ce14..874181c9 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/Converter.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/Converter.java @@ -1,24 +1,23 @@ package fr.robie.craftengineconverter.converter; import fr.robie.craftengineconverter.CraftEngineConverter; +import fr.robie.craftengineconverter.api.cache.FileCacheEntry; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.configuration.ConverterSettings; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.SectionProvider; import fr.robie.craftengineconverter.api.enums.ConverterOption; import fr.robie.craftengineconverter.api.enums.Plugins; import fr.robie.craftengineconverter.api.format.Message; - +import fr.robie.craftengineconverter.api.manager.FileCacheManager; import fr.robie.craftengineconverter.api.progress.BukkitProgressBar; import fr.robie.craftengineconverter.api.utils.ObjectUtils; -import fr.robie.craftengineconverter.common.cache.FileCacheEntry; -import fr.robie.craftengineconverter.common.manager.FileCacheManager; import fr.robie.craftengineconverter.converter.settings.BasicConverterSettings; import fr.robie.craftengineconverter.utils.ConfigFile; import fr.robie.messageflow.formatter.Placeholder; import fr.robie.messageflow.logger.Logger; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.bukkit.entity.Player; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; @@ -42,6 +41,7 @@ public abstract class Converter extends ObjectUtils { protected final String converterName; protected final ConverterSettings settings; protected final Map> packMappings = new HashMap<>(); + protected final UnsupportedFeatures unsupportedFeatures = new UnsupportedFeatures(); public Converter(@NotNull CraftEngineConverter plugin, @NotNull String converterName, @NotNull Plugins pluginType) { this.plugin = plugin; @@ -66,7 +66,7 @@ public CompletableFuture convert(@NotNull ConverterOption converterOption, case RECIPES -> this.convertRecipes(true, optionalPlayer); case PACKS -> this.convertPack(true, optionalPlayer); }; - return conversionTask.thenRun(this.settings::restoreBackup); + return conversionTask.whenComplete((ignored, throwable) -> this.settings.restoreBackup()); } public CompletableFuture convertAll(Optional player) { @@ -95,12 +95,36 @@ public CompletableFuture convertAll(Optional player) { public abstract CompletableFuture convertPack(boolean async, Optional player); + /** Notes configuration this conversion cannot carry over; see {@link #logUnsupportedFeatures()}. */ + public void reportUnsupported(@NotNull String feature, @NotNull String itemId) { + this.unsupportedFeatures.record(feature, itemId); + } + + /** + * Prints everything {@link #reportUnsupported} collected as one digest. Called once a conversion finishes, so a + * mechanic shared by a thousand items is reported on a single line instead of drowning the console. + */ + protected void logUnsupportedFeatures() { + if (this.unsupportedFeatures.isEmpty()) { + return; + } + + this.log(Message.WARNING__CONVERTER__UNSUPPORTED_SUMMARY_HEADER, Logger.LogType.WARNING, Placeholder.empty()); + for (UnsupportedFeatures.Summary summary : this.unsupportedFeatures.summaries()) { + this.log(Message.WARNING__CONVERTER__UNSUPPORTED_SUMMARY_LINE, Logger.LogType.WARNING, Placeholder.builder() + .register("feature", summary.feature()) + .register("count", String.valueOf(summary.count())) + .register("examples", summary.examples()) + .build()); + } + } + protected void log(@NotNull Message message, Logger.LogType logType, Placeholder placeholder) { this.processConverterLog(message, logType, placeholder); } protected void logDebug(@NotNull Message message, Logger.LogType logType, Placeholder placeholder) { - if (Configuration.get(ConfigurationKey.ENABLE_DEBUG)) { + if (Configuration.get(Keys.ENABLE_DEBUG)) { this.processConverterLog(message, logType, placeholder); } } @@ -392,7 +416,7 @@ protected void generateCategorie(List itemsIds, YamlConfiguration config } ConfigurationSection categoriesSection = config.createSection("categories"); ConfigurationSection categorySection = categoriesSection.createSection(itemsIds.getFirst()); - categorySection.set("name", (Configuration.get(ConfigurationKey.DISABLE_DEFAULT_ITALIC) ? "" : "") + "Category " + fileName); + categorySection.set("name", (Configuration.get(Keys.DISABLE_DEFAULT_ITALIC) ? "" : "") + "Category " + fileName); categorySection.set("icon", itemsIds.getFirst()); categorySection.set("list", itemsIds); } @@ -415,22 +439,6 @@ protected void saveConvertedConfig(YamlConfiguration convertedConfig, ConfigFile } } - protected void deleteDirectory(File directory) { - File[] files = directory.listFiles(); - if (files != null) { - for (File file : files) { - if (file.isDirectory()) { - this.deleteDirectory(file); - } else if (!file.delete()) { - this.logDebug(Message.WARNING__FILE__DELETE_FAILURE, Logger.LogType.ERROR, Placeholder.of("file", file.getName(), "path", file.getAbsolutePath())); - } - } - } - if (!directory.delete()) { - this.logDebug(Message.WARNING__FOLDER__DELETE_FAILURE, Logger.LogType.ERROR, Placeholder.of("folder", directory.getName(), "path", directory.getAbsolutePath())); - } - } - public record PackMapping(String namespaceSource, String originalPath, String namespaceTarget, String targetPath, String newName) { public boolean matches(String path) { @@ -497,9 +505,18 @@ protected static class ItemConversionContext implements private final List fileList; private final Set scannedFiles = new HashSet<>(); - private final Map convertersByRawId = new LinkedHashMap<>(); - private final Map fileByRawId = new HashMap<>(); - private final Map finalIdByRawId = new HashMap<>(); + // Keyed by final item id, which is the only identifier guaranteed to be unique: ItemsAdder scopes item ids + // per namespace, so two packs may legitimately both define "ruby". + private final Map convertersById = new LinkedHashMap<>(); + private final Map fileById = new HashMap<>(); + // Dependencies are declared with raw ids, so they need a way back to a final id. Ambiguous raw ids resolve to + // the first item that claimed them. + private final Map idByRawId = new HashMap<>(); + private final Map rawIdById = new HashMap<>(); + // getDependencies() re-reads the item's configuration section on every call, so it is asked exactly once per + // item and the answer - plus its inverse - is kept here. + private final Map> dependenciesById = new HashMap<>(); + private final Map> dependantsByRawDepId = new HashMap<>(); private final Map convertedConfigByFile = new LinkedHashMap<>(); private final Map itemsSectionByFile = new LinkedHashMap<>(); @@ -539,9 +556,9 @@ public void scanWithDependencies() { boolean pendingDependenciesFound = true; while (pendingDependenciesFound) { pendingDependenciesFound = false; - for (T converter : new ArrayList<>(this.convertersByRawId.values())) { - for (String depRawId : converter.getDependencies()) { - if (!this.convertersByRawId.containsKey(depRawId) && this.scanFileContaining(depRawId)) { + for (List dependencies : new ArrayList<>(this.dependenciesById.values())) { + for (String depRawId : dependencies) { + if (!this.idByRawId.containsKey(depRawId) && this.scanFileContaining(depRawId)) { pendingDependenciesFound = true; } } @@ -571,6 +588,16 @@ private void scanFile(ConfigFile configFile) { } String finalItemId = this.finalIdBuilder.build(configFile, rawItemId); try { + ConfigFile owner = this.fileById.get(finalItemId); + if (owner != null) { + Logger.warn(Message.WARNING__CONVERTER__DUPLICATE_ITEM_ID, Placeholder.builder() + .register("item", finalItemId) + .register("first-file", owner.sourceFile().getName()) + .register("second-file", configFile.sourceFile().getName()) + .build()); + continue; + } + T converter = this.factory.create( configFile, rawItemId, finalItemId, itemSection, convertedConfig @@ -578,9 +605,25 @@ private void scanFile(ConfigFile configFile) { if (converter == null) { continue; } - this.convertersByRawId.put(rawItemId, converter); - this.fileByRawId.put(rawItemId, configFile); - this.finalIdByRawId.put(rawItemId, finalItemId); + + List dependencies = converter.getDependencies(); + + this.convertersById.put(finalItemId, converter); + this.fileById.put(finalItemId, configFile); + this.rawIdById.put(finalItemId, rawItemId); + this.dependenciesById.put(finalItemId, dependencies); + for (String depRawId : dependencies) { + this.dependantsByRawDepId.computeIfAbsent(depRawId, k -> new ArrayList<>()).add(converter); + } + + String claimedBy = this.idByRawId.putIfAbsent(rawItemId, finalItemId); + if (claimedBy != null) { + Logger.warn(Message.WARNING__CONVERTER__AMBIGUOUS_DEPENDENCY, Placeholder.builder() + .register("raw-item", rawItemId) + .register("first", claimedBy) + .register("second", finalItemId) + .build()); + } } catch (Exception e) { Logger.error(Message.ERROR__CONVERTER__ITEM_LOAD_FAILURE, e, Placeholder.of("item", finalItemId, "file", configFile.sourceFile().getName())); } @@ -588,7 +631,7 @@ private void scanFile(ConfigFile configFile) { } private boolean scanFileContaining(String rawItemId) { - if (this.fileByRawId.containsKey(rawItemId)) { + if (this.idByRawId.containsKey(rawItemId)) { return false; } for (ConfigFile file : this.fileList) { @@ -596,7 +639,7 @@ private boolean scanFileContaining(String rawItemId) { continue; } this.scanFile(file); - if (this.fileByRawId.containsKey(rawItemId)) { + if (this.idByRawId.containsKey(rawItemId)) { return true; } } @@ -606,76 +649,88 @@ private boolean scanFileContaining(String rawItemId) { private List topologicalSort() { - Map pendingDepsCountByRawId = new LinkedHashMap<>(); - Map> dependantsByRawId = new HashMap<>(); + Map pendingDepsCountById = new LinkedHashMap<>(); + Map> dependantsById = new HashMap<>(); - for (String rawItemId : this.convertersByRawId.keySet()) { - pendingDepsCountByRawId.put(rawItemId, 0); - dependantsByRawId.put(rawItemId, new ArrayList<>()); + for (String itemId : this.convertersById.keySet()) { + pendingDepsCountById.put(itemId, 0); + dependantsById.put(itemId, new ArrayList<>()); } - for (Map.Entry entry : this.convertersByRawId.entrySet()) { - for (String depRawId : entry.getValue().getDependencies()) { - if (!this.convertersByRawId.containsKey(depRawId)) { - continue; - } - dependantsByRawId.get(depRawId).add(entry.getKey()); - pendingDepsCountByRawId.merge(entry.getKey(), 1, Integer::sum); + for (String itemId : this.convertersById.keySet()) { + for (String depId : this.resolveDependencies(itemId)) { + dependantsById.get(depId).add(itemId); + pendingDepsCountById.merge(itemId, 1, Integer::sum); } } Queue resolvedQueue = new LinkedList<>(); - for (Map.Entry entry : pendingDepsCountByRawId.entrySet()) { + for (Map.Entry entry : pendingDepsCountById.entrySet()) { if (entry.getValue() == 0) { resolvedQueue.add(entry.getKey()); } } - List sortedRawIds = new ArrayList<>(); + List sortedIds = new ArrayList<>(); while (!resolvedQueue.isEmpty()) { - String currentRawId = resolvedQueue.poll(); - sortedRawIds.add(currentRawId); - for (String dependantRawId : dependantsByRawId.getOrDefault(currentRawId, Collections.emptyList())) { - if (pendingDepsCountByRawId.merge(dependantRawId, -1, Integer::sum) == 0) { - resolvedQueue.add(dependantRawId); + String currentId = resolvedQueue.poll(); + sortedIds.add(currentId); + for (String dependantId : dependantsById.getOrDefault(currentId, Collections.emptyList())) { + if (pendingDepsCountById.merge(dependantId, -1, Integer::sum) == 0) { + resolvedQueue.add(dependantId); } } } - if (sortedRawIds.size() != this.convertersByRawId.size()) { + if (sortedIds.size() != this.convertersById.size()) { Logger.warn(Message.WARNING__CONVERTER__CIRCULAR_DEPENDENCY); - this.convertersByRawId.keySet().stream() - .filter(rawId -> !sortedRawIds.contains(rawId)) - .forEach(sortedRawIds::add); + Set sorted = new HashSet<>(sortedIds); + this.convertersById.keySet().stream() + .filter(itemId -> !sorted.contains(itemId)) + .forEach(sortedIds::add); } - return sortedRawIds; + return sortedIds; + } + + /** + * Translates a converter's declared dependencies - which are raw, unqualified ids - into the final ids this + * context is keyed by, dropping the ones that no scanned file provides. + */ + private List resolveDependencies(String itemId) { + List resolved = new ArrayList<>(); + for (String depRawId : this.dependenciesById.getOrDefault(itemId, Collections.emptyList())) { + String depId = this.idByRawId.get(depRawId); + if (depId != null && this.convertersById.containsKey(depId)) { + resolved.add(depId); + } + } + return resolved; } public void convertInOrder(BukkitProgressBar progress, @Nullable ItemPostProcessor itemPostProcessor) { - List sortedRawIds = this.topologicalSort(); + List sortedIds = this.topologicalSort(); - for (String rawItemId : sortedRawIds) { - T converter = this.convertersByRawId.get(rawItemId); + for (String finalItemId : sortedIds) { + T converter = this.convertersById.get(finalItemId); if (converter == null) { continue; } try { converter.convertItem(); if (itemPostProcessor != null) { - itemPostProcessor.process(rawItemId, converter); + itemPostProcessor.process(this.rawIdById.get(finalItemId), converter); } - this.injectResolvedDependency(rawItemId, converter); + this.injectResolvedDependency(this.rawIdById.get(finalItemId), converter); } catch (Exception e) { - Logger.error(Message.ERROR__CONVERTER__ITEM_CONVERT_EXCEPTION, e, Placeholder.of("item", this.finalIdByRawId.get(rawItemId))); + Logger.error(Message.ERROR__CONVERTER__ITEM_CONVERT_EXCEPTION, e, Placeholder.of("item", finalItemId)); } finally { progress.increment(); } } - for (String rawItemId : sortedRawIds) { - T converter = this.convertersByRawId.get(rawItemId); + for (String finalItemId : sortedIds) { + T converter = this.convertersById.get(finalItemId); if (converter == null || converter.isInternalOnly()) { continue; } - String finalItemId = this.finalIdByRawId.get(rawItemId); - ConfigFile configFile = this.fileByRawId.get(rawItemId); + ConfigFile configFile = this.fileById.get(finalItemId); try { converter.getCraftEngineItemsConfiguration().serialize( @@ -715,49 +770,14 @@ public void saveAll(File outputBase, Converter converter) { public void injectResolvedDependency(String rawItemId, T resolvedConverter) { - for (T converter : this.convertersByRawId.values()) { - if (converter.getDependencies().contains(rawItemId)) { - converter.addResolvedDependency(rawItemId, resolvedConverter); - } + for (T converter : this.dependantsByRawDepId.getOrDefault(rawItemId, Collections.emptyList())) { + converter.addResolvedDependency(rawItemId, resolvedConverter); } } - - public T getConverter(String rawItemId) { - return this.convertersByRawId.get(rawItemId); - } - - public ConfigFile getFile(String rawItemId) { - return this.fileByRawId.get(rawItemId); - } - - public String getFinalId(String rawItemId) { - return this.finalIdByRawId.get(rawItemId); - } - - public YamlConfiguration getConvertedConfig(ConfigFile file) { - return this.convertedConfigByFile.get(file); - } - - public ConfigurationSection getItemsSection(ConfigFile file) { - return this.itemsSectionByFile.get(file); - } - public List getFinalItemIds(ConfigFile file) { return this.finalItemIdsByFile.getOrDefault(file, Collections.emptyList()); } - public void addFinalItemId(ConfigFile file, String finalItemId) { - this.finalItemIdsByFile.get(file).add(finalItemId); - } - - public List getFiles() { - return this.fileList; - } - - public Set getAllRawIds() { - return this.convertersByRawId.keySet(); - } - } } \ No newline at end of file diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/CraftEngineItemUtils.java b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/CraftEngineItemUtils.java index aeb3b2dd..75431a2d 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/CraftEngineItemUtils.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/CraftEngineItemUtils.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.converter; import fr.robie.craftengineconverter.api.utils.ObjectUtils; -import org.bukkit.configuration.ConfigurationSection; +import fr.robie.yamllibrary.ConfigurationSection; public class CraftEngineItemUtils extends ObjectUtils { private final ConfigurationSection craftEngineItemSection; diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/ItemConverter.java b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/ItemConverter.java index 5acc0265..4a760fff 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/ItemConverter.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/ItemConverter.java @@ -1,13 +1,14 @@ package fr.robie.craftengineconverter.converter; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import org.bukkit.Material; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.configuration.CraftEngineItemsConfiguration; import fr.robie.craftengineconverter.api.configuration.item.models.model.GenerationConfiguration; import fr.robie.craftengineconverter.api.configuration.item.models.model.SimpleModelConfiguration; import fr.robie.craftengineconverter.api.utils.ObjectUtils; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -15,6 +16,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; public abstract class ItemConverter extends ObjectUtils { private final Map resolvedDependencies = new HashMap<>(); @@ -34,12 +36,19 @@ public ItemConverter(@NotNull String itemId, Converter converter, YamlConfigurat this.converter = converter; this.fileConfig = fileConfig; this.fileConfig.options().pathSeparator('\n'); - this.craftEngineItemsConfiguration = new CraftEngineItemsConfiguration(itemId, Configuration.get(ConfigurationKey.DEFAULT_MATERIAL)); + // FIXME: default-material resolves to either a Material or the string "auto", and this needs a Material. + // The untyped accessor hid that with an unchecked cast, so an "auto" here has always been a + // ClassCastException waiting to happen; typing the key only made it visible. Kept as-is so this refactor + // changes no behaviour - resolving "auto" properly (as DefaultMaterialResolver does) is its own + // change. + this.craftEngineItemsConfiguration = new CraftEngineItemsConfiguration( + itemId, (Material) Configuration.get(Keys.DEFAULT_MATERIAL)); } public void convertItem() { this.convertMaterial(); this.convertItemName(); + this.convertCustomName(); this.convertLore(); this.convertDyedColor(); this.convertUnbreakable(); @@ -86,8 +95,12 @@ public void convertItem() { this.convertDamageTypeComponent(); this.convertMinimumAttackChargeComponent(); this.convertProfileComponent(); + this.convertTrim(); + this.convertPotionEffects(); + this.convertWrittenBookContent(); this.convertItemTexture(); this.convertOther(); + this.reportUnsupportedConfiguration(); } public void convertMaterial() { @@ -96,6 +109,9 @@ public void convertMaterial() { public void convertItemName() { } + public void convertCustomName() { + } + public void convertLore() { } @@ -231,6 +247,15 @@ public void convertMinimumAttackChargeComponent() { public void convertProfileComponent() { } + public void convertTrim() { + } + + public void convertPotionEffects() { + } + + public void convertWrittenBookContent() { + } + public void convertItemTexture() { } @@ -240,6 +265,23 @@ public void convertExcludeFromInventory() { public void convertOther() { } + /** + * Runs last, once everything that could be converted has been. Implementations report the configuration they had + * to skip through {@link #reportUnsupported}, which the converter prints as one digest at the end. + */ + public void reportUnsupportedConfiguration() { + } + + /** Notes that this item configured something the conversion does not carry over. */ + protected void reportUnsupported(@NotNull String feature) { + this.converter.reportUnsupported(feature, this.itemId); + } + + /** Notes every key of {@code section} that this converter does not read, reported under {@code prefix}. */ + protected void reportUnhandledKeys(@NotNull String prefix, @Nullable ConfigurationSection section, @NotNull Set handledKeys) { + this.converter.unsupportedFeatures.recordUnhandledKeys(prefix, section, handledKeys, this.itemId); + } + protected boolean notEmptyOrNull(List list, int index) { return list != null && list.size() > index && list.get(index) != null && !list.get(index).isEmpty(); } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/UnsupportedFeatures.java b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/UnsupportedFeatures.java new file mode 100644 index 00000000..dfa7b983 --- /dev/null +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/UnsupportedFeatures.java @@ -0,0 +1,77 @@ +package fr.robie.craftengineconverter.converter; + +import fr.robie.yamllibrary.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/** + * Collects the configuration a converter had to leave behind, so it can be reported once at the end rather than as a + * warning per item. A pack with two thousand items that all use the same unsupported mechanic should produce one line, + * not two thousand. + */ +public final class UnsupportedFeatures { + private static final int MAX_EXAMPLES = 3; + + private final Map occurrencesByFeature = new TreeMap<>(); + + /** Notes that {@code itemId} configured {@code feature}, which the conversion does not carry over. */ + public void record(@NotNull String feature, @NotNull String itemId) { + this.occurrencesByFeature.computeIfAbsent(feature, key -> new Occurrences()).add(itemId); + } + + /** + * Records every key of {@code section} the converter does not read, reported under {@code prefix}. Driving this + * off what the converter actually reads - rather than off a list of what the source plugin supports - means a key + * cannot go quietly missing just because nobody remembered to add it here. + */ + public void recordUnhandledKeys(@NotNull String prefix, @Nullable ConfigurationSection section, + @NotNull Set handledKeys, @NotNull String itemId) { + if (section == null) { + return; + } + for (String key : section.getKeys(false)) { + if (!handledKeys.contains(key)) { + this.record(prefix.isEmpty() ? key : prefix + "." + key, itemId); + } + } + } + + public boolean isEmpty() { + return this.occurrencesByFeature.isEmpty(); + } + + public void clear() { + this.occurrencesByFeature.clear(); + } + + /** One entry per feature, ordered by name, each with how many items used it and a few of their ids. */ + public @NotNull Collection

summaries() { + List summaries = new ArrayList<>(); + this.occurrencesByFeature.forEach((feature, occurrences) -> + summaries.add(new Summary(feature, occurrences.count, String.join(", ", occurrences.examples)))); + return summaries; + } + + public record Summary(String feature, int count, String examples) { + } + + private static final class Occurrences { + private final Set examples = new LinkedHashSet<>(); + private int count; + + private void add(String itemId) { + this.count++; + if (this.examples.size() < MAX_EXAMPLES) { + this.examples.add(itemId); + } + } + } +} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/itemsadder/IAConverter.java b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/itemsadder/IAConverter.java index ff18419b..8596184e 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/itemsadder/IAConverter.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/itemsadder/IAConverter.java @@ -1,8 +1,9 @@ package fr.robie.craftengineconverter.converter.itemsadder; import fr.robie.craftengineconverter.CraftEngineConverter; +import fr.robie.craftengineconverter.api.cache.FileCacheEntry; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.configuration.image.SingleCharacterBitmapConfiguration; import fr.robie.craftengineconverter.api.configuration.recipe.AbstractRecipe; import fr.robie.craftengineconverter.api.configuration.recipe.CookingRecipe; @@ -19,29 +20,28 @@ import fr.robie.craftengineconverter.api.enums.Plugins; import fr.robie.craftengineconverter.api.enums.RecipeType; import fr.robie.craftengineconverter.api.format.Message; - +import fr.robie.craftengineconverter.api.manager.FileCacheManager; import fr.robie.craftengineconverter.api.progress.BukkitProgressBar; +import fr.robie.craftengineconverter.api.utils.FileUtils; import fr.robie.craftengineconverter.common.BlockStatesMapper; import fr.robie.craftengineconverter.common.PluginNameMapper; -import fr.robie.craftengineconverter.common.cache.FileCacheEntry; import fr.robie.craftengineconverter.common.enums.NmsVersion; -import fr.robie.craftengineconverter.common.manager.FileCacheManager; import fr.robie.craftengineconverter.common.records.ImageConversion; import fr.robie.craftengineconverter.common.utils.CacheConversion; import fr.robie.craftengineconverter.common.utils.CraftEngineImageUtils; -import fr.robie.craftengineconverter.common.utils.SnakeUtils; import fr.robie.craftengineconverter.common.utils.enums.ia.IARecipesTypes; import fr.robie.craftengineconverter.converter.Converter; import fr.robie.craftengineconverter.utils.ConfigFile; import fr.robie.craftengineconverter.utils.JsonFileValidator; import fr.robie.messageflow.formatter.Placeholder; import fr.robie.messageflow.logger.Logger; +import fr.robie.yamllibrary.ConfigurationSection; import net.momirealms.craftengine.core.item.recipe.CookingRecipeCategory; import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.io.File; import java.nio.file.Path; @@ -76,7 +76,7 @@ private void convertItemsSync(Optional player) { } if (outputFolder.exists()) { - this.deleteDirectory(outputFolder); + FileUtils.deleteDirectory(outputFolder); } if (!outputFolder.mkdirs()) { @@ -96,9 +96,11 @@ private void convertItemsSync(Optional player) { PluginNameMapper.getInstance().clearMappingsForPlugin(this.pluginType); BlockStatesMapper.getInstance().clearMappingsForPlugin(this.pluginType); + this.unsupportedFeatures.clear(); try { this.processItemFiles(toConvert, outputFolder, progressBar); + this.logUnsupportedFeatures(); for (CacheConversion conversion : this.conversions) { Optional> entryFile = FileCacheManager.getYamlCache() @@ -167,8 +169,22 @@ private void processItemFiles(Queue toConvert, File outputFolder, Bu ctx.scanWithDependencies(); ctx.convertInOrder(progressBar, (rawItemId, converter) -> { PluginNameMapper pluginNameMapper = PluginNameMapper.getInstance(); - pluginNameMapper.storeMapping(Plugins.ITEMS_ADDER, rawItemId, ctx.getFinalId(rawItemId)); - pluginNameMapper.storeMapping(Plugins.ITEMS_ADDER, ctx.getFinalId(rawItemId), ctx.getFinalId(rawItemId)); + String finalItemId = converter.getItemId(); + pluginNameMapper.storeMapping(Plugins.ITEMS_ADDER, finalItemId, finalItemId); + + // An unqualified id is only unambiguous while a single namespace claims it, so the first one wins and the + // rest are reported - a "namespace:id" reference still resolves correctly for every one of them. + String claimedBy = pluginNameMapper.getNewName(Plugins.ITEMS_ADDER, rawItemId); + if (claimedBy == null) { + pluginNameMapper.storeMapping(Plugins.ITEMS_ADDER, rawItemId, finalItemId); + } else if (!claimedBy.equals(finalItemId)) { + this.logDebug(Message.WARNING__CONVERTER__AMBIGUOUS_DEPENDENCY, Logger.LogType.WARNING, + Placeholder.builder() + .register("raw-item", rawItemId) + .register("first", claimedBy) + .register("second", finalItemId) + .build()); + } }); ctx.saveAll(outputFolder, this); } @@ -203,7 +219,7 @@ private void convertArmorSection(ConfigurationSection armorSection, YamlConfigur layer2 = layer2 + "_2"; } - List convertersToProcess = Configuration.get(ConfigurationKey.ARMOR_CONVERTER_TYPE).getComposition(); + List convertersToProcess = Configuration.get(Keys.ARMOR_CONVERTER_TYPE).getComposition(); Map converterSections = ArmorConverter.createArmorConverterSections( this.getOrCreateSection(convertedConfig, "equipments"), this.namespaced(equipmentId, namespace)); @@ -235,7 +251,7 @@ private String getFileName(@NotNull String path) { @Override public CompletableFuture convertEmojis(boolean async, Optional player) { - return null; + return this.executeTask(async, () -> this.log(Message.WARNING__CONVERTER__IA__EMOJIS__NOT_APPLICABLE, Logger.LogType.INFO, Placeholder.empty())); } @Override @@ -252,7 +268,7 @@ private void convertImagesSync(Optional optionalPlayer) { } if (outputBase.exists()) { - this.deleteDirectory(outputBase); + FileUtils.deleteDirectory(outputBase); } if (!outputBase.mkdirs()) { this.logDebug(Message.ERROR__CONVERTER__IA__OUTPUT_FOLDER_CREATION_FAILED, Logger.LogType.ERROR, Placeholder.of("path", outputBase.getAbsolutePath())); @@ -357,30 +373,28 @@ protected void convertLanguagesSync(Optional optionalPlayer) { int totalEntries = 0; for (ConfigFile configFile : toConvert) { - try (SnakeUtils config = new SnakeUtils(configFile.sourceFile())) { - SnakeUtils langSection = config.getSection("minecraft_lang_overwrite"); + YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(configFile.sourceFile()); + if (yamlConfiguration.isConfigurationSection("minecraft_lang_overwrite")) { + ConfigurationSection langSection = yamlConfiguration.getConfigurationSection("minecraft_lang_overwrite"); if (langSection != null) { - - for (String translationKey : langSection.getKeys()) { - SnakeUtils translationSection = langSection.getSection(translationKey); + for (String translationKey : langSection.getKeys(false)) { + ConfigurationSection translationSection = langSection.getConfigurationSection(translationKey); if (translationSection == null) { continue; } - - Map entries = translationSection.getMap("entries"); + ConfigurationSection entries = translationSection.getConfigurationSection("entries"); List languages = translationSection.getStringList("languages"); - if (entries != null) { - totalEntries += entries.size() * languages.size(); + totalEntries += entries.getKeys(false).size() * languages.size(); } } } - SnakeUtils dictionarySection = config.getSection("dictionary"); + } + if (yamlConfiguration.isConfigurationSection("dictionary")) { + ConfigurationSection dictionarySection = yamlConfiguration.getConfigurationSection("dictionary"); if (dictionarySection != null) { - totalEntries += dictionarySection.getKeys().size(); + totalEntries += dictionarySection.getKeys(false).size(); } - } catch (Exception e) { - this.logDebug(Message.ERROR__CONVERTER__IA__LANGUAGES__COUNT_FAILURE, Logger.LogType.ERROR, Placeholder.of("file", configFile.sourceFile().getName())); } } @@ -394,19 +408,18 @@ protected void convertLanguagesSync(Optional optionalPlayer) { progressBar.start(); try { - File tempOutputFile = File.createTempFile("craftengine_ia_languages", ".yml"); - tempOutputFile.deleteOnExit(); + YamlConfiguration yamlConfiguration = new YamlConfiguration(); + yamlConfiguration.options().pathSeparator('\\'); - try (SnakeUtils ceTranslation = SnakeUtils.createEmpty(tempOutputFile)) { - while (!toConvert.isEmpty()) { - ConfigFile configFile = toConvert.poll(); - this.convertLanguageFile(configFile, ceTranslation, progressBar); - } + while (!toConvert.isEmpty()) { + ConfigFile configFile = toConvert.poll(); + this.convertLanguageFile(configFile, yamlConfiguration, progressBar); + } - if (!this.settings.dryRunEnabled()) { - ceTranslation.save(outputFolder); - } + if (!this.settings.dryRunEnabled()) { + yamlConfiguration.save(outputFolder); } + } catch (Exception e) { Logger.error(Message.ERROR__CONVERTER__IA__LANGUAGES__CONVERSION_EXCEPTION, e); } finally { @@ -414,62 +427,47 @@ protected void convertLanguagesSync(Optional optionalPlayer) { } } - private void convertLanguageFile(ConfigFile configFile, SnakeUtils ceTranslation, BukkitProgressBar progressBar) { - try (SnakeUtils toTranslate = new SnakeUtils(configFile.sourceFile())) { - SnakeUtils minecraftLangOverwrite = toTranslate.getSection("minecraft_lang_overwrite"); - if (minecraftLangOverwrite != null) { - - for (String translationGroup : minecraftLangOverwrite.getKeys()) { - SnakeUtils section = minecraftLangOverwrite.getSection(translationGroup); - if (section == null) { - continue; - } - - Map entries = section.getMap("entries"); - List languages = section.getStringList("languages"); + private void convertLanguageFile(ConfigFile configFile, YamlConfiguration ceTranslation, BukkitProgressBar progressBar) { + YamlConfiguration toTranslate = YamlConfiguration.loadConfiguration(configFile.sourceFile()); + ConfigurationSection minecraftLangOverwrite = toTranslate.getConfigurationSection("minecraft_lang_overwrite"); + if (minecraftLangOverwrite != null) { + for (String translationGroup : minecraftLangOverwrite.getKeys(false)) { + ConfigurationSection section = minecraftLangOverwrite.getConfigurationSection(translationGroup); + if (section == null) { + continue; + } - if (entries == null || entries.isEmpty() || languages.isEmpty()) { - continue; - } + ConfigurationSection entries = section.getConfigurationSection("entries"); + List languages = section.getStringList("languages"); + if (entries != null) { for (String langKey : languages) { String ceLangKey = langKey.equalsIgnoreCase("ALL") ? "en" : langKey.toLowerCase(Locale.ROOT); - - for (Map.Entry entry : entries.entrySet()) { - try { - String translationKey = "translations\\n" + ceLangKey + "\\n" + entry.getKey(); - ceTranslation.addData(translationKey, entry.getValue(), "\\n"); - } catch (Exception e) { - Placeholder.Builder placeholderBuilder = Placeholder.builder(); - placeholderBuilder.register("key", entry.getKey()) - .register("lang", ceLangKey) - .register("file", configFile.sourceFile().getName()); - this.logDebug(Message.ERROR__CONVERTER__IA__LANGUAGES__KEY_CONVERSION_FAILURE, Logger.LogType.ERROR, placeholderBuilder.build()); - } - progressBar.increment(); - } + this.writeTranslation(configFile, ceTranslation, progressBar, entries, ceLangKey); } } } - SnakeUtils dictionarySection = toTranslate.getSection("dictionary"); - if (dictionarySection != null) { - String dictionaryLang = toTranslate.getString("info.dictionary-lang", "en").toLowerCase(Locale.ROOT); - for (String dictKey : dictionarySection.getKeys()) { - try { - String ceDictKey = "translations\\n" + dictionaryLang + "\\n" + dictKey; - ceTranslation.addData(ceDictKey, dictionarySection.getString(dictKey), "\\n"); - } catch (Exception e) { - Placeholder.Builder placeholderBuilder = Placeholder.builder(); - placeholderBuilder.register("key", dictKey) - .register("lang", dictionaryLang) - .register("file", configFile.sourceFile().getName()); - this.logDebug(Message.ERROR__CONVERTER__IA__LANGUAGES__KEY_CONVERSION_FAILURE, Logger.LogType.ERROR, placeholderBuilder.build()); - } - progressBar.increment(); - } + } + ConfigurationSection dictionarySection = toTranslate.getConfigurationSection("dictionary"); + if (dictionarySection != null) { + String dictionaryLang = toTranslate.getString("info.dictionary-lang", "en").toLowerCase(Locale.ROOT); + this.writeTranslation(configFile, ceTranslation, progressBar, dictionarySection, dictionaryLang); + } + } + + private void writeTranslation(ConfigFile configFile, YamlConfiguration ceTranslation, BukkitProgressBar progressBar, ConfigurationSection dictionarySection, String dictionaryLang) { + for (String dictKey : dictionarySection.getKeys(false)) { + try { + String ceDictKey = "translations\\" + dictionaryLang + "\\" + dictKey; + ceTranslation.set(ceDictKey, dictionarySection.getString(dictKey)); + } catch (Exception e) { + Placeholder.Builder placeholderBuilder = Placeholder.builder(); + placeholderBuilder.register("key", dictKey) + .register("lang", dictionaryLang) + .register("file", configFile.sourceFile().getName()); + this.logDebug(Message.ERROR__CONVERTER__IA__LANGUAGES__KEY_CONVERSION_FAILURE, Logger.LogType.ERROR, placeholderBuilder.build()); } - } catch (Exception e) { - Logger.error(Message.ERROR__CONVERTER__IA__LANGUAGES__FILE_CONVERSION_FAILURE, e, Placeholder.of("file", configFile.sourceFile().getName())); + progressBar.increment(); } } @@ -487,7 +485,7 @@ private void convertSoundsSync(Optional optionalPlayer) { } if (outputFolder.exists()) { - this.deleteDirectory(outputFolder); + FileUtils.deleteDirectory(outputFolder); } if (!outputFolder.mkdirs()) { @@ -597,7 +595,7 @@ private void convertRecipesSync(Optional optionalPlayer) { return; } if (outputFolder.exists()) { - this.deleteDirectory(outputFolder); + FileUtils.deleteDirectory(outputFolder); } if (!outputFolder.mkdirs()) { this.logDebug(Message.ERROR__CONVERTER__IA__OUTPUT_FOLDER_CREATION_FAILED, Logger.LogType.ERROR, Placeholder.of("path", outputFolder.getAbsolutePath())); @@ -773,9 +771,11 @@ private AbstractRecipe convertCraftingTableRecipe(ConfigurationSection iaRecipe, } RecipeResult result = this.convertRecipeResult(iaRecipe, recipeId, fileName); - if (result != null) { - recipe.setResult(result); + if (result == null) { + this.logDebug(Message.WARNING__CONVERTER__IA__RECIPES__SKIPPED_NO_RESULT, Logger.LogType.WARNING, Placeholder.of("recipe", recipeId, "file", fileName)); + return null; } + recipe.setResult(result); return recipe; } @@ -797,15 +797,18 @@ private void convertCookingRecipes(ConfigurationSection iaRecipe, ConfigurationS continue; } - String finalRecipeId = machines.size() > 1 ? baseRecipeId + "_" + (i + 1) : baseRecipeId; + CookingRecipe cookingRecipe = this.buildCookingRecipe(iaRecipe, recipeType, recipeId, fileName); + if (cookingRecipe == null) { + continue; + } - ConfigurationSection ceRecipe = recipesSection.createSection(finalRecipeId); - this.convertSingleCookingRecipe(iaRecipe, ceRecipe, recipeType, recipeId, fileName); + String finalRecipeId = machines.size() > 1 ? baseRecipeId + "_" + (i + 1) : baseRecipeId; + cookingRecipe.serialize(recipesSection.createSection(finalRecipeId)); } } - private void convertSingleCookingRecipe(ConfigurationSection iaRecipe, ConfigurationSection ceRecipe, - RecipeType recipeType, String recipeId, String fileName) { + private @Nullable CookingRecipe buildCookingRecipe(ConfigurationSection iaRecipe, RecipeType recipeType, + String recipeId, String fileName) { CookingRecipe cookingRecipe = new CookingRecipe(recipeType); ConfigurationSection ingredientSection = iaRecipe.getConfigurationSection("ingredient"); @@ -826,12 +829,14 @@ private void convertSingleCookingRecipe(ConfigurationSection iaRecipe, Configura cookingRecipe.setTime(cookTime); RecipeResult result = this.convertRecipeResult(iaRecipe, recipeId, fileName); - if (result != null) { - cookingRecipe.setResult(result); + if (result == null) { + this.logDebug(Message.WARNING__CONVERTER__IA__RECIPES__SKIPPED_NO_RESULT, Logger.LogType.WARNING, Placeholder.of("recipe", recipeId, "file", fileName)); + return null; } + cookingRecipe.setResult(result); cookingRecipe.setCategory(CookingRecipeCategory.MISC); - cookingRecipe.serialize(ceRecipe); + return cookingRecipe; } private AbstractRecipe convertSmithingRecipe(ConfigurationSection iaRecipe, String recipeId, String fileName) { @@ -864,9 +869,11 @@ private AbstractRecipe convertSmithingRecipe(ConfigurationSection iaRecipe, Stri } RecipeResult result = this.convertRecipeResult(iaRecipe, recipeId, fileName); - if (result != null) { - smithingRecipe.setResult(result); + if (result == null) { + this.logDebug(Message.WARNING__CONVERTER__IA__RECIPES__SKIPPED_NO_RESULT, Logger.LogType.WARNING, Placeholder.of("recipe", recipeId, "file", fileName)); + return null; } + smithingRecipe.setResult(result); return smithingRecipe; } @@ -881,7 +888,7 @@ private RecipeType getCookingTypeFromMachine(String machine) { }; } - private String convertItemReference(String itemReference, String recipeId, String fileName) { + private @Nullable String convertItemReference(String itemReference, String recipeId, String fileName) { if (!this.isValidString(itemReference)) { return null; } @@ -921,8 +928,8 @@ private String convertItemReference(String itemReference, String recipeId, Strin placeholderBuilder.register("item", itemReference) .register("recipe", recipeId) .register("file", fileName); - this.logDebug(Message.WARNING__CONVERTER__IA__RECIPES__ITEM_REFERENCE_CONVERSION_FAILURE, Logger.LogType.WARNING, placeholderBuilder.build()); - return itemReferenceLowerCase; + this.logDebug(Message.WARNING__CONVERTER__IA__RECIPES__ITEM_REFERENCE_CONVERSION_FAILURE, Logger.LogType.WARNING, placeholderBuilder.build()); + return null; } private RecipeResult convertRecipeResult(ConfigurationSection iaRecipe, String recipeId, String fileName) { @@ -959,7 +966,7 @@ private void convertPackSync(Optional optionalPlayer) { } if (outputPackFile.exists()) { - this.deleteDirectory(outputPackFile); + FileUtils.deleteDirectory(outputPackFile); } if (!outputPackFile.mkdirs()) { @@ -969,7 +976,7 @@ private void convertPackSync(Optional optionalPlayer) { int totalFiles = 0; List blacklistedNamespacesList = new ArrayList<>(List.of(".vscode")); - blacklistedNamespacesList.addAll(Configuration.>get(ConfigurationKey.ITEMS_ADDER_BLACKLISTED_CONTENT_FOLDERS_NAMESPACES)); + blacklistedNamespacesList.addAll(Configuration.get(Keys.ITEMS_ADDER_BLACKLISTED_CONTENT_FOLDERS_NAMESPACES)); List validMinecraftFolders = List.of("atlases", "blockstates", "equipment", "font", "items", "lang", "models", "particles", "post_effect", "shaders", "texts", "textures", "waypoint_style"); File[] listed = inputFolder.listFiles(); if (this.isNull(listed)) { diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/itemsadder/IAItemsConverter.java b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/itemsadder/IAItemsConverter.java index d515ea73..f7e485a0 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/itemsadder/IAItemsConverter.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/itemsadder/IAItemsConverter.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.converter.itemsadder; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.configuration.conditions.SurvivesExplosionCondition; import fr.robie.craftengineconverter.api.configuration.item.LoreConfiguration; import fr.robie.craftengineconverter.api.configuration.item.behavior.block.BlockConfiguration; @@ -27,8 +27,10 @@ import fr.robie.craftengineconverter.api.configuration.item.models.condition.ConditionModelConfiguration; import fr.robie.craftengineconverter.api.configuration.item.models.model.GenerationConfiguration; import fr.robie.craftengineconverter.api.configuration.item.models.model.SimpleModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.ChargeType; import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.UseDurationRangeDispatchConfiguration; import fr.robie.craftengineconverter.api.configuration.item.models.select.ChargeTypeSelectConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.select.DisplayContent; import fr.robie.craftengineconverter.api.configuration.item.models.select.DisplayContentSelectConfiguration; import fr.robie.craftengineconverter.api.configuration.item.settings.DropDisplayConfiguration; import fr.robie.craftengineconverter.api.configuration.item.settings.EquippableConfiguration; @@ -50,7 +52,8 @@ import fr.robie.craftengineconverter.converter.ItemConverter; import fr.robie.messageflow.formatter.Placeholder; import fr.robie.messageflow.logger.Logger; -import net.momirealms.craftengine.core.attribute.AttributeModifier; +import fr.robie.yamllibrary.ConfigurationSection; +import net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier; import net.momirealms.craftengine.core.entity.EquipmentSlot; import net.momirealms.craftengine.core.entity.display.Billboard; import org.bukkit.DyeColor; @@ -58,9 +61,9 @@ import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.attribute.Attribute; +import org.bukkit.potion.PotionType; import org.bukkit.block.BlockFace; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.bukkit.inventory.ItemFlag; import org.jetbrains.annotations.NotNull; @@ -96,7 +99,7 @@ public void convertItemName() { if (itemName.startsWith("display-name-")) { itemName = ""; } - this.craftEngineItemsConfiguration.addItemConfiguration(new ItemNameConfiguration(itemName, Configuration.get(ConfigurationKey.DISABLE_DEFAULT_ITALIC))); + this.craftEngineItemsConfiguration.addItemConfiguration(new ItemNameConfiguration(itemName, Configuration.get(Keys.DISABLE_DEFAULT_ITALIC))); } } @@ -110,21 +113,115 @@ public void convertLore() { lore.set(i, ""); } } - this.craftEngineItemsConfiguration.addItemConfiguration(new LoreConfiguration(lore, Configuration.get(ConfigurationKey.DISABLE_DEFAULT_ITALIC))); + this.craftEngineItemsConfiguration.addItemConfiguration(new LoreConfiguration(lore, Configuration.get(Keys.DISABLE_DEFAULT_ITALIC))); } } @Override public void convertDyedColor() { + // Leather horse armour carries its tint under its own property rather than under graphics. Object color = this.iaItemSection.get("graphics.color"); + if (this.isNull(color)) { + color = this.iaItemSection.get("specific_properties.leather_horse_armor.color"); + } if (this.isNotNull(color)) { try { this.craftEngineItemsConfiguration.addItemConfiguration(DyedColorConfiguration.parse(color)); - } catch (Exception ignored) { + } catch (Exception e) { + Logger.debug("[IAItemsConverter] Invalid colour '" + color + "' for item " + this.itemId); } } } + @Override + public void convertPotionEffects() { + ConfigurationSection potionSection = this.iaItemSection.getConfigurationSection("specific_properties.potion"); + if (this.isNull(potionSection)) { + return; + } + + PotionContentsConfiguration potionContents = new PotionContentsConfiguration(); + + String type = potionSection.getString("type"); + if (this.isValidString(type)) { + potionContents.setPotion(this.potionTypeKey(type)); + } + + String color = potionSection.getString("color"); + if (this.isValidString(color)) { + try { + potionContents.setCustomColor(DyedColorConfiguration.parseRgb(color)); + } catch (Exception e) { + Logger.debug("[IAItemsConverter] Invalid potion colour '" + color + "' for item " + this.itemId); + } + } + + // ItemsAdder keys the effects by an arbitrary label rather than listing them. + ConfigurationSection effectsSection = potionSection.getConfigurationSection("effects"); + if (this.isNotNull(effectsSection)) { + for (String label : effectsSection.getKeys(false)) { + ConfigurationSection effectSection = effectsSection.getConfigurationSection(label); + if (this.isNull(effectSection)) { + continue; + } + String effectType = effectSection.getString("type"); + if (!this.isValidString(effectType)) { + continue; + } + + potionContents.addEffect(new PotionContentsConfiguration.CustomEffect( + this.namespaced(effectType.toLowerCase(Locale.ROOT)), + effectSection.getInt("duration", 0), + effectSection.getInt("amplifier", 0), + effectSection.getBoolean("ambient", false), + effectSection.getBoolean("particles", true), + effectSection.getBoolean("icon", true) + )); + } + } + + if (potionContents.hasContents()) { + this.craftEngineItemsConfiguration.addItemConfiguration(potionContents); + } + } + + /** + * Bukkit's PotionType names do not all match the vanilla registry - SPEED is {@code minecraft:swiftness} - so the + * enum's own key is authoritative, with the raw name as a fallback if it is not a PotionType at all. + */ + private String potionTypeKey(String type) { + try { + return PotionType.valueOf(type.toUpperCase(Locale.ROOT)).getKey().toString(); + } catch (Exception e) { + return this.namespaced(type.toLowerCase(Locale.ROOT), "minecraft"); + } + } + + @Override + public void convertWrittenBookContent() { + ConfigurationSection bookSection = this.iaItemSection.getConfigurationSection("specific_properties.book"); + if (this.isNull(bookSection)) { + return; + } + + // ItemsAdder titles the book with the item's display name. + String title = this.iaItemSection.getString("name", this.iaItemSection.getString("display_name")); + String author = bookSection.getString("author"); + int generation = this.bookGeneration(bookSection.getString("generation", "TATTERED")); + + this.craftEngineItemsConfiguration.addItemConfiguration( + new WrittenBookContentConfiguration(title, author, generation, bookSection.getStringList("pages"))); + } + + private int bookGeneration(String generation) { + return switch (generation.toUpperCase(Locale.ROOT)) { + case "ORIGINAL" -> WrittenBookContentConfiguration.GENERATION_ORIGINAL; + case "COPY_OF_ORIGINAL" -> WrittenBookContentConfiguration.GENERATION_COPY_OF_ORIGINAL; + case "COPY_OF_COPY" -> WrittenBookContentConfiguration.GENERATION_COPY_OF_COPY; + default -> WrittenBookContentConfiguration.GENERATION_TATTERED; + }; + } + @Override public void convertUnbreakable() { ConfigurationSection durabilitySection = this.iaItemSection.getConfigurationSection("durability"); @@ -167,9 +264,9 @@ public void convertAttributeModifiers() { continue; } - net.momirealms.craftengine.core.attribute.AttributeModifier.Slot slot; + net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot slot; try { - slot = net.momirealms.craftengine.core.attribute.AttributeModifier.Slot.valueOf(equipmentSlot.toUpperCase(Locale.ROOT)); + slot = net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot.valueOf(equipmentSlot.toUpperCase(Locale.ROOT)); } catch (Exception e) { Logger.debug("[IAItemsConverter] Invalid equipment slot " + equipmentSlot + " for attribute modifiers for item " + this.itemId); continue; @@ -189,16 +286,16 @@ public void convertAttributeModifiers() { double value = attributeSection.getDouble("value", 0.0); String operationStr = attributeSection.getString("operation", "add_value").toUpperCase(Locale.ROOT); - net.momirealms.craftengine.core.attribute.AttributeModifier.Operation operation; + net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation operation; try { if (operationStr.equalsIgnoreCase("multiply_base")) { - operation = AttributeModifier.Operation.ADD_MULTIPLIED_BASE; + operation = VanillaAttributeModifier.Operation.ADD_MULTIPLIED_BASE; } else { - operation = AttributeModifier.Operation.valueOf(operationStr); + operation = VanillaAttributeModifier.Operation.valueOf(operationStr); } } catch (Exception e) { Logger.debug("[IAItemsConverter] Invalid operation " + operationStr + " for attribute " + attributeKey + " for item " + this.itemId + ", defaulting to ADD_VALUE"); - operation = net.momirealms.craftengine.core.attribute.AttributeModifier.Operation.ADD_VALUE; + operation = net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation.ADD_VALUE; } attributeModifiers.add(new fr.robie.craftengineconverter.api.configuration.item.data.AttributeModifier(attribute.name(), slot, null, value, operation, null)); } else { @@ -208,7 +305,7 @@ public void convertAttributeModifiers() { } double amount = slotSection.getDouble(attributeKey); - attributeModifiers.add(new fr.robie.craftengineconverter.api.configuration.item.data.AttributeModifier(attribute.name(), slot, null, amount, net.momirealms.craftengine.core.attribute.AttributeModifier.Operation.ADD_VALUE, null)); + attributeModifiers.add(new fr.robie.craftengineconverter.api.configuration.item.data.AttributeModifier(attribute.name(), slot, null, amount, net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation.ADD_VALUE, null)); } } } @@ -332,7 +429,7 @@ public void convertGlowDropColor() { if (glow) { String color = glowSection.getString("color"); try { - this.craftEngineItemsConfiguration.addItemConfiguration(new GlowDropColorConfiguration(DyeColor.valueOf(color.toLowerCase(Locale.ROOT)))); + this.craftEngineItemsConfiguration.addItemConfiguration(new GlowDropColorConfiguration(DyeColor.valueOf(color.toUpperCase(Locale.ROOT)))); } catch (Exception e) { Placeholder.Builder builder = Placeholder.builder(); builder.register("converter", "IAItemsConverter") @@ -415,31 +512,34 @@ private void convertEquipmentSection() { } private EquipmentSlot resolveEquipmentSlot(ConfigurationSection equipmentSection) { - EquipmentSlot fromItemId = this.getEquipmentSlotFromSuffix(this.itemId.toLowerCase(Locale.ROOT), false); - if (fromItemId != null) { - return fromItemId; - } - String slot = equipmentSection.getString("slot"); if (this.isValidString(slot)) { - return null; + EquipmentSlot configuredSlot = this.parseEquipmentSlot(slot); + if (configuredSlot != null) { + return configuredSlot; + } + } + + EquipmentSlot fromItemId = this.getEquipmentSlotFromSuffix(this.itemId); + if (fromItemId != null) { + return fromItemId; } - return this.getEquipmentSlotFromSuffix(this.craftEngineItemsConfiguration.getMaterial().name(), true); + return this.getEquipmentSlotFromSuffix(this.craftEngineItemsConfiguration.getMaterial().name()); } - private EquipmentSlot getEquipmentSlotFromSuffix(String name, boolean uppercase) { - String upString = uppercase ? name.toUpperCase(Locale.ROOT) : name; - if (upString.endsWith(uppercase ? "_HELMET" : "_helmet") || upString.endsWith("_SKULL") || upString.endsWith("_HAT")) { + private EquipmentSlot getEquipmentSlotFromSuffix(String name) { + String upperName = name.toUpperCase(Locale.ROOT); + if (upperName.endsWith("_HELMET") || upperName.endsWith("_SKULL") || upperName.endsWith("_HAT")) { return EquipmentSlot.HEAD; } - if (upString.endsWith(uppercase ? "_CHESTPLATE" : "_chestplate") || upString.endsWith("_ELYTRA")) { + if (upperName.endsWith("_CHESTPLATE") || upperName.endsWith("_ELYTRA")) { return EquipmentSlot.CHEST; } - if (upString.endsWith(uppercase ? "_LEGGINGS" : "_leggings")) { + if (upperName.endsWith("_LEGGINGS")) { return EquipmentSlot.LEGS; } - if (upString.endsWith(uppercase ? "_BOOTS" : "_boots")) { + if (upperName.endsWith("_BOOTS")) { return EquipmentSlot.FEET; } return null; @@ -455,22 +555,22 @@ private void applySlotAttributeModifiers(ConfigurationSection equipmentSection, return; } - net.momirealms.craftengine.core.attribute.AttributeModifier.Slot attributeSlot = this.toAttributeSlot(equipmentSlot); + net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot attributeSlot = this.toAttributeSlot(equipmentSlot); if (attributeSlot == null) { return; } double armor = slotAttributeModifiers.getDouble("armor", 0.0); - fr.robie.craftengineconverter.api.configuration.item.data.AttributeModifier modifier = new fr.robie.craftengineconverter.api.configuration.item.data.AttributeModifier("minecraft:armor", attributeSlot, null, armor, net.momirealms.craftengine.core.attribute.AttributeModifier.Operation.ADD_VALUE, null); + fr.robie.craftengineconverter.api.configuration.item.data.AttributeModifier modifier = new fr.robie.craftengineconverter.api.configuration.item.data.AttributeModifier("minecraft:armor", attributeSlot, null, armor, net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation.ADD_VALUE, null); this.craftEngineItemsConfiguration.addItemConfiguration(new AttributeModifiersConfiguration(List.of(modifier))); } - private net.momirealms.craftengine.core.attribute.AttributeModifier.Slot toAttributeSlot(EquipmentSlot equipmentSlot) { + private net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot toAttributeSlot(EquipmentSlot equipmentSlot) { return switch (equipmentSlot) { - case HEAD -> net.momirealms.craftengine.core.attribute.AttributeModifier.Slot.HEAD; - case CHEST -> net.momirealms.craftengine.core.attribute.AttributeModifier.Slot.CHEST; - case LEGS -> net.momirealms.craftengine.core.attribute.AttributeModifier.Slot.LEGS; - case FEET -> net.momirealms.craftengine.core.attribute.AttributeModifier.Slot.FEET; + case HEAD -> net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot.HEAD; + case CHEST -> net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot.CHEST; + case LEGS -> net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot.LEGS; + case FEET -> net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot.FEET; default -> null; }; } @@ -996,11 +1096,11 @@ private void handleComplexModels(ConfigurationSection graphicsSection) { private void handle2DModels(ConfigurationSection texturesSection) { Set keys = texturesSection.getKeys(false); - if (IAModelsKeys.BOW.containsAny(keys) && keys.size() == IAModelsKeys.BOW.getKeysCount()) { + if (IAModelsKeys.BOW.matches(keys)) { this.handleBow2D(texturesSection); - } else if (IAModelsKeys.FISHING_ROD.containsAny(keys) && keys.size() == IAModelsKeys.FISHING_ROD.getKeysCount()) { + } else if (IAModelsKeys.FISHING_ROD.matches(keys)) { this.handleFishingRod2D(texturesSection); - } else if (IAModelsKeys.CROSSBOW.containsAny(keys) && keys.size() == IAModelsKeys.CROSSBOW.getKeysCount()) { + } else if (IAModelsKeys.CROSSBOW.matches(keys)) { this.handleCrossbow2D(texturesSection); } } @@ -1008,19 +1108,19 @@ private void handle2DModels(ConfigurationSection texturesSection) { private void handle3DModels(ConfigurationSection modelsSection) { Set keys = modelsSection.getKeys(false); - if (IAModelsKeys.BOW.containsAny(keys) && keys.size() == IAModelsKeys.BOW.getKeysCount()) { + if (IAModelsKeys.BOW.matches(keys)) { this.handleBow3D(this.namespaced(modelsSection.getString("normal"), this.namespace), this.namespaced(modelsSection.getString("pulling_0"), this.namespace), this.namespaced(modelsSection.getString("pulling_1"), this.namespace), this.namespaced(modelsSection.getString("pulling_2"), this.namespace) ); - } else if (IAModelsKeys.FISHING_ROD.containsAny(keys) && keys.size() == IAModelsKeys.FISHING_ROD.getKeysCount()) { + } else if (IAModelsKeys.FISHING_ROD.matches(keys)) { this.handleFishingRod3D(this.namespaced(modelsSection.getString("normal"), this.namespace), this.namespaced(modelsSection.getString("cast"), this.namespace)); - } else if (IAModelsKeys.CROSSBOW.containsAny(keys) && keys.size() == IAModelsKeys.CROSSBOW.getKeysCount()) { + } else if (IAModelsKeys.CROSSBOW.matches(keys)) { this.handleCrossbow3D(modelsSection); - } else if (IAModelsKeys.TRIDENT.containsAny(keys) && keys.size() == IAModelsKeys.TRIDENT.getKeysCount()) { + } else if (IAModelsKeys.TRIDENT.matches(keys)) { this.handleTrident3D(modelsSection); - } else if (IAModelsKeys.SHIELD.containsAny(keys) && keys.size() == IAModelsKeys.SHIELD.getKeysCount()) { + } else if (IAModelsKeys.SHIELD.matches(keys)) { this.handleShield3D(this.namespaced(modelsSection.getString("normal"), this.namespace), this.namespaced(modelsSection.getString("blocking"), this.namespace) ); @@ -1034,7 +1134,7 @@ private void handleBow2D(ConfigurationSection texturesSection) { String pulling2Texture = this.namespaced(texturesSection.getString("pulling_2"), this.namespace); UseDurationRangeDispatchConfiguration pullingDispatch = new UseDurationRangeDispatchConfiguration(); - pullingDispatch.setScale(0.05); + pullingDispatch.setScale(0.05f); pullingDispatch.addEntry(0.65, this.buildSimpleModel("minecraft:item/bow_pulling_1", pulling1Texture)); pullingDispatch.addEntry(0.90, this.buildSimpleModel("minecraft:item/bow_pulling_2", pulling2Texture)); pullingDispatch.setFallback(this.buildSimpleModel("minecraft:item/bow_pulling_0", pulling0Texture)); @@ -1066,8 +1166,8 @@ private void handleCrossbow2D(ConfigurationSection texturesSection) { String arrowTexture = this.namespaced(texturesSection.getString("arrow"), this.namespace); ChargeTypeSelectConfiguration chargeTypeSelect = new ChargeTypeSelectConfiguration(); - chargeTypeSelect.addCase(ChargeTypeSelectConfiguration.ChargeType.ARROW, this.buildSimpleModel("minecraft:item/crossbow_arrow", arrowTexture)); - chargeTypeSelect.addCase(ChargeTypeSelectConfiguration.ChargeType.ROCKET, this.buildSimpleModel("minecraft:item/crossbow_firework", rocketTexture)); + chargeTypeSelect.addCase(ChargeType.ARROW, this.buildSimpleModel("minecraft:item/crossbow_arrow", arrowTexture)); + chargeTypeSelect.addCase(ChargeType.ROCKET, this.buildSimpleModel("minecraft:item/crossbow_firework", rocketTexture)); chargeTypeSelect.setFallback(this.buildSimpleModel("minecraft:item/crossbow", normalTexture)); UseDurationRangeDispatchConfiguration pullingDispatch = new UseDurationRangeDispatchConfiguration(); @@ -1084,7 +1184,7 @@ private void handleCrossbow2D(ConfigurationSection texturesSection) { private void handleBow3D(String defaultModelPath, String pulling0ModelPath, String pulling1ModelPath, String pulling2ModelPath) { UseDurationRangeDispatchConfiguration pullingDispatch = new UseDurationRangeDispatchConfiguration(); - pullingDispatch.setScale(0.05); + pullingDispatch.setScale(0.05f); pullingDispatch.addEntry(0.65, new SimpleModelConfiguration(pulling1ModelPath)); pullingDispatch.addEntry(0.90, new SimpleModelConfiguration(pulling2ModelPath)); pullingDispatch.setFallback(new SimpleModelConfiguration(pulling0ModelPath)); @@ -1113,8 +1213,8 @@ private void handleCrossbow3D(ConfigurationSection modelsSection) { String arrowModel = this.namespaced(modelsSection.getString("arrow"), this.namespace); ChargeTypeSelectConfiguration chargeTypeSelect = new ChargeTypeSelectConfiguration(); - chargeTypeSelect.addCase(ChargeTypeSelectConfiguration.ChargeType.ARROW, new SimpleModelConfiguration(arrowModel)); - chargeTypeSelect.addCase(ChargeTypeSelectConfiguration.ChargeType.ROCKET, new SimpleModelConfiguration(rocketModel)); + chargeTypeSelect.addCase(ChargeType.ARROW, new SimpleModelConfiguration(arrowModel)); + chargeTypeSelect.addCase(ChargeType.ROCKET, new SimpleModelConfiguration(rocketModel)); chargeTypeSelect.setFallback(new SimpleModelConfiguration(normalModel)); UseDurationRangeDispatchConfiguration pullingDispatch = new UseDurationRangeDispatchConfiguration(); @@ -1139,9 +1239,9 @@ private void handleTrident3D(ConfigurationSection modelsSection) { DisplayContentSelectConfiguration displayContentSelect = new DisplayContentSelectConfiguration(); displayContentSelect.addCase(new SimpleModelConfiguration(normalModel), - DisplayContentSelectConfiguration.DisplayContent.GUI, - DisplayContentSelectConfiguration.DisplayContent.GROUND, - DisplayContentSelectConfiguration.DisplayContent.FIXED + DisplayContent.GUI, + DisplayContent.GROUND, + DisplayContent.FIXED ); displayContentSelect.setFallback(usingItemCondition); @@ -1178,14 +1278,28 @@ public void convertOther() { // machines fuel type not supported } } - default -> { - - } + default -> this.reportUnsupported("behaviours." + behaviourKey); } } } } + /** Every key this converter reads off the item itself; anything else is reported as left out. */ + private static final Set HANDLED_ITEM_KEYS = Set.of( + "name", "display_name", "lore", "resource", "graphics", "durability", "item_flags", + "attribute_modifiers", "enchants", "item_model", "max_stack_size", "glint", "drop", "tooltip_style", + "consumable", "jukebox_disc", "equipment", "specific_properties", "behaviours"); + + private static final Set HANDLED_SPECIFIC_PROPERTIES = Set.of( + "armor", "block", "potion", "book", "leather_horse_armor"); + + @Override + public void reportUnsupportedConfiguration() { + this.reportUnhandledKeys("", this.iaItemSection, HANDLED_ITEM_KEYS); + this.reportUnhandledKeys("specific_properties", + this.iaItemSection.getConfigurationSection("specific_properties"), HANDLED_SPECIFIC_PROPERTIES); + } + private void convertFurniture(ConfigurationSection furnitureSection, ConfigurationSection behavioursSection) { IAEntityTypes entityType = IAEntityTypes.ITEM_FRAME; try { @@ -1193,7 +1307,7 @@ private void convertFurniture(ConfigurationSection furnitureSection, Configurati } catch (Exception ignored) { } - boolean isBig = furnitureSection.getBoolean("small", true); + boolean small = furnitureSection.getBoolean("small", false); Set placements = new HashSet<>(); ConfigurationSection placeableSection = furnitureSection.getConfigurationSection("placeable_on"); @@ -1221,7 +1335,7 @@ private void convertFurniture(ConfigurationSection furnitureSection, Configurati Billboard transformType = Billboard.FIXED; ItemDisplayType displayType = ItemDisplayType.NONE; FloatsUtils displayTranslation = new FloatsUtils(3, new float[]{0f, 0f, 0f}); -// if (isBig) { +// if (!small) { // displayTranslation.addValue(1, 1f); // } FloatsUtils scale = new FloatsUtils(3, new float[]{1f, 1f, 1f}); @@ -1286,7 +1400,7 @@ private void convertFurniture(ConfigurationSection furnitureSection, Configurati if (scale.isUpdated()) { armorStand.setScale(scale.getValue(0), scale.getValue(1), scale.getValue(2)); } - if (!isBig) { + if (small) { armorStand.setSmall(true); } element = armorStand; diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/nexo/NexoConverter.java b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/nexo/NexoConverter.java index 985b054b..b83599a2 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/nexo/NexoConverter.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/nexo/NexoConverter.java @@ -1,6 +1,7 @@ package fr.robie.craftengineconverter.converter.nexo; import fr.robie.craftengineconverter.CraftEngineConverter; +import fr.robie.craftengineconverter.api.cache.FileCacheEntry; import fr.robie.craftengineconverter.api.configuration.image.Bitmap; import fr.robie.craftengineconverter.api.configuration.image.MultipleCharactersBitmapConfiguration; import fr.robie.craftengineconverter.api.configuration.image.SingleCharacterBitmapConfiguration; @@ -17,24 +18,22 @@ import fr.robie.craftengineconverter.api.enums.Plugins; import fr.robie.craftengineconverter.api.enums.RecipeType; import fr.robie.craftengineconverter.api.format.Message; - +import fr.robie.craftengineconverter.api.manager.FileCacheManager; import fr.robie.craftengineconverter.api.progress.BukkitProgressBar; +import fr.robie.craftengineconverter.api.utils.FileUtils; import fr.robie.craftengineconverter.common.BlockStatesMapper; import fr.robie.craftengineconverter.common.PluginNameMapper; -import fr.robie.craftengineconverter.common.cache.FileCacheEntry; -import fr.robie.craftengineconverter.common.manager.FileCacheManager; import fr.robie.craftengineconverter.common.records.ImageConversion; import fr.robie.craftengineconverter.common.utils.CraftEngineImageUtils; -import fr.robie.craftengineconverter.common.utils.SnakeUtils; import fr.robie.craftengineconverter.converter.Converter; import fr.robie.craftengineconverter.utils.ConfigFile; import fr.robie.craftengineconverter.utils.JsonFileValidator; import fr.robie.messageflow.formatter.Placeholder; import fr.robie.messageflow.logger.Logger; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import net.momirealms.craftengine.core.item.recipe.CookingRecipeCategory; import net.momirealms.craftengine.core.item.recipe.CraftingRecipeCategory; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.jetbrains.annotations.Nullable; @@ -70,7 +69,7 @@ private void convertItemsSync(Optional player) { } if (outputBase.exists()) { - this.deleteDirectory(outputBase); + FileUtils.deleteDirectory(outputBase); } if (!outputBase.mkdirs()) { @@ -85,9 +84,13 @@ private void convertItemsSync(Optional player) { return; } + // Templates span every file, so they have to be known before anything is counted: an item that only exists to + // be inherited from is never converted, and must not be counted towards the progress bar either. + NexoItemTemplates templates = NexoItemTemplates.collect(toConvert); + int totalItems = 0; for (ConfigFile configFile : toConvert) { - totalItems += this.countItemsInConfig(configFile.config()); + totalItems += this.countConvertibleItems(configFile.config(), templates); } BukkitProgressBar progress = this.createProgressBar(player, totalItems, "Converting Nexo items", "items", ConverterOption.ITEMS); @@ -96,9 +99,11 @@ private void convertItemsSync(Optional player) { PluginNameMapper.getInstance().clearMappingsForPlugin(this.pluginType); BlockStatesMapper.getInstance().clearMappingsForPlugin(this.pluginType); + this.unsupportedFeatures.clear(); try { - this.processConfigs(toConvert, outputBase, progress); + this.processConfigs(toConvert, outputBase, progress, templates); + this.logUnsupportedFeatures(); toConvert.clear(); } catch (Exception e) { Logger.error(Message.ERROR__CONVERTER__NEXO__ITEMS__CONVERSION_EXCEPTION, e); @@ -112,14 +117,35 @@ private int countItemsInConfig(YamlConfiguration config) { return keys.size(); } - private void processConfigs(Queue toConvert, File outputBase, BukkitProgressBar progress) { + private int countConvertibleItems(YamlConfiguration config, NexoItemTemplates templates) { + int count = 0; + for (String itemId : config.getKeys(false)) { + if (!templates.isTemplate(itemId)) { + count++; + } + } + return count; + } + + private void processConfigs(Queue toConvert, File outputBase, BukkitProgressBar progress, NexoItemTemplates templates) { ItemConversionContext ctx = new ItemConversionContext<>(new ArrayList<>(toConvert), (configFile, rawItemId, finalItemId, itemSection, convertedConfig) -> - new NexoItemConverter(this, itemSection, finalItemId, convertedConfig) + new NexoItemConverter(this, itemSection, finalItemId, convertedConfig), + null, + configFile -> { + Set itemIds = new LinkedHashSet<>(configFile.config().getKeys(false)); + itemIds.removeIf(templates::isTemplate); + return itemIds; + }, + (configFile, rawItemId) -> { + ConfigurationSection itemSection = configFile.config().getConfigurationSection(rawItemId); + return itemSection == null ? null : templates.resolve(rawItemId, itemSection); + }, + (configFile, rawItemId) -> configFile.sourceFile().getName().replace(".yml", "") + ":" + rawItemId ); ctx.scanWithDependencies(); ctx.convertInOrder(progress, (rawItemId, converter) -> - PluginNameMapper.getInstance().storeMapping(Plugins.NEXO, rawItemId, ctx.getFinalId(rawItemId)) + PluginNameMapper.getInstance().storeMapping(Plugins.NEXO, rawItemId, converter.getItemId()) ); ctx.saveAll(outputBase, this); } @@ -139,7 +165,7 @@ private void convertEmojisSync(Optional player) { } if (outputEmojisFolder.exists()) { - this.deleteDirectory(outputEmojisFolder); + FileUtils.deleteDirectory(outputEmojisFolder); } if (!outputEmojisFolder.mkdirs()) { @@ -270,7 +296,7 @@ private void convertRecipesSync(Optional player) { return; } if (outputFolder.exists()) { - this.deleteDirectory(outputFolder); + FileUtils.deleteDirectory(outputFolder); } if (!outputFolder.mkdirs()) { this.logDebug(Message.ERROR__MKDIR_FAILURE, Logger.LogType.ERROR, Placeholder.of("directory", outputFolder.getName(), "path", outputFolder.getAbsolutePath())); @@ -311,14 +337,14 @@ private void processRecipeConfigs(Map> toConvert, F } } - private void processRecipeConfigFile(ConfigFile configFile, File outputFolder, RecipeType recipeType, BukkitProgressBar progress) { + private void processRecipeConfigFile(ConfigFile configFile, File outputFolder, @Nullable RecipeType recipeType, BukkitProgressBar progress) { File recipeFile = configFile.sourceFile(); YamlConfiguration config = configFile.config(); if (recipeFile.getName().equalsIgnoreCase("disabled_recipes.yml")) { List disabledRecipes = config.getStringList("disabled_recipes"); - if (!disabledRecipes.isEmpty()) { + if (!disabledRecipes.isEmpty() && !this.settings.dryRunEnabled()) { YamlConfiguration convertedConfig = new YamlConfiguration(); ConfigurationSection disableRecipeSection = this.getOrCreateSection(this.getOrCreateSection(convertedConfig, "recipe"), "disable-vanilla-recipes"); disableRecipeSection.set("list", disabledRecipes); @@ -334,6 +360,13 @@ private void processRecipeConfigFile(ConfigFile configFile, File outputFolder, R } Set keys = config.getKeys(false); + + if (recipeType == null) { + this.logDebug(Message.WARNING__CONVERTER__NEXO__RECIPE__COULD_NOT_DETERMINE_RECIPE_TYPE, Logger.LogType.WARNING, Placeholder.of("file", recipeFile.getAbsolutePath())); + keys.forEach(key -> progress.increment()); + return; + } + YamlConfiguration convertedConfig = new YamlConfiguration(); ConfigurationSection recipesSection = convertedConfig.createSection("recipes"); int convertedCount = 0; @@ -666,7 +699,7 @@ private void populateRecipeQueue(File baseDir, File currentDir, Map> entry = FileCacheManager.getYamlCache().getEntryFile(file.toPath()); if (entry.isPresent()) { RecipeType recipeType = this.determineRecipeType(file, baseDir); - if (recipeType != null || file.getName().equalsIgnoreCase("disabled_recipes.yml") || file.getName().equalsIgnoreCase("smithing.yml")) { + if (recipeType != null || file.getName().equalsIgnoreCase("disabled_recipes.yml")) { ConfigFile configFile = new ConfigFile(file, baseDir, entry.get().getData()); toConvert.computeIfAbsent(recipeType, k -> new ArrayList<>()).add(configFile); } else { @@ -679,22 +712,33 @@ private void populateRecipeQueue(File baseDir, File currentDir, Map 0) { + RecipeType fromDirectory = this.parseRecipeType(pathParts[0]); + if (fromDirectory != null) { + return fromDirectory; + } } - String recipeTypeName = pathParts[0].toUpperCase(Locale.ROOT); + // Nexo also accepts a flat layout where the file itself names the type, e.g. recipes/smithing.yml + String fileName = file.getName(); + return this.parseRecipeType(fileName.substring(0, fileName.length() - ".yml".length())); + } - if (recipeTypeName.equalsIgnoreCase("SMITHING")) { + private @Nullable RecipeType parseRecipeType(String name) { + if (!this.isValidString(name)) { + return null; + } + + if (name.equalsIgnoreCase("SMITHING")) { return RecipeType.SMITHING_TRANSFORM; } try { - return RecipeType.valueOf(recipeTypeName); + return RecipeType.valueOf(name.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { return null; } @@ -716,148 +760,114 @@ private void convertSoundsSync(Optional player) { } } - try (SnakeUtils nexoSounds = new SnakeUtils(inputSoundFile)) { - if (nexoSounds.isEmpty()) { - this.logDebug(Message.WARNING__CONVERTER__NEXO__SOUND__SOUNDS_FILE_EMPTY, Logger.LogType.INFO, Placeholder.of("path", inputSoundFile.getAbsolutePath())); - return; - } + fr.robie.yamllibrary.file.YamlConfiguration configuration = fr.robie.yamllibrary.file.YamlConfiguration.loadConfiguration(inputSoundFile); + List sounds = configuration.getSectionList("sounds"); - List> nexoSoundsList = nexoSounds.getListMap("sounds"); - if (nexoSoundsList.isEmpty()) { // No sounds to convert - nexoSounds.close(); - return; - } + int totalSounds = sounds.size(); - int totalSounds = nexoSoundsList.size(); - BukkitProgressBar progress = this.createProgressBar(player, totalSounds, "Converting Nexo sounds", "sounds", ConverterOption.SOUNDS); + BukkitProgressBar progress = this.createProgressBar(player, totalSounds, "Converting Nexo sounds", "sounds", ConverterOption.SOUNDS); - progress.start(); + progress.start(); + fr.robie.yamllibrary.file.YamlConfiguration convertedConfig = new fr.robie.yamllibrary.file.YamlConfiguration(); + fr.robie.yamllibrary.ConfigurationSection soundsSection = convertedConfig.createSection("sounds"); + fr.robie.yamllibrary.ConfigurationSection jukeboxSongsSection = convertedConfig.createSection("jukebox-songs"); + + for (fr.robie.yamllibrary.ConfigurationSection soundEntry : sounds) { try { - YamlConfiguration convertedConfig = new YamlConfiguration(); - ConfigurationSection soundsSection = convertedConfig.createSection("sounds"); - ConfigurationSection jukeboxSongsSection = convertedConfig.createSection("jukebox-songs"); +// this.convertSoundEntry(soundEntry.getValues(false), soundsSection, jukeboxSongsSection, progress); - for (Map soundEntry : nexoSoundsList) { - try { - this.convertSoundEntry(soundEntry, soundsSection, jukeboxSongsSection, progress); - } catch (Exception e) { - Object idObj = soundEntry.get("id"); - String soundId = idObj != null ? idObj.toString() : "unknown"; - this.logDebug(Message.ERROR__CONVERTER__FAILED_CONVERT_SOUND, Logger.LogType.ERROR, Placeholder.of("sound", soundId, "file", String.valueOf(inputSoundFile))); - progress.increment(); - } + String id = soundEntry.getString("id"); + if (id == null || id.isEmpty()) { + progress.increment(); + continue; } - if (!this.settings.dryRunEnabled()) { - if (jukeboxSongsSection.getKeys(false).isEmpty()) { - convertedConfig.set("jukebox-songs", null); - } - if (soundsSection.getKeys(false).isEmpty()) { - convertedConfig.set("sounds", null); + SoundConfiguration soundConfiguration = new SoundConfiguration() + .setReplace(soundEntry.getBoolean("replace", false)); + + String sound = soundEntry.getString("sound"); + if (sound != null && !sound.isEmpty()) { + soundConfiguration.addSound(this.createSound(sound, soundEntry)); + } + + List soundsList = soundEntry.getList("sounds"); + for (Object soundObj : soundsList) { + if (soundObj instanceof ConfigurationSection soundSection) { + String name = soundSection.getString("name"); + if (name != null && !name.isEmpty()) { + soundConfiguration.addSound(this.createSound(name, soundSection)); + } + } else if (soundObj instanceof String soundName) { + soundConfiguration.addSound(this.createSound(soundName, soundEntry)); } - convertedConfig.save(outputSoundFile); } - } catch (Exception e) { - Logger.error(Message.ERROR__CONVERTER__NEXO__SOUNDS__CONVERT_FAILURE, e, Placeholder.of("file", inputSoundFile.getName())); - } finally { - nexoSounds.close(); - progress.stop(); - } - } catch (Exception e) { - Logger.error(Message.ERROR__CONVERTER__NEXO__SOUNDS__LOAD_FAILURE, e, Placeholder.of("file", inputSoundFile.getName())); - } - } - private void convertSoundEntry(Map soundEntry, ConfigurationSection soundsSection, - ConfigurationSection jukeboxSongsSection, BukkitProgressBar progress) { - Object idObj = soundEntry.get("id"); - if (idObj == null) { - progress.increment(); - return; - } + fr.robie.yamllibrary.ConfigurationSection soundIdSection = soundsSection.createSection(id); + soundConfiguration.serialize(soundIdSection); - String soundId = idObj.toString(); - if (soundId.isEmpty()) { - progress.increment(); - return; - } + fr.robie.yamllibrary.ConfigurationSection jukeboxPlayable = soundEntry.getConfigurationSection("jukebox_playable"); + if (jukeboxPlayable != null) { + fr.robie.yamllibrary.ConfigurationSection jukeboxSoundSectionId = jukeboxSongsSection.createSection(id); + JukeboxSongConfiguration jukeboxConfig = new JukeboxSongConfiguration() + .setSound(id); - SoundConfiguration soundConfig = new SoundConfiguration() - .setReplace(this.parseBoolean(soundEntry.get("replace"))); + String durationStr = jukeboxPlayable.getString("duration"); + if (durationStr != null && durationStr.endsWith("s")) { + try { + double length = Double.parseDouble(durationStr.substring(0, durationStr.length() - 1)); + jukeboxConfig.setLength(length); + } catch (NumberFormatException e) { + this.logDebug(Message.ERROR__CONVERTER__NEXO__SOUND__INVALID_DURATION_FORMAT, Logger.LogType.INFO, Placeholder.of("duration", durationStr, "sound", id)); + } + } + String description = jukeboxPlayable.getString("description"); + if (description != null) { + jukeboxConfig.setDescription(description); + } + int comparatorOutput = jukeboxPlayable.getInt("comparator_output", 15); + jukeboxConfig.setComparatorOutput(comparatorOutput); - Object singleSound = soundEntry.get("sound"); - if (singleSound != null && this.isValidString(singleSound.toString())) { - soundConfig.addSound(this.createSound(singleSound.toString(), soundEntry)); - } + int range = jukeboxPlayable.getInt("range", 32); + jukeboxConfig.setRange(range); - Object soundsListObj = soundEntry.get("sounds"); - if (soundsListObj instanceof List soundsList) { - for (Object soundObj : soundsList) { - if (soundObj instanceof Map soundMap) { - @SuppressWarnings("unchecked") - Map finalSoundMap = (Map) soundMap; - Object nameObj = finalSoundMap.get("name"); - if (nameObj != null) { - soundConfig.addSound(this.createSound(nameObj.toString(), finalSoundMap)); - } - } else if (soundObj instanceof String soundName) { - soundConfig.addSound(this.createSound(soundName, soundEntry)); + jukeboxConfig.serialize(jukeboxSoundSectionId); } - } - } - ConfigurationSection soundIdSection = soundsSection.createSection(soundId); - soundConfig.serialize(soundIdSection); - - Object jukeboxPlayable = soundEntry.get("jukebox_playable"); - if (jukeboxPlayable instanceof Map jukeboxMap) { - @SuppressWarnings("unchecked") - Map finalJukeboxMap = (Map) jukeboxMap; - ConfigurationSection jukeboxSongSection = jukeboxSongsSection.createSection(soundId); - JukeboxSongConfiguration jukeboxConfig = new JukeboxSongConfiguration() - .setSound(soundId); + progress.increment(); - Object durationObj = finalJukeboxMap.get("duration"); - if (durationObj != null) { - String durationStr = durationObj.toString(); - if (durationStr.endsWith("s")) { - try { - double length = Double.parseDouble(durationStr.substring(0, durationStr.length() - 1)); - jukeboxConfig.setLength(length); - } catch (NumberFormatException e) { - this.logDebug(Message.ERROR__CONVERTER__NEXO__SOUND__INVALID_DURATION_FORMAT, Logger.LogType.INFO, Placeholder.of("duration", durationStr, "sound", soundId)); - } - } + } catch (Exception e) { + Object idObj = soundEntry.get("id"); + String soundId = idObj != null ? idObj.toString() : "unknown"; + this.logDebug(Message.ERROR__CONVERTER__FAILED_CONVERT_SOUND, Logger.LogType.ERROR, Placeholder.of("sound", soundId, "file", String.valueOf(inputSoundFile))); + progress.increment(); } + } - Object descriptionObj = finalJukeboxMap.get("description"); - if (descriptionObj != null) { - jukeboxConfig.setDescription(descriptionObj.toString()); + if (!this.settings.dryRunEnabled()) { + if (jukeboxSongsSection.getKeys(false).isEmpty()) { + convertedConfig.set("jukebox-songs", null); } - - int comparatorOutput = this.parseInt(finalJukeboxMap.get("comparator_output"), 15); - jukeboxConfig.setComparatorOutput(comparatorOutput); - - Object rangeObj = finalJukeboxMap.get("range"); - if (rangeObj != null) { - jukeboxConfig.setRange(this.parseInt(rangeObj, 32)); + if (soundsSection.getKeys(false).isEmpty()) { + convertedConfig.set("sounds", null); + } + try { + convertedConfig.save(outputSoundFile); + } catch (IOException e) { + Logger.error(Message.ERROR__CONVERTER__FAILED_SAVE_FILE, e, Placeholder.of("file", outputSoundFile.getAbsolutePath())); } - - jukeboxConfig.serialize(jukeboxSongSection); } - - progress.increment(); + progress.stop(); } - private Sound createSound(String soundName, Map properties) { - boolean stream = this.parseBoolean(properties.get("stream")); - boolean preload = this.parseBoolean(properties.get("preload")); - float volume = (float) this.parseDouble(properties.get("volume"), 1.0); - float pitch = (float) this.parseDouble(properties.get("pitch"), 1.0); - int weight = this.parseInt(properties.get("weight"), 1); - int attenuationDistance = this.parseInt(properties.get("attenuation_distance"), 16); + private Sound createSound(String soundName, fr.robie.yamllibrary.ConfigurationSection configurationSection) { + boolean stream = configurationSection.getBoolean("stream"); + boolean preload = configurationSection.getBoolean("preload"); + float volume = (float) configurationSection.getDouble("volume",1.0); + float pitch = (float) configurationSection.getDouble("pitch", 1.0); + int weight = configurationSection.getInt("weight",1); + int attenuationDistance = configurationSection.getInt("attenuation_distance",16); if (!stream && !preload && volume == 1.0f && pitch == 1.0f && weight == 1 && attenuationDistance == 16) { return new SimpleSound(soundName); @@ -881,84 +891,54 @@ private void convertLanguagesSync(Optional player) { return; } - try (SnakeUtils nexoLanguages = new SnakeUtils(languagesFile)) { - if (nexoLanguages.isEmpty()) { - this.logDebug(Message.WARNING__CONVERTER__NEXO__LANGUAGE__LANGUAGES_FILE_EMPTY, Logger.LogType.INFO, Placeholder.of("path", languagesFile.getAbsolutePath())); - return; - } + YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(languagesFile); + Set languagesKeys = yamlConfiguration.getKeys(false); - Set languageKeys = nexoLanguages.getKeys(); - if (languageKeys.isEmpty()) { - this.logDebug(Message.WARNING__CONVERTER__NEXO__LANGUAGE__NO_LANGUAGES_FOUND, Logger.LogType.INFO, Placeholder.empty()); - return; - } - - int totalTranslations = 0; - for (String langKey : languageKeys) { - Map langData = nexoLanguages.getMap(langKey); - if (langData != null) { - totalTranslations += langData.size(); - } + int totalTranslations = 0; + for (String langKey : languagesKeys) { + ConfigurationSection langSection = yamlConfiguration.getConfigurationSection(langKey); + if (langSection != null) { + totalTranslations += langSection.getKeys(false).size(); } + } - if (totalTranslations == 0) { - this.log(Message.WARNING__CONVERTER__NEXO__LANGUAGE__NO_LANGUAGES_FOUND, Logger.LogType.ERROR,Placeholder.empty()); - return; - } + if (totalTranslations == 0) { + this.log(Message.WARNING__CONVERTER__NEXO__LANGUAGE__NO_LANGUAGES_FOUND, Logger.LogType.INFO, Placeholder.empty()); + return; + } - BukkitProgressBar progress = this.createProgressBar(player, totalTranslations, "Converting Nexo languages", "translations", ConverterOption.LANGUAGES); + BukkitProgressBar progress = this.createProgressBar(player, totalTranslations, "Converting Nexo languages", "translations", ConverterOption.LANGUAGES); + progress.start(); - progress.start(); + try { + YamlConfiguration craftEngineLanguages = new YamlConfiguration(); + craftEngineLanguages.options().pathSeparator('\\'); - try { - File tempOutputFile = File.createTempFile("craftengine_languages", ".yml"); - tempOutputFile.deleteOnExit(); + for (String langKey : languagesKeys) { + ConfigurationSection langSection = yamlConfiguration.getConfigurationSection(langKey); + if (langSection == null) { + continue; + } - try (SnakeUtils craftEngineLanguages = SnakeUtils.createEmpty(tempOutputFile)) { - for (String langKey : languageKeys) { - try { - this.convertLanguage(langKey, nexoLanguages, craftEngineLanguages, progress); - } catch (Exception e) { - this.logDebug(Message.ERROR__CONVERTER__NEXO__LANGUAGE__FAILED_CONVERT_LANGUAGE, Logger.LogType.ERROR, Placeholder.of("lang", langKey, "file", languagesFile.getAbsolutePath())); - Map langData = nexoLanguages.getMap(langKey); - if (langData != null) { - progress.increment(langData.size()); - } - } - } - if (!this.settings.dryRunEnabled()) { - craftEngineLanguages.save(outputFile); + for (String translationKey : langSection.getKeys(false)) { + try { + String translationValue = langSection.getString(translationKey, ""); + String craftEngineLangKey = langKey.equals("global") ? "en" : langKey; + String finalTranslationKey = "translations\\" + craftEngineLangKey + "\\" + translationKey; + craftEngineLanguages.set(finalTranslationKey, translationValue); + } catch (Exception e) { + this.logDebug(Message.ERROR__CONVERTER__NEXO__LANGUAGE__FAILED_CONVERT_TRANSLATION, Logger.LogType.ERROR, Placeholder.of("key", translationKey, "lang", langKey)); } + progress.increment(); } - } catch (Exception e) { - Logger.error(Message.ERROR__CONVERTER__NEXO__LANGUAGES__CONVERT_FAILURE, e, Placeholder.of("file", languagesFile.getName())); - } finally { - progress.stop(); } - } catch (Exception e) { - Logger.error(Message.ERROR__CONVERTER__NEXO__LANGUAGES__LOAD_FAILURE, e, Placeholder.of("file", languagesFile.getName())); - } - } - - private void convertLanguage(String langKey, SnakeUtils nexoLanguages, - SnakeUtils craftEngineLanguages, BukkitProgressBar progress) { - Map nexoLangData = nexoLanguages.getMap(langKey); - - if (nexoLangData == null || nexoLangData.isEmpty()) { - return; - } - - String craftEngineLangKey = langKey.equals("global") ? "en" : langKey; - for (Map.Entry entry : nexoLangData.entrySet()) { - try { - String translationKey = "translations\\n" + craftEngineLangKey + "\\n" + entry.getKey(); - craftEngineLanguages.addData(translationKey, entry.getValue(), "\\n"); - } catch (Exception e) { - this.logDebug(Message.ERROR__CONVERTER__NEXO__LANGUAGE__FAILED_CONVERT_TRANSLATION, Logger.LogType.ERROR, Placeholder.of("key", entry.getKey(), "lang", langKey)); + if (!this.settings.dryRunEnabled()) { + craftEngineLanguages.save(outputFile); } - - progress.increment(); + } catch (IOException ignored) { + } finally { + progress.stop(); } } @@ -973,7 +953,7 @@ private void convertImagesSync(Optional player) { } if (outputFolder.exists()) { - this.deleteDirectory(outputFolder); + FileUtils.deleteDirectory(outputFolder); } if (!outputFolder.mkdirs()) { @@ -1139,7 +1119,7 @@ private void convertPackSync(Optional optionalPlayer) { } if (outputPackFile.exists()) { - this.deleteDirectory(outputPackFile); + FileUtils.deleteDirectory(outputPackFile); } if (!outputPackFile.mkdirs()) { this.logDebug(Message.ERROR__MKDIR_FAILURE, Logger.LogType.ERROR, Placeholder.of("directory", outputPackFile.getName(), "path", outputPackFile.getAbsolutePath())); @@ -1253,14 +1233,14 @@ private void extractAndCopyZipAssets(File zipFile, File outputAssetsFolder, Stri } if (!this.settings.dryRunEnabled()) { - this.deleteDirectory(tempDir); + FileUtils.deleteDirectory(tempDir); } } catch (IOException e) { Logger.error(Message.ERROR__CONVERTER__NEXO__PACK__ZIP_EXTRACT_FAILURE, e, Placeholder.of("file", zipFile.getName())); errorRef.compareAndSet(null, e); } finally { if (!this.settings.dryRunEnabled() && tempDir.exists()) { - this.deleteDirectory(tempDir); + FileUtils.deleteDirectory(tempDir); } } } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/nexo/NexoItemConverter.java b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/nexo/NexoItemConverter.java index 34425e64..abd3e043 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/nexo/NexoItemConverter.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/nexo/NexoItemConverter.java @@ -2,7 +2,7 @@ import fr.robie.craftengineconverter.api.builder.TimerBuilder; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.configuration.conditions.EnchantmentCondition; import fr.robie.craftengineconverter.api.configuration.conditions.InvertedCondition; import fr.robie.craftengineconverter.api.configuration.conditions.RandomCondition; @@ -19,6 +19,7 @@ import fr.robie.craftengineconverter.api.configuration.item.behavior.block.states.defaults.PillarBlockState; import fr.robie.craftengineconverter.api.configuration.item.behavior.furniture.*; import fr.robie.craftengineconverter.api.configuration.item.behavior.furniture.element.ItemDisplayElement; +import fr.robie.craftengineconverter.api.configuration.item.behavior.furniture.hitbox.BaseHitbox; import fr.robie.craftengineconverter.api.configuration.item.behavior.furniture.hitbox.HappyGhastHitbox; import fr.robie.craftengineconverter.api.configuration.item.behavior.furniture.hitbox.Hitbox; import fr.robie.craftengineconverter.api.configuration.item.behavior.furniture.hitbox.InteractionHitbox; @@ -37,15 +38,18 @@ import fr.robie.craftengineconverter.api.configuration.item.models.condition.ConditionModelConfiguration; import fr.robie.craftengineconverter.api.configuration.item.models.model.GenerationConfiguration; import fr.robie.craftengineconverter.api.configuration.item.models.model.SimpleModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.ChargeType; import fr.robie.craftengineconverter.api.configuration.item.models.range_dispatch.UseDurationRangeDispatchConfiguration; import fr.robie.craftengineconverter.api.configuration.item.models.select.ChargeTypeSelectConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.models.select.DisplayContent; import fr.robie.craftengineconverter.api.configuration.item.models.select.DisplayContentSelectConfiguration; import fr.robie.craftengineconverter.api.configuration.item.settings.InvulnerableSettingConfiguration; import fr.robie.craftengineconverter.api.configuration.item.settings.ProjectileSettingConfiguration; import fr.robie.craftengineconverter.api.enums.*; +import fr.robie.craftengineconverter.api.enums.item.component.ConsumableAnimation; import fr.robie.craftengineconverter.api.format.Message; - import fr.robie.craftengineconverter.api.utils.FloatsUtils; +import fr.robie.craftengineconverter.api.utils.item.component.ConsumeEffect; import fr.robie.craftengineconverter.common.BlockStatesMapper; import fr.robie.craftengineconverter.common.enums.BukkitFlagToComponentFlag; import fr.robie.craftengineconverter.common.utils.enums.nexo.NexoBestTool; @@ -60,9 +64,12 @@ import fr.robie.craftengineconverter.utils.loots.MinecraftItemLoot; import fr.robie.messageflow.formatter.Placeholder; import fr.robie.messageflow.logger.Logger; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; import net.momirealms.craftengine.core.entity.EquipmentSlot; import net.momirealms.craftengine.core.entity.display.Billboard; import net.momirealms.craftengine.core.item.setting.value.AnvilRepairItem; +import net.momirealms.craftengine.core.plugin.context.number.ConstantNumberProvider; import net.momirealms.craftengine.core.util.Direction; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -71,13 +78,12 @@ import org.bukkit.block.data.BlockData; import org.bukkit.block.data.MultipleFacing; import org.bukkit.block.data.type.Tripwire; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; +import org.jetbrains.annotations.Nullable; + import java.util.*; -import java.util.concurrent.atomic.AtomicBoolean; public class NexoItemConverter extends ItemConverter { private final ConfigurationSection nexoItemSection; @@ -126,15 +132,85 @@ public void convertMaterial() { public void convertItemName() { String itemName = this.nexoItemSection.getString("itemname"); if (this.isValidString(itemName)) { - this.craftEngineItemsConfiguration.addItemConfiguration(new ItemNameConfiguration(itemName, Configuration.get(ConfigurationKey.DISABLE_DEFAULT_ITALIC))); + this.craftEngineItemsConfiguration.addItemConfiguration(new ItemNameConfiguration(itemName, Configuration.get(Keys.DISABLE_DEFAULT_ITALIC))); + } + } + + @Override + public void convertCustomName() { + // Nexo sets both: `itemname` is the item_name component, `customname` the display name written onto the stack. + String customName = this.nexoItemSection.getString("customname"); + if (this.isValidString(customName)) { + this.craftEngineItemsConfiguration.addItemConfiguration(new CustomNameConfiguration(customName)); + } + } + + @Override + public void convertTrim() { + String material = this.nexoItemSection.getString("trim_material"); + String pattern = this.nexoItemSection.getString("trim_pattern"); + // CraftEngine's trim processor needs both halves; half a trim is not a trim. + if (!this.isValidString(material) || !this.isValidString(pattern)) { + if (this.isValidString(material) || this.isValidString(pattern)) { + this.reportUnsupported(this.isValidString(material) ? "trim_pattern (missing)" : "trim_material (missing)"); + } + return; + } + this.craftEngineItemsConfiguration.addItemConfiguration( + new TrimConfiguration(this.namespaced(material), this.namespaced(pattern))); + } + + @Override + public void convertPotionEffects() { + List> effects = this.nexoItemSection.getMapList("PotionEffects"); + if (effects.isEmpty()) { + return; + } + + PotionContentsConfiguration potionContents = new PotionContentsConfiguration(); + for (Map effect : effects) { + // Nexo reads the type from `type` and hands the rest of the map to Bukkit's PotionEffect, which spells + // its own key `effect`; accept either. + String type = this.stringOrNull(effect.get("type")); + if (!this.isValidString(type)) { + type = this.stringOrNull(effect.get("effect")); + } + if (!this.isValidString(type)) { + continue; + } + + potionContents.addEffect(new PotionContentsConfiguration.CustomEffect( + this.namespaced(type.toLowerCase(Locale.ROOT)), + this.intOrDefault(effect.get("duration"), 0), + this.intOrDefault(effect.get("amplifier"), 0), + this.booleanOrNull(effect.get("ambient")), + this.booleanOrNull(effect.get("has-particles")), + this.booleanOrNull(effect.get("has-icon")) + )); + } + + if (potionContents.hasContents()) { + this.craftEngineItemsConfiguration.addItemConfiguration(potionContents); } } + private @Nullable String stringOrNull(@Nullable Object value) { + return value instanceof String string ? string : null; + } + + private int intOrDefault(@Nullable Object value, int fallback) { + return value instanceof Number number ? number.intValue() : fallback; + } + + private @Nullable Boolean booleanOrNull(@Nullable Object value) { + return value instanceof Boolean bool ? bool : null; + } + @Override public void convertLore() { List lore = this.nexoItemSection.getStringList("lore"); if (!lore.isEmpty()) { - this.craftEngineItemsConfiguration.addItemConfiguration(new LoreConfiguration(lore, Configuration.get(ConfigurationKey.DISABLE_DEFAULT_ITALIC))); + this.craftEngineItemsConfiguration.addItemConfiguration(new LoreConfiguration(lore, Configuration.get(Keys.DISABLE_DEFAULT_ITALIC))); } } @@ -201,17 +277,17 @@ public void convertAttributeModifiers() { } Object rawOperation = attributeModifier.get("operation"); - net.momirealms.craftengine.core.attribute.AttributeModifier.Operation operation; + net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation operation; if (rawOperation instanceof String strOperation) { try { - operation = net.momirealms.craftengine.core.attribute.AttributeModifier.Operation.valueOf(strOperation.toUpperCase(Locale.ROOT)); + operation = net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation.valueOf(strOperation.toUpperCase(Locale.ROOT)); } catch (Exception e) { if (strOperation.equalsIgnoreCase("ADD_NUMBER")) { - operation = net.momirealms.craftengine.core.attribute.AttributeModifier.Operation.ADD_VALUE; + operation = net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation.ADD_VALUE; } else if (strOperation.equalsIgnoreCase("ADD_SCALAR")) { - operation = net.momirealms.craftengine.core.attribute.AttributeModifier.Operation.ADD_MULTIPLIED_BASE; + operation = net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation.ADD_MULTIPLIED_BASE; } else if (strOperation.equalsIgnoreCase("MULTIPLY_SCALAR_1")) { - operation = net.momirealms.craftengine.core.attribute.AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL; + operation = net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation.ADD_MULTIPLIED_TOTAL; } else { continue; } @@ -219,11 +295,11 @@ public void convertAttributeModifiers() { } else if (rawOperation instanceof Integer intOperation) { try { operation = switch (intOperation) { - case 0 -> net.momirealms.craftengine.core.attribute.AttributeModifier.Operation.ADD_VALUE; + case 0 -> net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation.ADD_VALUE; case 1 -> - net.momirealms.craftengine.core.attribute.AttributeModifier.Operation.ADD_MULTIPLIED_BASE; + net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation.ADD_MULTIPLIED_BASE; case 2 -> - net.momirealms.craftengine.core.attribute.AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL; + net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Operation.ADD_MULTIPLIED_TOTAL; default -> throw new IllegalArgumentException("Invalid operation id: " + intOperation); }; } catch (Exception e) { @@ -233,13 +309,13 @@ public void convertAttributeModifiers() { continue; } - net.momirealms.craftengine.core.attribute.AttributeModifier.Slot attributeSlot = null; + net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot attributeSlot = null; Object rawSlot = attributeModifier.get("slot"); if (!(rawSlot instanceof String strSlot)) { continue; } try { - attributeSlot = net.momirealms.craftengine.core.attribute.AttributeModifier.Slot.valueOf(strSlot.toUpperCase(Locale.ROOT)); + attributeSlot = net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Slot.valueOf(strSlot.toUpperCase(Locale.ROOT)); } catch (Exception ignored) { } if (attributeSlot == null) { @@ -251,9 +327,9 @@ public void convertAttributeModifiers() { Object typeObj = displayMap.get("type"); Object textObj = displayMap.get("text"); if (typeObj instanceof String typeStr && textObj instanceof String textStr) { - net.momirealms.craftengine.core.attribute.AttributeModifier.Display.Type displayType; + net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Display.Type displayType; try { - displayType = net.momirealms.craftengine.core.attribute.AttributeModifier.Display.Type.valueOf(typeStr.toUpperCase(Locale.ROOT)); + displayType = net.momirealms.craftengine.core.attribute.vanilla.VanillaAttributeModifier.Display.Type.valueOf(typeStr.toUpperCase(Locale.ROOT)); } catch (Exception e) { continue; } @@ -483,16 +559,16 @@ public void convertConsumable() { boolean hasConsumeParticles = consumableSection.getBoolean("consume_particles", true); double consumeSeconds = consumableSection.getDouble("consume_seconds", 1.6); - ConsumableConfiguration.Animation animation; + ConsumableAnimation animation; try { - animation = ConsumableConfiguration.Animation.valueOf( + animation = ConsumableAnimation.valueOf( consumableSection.getString("animation", "eat").toUpperCase(Locale.ROOT) ); } catch (IllegalArgumentException e) { - animation = ConsumableConfiguration.Animation.EAT; + animation = ConsumableAnimation.EAT; } - List consumeEffects = new ArrayList<>(); + List consumeEffects = new ArrayList<>(); ConfigurationSection effectsSection = consumableSection.getConfigurationSection("effects"); if (effectsSection != null) { @@ -672,11 +748,11 @@ public void convertAnvilRepairable() { List anvilRepairItems = new ArrayList<>(); Object singleRepairItem = componentsSection.get("anvil_repairable.repairable"); if (singleRepairItem instanceof String singleRepairItemStr && this.isValidString(singleRepairItemStr)) { - anvilRepairItems.add(new AnvilRepairItem(List.of(singleRepairItemStr), 1, 1.0)); + anvilRepairItems.add(new AnvilRepairItem(List.of(singleRepairItemStr), ConstantNumberProvider.constant(1), ConstantNumberProvider.constant(1.0))); } else if (singleRepairItem instanceof List singleRepairItemList) { for (Object item : singleRepairItemList) { if (item instanceof String itemStr && this.isValidString(itemStr)) { - anvilRepairItems.add(new AnvilRepairItem(List.of(itemStr), 1, 1.0)); + anvilRepairItems.add(new AnvilRepairItem(List.of(itemStr), ConstantNumberProvider.constant(1), ConstantNumberProvider.constant(1.0))); } } } @@ -700,7 +776,7 @@ public void convertDeathProtection() { return; } - List deathEffects = new ArrayList<>(); + List deathEffects = new ArrayList<>(); ConfigurationSection applyEffectsSection = deathEffectsSection.getConfigurationSection("APPLY_EFFECTS"); if (this.isNotNull(applyEffectsSection)) { @@ -1142,7 +1218,7 @@ private void convertModelWithoutParent(ConfigurationSection packSection) { } if (!equipmentLayers.isEmpty()) { - List convertersToProcess = Configuration.get(ConfigurationKey.ARMOR_CONVERTER_TYPE).getComposition(); + List convertersToProcess = Configuration.get(Keys.ARMOR_CONVERTER_TYPE).getComposition(); Map converterSections = ArmorConverter.createArmorConverterSections(fileEquipementsSection, assetId); for (var layerTypeTuple : equipmentLayers.entrySet()) { @@ -1150,7 +1226,7 @@ private void convertModelWithoutParent(ConfigurationSection packSection) { Map> converterTextures = new HashMap<>(); for (var layer : layerTypeTuple.getValue()) { - String originalKey = layer.getFirst(); + String originalKey = layer.first(); String mobTexture = customArmorSection.getString(originalKey); String namespacedTexture = this.namespaced(mobTexture); @@ -1158,7 +1234,7 @@ private void convertModelWithoutParent(ConfigurationSection packSection) { String[] split = namespacedTexture.split(":", 2); String namespace = split[0]; String path = split[1]; - String equipmentFolder = layer.getSecond().replace("-", "_"); + String equipmentFolder = layer.second().replace("-", "_"); // For layer1 and layer2 (humanoid/humanoid-leggings) if (originalKey.equals("layer1") || originalKey.equals("layer2")) { @@ -1219,7 +1295,7 @@ private void convertModelWithoutParent(ConfigurationSection packSection) { String assetId = this.determineAssetId(packSection, List.of("_helmet", "_chestplate", "_leggings", "_boots")); if (this.isValidString(assetId)) { - List convertersToProcess = Configuration.get(ConfigurationKey.ARMOR_CONVERTER_TYPE).getComposition(); + List convertersToProcess = Configuration.get(Keys.ARMOR_CONVERTER_TYPE).getComposition(); Map converterSections = ArmorConverter.createArmorConverterSections(fileEquipementsSection, assetId); String armorName = assetId.split(":", 2)[1]; @@ -1391,9 +1467,9 @@ private boolean tryBuildTridentModel(ConfigurationSection packSection, String mo DisplayContentSelectConfiguration displayContentSelect = new DisplayContentSelectConfiguration(); displayContentSelect.addCase(new SimpleModelConfiguration(namespacedModel), - DisplayContentSelectConfiguration.DisplayContent.GUI, - DisplayContentSelectConfiguration.DisplayContent.GROUND, - DisplayContentSelectConfiguration.DisplayContent.FIXED + DisplayContent.GUI, + DisplayContent.GROUND, + DisplayContent.FIXED ); displayContentSelect.setFallback(usingItemCondition); @@ -1898,7 +1974,7 @@ private void buildBowModel(ConfigurationSection packSection) { if (this.isNotNull(baseModel) && this.isNotNull(pulling0) && this.isNotNull(pulling1) && this.isNotNull(pulling2)) { UseDurationRangeDispatchConfiguration pullingDispatch = new UseDurationRangeDispatchConfiguration(); - pullingDispatch.setScale(0.05); + pullingDispatch.setScale(0.05f); pullingDispatch.addEntry(0.65, new SimpleModelConfiguration(pulling1)); pullingDispatch.addEntry(0.90, new SimpleModelConfiguration(pulling2)); pullingDispatch.setFallback(new SimpleModelConfiguration(pulling0)); @@ -1925,8 +2001,8 @@ private void buildCrossbowModel(ConfigurationSection packSection) { if (this.isNotNull(baseModel) && this.isNotNull(pulling0) && this.isNotNull(pulling1) && this.isNotNull(pulling2)) { ChargeTypeSelectConfiguration chargeTypeSelect = new ChargeTypeSelectConfiguration(); - chargeTypeSelect.addCase(ChargeTypeSelectConfiguration.ChargeType.ARROW, new SimpleModelConfiguration(arrowModel != null ? arrowModel : pulling2)); - chargeTypeSelect.addCase(ChargeTypeSelectConfiguration.ChargeType.ROCKET, new SimpleModelConfiguration(fireworkModel != null ? fireworkModel : pulling2)); + chargeTypeSelect.addCase(ChargeType.ARROW, new SimpleModelConfiguration(arrowModel != null ? arrowModel : pulling2)); + chargeTypeSelect.addCase(ChargeType.ROCKET, new SimpleModelConfiguration(fireworkModel != null ? fireworkModel : pulling2)); chargeTypeSelect.setFallback(new SimpleModelConfiguration(baseModel)); UseDurationRangeDispatchConfiguration pullingDispatch = new UseDurationRangeDispatchConfiguration(); @@ -1962,12 +2038,36 @@ public void convertOther() { this.convertCustomBlockMechanic(nexoCustomBlockSection); } //TODO: convert energyblast mechanic - default -> { - } + default -> this.reportUnsupported("Mechanics." + mechanicsKey); } } } + /** Every key this converter reads off the item itself; anything else is reported as left out. */ + private static final Set HANDLED_ITEM_KEYS = Set.of( + "material", "itemname", "customname", "lore", "color", "unbreakable", "excludeFromInventory", "ItemFlags", + "AttributeModifiers", "Enchantments", "Components", "Pack", "Mechanics", + "trim_material", "trim_pattern", "PotionEffects", + // Consumed before conversion, by NexoItemTemplates. + "template", "templates", "injectId"); + + private static final Set HANDLED_CUSTOM_BLOCK_KEYS = Set.of( + "type", "custom_variation", "log_strip", "directional", "block_sounds", "hardness", + "beacon_base_block", "is_falling", "sapling", "drop"); + + private static final Set HANDLED_FURNITURE_KEYS = Set.of( + "modelengine_id", "better-model", "block_sounds", "restricted_rotation", "seats", + "properties", "drop", "limited_placing", "hitbox", "storage"); + + @Override + public void reportUnsupportedConfiguration() { + this.reportUnhandledKeys("", this.nexoItemSection, HANDLED_ITEM_KEYS); + this.reportUnhandledKeys("Mechanics.custom_block", + this.nexoItemSection.getConfigurationSection("Mechanics.custom_block"), HANDLED_CUSTOM_BLOCK_KEYS); + this.reportUnhandledKeys("Mechanics.furniture", + this.nexoItemSection.getConfigurationSection("Mechanics.furniture"), HANDLED_FURNITURE_KEYS); + } + private void convertCustomBlockMechanic(ConfigurationSection nexoCustomBlockSection) { ModelConfiguration modelConfiguration = this.craftEngineItemsConfiguration.getModelConfiguration(); if (modelConfiguration == null) { @@ -2011,7 +2111,7 @@ private void convertCustomBlockMechanic(ConfigurationSection nexoCustomBlockSect ); } } - } else if (nexoCustomBlockType.equalsIgnoreCase("TRIPWIRE")) { + } else if (nexoCustomBlockType.equalsIgnoreCase("STRINGBLOCK")) { state = CraftEngineBlockState.TRIPWIRE; if (customVariation >= 0) { BlockData blockData = Bukkit.createBlockData(Material.TRIPWIRE); @@ -2283,6 +2383,34 @@ private void convertCustomBlockMechanic(ConfigurationSection nexoCustomBlockSect this.getCraftEngineItemsConfiguration().addItemConfiguration(blockConfiguration); } + /** + * Nexo's storage furniture. Only the plain STORAGE type has a CraftEngine counterpart - the others are a player's + * ender chest, a personal stash, a bin or a shulker's own inventory, none of which is furniture-owned storage. + */ + private void convertFurnitureStorage(ConfigurationSection nexoFurnitureMechanicsSection, FurnitureConfiguration furnitureConfiguration) { + ConfigurationSection storageSection = nexoFurnitureMechanicsSection.getConfigurationSection("storage"); + if (this.isNull(storageSection)) { + return; + } + + String type = storageSection.getString("type", "STORAGE"); + if (!type.equalsIgnoreCase("STORAGE")) { + this.reportUnsupported("Mechanics.furniture.storage (type " + type.toUpperCase(Locale.ROOT) + ")"); + return; + } + + furnitureConfiguration.addBehavior(new SimpleStorageFurnitureBehavior( + storageSection.getInt("rows", 6), + storageSection.getString("title", "Storage"), + storageSection.getString("open_sound", "minecraft:block.chest.open"), + storageSection.getString("close_sound", "minecraft:block.chest.close") + )); + } + + private String upperCaseOrEmpty(@Nullable String value) { + return value == null ? "" : value.toUpperCase(Locale.ROOT); + } + private void convertFurnitureMechanic(ConfigurationSection nexoFurnitureMechanicsSection) { String nexoMEGModel = nexoFurnitureMechanicsSection.getString("modelengine_id"); String nexoBetterModel = nexoFurnitureMechanicsSection.getString("better-model"); @@ -2299,29 +2427,25 @@ private void convertFurnitureMechanic(ConfigurationSection nexoFurnitureMechanic } // --- Rotation --- - FurnitureRotation furnitureRotation = FurnitureRotation.EIGHT; - if (!nexoFurnitureMechanicsSection.getBoolean("rotatable", true)) { - furnitureRotation = FurnitureRotation.FOUR; - } - String restrictedRotation = nexoFurnitureMechanicsSection.getString("restricted_rotation"); - if (this.isValidString(restrictedRotation)) { - if (restrictedRotation.equals("VERY_STRICT")) { - furnitureRotation = FurnitureRotation.FOUR; - } else if (restrictedRotation.equals("STRICT")) { - furnitureRotation = FurnitureRotation.EIGHT; - } - } + // Nexo snaps placement yaw by restricted_rotation - VERY_STRICT in 45 degree steps, STRICT in 22.5 - and + // defaults to STRICT when the key is absent or unrecognised. `rotatable` is a different feature entirely + // (whether a player may turn furniture that is already placed), so it must not change the placement rule. + FurnitureRotation furnitureRotation = switch (this.upperCaseOrEmpty(nexoFurnitureMechanicsSection.getString("restricted_rotation"))) { + case "NONE" -> FurnitureRotation.ANY; + case "VERY_STRICT" -> FurnitureRotation.EIGHT; + default -> FurnitureRotation.SIXTEEN; + }; // --- Seats --- - FloatsUtils seatPosition = new FloatsUtils(3, new float[]{0f, 0f, 0f}); - List seats = nexoFurnitureMechanicsSection.getStringList("seats"); - if (!seats.isEmpty()) { - String seat = seats.getFirst(); + // Nexo writes each seat as an "x,y,z" offset from the furniture origin, and allows any number of them. + List seatPositions = new ArrayList<>(); + for (String seat : nexoFurnitureMechanicsSection.getStringList("seats")) { String[] split = seat.split(",", 3); try { - seatPosition.setValue(0, Float.parseFloat(split[0].trim())); - seatPosition.setValue(1, Float.parseFloat(split[1].trim())); - seatPosition.setValue(2, Float.parseFloat(split[2].trim())); + seatPositions.add(new float[]{ + Float.parseFloat(split[0].trim()), + Float.parseFloat(split[1].trim()), + Float.parseFloat(split[2].trim())}); } catch (Exception e) { Logger.debug(Message.WARNING__FURNITURE__INVALID_SEAT_FORMAT, Placeholder.of("item", this.itemId, "value", seat)); } @@ -2369,6 +2493,9 @@ private void convertFurnitureMechanic(ConfigurationSection nexoFurnitureMechanic } } + // --- Storage --- + this.convertFurnitureStorage(nexoFurnitureMechanicsSection, furnitureConfiguration); + // --- Loot --- ConfigurationSection dropSection = nexoFurnitureMechanicsSection.getConfigurationSection("drop"); if (this.isNotNull(dropSection)) { @@ -2506,8 +2633,6 @@ private void convertFurnitureMechanic(ConfigurationSection nexoFurnitureMechanic List hitboxList = new ArrayList<>(); ConfigurationSection nexoHitboxesSection = nexoFurnitureMechanicsSection.getConfigurationSection("hitbox"); if (this.isNotNull(nexoHitboxesSection)) { - AtomicBoolean seatsAdded = new AtomicBoolean(false); - // Barriers for (Position pos : this.expandBarrierPositions(nexoHitboxesSection.getStringList("barriers"))) { ShulkerHitbox hitbox = new ShulkerHitbox(); @@ -2538,9 +2663,6 @@ private void convertFurnitureMechanic(ConfigurationSection nexoFurnitureMechanic String dir = parts[3].toUpperCase(Locale.ROOT); hitbox.setDirection(this.getDirectionFromString(dir)); } - if (seatPosition.isUpdated() && !seatsAdded.getAndSet(true)) { - hitbox.addSeat(seatPosition.getValue(0), seatPosition.getValue(1), seatPosition.getValue(2), 0); - } hitboxList.add(hitbox); } catch (NumberFormatException e) { Logger.debug(Message.WARNING__FURNITURE__NON_NUMERIC_SHULKER_VALUES, Placeholder.of("item", this.itemId, "entry", shulker)); @@ -2565,9 +2687,6 @@ private void convertFurnitureMechanic(ConfigurationSection nexoFurnitureMechanic HappyGhastHitbox hitbox = new HappyGhastHitbox(); hitbox.setPosition(Float.parseFloat(coords[0]), Float.parseFloat(coords[1]), Float.parseFloat(coords[2])); hitbox.setScale(Float.parseFloat(parts[1])); - if (seatPosition.isUpdated() && !seatsAdded.getAndSet(true)) { - hitbox.addSeat(seatPosition.getValue(0), seatPosition.getValue(1), seatPosition.getValue(2), 0); - } hitboxList.add(hitbox); } catch (NumberFormatException e) { Logger.debug(Message.WARNING__FURNITURE__NON_NUMERIC_GHAST_VALUES, Placeholder.of("item", this.itemId, "entry", ghast)); @@ -2601,6 +2720,18 @@ private void convertFurnitureMechanic(ConfigurationSection nexoFurnitureMechanic } } + // CraftEngine keys seats by their offset and shares them across a furniture's hitboxes, so they all + // hang off one hitbox rather than being spread over them. + if (!seatPositions.isEmpty()) { + if (hitboxList.isEmpty()) { + this.reportUnsupported("Mechanics.furniture.seats (no hitbox to sit on)"); + } else if (hitboxList.getFirst() instanceof BaseHitbox seatHitbox) { + for (float[] seat : seatPositions) { + seatHitbox.addSeat(seat[0], seat[1], seat[2], 0); + } + } + } + for (FurniturePlacement furniturePlacement : placementKeys) { Placement p = furnitureConfiguration.getOrCreatePlacement(furniturePlacement); Rules rules = p.getRules(); diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/converter/nexo/NexoItemTemplates.java b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/nexo/NexoItemTemplates.java new file mode 100644 index 00000000..fabe4623 --- /dev/null +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/converter/nexo/NexoItemTemplates.java @@ -0,0 +1,320 @@ +package fr.robie.craftengineconverter.converter.nexo; + +import fr.robie.craftengineconverter.api.format.Message; +import fr.robie.craftengineconverter.utils.ConfigFile; +import fr.robie.messageflow.formatter.Placeholder; +import fr.robie.messageflow.logger.Logger; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + +/** + * Nexo's item templates. + * + *

An item may name one or more other items under {@code template} (or {@code templates}); their sections are merged + * together in declaration order and the item is then merged on top, so the item always wins. Any item that is named as + * a template is not itself turned into an item. + * + *

Templates are written against placeholders - {@code }, {@code }, {@code } and friends - + * that are resolved against the item doing the inheriting, which is what makes one template usable by many items. + */ +public final class NexoItemTemplates { + private static final String ITEM_GENERATED = "minecraft:item/generated"; + + /** Resolved against the inheriting item's own section, never the template's. */ + private static final Map> PLACEHOLDERS = new LinkedHashMap<>(); + + static { + PLACEHOLDERS.put("item_id", PlaceholderContext::itemId); + PLACEHOLDERS.put("item_id_capitalized", context -> capitalize(context.itemId())); + PLACEHOLDERS.put("lore", PlaceholderContext::takeLore); + PLACEHOLDERS.put("parent", context -> { + String parentModel = context.string("Pack.parent_model"); + if (parentModel != null) { + return parentModel; + } + String parent = context.string("Pack.parent"); + return parent != null ? parent : ITEM_GENERATED; + }); + PLACEHOLDERS.put("model", context -> { + String model = context.string("Pack.model"); + return model != null ? model : context.itemId(); + }); + PLACEHOLDERS.put("texture", context -> stringListOrSingle(context.item(), "Pack.texture")); + } + + private final Map sectionsByItemId; + private final Set templateIds; + + private NexoItemTemplates(Map sectionsByItemId, Set templateIds) { + this.sectionsByItemId = sectionsByItemId; + this.templateIds = templateIds; + } + + /** + * Indexes every item across every file, then marks as a template each item that some other item inherits from. + * Templates are looked up globally, so an item can inherit from one declared in a different file. + */ + public static NexoItemTemplates collect(Collection files) { + Map sectionsByItemId = new LinkedHashMap<>(); + for (ConfigFile file : files) { + YamlConfiguration config = file.config(); + for (String itemId : config.getKeys(false)) { + ConfigurationSection section = config.getConfigurationSection(itemId); + if (section != null) { + sectionsByItemId.putIfAbsent(itemId, section); + } + } + } + + Set templateIds = new LinkedHashSet<>(); + for (ConfigurationSection section : sectionsByItemId.values()) { + templateIds.addAll(stringListOrSingle(section, "template")); + } + return new NexoItemTemplates(sectionsByItemId, templateIds); + } + + /** Whether this item only exists to be inherited from, and so must not be converted into an item of its own. */ + public boolean isTemplate(String itemId) { + return this.templateIds.contains(itemId); + } + + /** + * The item's section with everything it inherits folded in. Returns a detached copy, so the source configuration + * is never modified; an item without a template still gets a copy, which keeps the caller's contract uniform. + */ + public ConfigurationSection resolve(String itemId, ConfigurationSection itemSection) { + ConfigurationSection item = copyOf(itemId, itemSection); + + ConfigurationSection template = this.mergedTemplateOf(itemId, item, new LinkedHashSet<>()); + if (template == null) { + return item; + } + + template.set("injectId", null); + replacePlaceholders(template, new PlaceholderContext(itemId, item)); + + return deepMerge(template, item); + } + + /** + * Merges every template the section names, in declaration order, so a later template wins over an earlier one. + * Templates may themselves name templates; {@code visiting} keeps a self-referencing chain from recursing forever. + */ + private @Nullable ConfigurationSection mergedTemplateOf(String itemId, ConfigurationSection section, Set visiting) { + List templateIds = stringListOrSingle(section, "template"); + if (templateIds.isEmpty()) { + return null; + } + + ConfigurationSection merged = null; + for (String templateId : templateIds) { + ConfigurationSection templateSection = this.sectionsByItemId.get(templateId); + if (templateSection == null) { + Logger.warn(Message.WARNING__CONVERTER__NEXO__TEMPLATE__NOT_FOUND, Placeholder.of("item", itemId, "template", templateId)); + continue; + } + if (!visiting.add(templateId)) { + Logger.warn(Message.WARNING__CONVERTER__NEXO__TEMPLATE__CIRCULAR, Placeholder.of("item", itemId, "template", templateId)); + continue; + } + + ConfigurationSection resolved = this.resolveTemplate(itemId, templateId, templateSection, visiting); + visiting.remove(templateId); + + merged = merged == null ? resolved : deepMerge(merged, resolved); + } + return merged; + } + + /** + * A template with its own templates folded in. Placeholders are deliberately left alone here: they belong to the + * item that ends up inheriting the chain, not to the intermediate templates. + */ + private ConfigurationSection resolveTemplate(String itemId, String templateId, ConfigurationSection templateSection, Set visiting) { + ConfigurationSection template = copyOf(templateId, templateSection); + + ConfigurationSection parent = this.mergedTemplateOf(itemId, template, visiting); + if (parent == null) { + return template; + } + + parent.set("injectId", null); + return deepMerge(parent, template); + } + + // --- placeholders --------------------------------------------------------------------------------------------- + + private static void replacePlaceholders(ConfigurationSection section, PlaceholderContext context) { + for (String key : new ArrayList<>(section.getKeys(false))) { + if (section.isConfigurationSection(key)) { + ConfigurationSection child = section.getConfigurationSection(key); + if (child != null) { + replacePlaceholders(child, context); + } + continue; + } + + Object value = section.get(key); + if (value instanceof String string) { + List expanded = context.expand(string); + if (expanded.isEmpty()) { + // The placeholder resolved to nothing, so the key it was standing in for has nothing left to say. + section.set(key, null); + } else { + section.set(key, expanded.size() == 1 ? expanded.getFirst() : expanded); + } + } else if (value instanceof List list) { + List expanded = context.expandAll(list); + // A list that had entries and now has none was standing entirely on a placeholder that resolved empty. + section.set(key, expanded.isEmpty() && !list.isEmpty() ? null : expanded); + } + // Anything else - numbers, booleans - cannot carry a placeholder, so it is left exactly as it is. + } + } + + private record PlaceholderContext(String itemId, ConfigurationSection item, Map resolved) { + private PlaceholderContext(String itemId, ConfigurationSection item) { + this(itemId, item, new LinkedHashMap<>()); + } + + private @Nullable String string(String path) { + String value = this.item.getString(path); + return value == null || value.isEmpty() ? null : value; + } + + /** + * The inheriting item's own lore, which the template is expected to place somewhere inside its own. It is + * removed from the item so that the template's copy - the one with the placeholder expanded - is what survives + * the merge. + */ + private List takeLore() { + List lore = this.item.getStringList("lore"); + this.item.set("lore", null); + return lore; + } + + private @Nullable Object valueOf(String key) { + // Memoised because takeLore has a side effect: asking twice would give an empty list the second time. + return this.resolved.computeIfAbsent(key, k -> PLACEHOLDERS.get(k).apply(this)); + } + + private List expandAll(List values) { + List expanded = new ArrayList<>(); + for (Object value : values) { + if (value instanceof String string) { + expanded.addAll(this.expand(string)); + } else { + expanded.add(value); + } + } + return expanded; + } + + /** + * Substitutes every placeholder the value mentions. A list-valued placeholder only expands when the value is + * nothing but that placeholder - {@code lore: " and more"} cannot become several lines - which matches + * how Nexo resolves them. + */ + private List expand(String value) { + List current = new ArrayList<>(List.of(value)); + + for (String key : PLACEHOLDERS.keySet()) { + String token = "<" + key + ">"; + if (!value.contains(token)) { + continue; + } + + Object replacement = this.valueOf(key); + if (replacement == null) { + continue; + } + + List next = new ArrayList<>(); + for (Object element : current) { + if (!(element instanceof String string)) { + next.add(element); + } else if (!(replacement instanceof List list)) { + next.add(string.replace(token, String.valueOf(replacement))); + } else if (string.equals(token)) { + next.addAll(list); + } else { + next.add(string); + } + } + current = next; + } + return current; + } + } + + // --- section helpers ------------------------------------------------------------------------------------------ + + /** + * Nexo accepts either a single string or a list wherever one of these keys appears, and falls back to the same key + * with its plural flipped - {@code texture} also answers to {@code textures}. + */ + private static List stringListOrSingle(ConfigurationSection section, String key) { + List values = readStringListOrSingle(section, key); + if (!values.isEmpty()) { + return values; + } + + String alternateKey = key.endsWith("s") ? key.substring(0, key.length() - 1) : key + "s"; + return readStringListOrSingle(section, alternateKey); + } + + private static List readStringListOrSingle(ConfigurationSection section, String key) { + if (section.isList(key)) { + return section.getStringList(key); + } + String value = section.getString(key); + return value == null || value.isEmpty() ? List.of() : List.of(value); + } + + private static ConfigurationSection copyOf(String name, ConfigurationSection section) { + return deepMerge(new YamlConfiguration().createSection(name), section); + } + + /** Copies {@code source} over {@code target}, merging nested sections key by key so the two are not clobbered. */ + private static @NotNull ConfigurationSection deepMerge(@NotNull ConfigurationSection target, @NotNull ConfigurationSection source) { + for (String key : source.getKeys(false)) { + Object sourceValue = source.get(key); + if (!(sourceValue instanceof ConfigurationSection sourceSection)) { + target.set(key, sourceValue); + continue; + } + + ConfigurationSection targetSection = target.isConfigurationSection(key) + ? target.getConfigurationSection(key) + : target.createSection(key); + deepMerge(targetSection, sourceSection); + } + return target; + } + + private static String capitalize(String itemId) { + StringBuilder capitalized = new StringBuilder(); + for (String word : itemId.split("_")) { + if (!capitalized.isEmpty()) { + capitalized.append(' '); + } + if (word.isEmpty()) { + continue; + } + capitalized.append(word.substring(0, 1).toUpperCase(Locale.ROOT)).append(word.substring(1)); + } + return capitalized.toString(); + } +} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/database/ConversionHistoryQueries.java b/Plugin/src/main/java/fr/robie/craftengineconverter/database/ConversionHistoryQueries.java new file mode 100644 index 00000000..b74a1faa --- /dev/null +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/database/ConversionHistoryQueries.java @@ -0,0 +1,171 @@ +package fr.robie.craftengineconverter.database; + +import fr.robie.craftengineconverter.api.database.ActiveConversionReader; +import fr.robie.craftengineconverter.api.history.BlockHistory; +import fr.robie.craftengineconverter.api.history.EntityHistory; +import fr.robie.messageflow.logger.Logger; +import org.jetbrains.annotations.NotNull; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * The hand-written SQL behind the conversion history. + * + *

Separate from {@link DataBaseManager} because it is the part no compiler checks: a mistyped column, a paging + * clause that skips rows, a dialect that spells something differently. Taking a connection rather than a plugin is + * what lets it be run against a real database in a test. + */ +public class ConversionHistoryQueries implements ActiveConversionReader { + public static final String BLOCK_TABLE = "world_block_converter_historical"; + public static final String ENTITY_TABLE = "world_entity_converter_historical"; + + /** Rows the driver keeps in flight while streaming; a cursor, not a buffer of the whole result. */ + private static final int STREAM_FETCH_SIZE = 1_000; + + private final Supplier connections; + + public ConversionHistoryQueries(@NotNull Supplier connections) { + this.connections = connections; + } + + /** + * Reads straight over the JDBC cursor rather than through the ORM. + *

+ * Sarah's select builds a list of every matching row before returning, which for the startup index means holding + * millions of records at once purely to read four numbers out of each. Streaming keeps one row in flight. + */ + @Override + public void forEachActiveBlockPosition(@NotNull BlockPositionConsumer consumer) { + this.stream("SELECT world_name, block_x, block_y, block_z FROM " + BLOCK_TABLE + " WHERE reverted = ?", + row -> consumer.accept(row.getString(1), row.getInt(2), row.getInt(3), row.getInt(4))); + } + + @Override + public void forEachActiveEntityLocation(@NotNull Consumer consumer) { + this.stream("SELECT location FROM " + ENTITY_TABLE + " WHERE reverted = ?", + row -> consumer.accept(row.getString(1))); + } + + /** + * The next page of block conversions still in effect, ordered by id and starting after {@code afterId}. + *

+ * Paging by id rather than by offset is what keeps the walk correct while it marks rows reverted underneath + * itself: with an OFFSET, every page already passed would shift and the walk would skip rows. + */ + @NotNull + public List nextActiveBlockPage(long afterId, int limit) { + List page = new ArrayList<>(); + this.page(BLOCK_TABLE, "id, world_name, chunk_x, chunk_z, block_x, block_y, block_z, original_block", + afterId, limit, row -> page.add(new BlockHistory( + row.getLong(1), row.getString(2), + row.getInt(3), row.getInt(4), + row.getInt(5), row.getInt(6), row.getInt(7), + row.getString(8), false))); + return page; + } + + @NotNull + public List nextActiveEntityPage(long afterId, int limit) { + List page = new ArrayList<>(); + this.page(ENTITY_TABLE, "id, location, nbt", afterId, limit, + row -> page.add(new EntityHistory(row.getLong(1), row.getString(2), row.getString(3), false))); + return page; + } + + /** Marks the given block conversions reverted in one statement, rather than a round trip per row. */ + public void markBlocksAsReverted(@NotNull Collection ids) { + this.markAsReverted(BLOCK_TABLE, ids); + } + + public void markEntitiesAsReverted(@NotNull Collection ids) { + this.markAsReverted(ENTITY_TABLE, ids); + } + + public void markAllBlocksAsReverted() { + this.markAllAsReverted(BLOCK_TABLE); + } + + public void markAllEntitiesAsReverted() { + this.markAllAsReverted(ENTITY_TABLE); + } + + // --- plumbing --------------------------------------------------------------------------------------------- + + @FunctionalInterface + private interface RowReader { + + void read(ResultSet row) throws SQLException; + } + + private void stream(String sql, RowReader reader) { + try (PreparedStatement statement = this.connections.get() + .prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { + statement.setBoolean(1, false); + statement.setFetchSize(STREAM_FETCH_SIZE); + try (ResultSet rows = statement.executeQuery()) { + while (rows.next()) { + reader.read(rows); + } + } + } catch (Exception e) { + Logger.error("Failed to read active conversions", e); + } + } + + private void page(String table, String columns, long afterId, int limit, RowReader reader) { + String sql = "SELECT " + columns + " FROM " + table + + " WHERE reverted = ? AND id > ? ORDER BY id LIMIT " + Math.max(1, limit); + try (PreparedStatement statement = this.connections.get().prepareStatement(sql)) { + statement.setBoolean(1, false); + statement.setLong(2, afterId); + try (ResultSet rows = statement.executeQuery()) { + while (rows.next()) { + reader.read(rows); + } + } + } catch (Exception e) { + Logger.error("Failed to read a page of active conversions from " + table, e); + } + } + + private void markAsReverted(String table, Collection ids) { + if (ids.isEmpty()) { + return; + } + + StringBuilder sql = new StringBuilder("UPDATE ").append(table).append(" SET reverted = ? WHERE id IN ("); + sql.append("?,".repeat(ids.size())); + sql.setLength(sql.length() - 1); + sql.append(')'); + + try (PreparedStatement statement = this.connections.get().prepareStatement(sql.toString())) { + statement.setBoolean(1, true); + int index = 2; + for (Long id : ids) { + statement.setLong(index++, id); + } + statement.executeUpdate(); + } catch (Exception e) { + Logger.error("Failed to mark a page of conversions as reverted in " + table, e); + } + } + + private void markAllAsReverted(String table) { + try (PreparedStatement statement = this.connections.get() + .prepareStatement("UPDATE " + table + " SET reverted = ? WHERE reverted = ?")) { + statement.setBoolean(1, true); + statement.setBoolean(2, false); + statement.executeUpdate(); + } catch (Exception e) { + Logger.error("Failed to mark every conversion in " + table + " as reverted", e); + } + } +} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/database/ConvertedBlockIndex.java b/Plugin/src/main/java/fr/robie/craftengineconverter/database/ConvertedBlockIndex.java new file mode 100644 index 00000000..b4d0c643 --- /dev/null +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/database/ConvertedBlockIndex.java @@ -0,0 +1,88 @@ +package fr.robie.craftengineconverter.database; + +import fr.robie.craftengineconverter.api.database.ActiveConversionReader; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import org.jetbrains.annotations.NotNull; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Which blocks are currently converted, as positions rather than records. + * + *

It answers one question - has this been converted? - which is asked once per candidate block of every chunk + * that loads, so it has to be in memory. What does not have to be in memory is everything else about a conversion: + * holding the records cost around 375 bytes a block, most of it the block state string and a per-row copy of the + * world name, which put a world-sized conversion near two gigabytes of heap. A packed position is a tenth of that, + * and the record behind one is only wanted when something is restored, which reads it back from the database. + * + *

Positions are packed the way Minecraft packs a BlockPos: 26 bits of x, 12 of y, 26 of z. That covers every + * coordinate inside the world border and every height a world can have. + */ +public class ConvertedBlockIndex { + private static final int PACKED_X_BITS = 26; + private static final int PACKED_Z_BITS = 26; + private static final int PACKED_Y_BITS = 64 - PACKED_X_BITS - PACKED_Z_BITS; + private static final long PACKED_X_MASK = (1L << PACKED_X_BITS) - 1; + private static final long PACKED_Y_MASK = (1L << PACKED_Y_BITS) - 1; + private static final long PACKED_Z_MASK = (1L << PACKED_Z_BITS) - 1; + + /** + * One set per world, each guarded by itself. LongOpenHashSet is not thread safe and both chunk loading and + * interaction conversion touch it; locking per world rather than globally keeps worlds off each other's backs, + * and every critical section here is a single hash lookup. + */ + private final Map positionsByWorld = new ConcurrentHashMap<>(); + + static long pack(int blockX, int blockY, int blockZ) { + return ((blockX & PACKED_X_MASK) << (PACKED_Y_BITS + PACKED_Z_BITS)) + | ((blockY & PACKED_Y_MASK) << PACKED_Z_BITS) + | (blockZ & PACKED_Z_MASK); + } + + /** Fills the index from storage, one row at a time, keeping only each row's position. */ + public void loadFrom(@NotNull ActiveConversionReader reader) { + reader.forEachActiveBlockPosition(this::add); + } + + public void add(@NotNull String worldName, int blockX, int blockY, int blockZ) { + LongOpenHashSet positions = this.positionsByWorld.computeIfAbsent(worldName, world -> new LongOpenHashSet()); + synchronized (positions) { + positions.add(pack(blockX, blockY, blockZ)); + } + } + + public boolean contains(@NotNull String worldName, int blockX, int blockY, int blockZ) { + LongOpenHashSet positions = this.positionsByWorld.get(worldName); + if (positions == null) { + return false; + } + synchronized (positions) { + return positions.contains(pack(blockX, blockY, blockZ)); + } + } + + public void remove(@NotNull String worldName, int blockX, int blockY, int blockZ) { + LongOpenHashSet positions = this.positionsByWorld.get(worldName); + if (positions == null) { + return; + } + synchronized (positions) { + positions.remove(pack(blockX, blockY, blockZ)); + } + } + + public int size() { + int total = 0; + for (LongOpenHashSet positions : this.positionsByWorld.values()) { + synchronized (positions) { + total += positions.size(); + } + } + return total; + } + + public void clear() { + this.positionsByWorld.clear(); + } +} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/database/DataBaseManager.java b/Plugin/src/main/java/fr/robie/craftengineconverter/database/DataBaseManager.java index 171fbefc..7e201b3c 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/database/DataBaseManager.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/database/DataBaseManager.java @@ -8,12 +8,12 @@ import fr.robie.craftengineconverter.api.database.StorageType; import fr.robie.craftengineconverter.api.history.BlockHistory; import fr.robie.craftengineconverter.api.history.EntityHistory; +import fr.robie.craftengineconverter.api.manager.FileCacheManager; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; -import fr.robie.craftengineconverter.common.manager.FileCacheManager; import fr.robie.craftengineconverter.database.migrations.WorldBlockConverterHistorical; import fr.robie.craftengineconverter.database.migrations.WorldEntityConverterHistorical; import fr.robie.craftengineconverter.utils.TypedCache; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NonNull; @@ -31,8 +31,12 @@ public class DataBaseManager implements StorageManager { private final Map, TypedCache> caches = new ConcurrentHashMap<>(); - private static final int MAX_BATCH_SIZE = 250; // Max objects to process per batch - private static final long SAVE_INTERVAL_TICKS = 1200L; // 5 minutes (6000 ticks = 300 seconds) -> 1 min (1200 ticks = 60 seconds) + private static final int MAX_BATCH_SIZE = 250; // Max rows per INSERT + private static final long SAVE_INTERVAL_TICKS = 1200L; // 1 minute; only a floor, overflow drains sooner + /** Ceiling on one save cycle, so a large backlog cannot monopolise the connection in a single pass. */ + private static final int MAX_OBJECTS_PER_SAVE = 25_000; + /** Pending rows that trigger a drain without waiting for the next cycle. */ + private static final int OVERFLOW_THRESHOLD = 2_000; public DataBaseManager(CraftEngineConverterPlugin plugin) { this.plugin = plugin; @@ -139,6 +143,9 @@ public void loadDatabase() { MigrationManager.setDatabaseConfiguration(databaseConnection.getDatabaseConfiguration()); MigrationManager.execute(databaseConnection, logger); + for (TypedCache cache : this.caches.values()) { + cache.onOverflow(OVERFLOW_THRESHOLD, () -> this.drainSoon(cache)); + } this.plugin.getFoliaCompatibilityManager().runTimerAsync(this::saveAll, SAVE_INTERVAL_TICKS, SAVE_INTERVAL_TICKS); } @@ -152,10 +159,20 @@ private void saveAll() { } for (TypedCache cache : this.caches.values()) { - cache.processBatch(); + cache.drain(MAX_OBJECTS_PER_SAVE); } } + /** + * Drains a cache off the main thread as soon as it has built up, instead of waiting for the next save. + *

+ * A conversion produces rows far faster than one scheduled cycle used to remove them, so the buffer grew for as + * long as the conversion ran - holding every pending row, and its key, in memory the whole time. + */ + private void drainSoon(TypedCache cache) { + this.plugin.getFoliaCompatibilityManager().runAsync(() -> cache.drain(MAX_OBJECTS_PER_SAVE)); + } + /** * Adds a BlockHistory object to the cache for later batch insertion. * @@ -228,6 +245,65 @@ public void markEntityAsReverted(@NotNull EntityHistory entityHistory) { }); } + /** Delegated so the raw SQL can be exercised against a real database without a plugin around it. */ + private ConversionHistoryQueries queries() { + return new ConversionHistoryQueries(() -> this.requestHelper.getConnection().getConnection()); + } + + @Override + public void forEachActiveBlockPosition(@NotNull BlockPositionConsumer consumer) { + if (!this.isEnabled) { + return; + } + this.queries().forEachActiveBlockPosition(consumer); + } + + @Override + public void forEachActiveEntityLocation(@NotNull java.util.function.Consumer consumer) { + if (!this.isEnabled) { + return; + } + this.queries().forEachActiveEntityLocation(consumer); + } + + @Override + public @NotNull List nextActiveBlockPage(long afterId, int limit) { + return this.isEnabled ? this.queries().nextActiveBlockPage(afterId, limit) : List.of(); + } + + @Override + public @NotNull List nextActiveEntityPage(long afterId, int limit) { + return this.isEnabled ? this.queries().nextActiveEntityPage(afterId, limit) : List.of(); + } + + @Override + public void markBlocksAsReverted(@NotNull java.util.Collection ids) { + if (this.isEnabled) { + this.queries().markBlocksAsReverted(ids); + } + } + + @Override + public void markEntitiesAsReverted(@NotNull java.util.Collection ids) { + if (this.isEnabled) { + this.queries().markEntitiesAsReverted(ids); + } + } + + @Override + public void markAllBlocksAsReverted() { + if (this.isEnabled) { + this.queries().markAllBlocksAsReverted(); + } + } + + @Override + public void markAllEntitiesAsReverted() { + if (this.isEnabled) { + this.queries().markAllEntitiesAsReverted(); + } + } + /** * Gets the history of a specific block. * diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/database/ServerProfileManager.java b/Plugin/src/main/java/fr/robie/craftengineconverter/database/ServerProfileManager.java index 45ecb885..f9eed635 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/database/ServerProfileManager.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/database/ServerProfileManager.java @@ -8,93 +8,46 @@ import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NonNull; -import java.util.Collection; -import java.util.List; -import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** - * Manages an in-memory cache of non-reverted block conversions. - * This cache improves performance by reducing database queries when checking if blocks are already converted. + * Remembers which blocks and entities are currently converted, so a chunk being scanned does not have to ask the + * database once per candidate block. + * + *

Blocks live in a {@link ConvertedBlockIndex}, which holds positions rather than records. Entity conversions are + * keyed by their serialised location: there is one per piece of furniture rather than one per block, so they are not + * worth packing, but their NBT snapshots were the largest single thing this used to keep. */ public class ServerProfileManager implements ServerProfile { - private final CraftEngineConverter plugin; private final StorageManager storageManager; - - private final Map activeBlockCache = new ConcurrentHashMap<>(); - private final Map activeEntityCache = new ConcurrentHashMap<>(); + private final ConvertedBlockIndex convertedBlocks = new ConvertedBlockIndex(); + private final Set convertedEntities = ConcurrentHashMap.newKeySet(); public ServerProfileManager(CraftEngineConverter plugin) { - this.plugin = plugin; - this.storageManager = plugin.getStorageManager(); + this(plugin.getStorageManager()); + } + + ServerProfileManager(StorageManager storageManager) { + this.storageManager = storageManager; } - /** - * Loads all non-reverted block histories from the database into memory cache. - */ + /** Reads back every conversion still in effect, one row at a time, keeping only its position. */ @Override public void load() { if (!this.storageManager.isEnabled()) { return; } - List allBlockHistories = this.storageManager.getAllActiveConversions(); - - for (BlockHistory history : allBlockHistories) { - if (!history.isReverted()) { - String key = this.createCacheKey( - history.getWorldName(), - history.getChunkX(), - history.getChunkZ(), - history.getBlockX(), - history.getBlockY(), - history.getBlockZ() - ); - this.activeBlockCache.put(key, history); - } - } - List allActiveEntityConversions = this.storageManager.getAllActiveEntityConversions(); - for (EntityHistory entityHistory : allActiveEntityConversions) { - if (!entityHistory.isReverted()) { - this.activeEntityCache.put(entityHistory.getLocationString(), entityHistory); - } - } - } - - /** - * Creates a cache key from block and chunk coordinates. - * - * @param worldName The world name - * @param chunkX The chunk X coordinate - * @param chunkZ The chunk Z coordinate - * @param blockX The block X coordinate - * @param blockY The block Y coordinate - * @param blockZ The block Z coordinate - * @return The cache key string in format: world=name:chunkx:chunkz:blockx:blocky:blockz - */ - @NotNull - private String createCacheKey(@NotNull String worldName, int chunkX, int chunkZ, int blockX, int blockY, int blockZ) { - return worldName + ":" + chunkX + ":" + chunkZ + ":" + blockX + ":" + blockY + ":" + blockZ; + this.convertedBlocks.loadFrom(this.storageManager); + this.storageManager.forEachActiveEntityLocation(this.convertedEntities::add); } - /** - * Adds a new block conversion to the cache. - * Should be called after inserting into the database. - * - * @param blockHistory The block history to add to cache - */ @Override public void addBlockHistory(@NotNull BlockHistory blockHistory) { if (!blockHistory.isReverted()) { - String key = this.createCacheKey( - blockHistory.getWorldName(), - blockHistory.getChunkX(), - blockHistory.getChunkZ(), - blockHistory.getBlockX(), - blockHistory.getBlockY(), - blockHistory.getBlockZ() - ); - this.activeBlockCache.put(key, blockHistory); + this.convertedBlocks.add(blockHistory.getWorldName(), + blockHistory.getBlockX(), blockHistory.getBlockY(), blockHistory.getBlockZ()); } this.storageManager.upsertBlockHistory(blockHistory); } @@ -102,97 +55,57 @@ public void addBlockHistory(@NotNull BlockHistory blockHistory) { @Override public void addEntityHistory(@NotNull EntityHistory entityHistory) { if (!entityHistory.isReverted()) { - this.activeEntityCache.put(entityHistory.getLocationString(), entityHistory); + this.convertedEntities.add(entityHistory.getLocationString()); } this.storageManager.upsertEntityHistory(entityHistory); } - /** - * Checks if a block is already converted (and not reverted) using the cache. - * This is a fast O(1) operation. - * - * @param worldName The world name - * @param blockX The block X coordinate - * @param blockY The block Y coordinate - * @param blockZ The block Z coordinate - * @return true if the block is converted and not reverted - */ @Override public boolean isBlockConverted(@NotNull String worldName, int blockX, int blockY, int blockZ) { - int chunkX = blockX >> 4; // Equivalent to blockX / 16 - int chunkZ = blockZ >> 4; // Equivalent to blockZ / 16 - String key = this.createCacheKey(worldName, chunkX, chunkZ, blockX, blockY, blockZ); - return this.activeBlockCache.containsKey(key); + return this.convertedBlocks.contains(worldName, blockX, blockY, blockZ); } @Override public boolean isEntityConverted(@NotNull String locationString) { - return this.activeEntityCache.containsKey(locationString); + return this.convertedEntities.contains(locationString); } - /** - * Gets the current number of cached block conversions. - * - * @return The cache size - */ @Override public int getActiveBlockCount() { - return this.activeBlockCache.size(); + return this.convertedBlocks.size(); } - /** - * Gets the current number of cached entity conversions. - * - * @return The entity cache size - */ @Override public int getActiveEntityCount() { - return this.activeEntityCache.size(); + return this.convertedEntities.size(); } - /** - * Clears all entries from the cache. - */ @Override public void clearBlockHistory() { - for (var blockHistory : this.activeBlockCache.values()) { - this.storageManager.markBlockAsReverted(blockHistory); - } - this.activeBlockCache.clear(); + this.convertedBlocks.clear(); + this.storageManager.markAllBlocksAsReverted(); } @Override public void markBlockAsReverted(@NonNull BlockHistory history) { - String key = this.createCacheKey( - history.getWorldName(), - history.getChunkX(), - history.getChunkZ(), - history.getBlockX(), - history.getBlockY(), - history.getBlockZ() - ); - this.activeBlockCache.remove(key); + this.forgetBlock(history); this.storageManager.markBlockAsReverted(history); } @Override public void markEntityAsReverted(@NotNull EntityHistory history) { - this.activeEntityCache.remove(history.getLocationString()); + this.forgetEntity(history); this.storageManager.markEntityAsReverted(history); } - /** - * Gets all active (non-reverted) block conversions from the cache. - * - * @return Collection of all active BlockHistory records in the cache - */ @Override - public @NonNull Collection getAllActiveConversions() { - return this.activeBlockCache.values(); + public void forgetBlock(@NotNull BlockHistory history) { + this.convertedBlocks.remove(history.getWorldName(), + history.getBlockX(), history.getBlockY(), history.getBlockZ()); } @Override - public @NotNull Collection getAllActiveEntityConversions() { - return this.activeEntityCache.values(); + public void forgetEntity(@NotNull EntityHistory history) { + this.convertedEntities.remove(history.getLocationString()); } } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/listener/WorldConverterManager.java b/Plugin/src/main/java/fr/robie/craftengineconverter/listener/WorldConverterManager.java index e8a20734..81ec63af 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/listener/WorldConverterManager.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/listener/WorldConverterManager.java @@ -11,7 +11,7 @@ import fr.robie.craftengineconverter.common.BlockStatesMapper; import fr.robie.craftengineconverter.common.CraftEnginePlacementTracker; import fr.robie.craftengineconverter.common.converter.WorldConverter; -import fr.robie.craftengineconverter.common.records.ChunkPosition; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import fr.robie.messageflow.logger.Logger; import net.momirealms.craftengine.bukkit.api.CraftEngineBlocks; import org.bukkit.*; @@ -29,13 +29,28 @@ import java.util.*; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; public class WorldConverterManager implements Listener { private final Set converters = new HashSet<>(); - private final Set processedChunks = new HashSet<>(); + /** + * Chunks already scanned this session, packed as x and z into one long per world. + *

+ * A record per chunk carried a world-name reference and its own object header for two numbers, and nothing ever + * evicts them - a server that stays up long enough to walk a million chunks paid tens of megabytes for a set of + * "already looked at this". Two ints fit in a long exactly. + */ + private final Map processedChunksByWorld = new ConcurrentHashMap<>(); private final CraftEnginePlacementTracker placementTracker; private final FoliaCompatibilityManager foliaCompatibilityManager; - private final List> conversionTasks = new ArrayList<>(); + /** + * Conversions still running, added as a chunk starts one and removed as it finishes. + *

+ * Those two happen on different threads - a chunk is scanned on its region's thread, while the completion + * callback runs on whichever thread finished the last batch - and the set is iterated by the status and + * shutdown paths at the same time. An ArrayList corrupts under that, or throws part way through a walk. + */ + private final Set> conversionTasks = ConcurrentHashMap.newKeySet(); private final StorageManager storageManager; private final ServerProfile serverProfile; @@ -57,14 +72,12 @@ private void processChunk(@NotNull Chunk chunk, @Nullable BukkitProgressBar prog int z = chunk.getZ(); World world = chunk.getWorld(); String worldName = world.getName(); - ChunkPosition position = new ChunkPosition(worldName, x, z); - if (this.processedChunks.contains(position) || !chunk.isLoaded()) { + if (this.alreadyProcessed(worldName, x, z) || !chunk.isLoaded()) { if (progressBar != null) { progressBar.increment(); } return; } - this.processedChunks.add(position); @NotNull Entity[] entities = chunk.getEntities(); List entityHistories = new ArrayList<>(); @@ -191,7 +204,7 @@ record BlockConversion(Location location, String ceEquivalent, String originalBl progressBar.increment(); } if (ex != null) { - Logger.error("[WorldConverterManager] Error during chunk conversion at " + position, ex); + Logger.error("[WorldConverterManager] Error during chunk conversion at " + worldName + " " + x + "," + z, ex); } }); } @@ -235,15 +248,34 @@ public void registerConverter(WorldConverter converter) { this.converters.add(converter); } + /** + * Whether this chunk has been scanned before, marking it scanned if not. + * + * @return true when it had already been seen + */ + private boolean alreadyProcessed(String worldName, int chunkX, int chunkZ) { + LongOpenHashSet processed = this.processedChunksByWorld.computeIfAbsent(worldName, world -> new LongOpenHashSet()); + long key = ((long) chunkX << 32) | (chunkZ & 0xFFFFFFFFL); + synchronized (processed) { + return !processed.add(key); + } + } + public void clearProcessedChunks() { - this.processedChunks.clear(); + this.processedChunksByWorld.clear(); } /** * Get the number of processed chunks */ public int getProcessedChunksCount() { - return this.processedChunks.size(); + int total = 0; + for (LongOpenHashSet processed : this.processedChunksByWorld.values()) { + synchronized (processed) { + total += processed.size(); + } + } + return total; } /** diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/ConfigFile.java b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/ConfigFile.java index 33a1d865..dc9dfcfe 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/ConfigFile.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/ConfigFile.java @@ -1,6 +1,6 @@ package fr.robie.craftengineconverter.utils; -import org.bukkit.configuration.file.YamlConfiguration; +import fr.robie.yamllibrary.file.YamlConfiguration; import java.io.File; diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/JsonFileValidator.java b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/JsonFileValidator.java index 1ad68de1..40ab6a8f 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/JsonFileValidator.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/JsonFileValidator.java @@ -3,11 +3,11 @@ import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import fr.robie.craftengineconverter.api.cache.FileCacheEntry; +import fr.robie.craftengineconverter.api.manager.FileCacheManager; import fr.robie.craftengineconverter.api.progress.BukkitProgressBar; import fr.robie.craftengineconverter.common.CraftEngineConverterPlugin; -import fr.robie.craftengineconverter.common.cache.FileCacheEntry; -import fr.robie.craftengineconverter.common.manager.FileCacheManager; import fr.robie.messageflow.logger.Logger; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/TagResolver.java b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/TagResolver.java index 3e664050..3c8f67f0 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/TagResolver.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/TagResolver.java @@ -1,7 +1,7 @@ package fr.robie.craftengineconverter.utils; import fr.robie.craftengineconverter.api.configuration.Configuration; -import fr.robie.craftengineconverter.api.configuration.ConfigurationKey; +import fr.robie.craftengineconverter.api.configuration.Keys; import fr.robie.craftengineconverter.api.enums.Plugins; import fr.robie.craftengineconverter.api.tag.ITagResolver; import fr.robie.craftengineconverter.api.tag.TagProcessor; @@ -19,13 +19,13 @@ public class TagResolver implements ITagResolver { private final List tagProcessors = new ArrayList<>(); public void initTagProcessors() { - if (Configuration.get(ConfigurationKey.GLYPH_TAG_ENABLED)){ + if (Configuration.get(Keys.GLYPH_TAG_ENABLED)){ this.registerTagProcessor(new GlyphTagProcessor()); } - if (Configuration.get(ConfigurationKey.IMAGE_TAG_ENABLED)){ + if (Configuration.get(Keys.IMAGE_TAG_ENABLED)){ this.registerTagProcessor(new IAImageTagProcessor()); } - if (Plugins.PLACEHOLDER_API.isPresent() && Configuration.get(ConfigurationKey.PLACEHOLDER_API_TAG_ENABLED)){ + if (Plugins.PLACEHOLDER_API.isPresent() && Configuration.get(Keys.PLACEHOLDER_API_TAG_ENABLED)){ this.registerTagProcessor(new PlaceholderAPITag()); } } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/Tuple.java b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/Tuple.java index 694ef033..e562cb7a 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/Tuple.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/Tuple.java @@ -1,21 +1,6 @@ package fr.robie.craftengineconverter.utils; -public class Tuple { - public final T first; - public final T second; - - public Tuple(T first, T second) { - this.first = first; - this.second = second; - } - - public T getFirst() { - return this.first; - } - - public T getSecond() { - return this.second; - } +public record Tuple(T first, T second) { public static Tuple of(T first, T second) { return new Tuple<>(first, second); diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/TypedCache.java b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/TypedCache.java index f5572dd9..389ed9d9 100644 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/TypedCache.java +++ b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/TypedCache.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.Function; @@ -23,6 +24,12 @@ public class TypedCache { private final Consumer> batchProcessor; private final int maxBatchSize; private final Function keyExtractor; + private final AtomicBoolean draining = new AtomicBoolean(); + private volatile int overflowThreshold = Integer.MAX_VALUE; + private volatile Runnable overflowHandler; + + private static final int FLUSH_ATTEMPTS = 100; + private static final long FLUSH_RETRY_DELAY_MS = 20L; /** * Creates a new TypedCache. @@ -47,10 +54,28 @@ public TypedCache(Class type, Consumer> batchProcessor, int maxBatchS * @param object The object to cache */ public void add(T object) { - if (object != null) { - String key = this.keyExtractor.apply(object); - this.cache.put(key, object); + if (object == null) { + return; } + this.cache.put(this.keyExtractor.apply(object), object); + + Runnable handler = this.overflowHandler; + if (handler != null && this.cache.size() >= this.overflowThreshold && !this.draining.get()) { + handler.run(); + } + } + + /** + * Asks to be drained early once it holds {@code threshold} objects, rather than waiting for the next scheduled + * save. Without this the buffer only empties on a timer, and anything producing rows faster than one cycle + * removes them grows without bound - which is precisely what a world-wide conversion does. + * + * @param threshold how many pending objects trigger the handler + * @param handler runs on the caller's thread; it is expected to schedule the drain elsewhere, not perform it + */ + public void onOverflow(int threshold, Runnable handler) { + this.overflowThreshold = threshold; + this.overflowHandler = handler; } /** @@ -58,9 +83,42 @@ public void add(T object) { * * @return Number of objects processed */ - public void processBatch() { + /** + * Writes out everything pending, a batch at a time, up to {@code maxObjects}. + *

+ * Draining one batch per scheduled save was the whole problem: at 250 rows a minute the buffer could not keep up + * with a conversion, so it grew for as long as the conversion ran. The cap is here only to stop a single cycle + * monopolising the database connection. + * + * @return how many objects were written + */ + public int drain(int maxObjects) { + if (!this.draining.compareAndSet(false, true)) { + return 0; + } + try { + int written = 0; + while (written < maxObjects && !this.cache.isEmpty()) { + int batch = this.processBatch(); + if (batch == 0) { + break; + } + written += batch; + } + return written; + } finally { + this.draining.set(false); + } + } + + /** + * Processes up to maxBatchSize objects from the cache. + * + * @return the number of objects written, or 0 when nothing could be + */ + public int processBatch() { if (this.cache.isEmpty()) { - return; + return 0; } List batch = new ArrayList<>(); @@ -76,49 +134,56 @@ public void processBatch() { count++; } - if (!batch.isEmpty()) { - try { - this.batchProcessor.accept(batch); - keysToRemove.forEach(this.cache::remove); - } catch (Exception e) { - Logger.error( - "Failed to process batch of " + this.type.getSimpleName() + " objects", - e - ); - } + if (batch.isEmpty()) { + return 0; + } + + try { + this.batchProcessor.accept(batch); + keysToRemove.forEach(this.cache::remove); + return batch.size(); + } catch (Exception e) { + Logger.error( + "Failed to process batch of " + this.type.getSimpleName() + " objects", + e + ); + return 0; } } /** - * Processes all remaining objects in the cache without batch size limit. - * Should be called during shutdown. + * Writes out everything pending, however long that takes. Called at shutdown, where losing rows is the one + * outcome worth blocking to avoid. + *

+ * A scheduled drain may hold the lock when this runs, which is why it retries rather than returning: {@code + * drain} declines to run concurrently with itself, and treating that as "nothing left to write" would drop + * whatever the other drain had not reached. */ public void flush() { - while (!this.cache.isEmpty()) { - Logger.info("Flushing " + this.cache.size() + " remaining " + this.type.getSimpleName() + " objects from cache..."); - List all = new ArrayList<>(this.cache.values()); - List allKeys = new ArrayList<>(this.cache.keySet()); - int size = all.size(); - for (int i = 0; i < size; i += this.maxBatchSize) { - int end = Math.min(i + this.maxBatchSize, size); - List batch = all.subList(i, end); - List keysToRemove = allKeys.subList(i, end); - if (!batch.isEmpty()) { - try { - this.batchProcessor.accept(new ArrayList<>(batch)); - for (String k : new ArrayList<>(keysToRemove)) { - this.cache.remove(k); - } - } catch (Exception e) { - Logger.error( - "Failed to flush batch of " + this.type.getSimpleName() + " objects", - e - ); - return; - } + if (this.cache.isEmpty()) { + return; + } + + Logger.info("Flushing " + this.cache.size() + " remaining " + this.type.getSimpleName() + " objects from cache..."); + int written = 0; + for (int attempt = 0; attempt < FLUSH_ATTEMPTS && !this.cache.isEmpty(); attempt++) { + int batch = this.drain(Integer.MAX_VALUE); + written += batch; + if (batch == 0 && !this.cache.isEmpty()) { + try { + Thread.sleep(FLUSH_RETRY_DELAY_MS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; } } - Logger.info("Finished flushing " + this.type.getSimpleName() + " cache."); + } + + if (this.cache.isEmpty()) { + Logger.info("Finished flushing " + written + " " + this.type.getSimpleName() + " objects."); + } else { + Logger.error("Gave up flushing with " + this.cache.size() + " " + this.type.getSimpleName() + + " objects still pending; they will not be written."); } } diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/Arguments.java b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/Arguments.java deleted file mode 100644 index 887a7b8d..00000000 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/Arguments.java +++ /dev/null @@ -1,307 +0,0 @@ -package fr.robie.craftengineconverter.utils.command; - -import fr.robie.craftengineconverter.utils.CraftEngineConverterUtils; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.World; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -public abstract class Arguments extends CraftEngineConverterUtils { - protected String[] args; - protected Map flags = new HashMap<>(); - protected int parentCount = 0; - - /** - * - * @param index - * @return - */ - protected String argAsString(int index) { - try { - return this.args[index + this.parentCount]; - } catch (Exception e) { - return null; - } - } - - /** - * - * @param index - * @param defaultValue - * @return - */ - protected String argAsString(int index, String defaultValue) { - try { - return this.args[index + this.parentCount]; - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * - * @param index - * @return - */ - protected boolean argAsBoolean(int index) { - return Boolean.valueOf(this.argAsString(index)); - } - - /** - * - * @param index - * @param defaultValue - * @return - */ - protected boolean argAsBoolean(int index, boolean defaultValue) { - try { - return Boolean.valueOf(this.argAsString(index)); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * - * @param index - * @return - */ - protected int argAsInteger(int index) { - return Integer.valueOf(this.argAsString(index)); - } - - /** - * - * @param index - * @param defaultValue - * @return - */ - protected int argAsInteger(int index, int defaultValue) { - try { - return Integer.valueOf(this.argAsString(index)); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * - * @param index - * @return - */ - protected long argAsLong(int index) { - return Long.valueOf(this.argAsString(index)); - } - - /** - * - * @param index - * @param defaultValue - * @return - */ - protected long argAsLong(int index, long defaultValue) { - try { - return Long.valueOf(this.argAsString(index)); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * - * @param index - * @param defaultValue - * @return - */ - protected double argAsDouble(int index, double defaultValue) { - try { - return Double.valueOf(this.argAsString(index).replace(",", ".")); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * - * @param index - * @return - */ - protected double argAsDouble(int index) { - return Double.valueOf(this.argAsString(index).replace(",", ".")); - } - - /** - * - * @param index - * @return - */ - protected Player argAsPlayer(int index) { - return Bukkit.getPlayer(this.argAsString(index)); - } - - /** - * - * @param index - * @return Material - */ - protected Material argAsMaterial(int index) { - try { - return Material.valueOf(this.argAsString(index).toUpperCase(Locale.ROOT)); - } catch (Exception e) { - return null; - } - } - - /** - * - * @param index - * @param defaultValue - * @return - */ - protected Player argAsPlayer(int index, Player defaultValue) { - try { - return Bukkit.getPlayer(this.argAsString(index)); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * - * @param index - * @return - */ - protected OfflinePlayer argAsOfflinePlayer(int index) { - return Bukkit.getOfflinePlayer(this.argAsString(index)); - } - - /** - * - * @param index - * @param defaultValue - * @return - */ - protected OfflinePlayer argAsOfflinePlayer(int index, OfflinePlayer defaultValue) { - try { - return Bukkit.getOfflinePlayer(this.argAsString(index)); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * - * @param index - * @return - */ - protected EntityType argAsEntityType(int index) { - return EntityType.valueOf(this.argAsString(index).toUpperCase(Locale.ROOT)); - } - - /** - * - * @param index - * @param defaultValue - * @return - */ - protected EntityType argAsEntityType(int index, EntityType defaultValue) { - try { - return EntityType.valueOf(this.argAsString(index).toUpperCase(Locale.ROOT)); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * - * @param index - * @return - */ - protected World argAsWorld(int index) { - try { - return Bukkit.getWorld(this.argAsString(index)); - } catch (Exception e) { - return null; - } - } - - /** - * - * @param index - * @return - */ - protected World argAsWorld(int index, World world) { - try { - return Bukkit.getWorld(this.argAsString(index)); - } catch (Exception e) { - return world; - } - } - - protected > T argAsEnum(int index, Class enumClass) { - try { - String s = this.argAsString(index); - if (s == null) { - return null; - } - return Enum.valueOf(enumClass, s.toUpperCase(Locale.ROOT)); - } catch (Exception e) { - return null; - } - } - - protected > T argAsEnum(int index, Class enumClass, T defaultValue) { - try { - String s = this.argAsString(index); - if (s == null) { - return defaultValue; - } - return Enum.valueOf(enumClass, s.toUpperCase(Locale.ROOT)); - } catch (Exception e) { - return defaultValue; - } - } - - protected boolean containFlag(@NotNull String flag) { - return this.flags.containsKey(flag); - } - - @Nullable - protected String getFlagValue(@NotNull String flag) { - Object value = this.flags.get(flag); - if (value != null) { - return String.valueOf(value); - } - return null; - } - - protected Object getFlagObjectValue(@NotNull String flag) { - return this.flags.get(flag); - } - - protected int getFlagValueAsInteger(@NotNull String flag, int defaultValue) { - Object value = this.flags.get(flag); - if (value != null) { - try { - return Integer.parseInt(String.valueOf(value)); - } catch (NumberFormatException e) { - return defaultValue; - } - } - return defaultValue; - } - - protected int getFlagValueAsInteger(@NotNull String flag) { - return this.getFlagValueAsInteger(flag, 0); - } - -} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/CommandManager.java b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/CommandManager.java deleted file mode 100644 index 962c54c2..00000000 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/CommandManager.java +++ /dev/null @@ -1,356 +0,0 @@ -package fr.robie.craftengineconverter.utils.command; - -import fr.robie.craftengineconverter.CraftEngineConverter; -import fr.robie.craftengineconverter.api.format.Message; - -import fr.robie.craftengineconverter.utils.CraftEngineConverterUtils; -import fr.robie.messageflow.formatter.MessageFormatter; -import fr.robie.messageflow.formatter.Placeholder; -import fr.robie.messageflow.logger.Logger; -import org.bukkit.Bukkit; -import org.bukkit.command.*; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.function.Consumer; - -public class CommandManager extends CraftEngineConverterUtils implements CommandExecutor, TabCompleter, CommandManagerInt { - private static CommandMap commandMap; - private static Constructor constructor; - - private MessageFormatter messageFormatter; - - static { - try { - Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap"); - bukkitCommandMap.setAccessible(true); - commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer()); - constructor = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class); - constructor.setAccessible(true); - } catch (Exception ignored) { - } - } - - private final CraftEngineConverter plugin; - private final List commands = new ArrayList(); - - /** - * F - * - * @param corePlugin - */ - public CommandManager(CraftEngineConverter corePlugin) { - this.plugin = corePlugin; - } - - /** - * Load all commands by calling their onLoad method recursively. - * This method should be called when the plugin is being loaded. - */ - public void loadCommands() { - this.messageFormatter = this.plugin.getMessageFormatter(); - this.applyToCommands(VCommand::onLoad); - } - - /** - * Enable all commands by calling their onEnable method recursively. - * This method should be called when the plugin is being enabled. - */ - public void enableCommands() { - this.applyToCommands(VCommand::onEnable); - } - - /** - * Disable all commands by calling their onDisable method recursively. - * This method is called when the plugin is being disabled. - */ - public void disableCommands() { - this.applyToCommands(VCommand::onDisable); - } - - - /** - * Apply a consumer action to all registered commands recursively with simple start/end logging. - * The provided action should be safe (exceptions are caught and logged). - * - * @param action action to apply to each VCommand - */ - private void applyToCommands(Consumer action) { - for (VCommand command : this.commands) { - this.applyRecursive(command, action); - } - } - - private void applyRecursive(VCommand command, Consumer action) { - if (command == null) { - return; - } - try { - action.accept(command); - } catch (Exception e) { - Logger.error("Error while applying command action to: " + command.getSyntax() + " - " + e.getMessage()); - } - List children = command.getSubVCommands(); - if (children != null && !children.isEmpty()) { - for (VCommand child : children) { - this.applyRecursive(child, action); - } - } - } - - /** - * Valid commands - */ - @Override - public void validCommands() { - Logger.info("Loading %count% commands", Placeholder.of("count", String.valueOf(this.getUniqueCommand()))); - this.commandChecking(); - Logger.info("Commands loaded successfully"); - } - - /** - * - * @param command - * @return - */ - @Override - public VCommand registerCommand(VCommand command) { - this.commands.add(command); - return command; - } - - @Override - public void registerCommand(String string, VCommand command) { - this.registerCommand(this.plugin, string, command, new ArrayList<>()); - } - - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - for (VCommand command : this.commands) { - if (command.getSubCommands().contains(cmd.getName().toLowerCase(Locale.ROOT))) { - if ((args.length == 0 || command.isIgnoreParent()) && command.getParent() == null) { - CommandType type = this.processRequirements(command, sender, args); - if (!type.equals(CommandType.CONTINUE)) { - return true; - } - } - } else if (args.length >= 1 && command.getParent() != null - && this.canExecute(args, cmd.getName().toLowerCase(Locale.ROOT), command)) { - CommandType type = this.processRequirements(command, sender, args); - if (!type.equals(CommandType.CONTINUE)) { - return true; - } - } - } - this.messageFormatter.sendMessage(Message.COMMAND__NO_ARGS, sender); - return true; - } - - /** - * @param args - * @param cmd - * @param command - * @return true if can execute - */ - private boolean canExecute(String[] args, String cmd, VCommand command) { - for (int index = args.length - 1; index > -1; index--) { - if (command.getSubCommands().contains(args[index].toLowerCase(Locale.ROOT))) { - if (command.isIgnoreArgs() - && (command.getParent() == null || this.canExecute(args, cmd, command.getParent(), index - 1))) { - return true; - } - if (index < args.length - 1) { - return false; - } - return this.canExecute(args, cmd, command.getParent(), index - 1); - } - } - return false; - } - - /** - * @param args - * @param cmd - * @param command - * @param index - * @return - */ - private boolean canExecute(String[] args, String cmd, VCommand command, int index) { - if (index < 0 && command.getSubCommands().contains(cmd.toLowerCase(Locale.ROOT))) { - return true; - } else if (index < 0) { - return false; - } else if (command.getSubCommands().contains(args[index].toLowerCase(Locale.ROOT))) { - return this.canExecute(args, cmd, command.getParent(), index - 1); - } - return false; - } - - /** - * Allows you to process an order. First we check if the sender has the - * permission or if the command has a permission. If yes then we execute the - * command otherwise we send the message for the permission - * - * @param command - Object that contains the command - * @param sender - Person who executes the command - * @param strings - Argument of the command - * @return CommandType - Return of the command - */ - private CommandType processRequirements(VCommand command, CommandSender sender, String[] strings) { - - if (!(sender instanceof Player) && !command.isConsoleCanUse()) { - this.messageFormatter.sendMessage(Message.COMMAND__PLAYER_ONLY, sender); - return CommandType.DEFAULT; - } - - if (command.getPermission() == null || this.hasPermission(sender, command.getPermission())) { - - if (command.runAsync) { - super.runAsync(this.plugin, () -> { - CommandType returnType = command.prePerform(this.plugin, sender, strings); - if (returnType == CommandType.SYNTAX_ERROR) { - this.messageFormatter.sendMessage(Message.COMMAND__SYNTAX__ERROR, sender, Placeholder.of("syntax", command.getSyntax())); - } - }); - return CommandType.DEFAULT; - } - - CommandType returnType = command.prePerform(this.plugin, sender, strings); - if (returnType == CommandType.SYNTAX_ERROR) { - this.messageFormatter.sendMessage(Message.COMMAND__SYNTAX__ERROR, sender, Placeholder.of("syntax", command.getSyntax())); - } - return returnType; - } - this.messageFormatter.sendMessage(Message.COMMAND__NO_PERMISSION, sender); - return CommandType.DEFAULT; - } - - public List getCommands() { - return this.commands; - } - - private int getUniqueCommand() { - return (int) this.commands.stream().filter(command -> command.getParent() == null).count(); - } - - /** - * @param command - * @param commandString - * @return - */ - public boolean isValid(VCommand command, String commandString) { - return command.getParent() != null ? this.isValid(command.getParent(), commandString) - : command.getSubCommands().contains(commandString.toLowerCase(Locale.ROOT)); - } - - /** - * Allows you to check if all commands are correct If an command does not - * have - */ - private void commandChecking() { - this.commands.forEach(command -> { - if (command.sameSubCommands()) { - Logger.error(command + " command to an argument similar to its parent command !"); - this.plugin.getServer().getPluginManager().disablePlugin(this.plugin); - } - }); - } - - @Override - public List onTabComplete(CommandSender sender, Command cmd, String str, String[] args) { - - for (VCommand command : this.commands) { - - if (command.getSubCommands().contains(cmd.getName().toLowerCase(Locale.ROOT))) { - if (args.length == 1 && command.getParent() == null) { - return this.proccessTab(sender, command, args); - } - } else { - String[] newArgs = Arrays.copyOf(args, args.length - 1); - if (newArgs.length >= 1 && command.getParent() != null - && this.canExecute(newArgs, cmd.getName().toLowerCase(Locale.ROOT), command)) { - return this.proccessTab(sender, command, args); - } - } - } - - return null; - } - - /** - * Allows to execute the tab completion - * - * @param sender - * @param command - * @param args - * @return - */ - private List proccessTab(CommandSender sender, VCommand command, String[] args) { - - CommandType type = command.getTabCompleter(); - if (type.equals(CommandType.DEFAULT)) { - String startWith = args[args.length - 1]; - - List tabCompleter = new ArrayList<>(); - for (VCommand vCommand : this.commands) { - if ((vCommand.getParent() != null && vCommand.getParent() == command)) { - for (String subCmd : vCommand.getSubCommands()) { - if (vCommand.getPermission() == null || sender.hasPermission(vCommand.getPermission())) { - if (startWith.isEmpty() || subCmd.startsWith(startWith)) { - tabCompleter.add(subCmd); - } - } - } - } - } - return tabCompleter.isEmpty() ? null : tabCompleter; - - } else if (type.equals(CommandType.SUCCESS)) { - return command.toTab(this.plugin, sender, args); - } - - return null; - } - - @Override - public void registerCommand(String command, VCommand vCommand, String... aliases) { - this.registerCommand(this.plugin, command, vCommand, Arrays.asList(aliases)); - } - - /** - * Register spigot command without plugin.yml This method will allow to - * onLoad a command in the spigot without using the plugin.yml This saves - * time and understanding, the plugin.yml file is clearer - * - * @param string - Main command - * @param vCommand - Command object - * @param aliases - Command aliases - */ - public void registerCommand(Plugin plugin, String string, VCommand vCommand, List aliases) { - try { - PluginCommand command = constructor.newInstance(string, this.plugin); - command.setExecutor(this); - command.setTabCompleter(this); - if (aliases != null && !aliases.isEmpty()) { - command.setAliases(aliases); - } - - - this.commands.add(vCommand.addSubCommand(string)); - vCommand.addSubCommand(aliases); - - if (!commandMap.register(command.getName(), plugin.getPluginMeta().getName(), command)) { - Logger.info("Unable to add the command " + vCommand.getSyntax()); - } - } catch (Exception exception) { - Logger.error("Error while registering command " + vCommand.getSyntax(), exception); - } - } -} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/CommandManagerInt.java b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/CommandManagerInt.java deleted file mode 100644 index e4279217..00000000 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/CommandManagerInt.java +++ /dev/null @@ -1,30 +0,0 @@ -package fr.robie.craftengineconverter.utils.command; - -public interface CommandManagerInt { - /** - * Registers a command - * @param command the command to onLoad - * @return the registered command - */ - VCommand registerCommand(VCommand command); - - /** - * Register a command with a single name - * @param string the command name - * @param command the command to onLoad - */ - void registerCommand(String string, VCommand command); - - /** - * Register a command with aliases - * @param command the command name - * @param vCommand the command to onLoad - * @param aliases the command aliases - */ - void registerCommand(String command, VCommand vCommand, String... aliases); - - /** - * Starts the validation of all registered commands - */ - void validCommands(); -} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/CommandType.java b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/CommandType.java deleted file mode 100644 index 409d32e5..00000000 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/CommandType.java +++ /dev/null @@ -1,12 +0,0 @@ -package fr.robie.craftengineconverter.utils.command; - - -public enum CommandType { - - SUCCESS, - SYNTAX_ERROR, - EXCEPTION_ERROR, - DEFAULT, - CONTINUE, - -} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/Tab.java b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/Tab.java deleted file mode 100644 index dc447b8a..00000000 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/Tab.java +++ /dev/null @@ -1,6 +0,0 @@ -package fr.robie.craftengineconverter.utils.command; - -public enum Tab { - START, - CONTAINS, -} diff --git a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/VCommand.java b/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/VCommand.java deleted file mode 100644 index e8e3ebae..00000000 --- a/Plugin/src/main/java/fr/robie/craftengineconverter/utils/command/VCommand.java +++ /dev/null @@ -1,835 +0,0 @@ -package fr.robie.craftengineconverter.utils.command; - -import fr.robie.craftengineconverter.CraftEngineConverter; -import fr.robie.craftengineconverter.api.format.Message; - -import fr.robie.craftengineconverter.common.permission.Permission; -import fr.robie.craftengineconverter.utils.collection.CollectionBiConsumer; -import fr.robie.messageflow.formatter.MessageFormatter; -import fr.robie.messageflow.formatter.Placeholder; -import fr.robie.messageflow.logger.Logger; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.*; -import java.util.stream.Collectors; - -public abstract class VCommand extends Arguments { - record FlagValue(String flag, boolean hasValue, Class type, T defaultValue) { - public T parseValue(String value) { - if (this.type.equals(Boolean.class)) { - return this.type.cast(Boolean.parseBoolean(value)); - } else if (this.type.equals(Integer.class)) { - try { - return this.type.cast(Integer.parseInt(value)); - } catch (NumberFormatException e) { - return this.defaultValue; - } - } else if (this.type.equals(Double.class)) { - try { - return this.type.cast(Double.parseDouble(value)); - } catch (NumberFormatException e) { - return this.defaultValue; - } - } - return this.type.cast(value); - } - } - - protected final CraftEngineConverter plugin; - protected final MessageFormatter messageFormatter; - - /** - * Permission used for the command, if it is a null then everyone can - * execute the command - */ - private String permission; - - /** - * Mother command of this command - */ - protected VCommand parent; - - /** - * Are all sub commands used - */ - private final List subCommands = new ArrayList<>(); - protected List subVCommands = new ArrayList<>(); - - private final List requireArgs = new ArrayList<>(); - private final List optionalArgs = new ArrayList<>(); - private final List> flagsArgs = new ArrayList<>(); - /** - * If this variable is false the command will not be able to use this - * command - */ - private boolean consoleCanUse = true; - - /** - * This variable allows to run the main class of the command even with - * arguments convenient for commands like /ban - */ - private boolean ignoreParent = false; - private boolean ignoreArgs = false; - private boolean extendedArgs = false; - public boolean runAsync = false; - private CommandType tabCompleter = CommandType.DEFAULT; - - /** - * This is the person who executes the command - */ - protected CommandSender sender; - protected @Nullable Player player; // Null if console - - private String syntax; - private String description; - private int argsMinLength; - private int argsMaxLength; - - protected Map tabCompletions = new HashMap<>(); - - /** - * @param plugin - */ - public VCommand(CraftEngineConverter plugin) { - super(); - this.plugin = plugin; - this.messageFormatter = plugin.getMessageFormatter(); - } - - // - // GETTER - // - - public Optional getCompletionAt(int index) { - return Optional.ofNullable(this.tabCompletions.getOrDefault(index, null)); - } - - /** - * Return command permission - * - * @return the permission - */ - public String getPermission() { - return this.permission; - } - - /** - * @return the parent - */ - public VCommand getParent() { - return this.parent; - } - - /** - * @return the subCommand - */ - public List getSubCommands() { - return this.subCommands; - } - - /** - * @return the list of child VCommands - */ - public List getSubVCommands() { - return this.subVCommands; - } - - /** - * @return the consoleCanUse - */ - public boolean isConsoleCanUse() { - return this.consoleCanUse; - } - - /** - * @return the ignoreParent - */ - public boolean isIgnoreParent() { - return this.ignoreParent; - } - - public CommandSender getSender() { - return this.sender; - } - - /** - * @return the argsMinLength - */ - public int getArgsMinLength() { - return this.argsMinLength; - } - - /** - * @return the argsMaxLength - */ - public int getArgsMaxLength() { - return this.argsMaxLength; - } - - /** - * @return the player - */ - public Player getPlayer() { - return this.player; - } - - /** - * Return the generate or custom syntax - * - * @return the syntax - */ - public String getSyntax() { - if (this.syntax == null) { - this.syntax = this.generateDefaultSyntax(""); - } - return this.syntax; - } - - public boolean isIgnoreArgs() { - return this.ignoreArgs; - } - - public String getDescription() { - return this.description == null ? "no description" : this.description; - } - - public CommandType getTabCompleter() { - return this.tabCompleter; - } - - /* - * - */ - protected void setTabCompletor() { - this.tabCompleter = CommandType.SUCCESS; - } - - // - // SETTER - // - - public void setIgnoreArgs(boolean ignoreArgs) { - this.ignoreArgs = ignoreArgs; - } - - public void setIgnoreParent(boolean ignoreParent) { - this.ignoreParent = ignoreParent; - } - - public void setExtendedArgs(boolean extendedArgs) { - this.extendedArgs = extendedArgs; - } - - /** - * @param syntax the syntax to set - */ - protected VCommand setSyntax(String syntax) { - this.syntax = syntax; - return this; - } - - /** - * @param permission the permission to set - */ - protected VCommand setPermission(String permission) { - this.permission = permission; - return this; - } - - /** - * @param permission the permission to set - */ - protected VCommand setPermission(Permission permission) { - this.permission = permission.asPermission(); - return this; - } - - /** - * @param parent the parent to set - */ - protected VCommand setParent(VCommand parent) { - this.parent = parent; - return this; - } - - /** - * @param consoleCanUse the consoleCanUse to set - */ - protected VCommand setConsoleCanUse(boolean consoleCanUse) { - this.consoleCanUse = consoleCanUse; - return this; - } - - protected VCommand onlyPlayers() { - this.consoleCanUse = false; - return this; - } - - /** - * Mettre la description de la commande - * - * @param description - * @return - */ - protected VCommand setDescription(String description) { - this.description = description; - return this; - } - - /* - * Ajouter un argument obligatoire - */ - protected void addRequireArg(String message) { - this.requireArgs.add(message); - this.ignoreParent = this.parent == null; - this.ignoreArgs = true; - } - - /* - * Ajouter un argument obligatoire - */ - protected void addRequireArg(String message, CollectionBiConsumer runnable) { - this.addRequireArg(message); - int index = this.requireArgs.size(); - this.addCompletion(index - 1, runnable); - } - - /** - * Ajouter un argument optionel - * - * @param message - */ - protected void addOptionalArg(String message, CollectionBiConsumer runnable) { - this.addOptionalArg(message); - int index = this.requireArgs.size() + this.optionalArgs.size(); - this.addCompletion(index - 1, runnable); - } - - /** - * Ajouter un argument optionel - * - * @param message - */ - protected void addOptionalArg(String message) { - this.optionalArgs.add(message); - this.ignoreParent = this.parent == null; - this.ignoreArgs = true; - } - - protected void addFlag(@NotNull String flag) { - this.addFlag(flag, false, String.class, null); - } - - protected void addFlag(@NotNull String flag, boolean hasValue) { - this.addFlag(flag, hasValue, String.class, null); - } - - protected void addFlag(@NotNull String flag, @NotNull Class type, @Nullable T defaultValue) { - this.addFlag(flag, true, type, defaultValue); - } - - private void addFlag(@NotNull String flag, boolean hasValue, @NotNull Class type, @Nullable T defaultValue) { - this.flagsArgs.add(new FlagValue<>(flag, hasValue, type, defaultValue)); - this.ignoreParent = this.parent == null; - this.ignoreArgs = true; - this.setTabCompletor(); - } - - /** - * Mettre la description de la commande - * - * @param description - * @return - */ - protected VCommand setDescription(Message description) { - this.description = description.firstLine(); - return this; - } - - /** - * - * @return first command - */ - public String getFirst() { - return this.subCommands.getFirst(); - } - - // - // OTHER - // - - /** - * Adds sub orders - * - * @param subCommand - * @return this - */ - public VCommand addSubCommand(String subCommand) { - this.subCommands.add(subCommand); - return this; - } - - /** - * Adds sub orders - * - * @param command - * @return this - */ - public VCommand addSubCommand(VCommand command) { - command.setParent(this); - this.plugin.getCommandManager().registerCommand(command); - this.subVCommands.add(command); - return this; - } - - /** - * Adds sub orders - * - * @param subCommand - * @return this - */ - public VCommand addSubCommand(String... subCommand) { - this.subCommands.addAll(Arrays.asList(subCommand)); - return this; - } - - /** - * Add a {@link CollectionBiConsumer} to the index for the tab completion - * - * @param index - * @param runnable - */ - public void addCompletion(int index, CollectionBiConsumer runnable) { - this.tabCompletions.put(index, runnable); - this.setTabCompletor(); - } - - /** - * Allows you to generate the syntax of the command manually But you you can - * set it yourself with the setSyntax() - * - * @param syntax - * @return generate syntax - */ - private String generateDefaultSyntax(String syntax) { - boolean update = syntax.isEmpty(); - - StringBuilder syntaxBuilder = new StringBuilder(); - if (update) { - this.appendRequiredArguments(syntaxBuilder); - this.appendOptionalArguments(syntaxBuilder); - this.appendFlags(syntaxBuilder); - syntax = syntaxBuilder.toString().trim(); - } - - String tmpString = this.subCommands.getFirst() + syntax; - return this.parent == null ? "/" + tmpString : this.parent.generateDefaultSyntax(" " + tmpString); - } - - private void appendRequiredArguments(StringBuilder syntaxBuilder) { - this.requireArgs.forEach(arg -> syntaxBuilder.append(" <").append(arg).append(">")); - } - - private void appendOptionalArguments(StringBuilder syntaxBuilder) { - this.optionalArgs.forEach(arg -> syntaxBuilder.append(" [<").append(arg).append(">]")); - } - - private void appendFlags(StringBuilder syntaxBuilder) { - this.flagsArgs.forEach(flag -> { - syntaxBuilder.append(" [").append(flag.flag); - if (flag.hasValue) { - syntaxBuilder.append("=<").append(this.getSimpleTypeName(flag.type)).append(">"); - } - syntaxBuilder.append("]"); - }); - } - - private String getSimpleTypeName(Class type) { - if (type == Boolean.class) { - return "bool"; - } - if (type == Integer.class) { - return "int"; - } - if (type == Double.class) { - return "double"; - } - if (type == String.class) { - return "string"; - } - return type.getSimpleName().toLowerCase(Locale.ROOT); - } - - - /** - * Allows to know the number of parents in a recursive way - * - * @param defaultParent - * @return - */ - private int parentCount(int defaultParent) { - return this.parent == null ? defaultParent : this.parent.parentCount(defaultParent + 1); - } - - /** - * Allows you to manage the arguments and check that the command is valid - * - * @param plugin - * @param commandSender - * @param args - * @return - */ - public CommandType prePerform(CraftEngineConverter plugin, CommandSender commandSender, String[] args) { - - this.parentCount = this.parentCount(0); - - String[] cleanedArgs = this.parseFlags(args); - - this.argsMaxLength = this.requireArgs.size() + this.optionalArgs.size() + this.parentCount; - this.argsMinLength = this.requireArgs.size() + this.parentCount; - - if (this.syntax == null) { - this.syntax = this.generateDefaultSyntax(""); - } - - this.args = cleanedArgs; - - String defaultString = super.argAsString(0); - - if (defaultString != null) { - for (VCommand subCommand : this.subVCommands) { - if (subCommand.getSubCommands().contains(defaultString.toLowerCase(Locale.ROOT))) { - return CommandType.CONTINUE; - } - } - } - - if (!this.ignoreArgs) { - if ((this.argsMinLength != 0 && cleanedArgs.length < this.argsMinLength) || - this.argsMaxLength != 0 && cleanedArgs.length > this.argsMaxLength && !this.extendedArgs) { - return CommandType.SYNTAX_ERROR; - } - } - - this.sender = commandSender; - if (this.sender instanceof Player playerInstance) { - this.player = playerInstance; - } else { - this.player = null; - } - - try { - return this.perform(plugin); - } catch (Exception e) { - Logger.error("An error occurred while executing command: " + this.getSyntax(), e); - return CommandType.SYNTAX_ERROR; - } - } - - private String[] parseFlags(String[] args) { - this.flags.clear(); - List cleanedArgs = new ArrayList<>(); - - for (int i = 0; i < args.length; i++) { - String arg = args[i]; - - boolean isFlag = false; - for (FlagValue flag : this.flagsArgs) { - String flagKey = flag.flag; - if (arg.equals(flagKey)) { - isFlag = true; - - if (flag.hasValue && i + 1 < args.length && !args[i + 1].startsWith("--")) { - Object value; - try { - value = flag.parseValue(args[i + 1]); - } catch (ClassCastException e) { - value = flag.defaultValue; - } - this.flags.put(flagKey, value); - i++; - } else { - this.flags.put(flagKey, "true"); - } - break; - } else if (arg.startsWith(flagKey + "=")) { - isFlag = true; - String value; - if (flag.hasValue) { - value = arg.substring((flag.flag + "=").length()); - } else { - value = "true"; - } - Object parsedValue; - try { - parsedValue = flag.parseValue(value); - } catch (ClassCastException e) { - parsedValue = flag.defaultValue; - } - this.flags.put(flagKey, parsedValue); - break; - } - } - - if (!isFlag) { - cleanedArgs.add(arg); - } - } - - return cleanedArgs.toArray(new String[0]); - } - - /** - * Method that allows you to execute the command - */ - protected abstract CommandType perform(CraftEngineConverter plugin); - - public boolean sameSubCommands() { - if (this.parent == null) { - return false; - } - for (String command : this.subCommands) { - if (this.parent.getSubCommands().contains(command)) { - return true; - } - } - return false; - } - - @Override - public String toString() { - return "VCommand [permission=" + this.permission + ", subCommands=" + this.subCommands + ", consoleCanUse=" - + this.consoleCanUse + ", description=" + this.description + "]"; - } - - /** - * Generate tab completion - * - * @param plugin plugin - * @param sender sender - * @param args arguments - * @return list of completions or null - */ - public List toTab(CraftEngineConverter plugin, CommandSender sender, String[] args) { - - this.parentCount = this.parentCount(0); - - TabParseResult parseResult = this.parseArgsForTab(args); - - int currentIndex = (parseResult.cleanedArgs.size() - this.parentCount) - 1; - String lastArg = args[args.length - 1]; - - Optional optional = this.getCompletionAt(currentIndex); - List completions = optional.map(consumer -> - this.generateList(consumer.accept(sender, args), lastArg) - ).orElse(null); - - List availableFlags = this.getAvailableFlags(parseResult.usedFlags, lastArg); - - return this.combineCompletions(completions, availableFlags, currentIndex); - } - - private TabParseResult parseArgsForTab(String[] args) { - Set usedFlags = new HashSet<>(); - List cleanedArgs = new ArrayList<>(); - - Set flagSet = this.flagsArgs.stream() - .map(f -> f.flag) - .collect(Collectors.toSet()); - - for (int i = 0; i < args.length; i++) { - String arg = args[i]; - - if (flagSet.contains(arg)) { - usedFlags.add(arg); - - FlagValue flagValue = this.findFlag(arg); - if (flagValue != null && flagValue.hasValue && - i + 1 < args.length && !args[i + 1].startsWith("--")) { - i++; - } - } else if (arg.contains("=")) { - String flagPart = arg.substring(0, arg.indexOf('=')); - if (flagSet.contains(flagPart)) { - usedFlags.add(flagPart); - } else { - cleanedArgs.add(arg); - } - } else { - cleanedArgs.add(arg); - } - } - - return new TabParseResult(usedFlags, cleanedArgs); - } - - private FlagValue findFlag(String flag) { - return this.flagsArgs.stream() - .filter(f -> f.flag.equals(flag)) - .findFirst() - .orElse(null); - } - - private List getAvailableFlags(Set usedFlags, String filter) { - if (this.flagsArgs.isEmpty()) { - return Collections.emptyList(); - } - - String lowerFilter = filter.toLowerCase(Locale.ROOT); - - return this.flagsArgs.stream() - .map(f -> f.flag) - .filter(flag -> !usedFlags.contains(flag)) - .filter(flag -> filter.isEmpty() || flag.toLowerCase(Locale.ROOT).startsWith(lowerFilter)) - .collect(Collectors.toList()); - } - - private List combineCompletions(List completions, List flags, int currentIndex) { - boolean canShowFlags = currentIndex >= this.requireArgs.size() && !flags.isEmpty(); - - if (!canShowFlags) { - return completions; - } - - if (completions == null || completions.isEmpty()) { - return flags; - } - - List combined = new ArrayList<>(flags); - combined.addAll(completions); - return combined; - } - - /** - * Classe interne pour stocker les résultats du parsing - */ - private static class TabParseResult { - final Set usedFlags; - final List cleanedArgs; - - TabParseResult(Set usedFlags, List cleanedArgs) { - this.usedFlags = usedFlags; - this.cleanedArgs = cleanedArgs; - } - } - - /** - * Generate list for tab completer - * - * @param startWith - * @param strings - * @return - */ - protected List generateList(String startWith, String... strings) { - return this.generateList(Arrays.asList(strings), startWith); - } - - /** - * Generate list for tab completer - * - * @param startWith - * @param strings - * @return - */ - protected List generateList(Tab tab, String startWith, String... strings) { - return this.generateList(Arrays.asList(strings), startWith, tab); - } - - /** - * Generate list for tab completer - * - * @param defaultList - * @param startWith - * @return - */ - protected List generateList(Collection defaultList, String startWith) { - return this.generateList(defaultList, startWith, Tab.CONTAINS); - } - - /** - * Generate list for tab completer - * - * @param defaultList - * @param startWith - * @param tab - * @return - */ - protected List generateList(Collection defaultList, String startWith, Tab tab) { - List newList = new ArrayList<>(); - for (String str : defaultList) { - if (startWith.isEmpty() - || (tab.equals(Tab.START) ? str.toLowerCase(Locale.ROOT).startsWith(startWith.toLowerCase(Locale.ROOT)) - : str.toLowerCase(Locale.ROOT).contains(startWith.toLowerCase(Locale.ROOT)))) { - newList.add(str); - } - } - return newList.isEmpty() ? null : newList; - } - - /** - * Add list of aliases - * - * @param aliases Command aliases to add - */ - public void addSubCommand(List aliases) { - this.subCommands.addAll(aliases); - } - - /** - * Called when the plugin is being disabled. - * Override this method to perform cleanup tasks such as: - * - Cancelling running tasks - * - Clearing caches - * - Releasing resources - *

- * This method is automatically called recursively for all child commands - * by the CommandManager.disableCommands() method. - */ - protected void onDisable() { - // Override this method in subclasses if needed - } - - /** - * Called when the plugin is being loaded (onLoad phase). - * Override this method to perform early initialization tasks such as: - * - Loading configuration files - * - Initializing variables - * - Setting up dependencies that need to be available before plugin enable - *

- * This method is automatically called recursively for all child commands - * by the CommandManager.loadCommands() method. - */ - protected void onLoad() { - // Override this method in subclasses if needed - } - - /** - * Called when the plugin is being enabled (onEnable phase). - * Override this method to perform startup tasks such as: - * - Starting scheduled tasks - * - Registering event listeners specific to this command - * - Connecting to external services - *

- * This method is automatically called recursively for all child commands - * by the CommandManager.enableCommands() method. - */ - protected void onEnable() { - // Override this method in subclasses if needed - } - - /** - * Allows to send the syntax of the commands - * - */ - public void syntaxMessage() { - this.subVCommands.forEach(command -> { - if (command.getPermission() == null || this.hasPermission(this.sender, command.getPermission())) { - this.messageFormatter.sendMessage(Message.COMMAND__SYNTAX__HELP, this.sender, Placeholder.of("syntax", command.getSyntax(), "description", - command.getDescription())); - } - }); - } -} diff --git a/Plugin/src/main/resources/config.yml b/Plugin/src/main/resources/config.yml index 3891fb2a..feab4a24 100644 --- a/Plugin/src/main/resources/config.yml +++ b/Plugin/src/main/resources/config.yml @@ -1,8 +1,22 @@ +# General settings. Anything belonging to one converter lives in that converter's own file beside this one: +# +# nexo.yml Nexo integration +# itemsadder.yml ItemsAdder integration +# world-converter.yml converting blocks as chunks are explored + enable-debug: false # Language settings (available languages: EN, FR) language: "EN" +# Item conversion settings, shared by every item converter (ItemsAdder, Nexo). +# Hide the italic that items get by default. +disable-default-italic: true +# How armor is converted: COMPONENT (the item's own model), TRIM (the armor trim texture) or BOTH. +armor-converter-type: COMPONENT +# Material for items that don't name one; "auto" lets the converter choose. +default-material: "auto" + # Each block has a usage limit for a block-state. This setting controls how those limits are enforced when multiple plugins are installed: # - "plugin": Each plugin gets its own separate limit. Different plugins can use the same block-states independently without affecting each other. # - "global": All plugins share the same limit. Once any plugin uses up the limit for a block-state, other plugins cannot use it (prevents conflicts and duplicates). @@ -80,23 +94,16 @@ auto-convert-on-startup: false # Select which converters and options should be used on startup # If empty, all options for all converters will be used # Available options: ITEMS, EMOJIS, IMAGES, LANGUAGES, SOUNDS, RECIPES, PACKS, ALL -# auto-convert-on-startup-types: -# nexo: -# - ITEMS -# - EMOJIS -# itemsadder: -# - ITEMS -# - IMAGES - -# Default material for items -default-material: "PAPER" - -# Disable italic formatting in item lore by adding tag -disable-default-italic: true - -# Armor converter settings -# Available types: COMPONENT, TRIM , BOTH -armor-converter-type: "COMPONENT" +# +# Example: +# auto-convert-on-startup-types: +# nexo: +# - ITEMS +# - EMOJIS +# itemsadder: +# - ITEMS +# - IMAGES +auto-convert-on-startup-types: {} blacklisted-paths: - "shaders/*" # Blacklist all files in shaders folder @@ -120,40 +127,7 @@ tag: enabled: true allow-block-conversion-propagation: true # When enabled, if a block is converted, the surrounding blocks will also be checked for conversion -max-block-conversion-propagation-depth: 64 # Maximum number of blocks to propagate conversion in one block interaction event - -nexo: - enable-hook: true # Enable Nexo integration if Nexo is installed - # Require this permission to allow Nexo block interaction conversion : craftengineconverter.nexo.block.interact.conversion - enable-block-interaction-conversion: true # When enabled, when you interact with a nexo block, it will convert the nexo block to their CE equivalent - # Require this permission to allow Nexo furniture interaction conversion : craftengineconverter.nexo.furniture.interact.conversion - enable-furniture-interaction-conversion: true # When enabled, when you interact with a nexo furniture, it will convert the furniture to their CE equivalent - enable-chunk-load-conversion: false # When enabled, when a chunk is loaded, it will convert all Nexo blocks and furnitures to CE equivalents - -itemsadder: - enable-hook: true # Enable ItemsAdder integration if ItemsAdder is installed - img-placeholderapi-support: true # Register a placeholder %img:old_name% to get the new image - # Require this permission to allow ItemsAdder block interaction conversion : craftengineconverter.itemsadder.block.interact.conversion - enable-block-interaction-conversion: true # When enabled, when you interact with an ItemsAdder block, it will convert the block to their CE equivalent - # Require this permission to allow ItemsAdder furniture interaction conversion : craftengineconverter.itemsadder.furniture.interact.conversion - enable-furniture-interaction-conversion: true # When enabled, when you interact with an ItemsAdder furniture, it will convert the furniture to their CE equivalent - enable-chunk-load-conversion: false # When enabled, when a chunk is loaded, it will convert all ItemsAdder blocks and furnitures to CE equivalents - blacklisted-content-folders-namespaces: [ ] # List of content folders or namespaces to ignore during conversion - -world-converter: - enable: false # Enable world conversion feature (Requires server restart to take effect) - nexo: - enable: true # Enable Nexo world conversion without nexo plugin installed ! Just explore and let the lugin convert Nexo blocks and furnitures to CE equivalents - itemsadder: - enable: true # Enable ItemsAdder world conversion without ItemsAdder plugin installed ! Just explore and let the lugin convert ItemsAdder blocks and furnitures to CE equivalents - progress-bar-options: - progress-color: GREEN - empty-color: DARK_GRAY - percent-color: YELLOW - progress-char: █ - empty-char: ░ - bar-width: 50 - +max-block-conversion-propagation-limit: 64 # Maximum number of blocks to propagate conversion in one block interaction event # Available colors: # BLACK, DARK_BLUE, DARK_GREEN, DARK_AQUA, DARK_RED, DARK_PURPLE, @@ -200,4 +174,4 @@ progress-bar-options: percent-color: YELLOW progress-char: █ empty-char: ░ - bar-width: 50 \ No newline at end of file + bar-width: 50 diff --git a/Plugin/src/main/resources/itemsadder.yml b/Plugin/src/main/resources/itemsadder.yml new file mode 100644 index 00000000..7b6737ba --- /dev/null +++ b/Plugin/src/main/resources/itemsadder.yml @@ -0,0 +1,18 @@ +# ItemsAdder integration. +# +# Only read when ItemsAdder is installed. Settings that were "itemsadder.enable-hook" in the old single config.yml +# are simply "enable-hook" here - the file already says which plugin it is about. + +enable-hook: true # Enable ItemsAdder integration if ItemsAdder is installed + +img-placeholderapi-support: true # Register a placeholder %img:old_name% to get the new image + +# Require this permission to allow ItemsAdder block interaction conversion : craftengineconverter.itemsadder.block.interact.conversion +enable-block-interaction-conversion: true # When enabled, when you interact with an ItemsAdder block, it will convert the block to their CE equivalent + +# Require this permission to allow ItemsAdder furniture interaction conversion : craftengineconverter.itemsadder.furniture.interact.conversion +enable-furniture-interaction-conversion: true # When enabled, when you interact with an ItemsAdder furniture, it will convert the furniture to their CE equivalent + +enable-chunk-load-conversion: false # When enabled, when a chunk is loaded, it will convert all ItemsAdder blocks and furnitures to CE equivalents + +blacklisted-content-folders-namespaces: [ ] # List of content folders or namespaces to ignore during conversion diff --git a/Plugin/src/main/resources/nexo.yml b/Plugin/src/main/resources/nexo.yml new file mode 100644 index 00000000..e914a600 --- /dev/null +++ b/Plugin/src/main/resources/nexo.yml @@ -0,0 +1,14 @@ +# Nexo integration. +# +# Only read when Nexo is installed. Settings that were "nexo.enable-hook" in the old single config.yml are simply +# "enable-hook" here - the file already says which plugin it is about. + +enable-hook: true # Enable Nexo integration if Nexo is installed + +# Require this permission to allow Nexo block interaction conversion : craftengineconverter.nexo.block.interact.conversion +enable-block-interaction-conversion: true # When enabled, when you interact with a nexo block, it will convert the nexo block to their CE equivalent + +# Require this permission to allow Nexo furniture interaction conversion : craftengineconverter.nexo.furniture.interact.conversion +enable-furniture-interaction-conversion: true # When enabled, when you interact with a nexo furniture, it will convert the furniture to their CE equivalent + +enable-chunk-load-conversion: false # When enabled, when a chunk is loaded, it will convert all Nexo blocks and furnitures to CE equivalents diff --git a/Plugin/src/main/resources/paper-plugin.yml b/Plugin/src/main/resources/paper-plugin.yml new file mode 100644 index 00000000..6b9811b7 --- /dev/null +++ b/Plugin/src/main/resources/paper-plugin.yml @@ -0,0 +1,25 @@ +name: ${project.parent.artifactId} +version: ${plugin.finalVersion} +authors: [ ${plugin.author} ] +description: ${plugin.description} +api-version: ${plugin.apiVersion} +main: ${plugin.mainClass} +bootstrapper: ${plugin.bootstrapper} +loader: ${plugin.loader} +folia-supported: true +dependencies: + server: + CraftEngine: + load: BEFORE + required: true + join-classpath: true + + packetevents: + load: BEFORE + required: false + join-classpath: true + + PlaceholderAPI: + load: BEFORE + required: false + join-classpath: true \ No newline at end of file diff --git a/Plugin/src/main/resources/plugin.yml b/Plugin/src/main/resources/plugin.yml deleted file mode 100644 index 547e8ca7..00000000 --- a/Plugin/src/main/resources/plugin.yml +++ /dev/null @@ -1,11 +0,0 @@ -name: ${project.parent.artifactId} -version: ${plugin.finalVersion} -authors: [ ${plugin.author} ] -description: ${plugin.description} -main: ${plugin.mainClass} -api-version: ${plugin.apiVersion} -softdepend: - - CraftEngine - - packetevents - - PlaceholderAPI -folia-supported: true \ No newline at end of file diff --git a/Plugin/src/main/resources/world-converter.yml b/Plugin/src/main/resources/world-converter.yml new file mode 100644 index 00000000..532dcf34 --- /dev/null +++ b/Plugin/src/main/resources/world-converter.yml @@ -0,0 +1,23 @@ +# World conversion. +# +# Converts blocks and furniture belonging to other plugins as chunks are explored, without those plugins being +# installed. Settings that were "world-converter.enable" in the old single config.yml are simply "enable" here. + +enable: false # Enable world conversion feature (Requires server restart to take effect) + +nexo: + enable: true # Enable Nexo world conversion without nexo plugin installed ! Just explore and let the lugin convert Nexo blocks and furnitures to CE equivalents + +itemsadder: + enable: true # Enable ItemsAdder world conversion without ItemsAdder plugin installed ! Just explore and let the lugin convert ItemsAdder blocks and furnitures to CE equivalents + +# Available colors: +# BLACK, DARK_BLUE, DARK_GREEN, DARK_AQUA, DARK_RED, DARK_PURPLE, +# GOLD, GRAY, DARK_GRAY, BLUE, GREEN, AQUA, RED, LIGHT_PURPLE, YELLOW, WHITE +progress-bar-options: + progress-color: GREEN + empty-color: DARK_GRAY + percent-color: YELLOW + progress-char: █ + empty-char: ░ + bar-width: 50 diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/FurnitureBehaviorTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/FurnitureBehaviorTest.java new file mode 100644 index 00000000..ebb8a88d --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/FurnitureBehaviorTest.java @@ -0,0 +1,76 @@ +package fr.robie.craftengineconverter; + +import fr.robie.craftengineconverter.api.configuration.CraftEngineItemsConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.behavior.furniture.FurnitureConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.behavior.furniture.SimpleStorageFurnitureBehavior; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.bukkit.Material; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The {@code behavior} list a furniture definition carries. CraftEngine reads it as a list of maps keyed by + * {@code type}, not as a section per behaviour. + */ +class FurnitureBehaviorTest { + + @SuppressWarnings("unchecked") + private static List> behaviors(FurnitureConfiguration furniture) { + CraftEngineItemsConfiguration configuration = new CraftEngineItemsConfiguration("default:chair", Material.PAPER); + configuration.addItemConfiguration(furniture); + + YamlConfiguration yaml = new YamlConfiguration(); + ConfigurationSection itemSection = yaml.createSection("items.default:chair"); + configuration.serialize(yaml, "items.default:chair", itemSection); + + return (List>) itemSection.getList("behavior.furniture.behavior"); + } + + @Test + void writesStorageAsAnEntryInTheBehaviorList() { + FurnitureConfiguration furniture = new FurnitureConfiguration(); + furniture.addBehavior(new SimpleStorageFurnitureBehavior( + 3, "Chest", "minecraft:block.chest.open", "minecraft:block.chest.close")); + + List> behaviors = behaviors(furniture); + assertEquals(1, behaviors.size()); + + Map storage = behaviors.getFirst(); + assertEquals("simple_storage_furniture", storage.get("type")); + assertEquals(3, storage.get("rows")); + assertEquals("Chest", storage.get("title")); + assertEquals(Map.of("open", "minecraft:block.chest.open", "close", "minecraft:block.chest.close"), + storage.get("sounds")); + } + + @Test + void leavesOutSoundsThatWereNotConfigured() { + FurnitureConfiguration furniture = new FurnitureConfiguration(); + furniture.addBehavior(new SimpleStorageFurnitureBehavior(6, null, null, null)); + + Map storage = behaviors(furniture).getFirst(); + assertEquals(6, storage.get("rows")); + assertFalse(storage.containsKey("title")); + assertFalse(storage.containsKey("sounds"), "an empty sounds map is noise, not configuration"); + } + + @Test + void writesNoBehaviorKeyWhenThereAreNone() { + CraftEngineItemsConfiguration configuration = new CraftEngineItemsConfiguration("default:chair", Material.PAPER); + configuration.addItemConfiguration(new FurnitureConfiguration()); + + YamlConfiguration yaml = new YamlConfiguration(); + ConfigurationSection itemSection = yaml.createSection("items.default:chair"); + configuration.serialize(yaml, "items.default:chair", itemSection); + + assertTrue(itemSection.contains("behavior.furniture"), "the furniture itself is still written"); + assertFalse(itemSection.contains("behavior.furniture.behavior")); + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/IconEncodingTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/IconEncodingTest.java new file mode 100644 index 00000000..e6c956b9 --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/IconEncodingTest.java @@ -0,0 +1,90 @@ +package fr.robie.craftengineconverter; + +import org.junit.jupiter.api.Test; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Encoding a rendered icon once and writing the bytes later has to produce the same file as encoding it at the point + * of writing. + * + *

Rendered icons used to be kept as decoded rasters and encoded when the mapping that needed one was assigned; + * they are kept encoded now, so the write is a byte copy. That is only a memory change if the resulting PNG is + * identical, and nothing else in the pipeline would notice if it were not. + */ +class IconEncodingTest { + + private static BufferedImage icon(int size, long seed) { + BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); + Random random = new Random(seed); + for (int x = 0; x < size; x++) { + for (int y = 0; y < size; y++) { + // Flat runs and transparency, the way a rendered item sprite actually looks. + int alpha = (x + y) % 7 == 0 ? 0 : 0xFF; + int shade = ((x / 4) * 37 + (y / 4) * 11 + random.nextInt(3)) & 0xFF; + image.setRGB(x, y, (alpha << 24) | (shade << 16) | (shade << 8) | shade); + } + } + return image; + } + + private static byte[] encodeToMemory(BufferedImage image) throws Exception { + try (ByteArrayOutputStream encoded = new ByteArrayOutputStream()) { + ImageIO.write(image, "png", encoded); + return encoded.toByteArray(); + } + } + + private static byte[] encodeToFile(BufferedImage image) throws Exception { + Path file = Files.createTempFile("icon", ".png"); + try { + ImageIO.write(image, "png", file.toFile()); + return Files.readAllBytes(file); + } finally { + Files.deleteIfExists(file); + } + } + + @Test + void producesTheSameFileWhicheverWayItIsWritten() throws Exception { + for (int size : new int[]{16, 64, 128, 256}) { + BufferedImage image = icon(size, size); + assertArrayEquals(encodeToFile(image), encodeToMemory(image), + "a " + size + "px icon must encode identically"); + } + } + + @Test + void theEncodedFormIsWorthKeepingInsteadOfTheRaster() throws Exception { + BufferedImage image = icon(64, 1); + int rasterBytes = 64 * 64 * 4; + byte[] encoded = encodeToMemory(image); + + assertTrue(encoded.length < rasterBytes / 2, + "encoded " + encoded.length + " bytes against " + rasterBytes + " raw - if this ever stops holding, " + + "keeping icons encoded is no longer buying anything"); + } + + @Test + void surviveARoundTripUnchanged() throws Exception { + BufferedImage original = icon(64, 3); + BufferedImage decoded = ImageIO.read(new java.io.ByteArrayInputStream(encodeToMemory(original))); + + assertEquals(original.getWidth(), decoded.getWidth()); + assertEquals(original.getHeight(), decoded.getHeight()); + for (int x = 0; x < original.getWidth(); x++) { + for (int y = 0; y < original.getHeight(); y++) { + assertEquals(original.getRGB(x, y), decoded.getRGB(x, y), "pixel " + x + "," + y); + } + } + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/ItemDataPlacementTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/ItemDataPlacementTest.java new file mode 100644 index 00000000..97275c1f --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/ItemDataPlacementTest.java @@ -0,0 +1,79 @@ +package fr.robie.craftengineconverter; + +import fr.robie.craftengineconverter.api.configuration.CraftEngineItemsConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.components.FoodConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.components.ItemModelConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.components.MaxStackSizeConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.data.CustomNameConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.data.UnbreakableConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.bukkit.Material; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Where converted item configuration has to land for CraftEngine to read it. + * + *

{@code AbstractItemManager} only feeds an item's {@code data} section to {@code ItemProcessors}, and raw vanilla + * components live under {@code data.components}. A key written straight onto the item is parsed as YAML perfectly + * happily and then ignored, which is the kind of mistake nothing downstream complains about - hence this test. + */ +class ItemDataPlacementTest { + + private static ConfigurationSection serialize(CraftEngineItemsConfiguration configuration) { + YamlConfiguration yaml = new YamlConfiguration(); + ConfigurationSection itemSection = yaml.createSection("items.default:test_item"); + configuration.serialize(yaml, "items.default:test_item", itemSection); + return itemSection; + } + + private static CraftEngineItemsConfiguration configuration() { + return new CraftEngineItemsConfiguration("default:test_item", Material.PAPER); + } + + @Test + void putsVanillaComponentsUnderDataComponents() { + CraftEngineItemsConfiguration configuration = configuration(); + configuration.addItemConfiguration(new FoodConfiguration(4, 2.5f)); + configuration.addItemConfiguration(new MaxStackSizeConfiguration(16)); + configuration.addItemConfiguration(new ItemModelConfiguration("default:test_item")); + + ConfigurationSection item = serialize(configuration); + + assertTrue(item.isConfigurationSection("data.components"), "components belong under data"); + assertFalse(item.contains("components"), "a top-level components section is never read by CraftEngine"); + assertEquals(16, item.getInt("data.components.minecraft:max_stack_size")); + assertEquals("default:test_item", item.getString("data.components.minecraft:item_model")); + assertEquals(4, item.getInt("data.components.minecraft:food.nutrition")); + } + + @Test + void keepsDedicatedDataEntriesOnDataItself() { + CraftEngineItemsConfiguration configuration = configuration(); + configuration.addItemConfiguration(new CustomNameConfiguration("Test")); + configuration.addItemConfiguration(new UnbreakableConfiguration(true)); + + ConfigurationSection item = serialize(configuration); + + // These have their own processors, so they sit directly on data rather than among the raw components. + assertEquals("Test", item.getString("data.custom-name")); + assertTrue(item.getBoolean("data.unbreakable")); + } + + @Test + void sharesOneDataSectionBetweenBothKinds() { + CraftEngineItemsConfiguration configuration = configuration(); + configuration.addItemConfiguration(new CustomNameConfiguration("Test")); + configuration.addItemConfiguration(new FoodConfiguration(4, 2.5f)); + + ConfigurationSection item = serialize(configuration); + + // One data section holding both, not two competing ones. + assertEquals("Test", item.getString("data.custom-name")); + assertEquals(4, item.getInt("data.components.minecraft:food.nutrition")); + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/JsonConfigurationAdapterTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/JsonConfigurationAdapterTest.java new file mode 100644 index 00000000..e4c79db3 --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/JsonConfigurationAdapterTest.java @@ -0,0 +1,109 @@ +package fr.robie.craftengineconverter; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import fr.robie.craftengineconverter.api.configuration.loader.JsonConfigurationAdapter; +import fr.robie.yamllibrary.ConfigurationSection; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Locks in the JSON-to-ConfigurationSection semantics the {@code ModelConfiguration} loaders rely on. + * These loaders call {@code getConfigurationSection}, {@code getInt}, {@code getDouble} and + * {@code getMapList}, so nested objects must become real child sections and numbers must keep their + * natural type rather than arriving as Gson's LazilyParsedNumber. + */ +class JsonConfigurationAdapterTest { + + private static ConfigurationSection parse(String json) { + return JsonConfigurationAdapter.toSection(JsonParser.parseString(json).getAsJsonObject()); + } + + @Test + void nestedObjectsBecomeChildSections() { + // The shape of assets/default/items/drill.json. + ConfigurationSection root = parse(""" + { + "type": "condition", + "property": "selected", + "on_true": { "type": "model", "model": "item/custom/drill_selected" }, + "on_false": { "type": "model", "model": "item/custom/drill" } + } + """); + + assertEquals("condition", root.getString("type")); + + ConfigurationSection onTrue = root.getConfigurationSection("on_true"); + assertNotNull(onTrue, "nested object must become a child section, not stay a Map"); + assertEquals("model", onTrue.getString("type")); + assertEquals("item/custom/drill_selected", onTrue.getString("model")); + } + + @Test + void integersAndDecimalsKeepTheirNaturalType() { + ConfigurationSection root = parse(""" + { "index": 1, "threshold": 0.65, "scale": 0.05, "big": 3000000000 } + """); + + assertEquals(1, root.getInt("index")); + assertEquals(0.65, root.getDouble("threshold"), 1e-9); + assertEquals(3000000000L, root.getLong("big")); + // AbstractRangeDispatchConfigurationLoader reads scale as (float) getDouble("scale", 1.0); + // there is no single-value getFloat on ConfigurationSection, so this is the only path. + assertEquals(0.05f, (float) root.getDouble("scale", 1.0), 1e-9f); + assertEquals(1.0, root.getDouble("absent_scale", 1.0), 1e-9); + } + + @Test + void arraysOfObjectsSurviveAsMapLists() { + // The shape of range_dispatch entries in assets/default/items/topaz_bow.json. + ConfigurationSection root = parse(""" + { + "entries": [ + { "threshold": 0.65, "model": { "type": "model", "model": "a" } }, + { "threshold": 0.9, "model": { "type": "model", "model": "b" } } + ] + } + """); + + List entries = root.getMapList("entries"); + assertEquals(2, entries.size()); + assertTrue(entries.getFirst() instanceof java.util.Map); + } + + @Test + void booleansAndStringListsRoundTrip() { + ConfigurationSection root = parse(""" + { "oversized_in_gui": true, "tags": ["default:topaz_tools", "default:other"] } + """); + + assertTrue(root.getBoolean("oversized_in_gui")); + assertEquals(List.of("default:topaz_tools", "default:other"), root.getStringList("tags")); + } + + @Test + void realItemDefinitionLoadsThroughTheRegistry() { + JsonObject json = JsonParser.parseString(""" + { + "type": "select", + "property": "charge_type", + "cases": [ + { "when": "arrow", "model": { "type": "model", "model": "item/custom/cb_arrow" } }, + { "when": "rocket", "model": { "type": "model", "model": "item/custom/cb_rocket" } } + ], + "fallback": { "type": "model", "model": "item/custom/cb" } + } + """).getAsJsonObject(); + + ConfigurationSection section = JsonConfigurationAdapter.toSection(json); + assertEquals("select", section.getString("type")); + assertEquals("charge_type", section.getString("property")); + assertNotNull(section.getConfigurationSection("fallback")); + assertEquals(2, section.getMapList("cases").size()); + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/KeyRegistryTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/KeyRegistryTest.java new file mode 100644 index 00000000..b1330fa5 --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/KeyRegistryTest.java @@ -0,0 +1,67 @@ +package fr.robie.craftengineconverter; + +import fr.robie.craftengineconverter.api.configuration.ConfigFile; +import fr.robie.craftengineconverter.api.configuration.Key; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The registry has to answer correctly to a caller that has never mentioned {@code Keys}. + *

+ * A key only exists once its declaration has run, and the declarations live in a class nothing else needs to name. + * If asking for the keys did not force that class to load, the registry would come back empty — which reads as a + * configuration with no settings rather than as an error, and would silently leave every value at its default. + *

+ * This test deliberately never references {@code Keys}, so it fails if that guarantee is ever removed. + */ +class KeyRegistryTest { + + @Test + void theRegistryFillsWithoutBeingPrimedFirst() { + List> all = Key.all(); + assertFalse(all.isEmpty(), "asking for the keys must load their declarations"); + assertTrue(all.size() >= 33, "expected the whole settings table, got " + all.size()); + } + + @Test + void everyKeyBelongsToExactlyOneFileAndEveryFileHasKeys() { + for (ConfigFile file : ConfigFile.values()) { + assertFalse(Key.in(file).isEmpty(), file.fileName() + " ended up with no settings at all"); + } + + int perFile = 0; + for (ConfigFile file : ConfigFile.values()) perFile += Key.in(file).size(); + assertEquals(Key.all().size(), perFile, "a key is missing from its file, or counted twice"); + } + + /** Two keys sharing a path in one file would make the second silently unreachable. */ + @Test + void noTwoKeysShareAPathWithinAFile() { + for (ConfigFile file : ConfigFile.values()) { + Set seen = new HashSet<>(); + for (Key key : Key.in(file)) { + assertTrue(seen.add(key.path()), "duplicate path " + key.path() + " in " + file.fileName()); + } + } + } + + /** + * The migration reads a value from its old path and writes it to the new one, so two settings that used to be + * distinct must not collapse onto one legacy path. + */ + @Test + void noTwoKeysShareALegacyPath() { + Set seen = new HashSet<>(); + for (Key key : Key.all()) { + assertTrue(seen.add(key.legacyPath()), + "two settings claim the old path " + key.legacyPath() + "; migration would lose one"); + } + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/NexoItemTemplatesTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/NexoItemTemplatesTest.java new file mode 100644 index 00000000..00abb932 --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/NexoItemTemplatesTest.java @@ -0,0 +1,243 @@ +package fr.robie.craftengineconverter; + +import fr.robie.craftengineconverter.converter.nexo.NexoItemTemplates; +import fr.robie.craftengineconverter.utils.ConfigFile; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.InvalidConfigurationException; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Nexo item templates, checked against how Nexo's own {@code ItemParser} resolves them: templates are looked up + * globally, merged in declaration order, overridden by the inheriting item, and never emitted as items themselves. + */ +class NexoItemTemplatesTest { + + private static YamlConfiguration yaml(String content) { + YamlConfiguration config = new YamlConfiguration(); + try { + config.loadFromString(content); + } catch (InvalidConfigurationException e) { + throw new IllegalArgumentException(e); + } + return config; + } + + private static ConfigFile file(String name, String content) { + return new ConfigFile(new File(name), new File("."), yaml(content)); + } + + private static ConfigurationSection resolve(NexoItemTemplates templates, ConfigFile file, String itemId) { + return templates.resolve(itemId, file.config().getConfigurationSection(itemId)); + } + + @Test + void inheritsFromTheTemplateAndLetsTheItemWin() { + ConfigFile items = file("swords.yml", """ + base_sword: + material: IRON_SWORD + unbreakable: true + Components: + max_damage: 500 + enchantment_glint_override: true + ruby_sword: + template: base_sword + Components: + max_damage: 900 + """); + NexoItemTemplates templates = NexoItemTemplates.collect(List.of(items)); + + assertTrue(templates.isTemplate("base_sword"), "an item named by a template key is a template"); + assertFalse(templates.isTemplate("ruby_sword")); + + ConfigurationSection sword = resolve(templates, items, "ruby_sword"); + assertEquals("IRON_SWORD", sword.getString("material"), "inherited from the template"); + assertTrue(sword.getBoolean("unbreakable")); + assertEquals(900, sword.getInt("Components.max_damage"), "the item overrides the template"); + // Sibling keys inside a nested section survive: the merge is per key, not per section. + assertTrue(sword.getBoolean("Components.enchantment_glint_override")); + } + + @Test + void doesNotTouchTheSourceConfiguration() { + ConfigFile items = file("swords.yml", """ + base_sword: + material: IRON_SWORD + ruby_sword: + template: base_sword + """); + NexoItemTemplates templates = NexoItemTemplates.collect(List.of(items)); + + resolve(templates, items, "ruby_sword"); + + assertNull(items.config().getString("ruby_sword.material"), "resolving must not write back into the file"); + } + + @Test + void mergesSeveralTemplatesWithTheLastWinning() { + ConfigFile items = file("swords.yml", """ + glowing: + Components: + enchantment_glint_override: true + max_damage: 100 + sturdy: + Components: + max_damage: 800 + ruby_sword: + template: + - glowing + - sturdy + """); + NexoItemTemplates templates = NexoItemTemplates.collect(List.of(items)); + + ConfigurationSection sword = resolve(templates, items, "ruby_sword"); + assertTrue(sword.getBoolean("Components.enchantment_glint_override"), "kept from the first template"); + assertEquals(800, sword.getInt("Components.max_damage"), "the later template wins"); + } + + @Test + void followsTemplateChains() { + ConfigFile items = file("swords.yml", """ + metal: + material: IRON_SWORD + unbreakable: true + sturdy: + template: metal + Components: + max_damage: 800 + ruby_sword: + template: sturdy + """); + NexoItemTemplates templates = NexoItemTemplates.collect(List.of(items)); + + ConfigurationSection sword = resolve(templates, items, "ruby_sword"); + assertEquals("IRON_SWORD", sword.getString("material"), "reached through sturdy's own template"); + assertTrue(sword.getBoolean("unbreakable")); + assertEquals(800, sword.getInt("Components.max_damage")); + } + + @Test + void findsTemplatesDeclaredInAnotherFile() { + ConfigFile bases = file("bases.yml", """ + base_sword: + material: IRON_SWORD + """); + ConfigFile swords = file("swords.yml", """ + ruby_sword: + template: base_sword + """); + NexoItemTemplates templates = NexoItemTemplates.collect(List.of(bases, swords)); + + assertTrue(templates.isTemplate("base_sword")); + assertEquals("IRON_SWORD", resolve(templates, swords, "ruby_sword").getString("material")); + } + + @Test + void acceptsThePluralSpelling() { + ConfigFile items = file("swords.yml", """ + base_sword: + material: IRON_SWORD + ruby_sword: + templates: base_sword + """); + NexoItemTemplates templates = NexoItemTemplates.collect(List.of(items)); + + assertTrue(templates.isTemplate("base_sword")); + assertEquals("IRON_SWORD", resolve(templates, items, "ruby_sword").getString("material")); + } + + @Test + void expandsIdAndModelPlaceholders() { + ConfigFile items = file("swords.yml", """ + base_sword: + itemname: "" + Pack: + generate_model: true + parent_model: "" + model: "" + texture: "" + ruby_sword: + template: base_sword + Pack: + texture: item/ruby_sword + """); + NexoItemTemplates templates = NexoItemTemplates.collect(List.of(items)); + + ConfigurationSection sword = resolve(templates, items, "ruby_sword"); + assertEquals("Ruby Sword", sword.getString("itemname")); + // No Pack.parent_model or Pack.parent on the item, so falls back to the vanilla generated model. + assertEquals("minecraft:item/generated", sword.getString("Pack.parent_model")); + // No Pack.model either, so falls back to the item id. + assertEquals("ruby_sword", sword.getString("Pack.model")); + // The item's own texture wins over the template's expanded placeholder anyway, but it must not stay literal. + assertEquals("item/ruby_sword", sword.getString("Pack.texture")); + } + + @Test + void expandsAListPlaceholderIntoSeveralEntries() { + ConfigFile items = file("swords.yml", """ + base_sword: + lore: + - "A blade." + - "" + - "Forged in Nexo." + ruby_sword: + template: base_sword + lore: + - "Rare" + - "Sharp" + """); + NexoItemTemplates templates = NexoItemTemplates.collect(List.of(items)); + + ConfigurationSection sword = resolve(templates, items, "ruby_sword"); + assertEquals( + List.of("A blade.", "Rare", "Sharp", "Forged in Nexo."), + sword.getStringList("lore"), + "the item's own lore is spliced in where the template asked for it"); + // consumes the item's own lore, but only on the working copy. + assertEquals(List.of("Rare", "Sharp"), items.config().getStringList("ruby_sword.lore")); + } + + @Test + void leavesAnItemWithoutTemplatesAlone() { + ConfigFile items = file("swords.yml", """ + ruby_sword: + material: IRON_SWORD + Components: + max_damage: 900 + """); + NexoItemTemplates templates = NexoItemTemplates.collect(List.of(items)); + + ConfigurationSection sword = resolve(templates, items, "ruby_sword"); + assertEquals("IRON_SWORD", sword.getString("material")); + assertEquals(900, sword.getInt("Components.max_damage")); + } + + @Test + void survivesATemplateCycle() { + ConfigFile items = file("swords.yml", """ + a: + template: b + material: IRON_SWORD + b: + template: a + unbreakable: true + ruby_sword: + template: a + """); + NexoItemTemplates templates = NexoItemTemplates.collect(List.of(items)); + + // The point is that this terminates rather than blowing the stack; what it inherits on the way is incidental. + ConfigurationSection sword = resolve(templates, items, "ruby_sword"); + assertEquals("IRON_SWORD", sword.getString("material")); + assertTrue(sword.getBoolean("unbreakable")); + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/NullArgumentYamlTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/NullArgumentYamlTest.java new file mode 100644 index 00000000..05c770a8 --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/NullArgumentYamlTest.java @@ -0,0 +1,73 @@ +package fr.robie.craftengineconverter; + +import fr.robie.craftengineconverter.api.configuration.loader.ConfigurationTrees; +import fr.robie.craftengineconverter.api.configuration.template.TemplateEngine; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Pins down how an explicit {@code key: null} survives YAML loading. + *

+ * It matters because CraftEngine uses {@code lore: null} to bind a template argument to nothing, which + * makes the template drop that key. If the loader discards the key instead of keeping a null value, the + * argument looks unbound — and an unbound argument is an error, which would skip the whole item. + */ +class NullArgumentYamlTest { + + private static ConfigurationSection load(String... lines) throws Exception { + File file = Files.createTempFile("nullarg", ".yml").toFile(); + try (PrintWriter writer = new PrintWriter(file)) { + for (String line : lines) writer.println(line); + } + ConfigurationSection section = YamlConfiguration.loadConfiguration(file).getConfigurationSection("args"); + file.delete(); + return section; + } + + @Test + void explicitNullKeyIsErasedByTheYamlLayer() throws Exception { + ConfigurationSection args = load("args:", " name: hello", " lore: null", " tilde: ~"); + + Map tree = ConfigurationTrees.toMap(args); + assertTrue(tree.containsKey("name")); + // Bukkit semantics: assigning null removes the key, so the information that the author wrote + // "lore: null" is gone before the template engine ever sees it. This is why an unbound argument + // has to be treated leniently — see ArgumentString.Placeholder.resolve. + assertFalse(tree.containsKey("lore"), "documents the erasure that forces lenient resolution"); + assertFalse(tree.containsKey("tilde"), "'~' is YAML null and is erased the same way"); + } + + @Test + void nulledTemplateArgumentStillProducesTheItem() { + TemplateEngine engine = new TemplateEngine(); + engine.register("icon", Map.of("material", "arrow", "item_name", "${name}", "lore", "${lore}")); + + // The real shape of CraftEngine's internal:exit — "lore: null" plus a template that references it. + // The item must survive with its material intact; only the lore key goes. + Map item = new LinkedHashMap<>(); + item.put("template", "icon"); + item.put("arguments", Map.of("name", "Exit")); + + @SuppressWarnings("unchecked") + Map out = (Map) engine.resolve("internal:exit", item); + assertEquals("arrow", out.get("material")); + assertEquals("Exit", out.get("item_name")); + // A null *value* keeps its key, as in CraftEngine — only a null *key* drops the entry. Either + // way the key vanishes when the map becomes a ConfigurationSection, since assigning null there + // removes it, so nothing downstream sees an empty lore. + assertNull(out.get("lore")); + assertFalse(ConfigurationTrees.toSection(out).contains("lore")); + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/ShippedConfigCoverageTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/ShippedConfigCoverageTest.java new file mode 100644 index 00000000..1ee4d169 --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/ShippedConfigCoverageTest.java @@ -0,0 +1,57 @@ +package fr.robie.craftengineconverter; + +import fr.robie.craftengineconverter.api.configuration.ConfigFile; +import fr.robie.craftengineconverter.api.configuration.Key; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.junit.jupiter.api.Test; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Every setting has to appear in the file that ships with the plugin. + *

+ * A key missing from its resource is invisible: the plugin writes the default back on first run, so it works, but + * nobody editing the file ever learns the setting exists. That is how settings went years without being documented: + * they were read from a section the shipped config never contained. + *

+ * This also catches the reverse mistake the split made easy: declaring a key under one {@link ConfigFile} while + * writing its YAML into another. + */ +class ShippedConfigCoverageTest { + + private static YamlConfiguration shipped(ConfigFile file) { + InputStream stream = ShippedConfigCoverageTest.class.getClassLoader() + .getResourceAsStream(file.fileName()); + assertNotNull(stream, file.fileName() + " is not shipped in the jar; saveResource would fail at runtime"); + return YamlConfiguration.loadConfiguration(new InputStreamReader(stream, StandardCharsets.UTF_8)); + } + + @Test + void everyFileIsActuallyShipped() { + for (ConfigFile file : ConfigFile.values()) { + shipped(file); + } + } + + @Test + void everyKeyAppearsInItsOwnFile() { + List missing = new ArrayList<>(); + for (ConfigFile file : ConfigFile.values()) { + YamlConfiguration yaml = shipped(file); + for (Key key : Key.in(file)) { + if (yaml.get(key.path()) == null) { + missing.add(file.fileName() + " is missing " + key.path()); + } + } + } + assertTrue(missing.isEmpty(), "settings a server owner would never discover:\n " + String.join("\n ", missing)); + } + +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/TemplateEngineTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/TemplateEngineTest.java new file mode 100644 index 00000000..10a6067e --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/TemplateEngineTest.java @@ -0,0 +1,264 @@ +package fr.robie.craftengineconverter; + +import fr.robie.craftengineconverter.api.configuration.template.TemplateEngine; +import fr.robie.craftengineconverter.api.configuration.template.TemplateException; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Locks in the template merge semantics. Packs are authored against CraftEngine's exact behaviour, so these + * assert the rules rather than merely that resolution runs. + */ +class TemplateEngineTest { + + private static Map map(Object... keyValues) { + Map out = new LinkedHashMap<>(); + for (int i = 0; i < keyValues.length; i += 2) { + out.put((String) keyValues[i], keyValues[i + 1]); + } + return out; + } + + @SuppressWarnings("unchecked") + private static Map asMap(Object value) { + return (Map) value; + } + + // ---- placeholders ------------------------------------------------------- + + @Test + void substitutesPlaceholdersInValuesAndKeys() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("material", "chainmail_${part}", "${part}_key", "v")); + + Map out = asMap(engine.resolve("ns:id", + map("template", "t", "arguments", map("part", "boots")))); + + assertEquals("chainmail_boots", out.get("material")); + assertEquals("v", out.get("boots_key")); + } + + @Test + void usesFallbackWhenArgumentUnbound() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("a", "${missing:-fallback}", "b", "${missing:-}")); + + Map out = asMap(engine.resolve("ns:id", map("template", "t"))); + assertEquals("fallback", out.get("a")); + assertEquals("", out.get("b")); + } + + /** + * A quoted fallback loses its quotes. Configs write {@code ${fence_type:-"oak"}_fence} meaning the block + * {@code oak_fence}; inside a YAML plain scalar those quotes are ordinary characters, so keeping them produced + * {@code "oak"_fence}, an id no block has — which is what made the whole fence resolve to nothing. + */ + @Test + void aQuotedFallbackIsUnquoted() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map( + "double", "${missing:-\"oak\"}_fence", + "single", "${missing:-'oak'}_fence", + "bare", "${missing:-oak}_fence", + "inner", "${missing:-say \"hi\"}")); + + Map out = asMap(engine.resolve("ns:id", map("template", "t"))); + assertEquals("oak_fence", out.get("double")); + assertEquals("oak_fence", out.get("single")); + assertEquals("oak_fence", out.get("bare")); + // Only a matching outer pair goes; quotes inside the text are content. + assertEquals("say \"hi\"", out.get("inner")); + } + + @Test + void unboundPlaceholderDropsItsEntry() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("kept", "yes", "a", "${nope}")); + + // Lenient by necessity: the YAML layer erases an explicit "lore: null", so a deliberately + // nulled argument is indistinguishable from a missing one. Dropping the entry matches what + // CraftEngine produces for the nulled case; failing would discard the whole item. + Map out = asMap(engine.resolve("ns:id", map("template", "t"))); + assertEquals("yes", out.get("kept")); + assertNull(out.get("a")); + } + + @Test + void appliesCasingModifiers() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("cap", "${p^}", "upper", "${p^^}", "plain", "${p}")); + + Map out = asMap(engine.resolve("ns:id", + map("template", "t", "arguments", map("p", "topaz")))); + + assertEquals("Topaz", out.get("cap")); + assertEquals("TOPAZ", out.get("upper")); + assertEquals("topaz", out.get("plain")); + } + + @Test + void escapedDollarStaysLiteral() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("a", "\\${not_a_placeholder}", "b", "cost: 5\\$")); + + Map out = asMap(engine.resolve("ns:id", map("template", "t"))); + assertEquals("${not_a_placeholder}", out.get("a")); + assertEquals("cost: 5$", out.get("b")); + } + + @Test + void unclosedPlaceholderIsTreatedAsText() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("a", "${unclosed")); + // A malformed string should not abort a conversion. + assertEquals("${unclosed", asMap(engine.resolve("ns:id", map("template", "t"))).get("a")); + } + + @Test + void nullArgumentDropsItsEntry() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("kept", "yes", "${gone}", "value", "also_gone", "${gone}")); + + Map args = map("gone", null); + Map out = asMap(engine.resolve( + map("template", "t", "arguments", args), Map.of())); + + assertEquals("yes", out.get("kept")); + assertFalse(out.containsKey("value"), "a null key must drop the entry entirely"); + assertNull(out.get("also_gone")); + } + + @Test + void injectsNamespaceAndIdArguments() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("asset", "${__NAMESPACE__}:${__ID__}")); + + assertEquals("default:topaz_boots", + asMap(engine.resolve("default:topaz_boots", map("template", "t"))).get("asset")); + } + + // ---- merge semantics ---------------------------------------------------- + + @Test + void multipleTemplatesDeepMergeInOrder() { + TemplateEngine engine = new TemplateEngine(); + engine.register("a", map("shared", "from_a", "only_a", 1, "nested", map("x", 1, "y", 1))); + engine.register("b", map("shared", "from_b", "only_b", 2, "nested", map("y", 2, "z", 2))); + + Map out = asMap(engine.resolve("ns:id", map("templates", List.of("a", "b")))); + + assertEquals("from_b", out.get("shared"), "later template wins"); + assertEquals(1, out.get("only_a")); + assertEquals(2, out.get("only_b")); + assertEquals(map("x", 1, "y", 2, "z", 2), out.get("nested"), "nested maps merge, not replace"); + } + + @Test + void singleTemplateKeyAcceptsBothSpellings() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("k", "v")); + assertEquals("v", asMap(engine.resolve("ns:id", map("template", "t"))).get("k")); + assertEquals("v", asMap(engine.resolve("ns:id", map("templates", "t"))).get("k")); + } + + @Test + void overridesReplaceAndMergesGoDeep() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("nested", map("keep", 1, "replace", 1))); + + Map overridden = asMap(engine.resolve("ns:id", + map("template", "t", "overrides", map("nested", map("replace", 2))))); + assertEquals(map("replace", 2), overridden.get("nested"), + "overrides replaces the whole value at the top level"); + + Map merged = asMap(engine.resolve("ns:id", + map("template", "t", "merges", map("nested", map("replace", 2))))); + assertEquals(map("keep", 1, "replace", 2), merged.get("nested"), + "merges recurses into the value"); + } + + @Test + void strayKeysBesideTemplateAreMerged() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("a", 1)); + // CraftEngine tolerates config mixed in beside the template rather than discarding it. + Map out = asMap(engine.resolve("ns:id", map("template", "t", "b", 2))); + assertEquals(1, out.get("a")); + assertEquals(2, out.get("b")); + } + + @Test + void parentArgumentsWinOverNested() { + TemplateEngine engine = new TemplateEngine(); + engine.register("inner", map("value", "${shared}")); + engine.register("outer", map("template", "inner", "arguments", map("shared", "inner_default"))); + + // The caller's value must survive an inner template re-declaring the same argument. + Map out = asMap(engine.resolve("ns:id", + map("template", "outer", "arguments", map("shared", "from_caller")))); + assertEquals("from_caller", out.get("value")); + } + + @Test + void doubleDollarKeyForcesReplacement() { + TemplateEngine engine = new TemplateEngine(); + engine.register("a", map("nested", map("keep", 1))); + engine.register("b", map("$$nested", map("only", 2))); + + Map out = asMap(engine.resolve("ns:id", map("templates", List.of("a", "b")))); + assertEquals(map("only", 2), out.get("nested"), "$$ discards what was inherited"); + assertFalse(out.containsKey("$$nested")); + } + + @Test + void listTemplatesConcatenateAndOverrideReplaces() { + TemplateEngine engine = new TemplateEngine(); + engine.register("a", List.of(1, 2)); + engine.register("b", List.of(3)); + + assertEquals(List.of(1, 2, 3), engine.resolve("ns:id", map("templates", List.of("a", "b")))); + assertEquals(List.of(9), engine.resolve("ns:id", + map("template", "a", "overrides", List.of(9)))); + assertEquals(List.of(1, 2, 9), engine.resolve("ns:id", + map("template", "a", "merges", List.of(9)))); + } + + @Test + void unknownTemplateFails() { + TemplateEngine engine = new TemplateEngine(); + assertThrows(TemplateException.class, () -> engine.resolve("ns:id", map("template", "nope"))); + } + + @Test + void conditionArgumentPicksBranch() { + TemplateEngine engine = new TemplateEngine(); + engine.register("t", map("value", "${branch}")); + + Map condition = + map("type", "condition", "condition", "true", "on_true", "yes", "on_false", "no"); + assertEquals("yes", asMap(engine.resolve("ns:id", + map("template", "t", "arguments", map("branch", condition)))).get("value")); + + condition.put("condition", "false"); + assertEquals("no", asMap(engine.resolve("ns:id", + map("template", "t", "arguments", map("branch", condition)))).get("value")); + } + + @Test + void treeWithoutTemplatesStillResolvesPlaceholders() { + TemplateEngine engine = new TemplateEngine(); + Object out = engine.resolve("default:thing", map("id", "${__ID__}", "nested", map("ns", "${__NAMESPACE__}"))); + assertEquals("thing", asMap(out).get("id")); + assertEquals("default", asMap(asMap(out).get("nested")).get("ns")); + assertTrue(engine.isEmpty()); + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/TrimAndPotionContentsTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/TrimAndPotionContentsTest.java new file mode 100644 index 00000000..e1f422e2 --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/TrimAndPotionContentsTest.java @@ -0,0 +1,154 @@ +package fr.robie.craftengineconverter; + +import fr.robie.craftengineconverter.api.configuration.CraftEngineItemsConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.components.PotionContentsConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.data.TrimConfiguration; +import fr.robie.craftengineconverter.api.configuration.item.data.WrittenBookContentConfiguration; +import fr.robie.yamllibrary.ConfigurationSection; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.bukkit.Material; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The two shapes Nexo's {@code trim_material}/{@code trim_pattern} and {@code PotionEffects} convert into. + * + *

They land in different places on purpose: CraftEngine registers a {@code trim} processor, so a trim sits directly + * on {@code data}, while nothing handles potion contents and it has to go through {@code data.components} as a raw + * vanilla component. + */ +class TrimAndPotionContentsTest { + + private static ConfigurationSection serialize(CraftEngineItemsConfiguration configuration) { + YamlConfiguration yaml = new YamlConfiguration(); + ConfigurationSection itemSection = yaml.createSection("items.default:test_item"); + configuration.serialize(yaml, "items.default:test_item", itemSection); + return itemSection; + } + + private static CraftEngineItemsConfiguration configuration() { + return new CraftEngineItemsConfiguration("default:test_item", Material.PAPER); + } + + @SuppressWarnings("unchecked") + private static List> effects(ConfigurationSection item) { + return (List>) item.getList("data.components.minecraft:potion_contents.custom_effects"); + } + + @Test + void writesATrimOnDataWhereTheProcessorLooksForIt() { + CraftEngineItemsConfiguration configuration = configuration(); + configuration.addItemConfiguration(new TrimConfiguration("minecraft:gold", "minecraft:coast")); + + ConfigurationSection item = serialize(configuration); + + assertEquals("minecraft:gold", item.getString("data.trim.material")); + assertEquals("minecraft:coast", item.getString("data.trim.pattern")); + assertFalse(item.contains("data.components.minecraft:trim"), "the dedicated processor takes precedence"); + } + + @Test + void writesPotionEffectsAsARawComponent() { + CraftEngineItemsConfiguration configuration = configuration(); + configuration.addItemConfiguration(new PotionContentsConfiguration() + .addEffect(new PotionContentsConfiguration.CustomEffect("minecraft:speed", 200, 1, null, null, null))); + + ConfigurationSection item = serialize(configuration); + + List> effects = effects(item); + assertEquals(1, effects.size()); + assertEquals("minecraft:speed", effects.getFirst().get("id")); + assertEquals(200, effects.getFirst().get("duration")); + assertEquals(1, effects.getFirst().get("amplifier")); + // Nothing was configured beyond the essentials, so no flags are written and vanilla's defaults stand. + assertEquals(3, effects.getFirst().size()); + } + + @Test + void keepsOnlyTheFlagsThatWereActuallySet() { + CraftEngineItemsConfiguration configuration = configuration(); + configuration.addItemConfiguration(new PotionContentsConfiguration() + .addEffect(new PotionContentsConfiguration.CustomEffect("minecraft:speed", 200, 0, true, false, null))); + + ConfigurationSection item = serialize(configuration); + + Map effect = effects(item).getFirst(); + assertEquals(Boolean.TRUE, effect.get("ambient")); + assertEquals(Boolean.FALSE, effect.get("show_particles")); + assertFalse(effect.containsKey("show_icon"), "an unset flag must not be invented"); + } + + @Test + void carriesEveryEffectInOrder() { + CraftEngineItemsConfiguration configuration = configuration(); + configuration.addItemConfiguration(new PotionContentsConfiguration() + .addEffect(new PotionContentsConfiguration.CustomEffect("minecraft:speed", 200, 0, null, null, null)) + .addEffect(new PotionContentsConfiguration.CustomEffect("minecraft:strength", 400, 2, null, null, null))); + + List> effects = effects(serialize(configuration)); + assertEquals(List.of("minecraft:speed", "minecraft:strength"), effects.stream().map(e -> e.get("id")).toList()); + } + + @Test + void carriesTheBasePotionAndItsTint() { + CraftEngineItemsConfiguration configuration = configuration(); + configuration.addItemConfiguration(new PotionContentsConfiguration() + .setPotion("minecraft:swiftness") + .setCustomColor(0xFF0000)); + + ConfigurationSection item = serialize(configuration); + + assertEquals("minecraft:swiftness", item.getString("data.components.minecraft:potion_contents.potion")); + assertEquals(0xFF0000, item.getInt("data.components.minecraft:potion_contents.custom_color")); + // A base potion on its own is a complete component; there is nothing to list under custom_effects. + assertFalse(item.contains("data.components.minecraft:potion_contents.custom_effects")); + } + + @Test + void writesBookContentOnDataWithVanillaGenerationNumbers() { + CraftEngineItemsConfiguration configuration = configuration(); + configuration.addItemConfiguration(new WrittenBookContentConfiguration( + "Field Notes", "A. Cartographer", + WrittenBookContentConfiguration.GENERATION_COPY_OF_ORIGINAL, + List.of("page one", "page two"))); + + ConfigurationSection item = serialize(configuration); + + assertEquals("Field Notes", item.getString("data.written_book_content.title")); + assertEquals("A. Cartographer", item.getString("data.written_book_content.author")); + assertEquals(1, item.getInt("data.written_book_content.generation")); + assertEquals(List.of("page one", "page two"), item.getStringList("data.written_book_content.pages")); + } + + @Test + void leavesOutBookFieldsThatWereNotConfigured() { + CraftEngineItemsConfiguration configuration = configuration(); + configuration.addItemConfiguration(new WrittenBookContentConfiguration( + null, " ", WrittenBookContentConfiguration.GENERATION_ORIGINAL, List.of())); + + ConfigurationSection item = serialize(configuration); + + assertFalse(item.contains("data.written_book_content.title")); + assertFalse(item.contains("data.written_book_content.author"), "a blank author is not an author"); + assertFalse(item.contains("data.written_book_content.generation"), "0 is the processor's own default"); + assertFalse(item.contains("data.written_book_content.pages")); + } + + @Test + void writesNothingWhenThereAreNoEffects() { + CraftEngineItemsConfiguration configuration = configuration(); + PotionContentsConfiguration potionContents = new PotionContentsConfiguration(); + assertFalse(potionContents.hasContents()); + configuration.addItemConfiguration(potionContents); + + ConfigurationSection item = serialize(configuration); + assertFalse(item.contains("data.components.minecraft:potion_contents")); + assertTrue(item.contains("material"), "the item itself is still written"); + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/TypedCacheDrainTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/TypedCacheDrainTest.java new file mode 100644 index 00000000..05e98d98 --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/TypedCacheDrainTest.java @@ -0,0 +1,92 @@ +package fr.robie.craftengineconverter; + +import fr.robie.craftengineconverter.utils.TypedCache; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * How fast the write buffer empties. + * + *

It used to write one batch per scheduled save - 250 rows a minute - while a world conversion produces rows far + * faster than that. The buffer therefore grew for as long as the conversion ran, holding every pending row in memory. + */ +class TypedCacheDrainTest { + + private record Row(String id) { + } + + private static TypedCache cache(List> writes) { + return new TypedCache<>(Row.class, batch -> writes.add(List.copyOf(batch)), 250, Row::id); + } + + private static void fill(TypedCache cache, int count) { + for (int i = 0; i < count; i++) { + cache.add(new Row("row-" + i)); + } + } + + @Test + void drainsEverythingRatherThanOneBatch() { + List> writes = new ArrayList<>(); + TypedCache cache = cache(writes); + fill(cache, 1_000); + + int written = cache.drain(Integer.MAX_VALUE); + + assertEquals(1_000, written); + assertTrue(cache.isEmpty(), "a drain leaves nothing behind"); + assertEquals(4, writes.size(), "still batched at 250 rows per insert"); + } + + @Test + void honoursTheCeilingSoOneCycleCannotRunAway() { + List> writes = new ArrayList<>(); + TypedCache cache = cache(writes); + fill(cache, 1_000); + + assertEquals(500, cache.drain(500), "stops once the ceiling is reached"); + assertEquals(500, cache.size(), "the rest waits for the next cycle"); + } + + @Test + void asksToBeDrainedOnceItHasBuiltUp() { + AtomicInteger overflows = new AtomicInteger(); + TypedCache cache = cache(new ArrayList<>()); + cache.onOverflow(100, overflows::incrementAndGet); + + fill(cache, 99); + assertEquals(0, overflows.get(), "quiet below the threshold"); + + cache.add(new Row("row-99")); + assertTrue(overflows.get() > 0, "the hundredth row asks for a drain"); + } + + @Test + void aFailedWriteKeepsItsRowsInsteadOfLosingThem() { + TypedCache cache = new TypedCache<>(Row.class, batch -> { + throw new IllegalStateException("database is down"); + }, 250, Row::id); + fill(cache, 300); + + assertEquals(0, cache.drain(Integer.MAX_VALUE), "nothing was written"); + assertEquals(300, cache.size(), "and nothing was dropped either"); + } + + @Test + void flushLeavesNothingPending() { + List> writes = new ArrayList<>(); + TypedCache cache = cache(writes); + fill(cache, 700); + + cache.flush(); + + assertTrue(cache.isEmpty()); + assertEquals(700, writes.stream().mapToInt(List::size).sum()); + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/UnsupportedFeaturesTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/UnsupportedFeaturesTest.java new file mode 100644 index 00000000..eb39732b --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/UnsupportedFeaturesTest.java @@ -0,0 +1,133 @@ +package fr.robie.craftengineconverter; + +import fr.robie.craftengineconverter.converter.UnsupportedFeatures; +import fr.robie.yamllibrary.InvalidConfigurationException; +import fr.robie.yamllibrary.file.YamlConfiguration; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The digest a converter prints for configuration it could not carry over. + */ +class UnsupportedFeaturesTest { + + private static YamlConfiguration yaml(String content) { + YamlConfiguration config = new YamlConfiguration(); + try { + config.loadFromString(content); + } catch (InvalidConfigurationException e) { + throw new IllegalArgumentException(e); + } + return config; + } + + private static List summaries(UnsupportedFeatures features) { + return List.copyOf(features.summaries()); + } + + @Test + void collapsesTheSameFeatureAcrossItems() { + UnsupportedFeatures features = new UnsupportedFeatures(); + features.record("Mechanics.soulbound", "sword"); + features.record("Mechanics.soulbound", "axe"); + features.record("Mechanics.backpack", "pouch"); + + List summaries = summaries(features); + assertEquals(2, summaries.size(), "one line per feature, not per item"); + // Ordered by feature name so the digest reads the same way every run. + assertEquals("Mechanics.backpack", summaries.get(0).feature()); + assertEquals(1, summaries.get(0).count()); + assertEquals("Mechanics.soulbound", summaries.get(1).feature()); + assertEquals(2, summaries.get(1).count()); + assertEquals("sword, axe", summaries.get(1).examples()); + } + + @Test + void keepsOnlyAFewExamplesButCountsEverything() { + UnsupportedFeatures features = new UnsupportedFeatures(); + for (int i = 1; i <= 500; i++) { + features.record("Mechanics.soulbound", "item_" + i); + } + + UnsupportedFeatures.Summary summary = summaries(features).getFirst(); + assertEquals(500, summary.count()); + assertEquals("item_1, item_2, item_3", summary.examples(), "a digest should not print five hundred ids"); + } + + @Test + void countsTheSameItemTwiceOnlyOnceInTheExamples() { + UnsupportedFeatures features = new UnsupportedFeatures(); + features.record("Mechanics.soulbound", "sword"); + features.record("Mechanics.soulbound", "sword"); + + UnsupportedFeatures.Summary summary = summaries(features).getFirst(); + assertEquals(2, summary.count()); + assertEquals("sword", summary.examples()); + } + + @Test + void reportsExactlyTheKeysTheConverterDoesNotRead() { + YamlConfiguration config = yaml(""" + ruby_sword: + material: IRON_SWORD + soulbound: true + PotionEffects: + - effect: SPEED + """); + + UnsupportedFeatures features = new UnsupportedFeatures(); + features.recordUnhandledKeys("", config.getConfigurationSection("ruby_sword"), + Set.of("material", "lore"), "swords:ruby_sword"); + + assertEquals( + List.of("PotionEffects", "soulbound"), + summaries(features).stream().map(UnsupportedFeatures.Summary::feature).toList(), + "a handled key is never reported, and a key absent from the config is not invented"); + assertEquals("swords:ruby_sword", summaries(features).getFirst().examples()); + } + + @Test + void qualifiesNestedKeysWithTheirPrefix() { + YamlConfiguration config = yaml(""" + ruby_sword: + Mechanics: + furniture: + hitbox: + barriers: [ "0,0,0" ] + storage: + rows: 3 + jukebox: + playing_song: true + """); + + UnsupportedFeatures features = new UnsupportedFeatures(); + features.recordUnhandledKeys("Mechanics.furniture", + config.getConfigurationSection("ruby_sword.Mechanics.furniture"), Set.of("hitbox"), "ruby_sword"); + + assertEquals( + List.of("Mechanics.furniture.jukebox", "Mechanics.furniture.storage"), + summaries(features).stream().map(UnsupportedFeatures.Summary::feature).toList()); + } + + @Test + void staysQuietWhenThereIsNothingToSayAndClearsBetweenRuns() { + UnsupportedFeatures features = new UnsupportedFeatures(); + assertTrue(features.isEmpty()); + + // A missing section is not a complaint: the item simply did not configure that part. + features.recordUnhandledKeys("Mechanics.furniture", null, Set.of(), "ruby_sword"); + assertTrue(features.isEmpty()); + + features.record("Mechanics.soulbound", "sword"); + assertFalse(features.isEmpty()); + + features.clear(); + assertTrue(features.isEmpty(), "a second conversion must not inherit the first one's findings"); + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/database/BlockPositionPackingTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/database/BlockPositionPackingTest.java new file mode 100644 index 00000000..856f72ba --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/database/BlockPositionPackingTest.java @@ -0,0 +1,78 @@ +package fr.robie.craftengineconverter.database; + +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Random; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * The packing behind the converted-block index. + * + *

Every position in the index is one long, so two different blocks packing to the same value would make one of + * them look already converted and get skipped. The ranges have room to spare for any world Minecraft can generate, + * but the arithmetic has to survive negative coordinates, which is where a mask like this usually goes wrong. + */ +class BlockPositionPackingTest { + + /** Vanilla's world border caps a coordinate at just under 30 million. */ + private static final int WORLD_LIMIT = 29_999_984; + + @Test + void distinguishesTheCornersOfTheLargestPossibleWorld() { + Set packed = new HashSet<>(); + for (int x : new int[]{-WORLD_LIMIT, -1, 0, 1, WORLD_LIMIT}) { + for (int y : new int[]{-2048, -64, 0, 319, 2047}) { + for (int z : new int[]{-WORLD_LIMIT, -1, 0, 1, WORLD_LIMIT}) { + assertEquals(true, packed.add(ConvertedBlockIndex.pack(x, y, z)), + "collision at " + x + "," + y + "," + z); + } + } + } + assertEquals(5 * 5 * 5, packed.size()); + } + + @Test + void keepsNeighboursApartOnEveryAxis() { + long origin = ConvertedBlockIndex.pack(0, 0, 0); + assertNotEquals(origin, ConvertedBlockIndex.pack(1, 0, 0)); + assertNotEquals(origin, ConvertedBlockIndex.pack(-1, 0, 0)); + assertNotEquals(origin, ConvertedBlockIndex.pack(0, 1, 0)); + assertNotEquals(origin, ConvertedBlockIndex.pack(0, -1, 0)); + assertNotEquals(origin, ConvertedBlockIndex.pack(0, 0, 1)); + assertNotEquals(origin, ConvertedBlockIndex.pack(0, 0, -1)); + } + + @Test + void doesNotConfuseTheAxesWithEachOther() { + // A shift that is one bit out would make these three the same value. + assertNotEquals(ConvertedBlockIndex.pack(5, 0, 0), ConvertedBlockIndex.pack(0, 5, 0)); + assertNotEquals(ConvertedBlockIndex.pack(5, 0, 0), ConvertedBlockIndex.pack(0, 0, 5)); + assertNotEquals(ConvertedBlockIndex.pack(0, 5, 0), ConvertedBlockIndex.pack(0, 0, 5)); + } + + @Test + void isStableForTheSamePosition() { + assertEquals(ConvertedBlockIndex.pack(-1234, 71, 5678), ConvertedBlockIndex.pack(-1234, 71, 5678)); + } + + @Test + void survivesAWideRandomSample() { + Random random = new Random(20260824L); + Set packed = new HashSet<>(); + Set positions = new HashSet<>(); + + for (int i = 0; i < 200_000; i++) { + int x = random.nextInt(2 * WORLD_LIMIT) - WORLD_LIMIT; + int y = random.nextInt(4096) - 2048; + int z = random.nextInt(2 * WORLD_LIMIT) - WORLD_LIMIT; + positions.add(x + "," + y + "," + z); + packed.add(ConvertedBlockIndex.pack(x, y, z)); + } + + assertEquals(positions.size(), packed.size(), "distinct positions must give distinct packed values"); + } +} diff --git a/Plugin/src/test/java/fr/robie/craftengineconverter/database/ConversionHistoryQueriesTest.java b/Plugin/src/test/java/fr/robie/craftengineconverter/database/ConversionHistoryQueriesTest.java new file mode 100644 index 00000000..d57398e4 --- /dev/null +++ b/Plugin/src/test/java/fr/robie/craftengineconverter/database/ConversionHistoryQueriesTest.java @@ -0,0 +1,278 @@ +package fr.robie.craftengineconverter.database; + +import fr.robie.craftengineconverter.api.history.BlockHistory; +import fr.robie.craftengineconverter.api.history.EntityHistory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The conversion-history SQL, run against a real database. + * + *

These queries are written by hand rather than built by the ORM, so nothing but running them catches a mistyped + * column, a paging clause that skips rows, or a boolean comparison a driver spells differently. SQLite is what the + * plugin ships with by default, so it is what this runs on. + */ +class ConversionHistoryQueriesTest { + + private Path databaseFile; + private Connection connection; + private ConversionHistoryQueries queries; + + @BeforeEach + void openDatabase() throws Exception { + this.databaseFile = Files.createTempFile("conversion-history", ".db"); + this.connection = DriverManager.getConnection("jdbc:sqlite:" + this.databaseFile); + this.queries = new ConversionHistoryQueries(() -> this.connection); + + try (Statement statement = this.connection.createStatement()) { + statement.executeUpdate(""" + CREATE TABLE %s ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + world_name TEXT NOT NULL, + chunk_x INTEGER NOT NULL, chunk_z INTEGER NOT NULL, + block_x INTEGER NOT NULL, block_y INTEGER NOT NULL, block_z INTEGER NOT NULL, + original_block TEXT NOT NULL, + reverted BOOLEAN NOT NULL)""".formatted(ConversionHistoryQueries.BLOCK_TABLE)); + statement.executeUpdate(""" + CREATE TABLE %s ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + location TEXT NOT NULL, + nbt TEXT NOT NULL, + reverted BOOLEAN NOT NULL)""".formatted(ConversionHistoryQueries.ENTITY_TABLE)); + } + } + + @AfterEach + void closeDatabase() throws Exception { + this.connection.close(); + Files.deleteIfExists(this.databaseFile); + } + + private void insertBlock(String world, int x, int y, int z, boolean reverted) throws Exception { + try (PreparedStatement statement = this.connection.prepareStatement( + "INSERT INTO " + ConversionHistoryQueries.BLOCK_TABLE + + " (world_name, chunk_x, chunk_z, block_x, block_y, block_z, original_block, reverted)" + + " VALUES (?,?,?,?,?,?,?,?)")) { + statement.setString(1, world); + statement.setInt(2, x >> 4); + statement.setInt(3, z >> 4); + statement.setInt(4, x); + statement.setInt(5, y); + statement.setInt(6, z); + statement.setString(7, "minecraft:note_block[instrument=harp,note=5,powered=false]"); + statement.setBoolean(8, reverted); + statement.executeUpdate(); + } + } + + private void insertEntity(String location, boolean reverted) throws Exception { + try (PreparedStatement statement = this.connection.prepareStatement( + "INSERT INTO " + ConversionHistoryQueries.ENTITY_TABLE + " (location, nbt, reverted) VALUES (?,?,?)")) { + statement.setString(1, location); + statement.setString(2, "{id:\"minecraft:item_display\"}"); + statement.setBoolean(3, reverted); + statement.executeUpdate(); + } + } + + private long activeBlockCount() throws Exception { + try (Statement statement = this.connection.createStatement(); + ResultSet rows = statement.executeQuery( + "SELECT COUNT(*) FROM " + ConversionHistoryQueries.BLOCK_TABLE + " WHERE reverted = 0")) { + rows.next(); + return rows.getLong(1); + } + } + + @Test + void streamsOnlyThePositionsOfConversionsStillInEffect() throws Exception { + insertBlock("world", 10, 64, -20, false); + insertBlock("world_nether", -3000, 31, 4000, false); + insertBlock("world", 99, 12, 99, true); + + List seen = new ArrayList<>(); + this.queries.forEachActiveBlockPosition((world, x, y, z) -> seen.add(world + " " + x + "," + y + "," + z)); + + assertEquals(List.of("world 10,64,-20", "world_nether -3000,31,4000"), seen, + "a reverted row is not part of the index"); + } + + @Test + void streamsEntityLocations() throws Exception { + insertEntity("{\"world\":\"world\",\"x\":1.5}", false); + insertEntity("{\"world\":\"world\",\"x\":2.5}", true); + + List seen = new ArrayList<>(); + this.queries.forEachActiveEntityLocation(seen::add); + + assertEquals(List.of("{\"world\":\"world\",\"x\":1.5}"), seen); + } + + @Test + void readsEveryRowExactlyOnceWhilePagingMarksThemReverted() throws Exception { + for (int i = 0; i < 250; i++) { + insertBlock("world", i, 64, 0, false); + } + + // Exactly what the restore does: read a page, revert it, ask for the next. + List restored = new ArrayList<>(); + long afterId = 0L; + while (true) { + List page = this.queries.nextActiveBlockPage(afterId, 50); + if (page.isEmpty()) { + break; + } + + List ids = new ArrayList<>(page.size()); + for (BlockHistory history : page) { + restored.add(history.getBlockX()); + ids.add(history.getId()); + afterId = history.getId(); + } + this.queries.markBlocksAsReverted(ids); + } + + assertEquals(250, restored.size(), "every row is visited"); + assertEquals(250, restored.stream().distinct().count(), "and none of them twice"); + assertEquals(0, activeBlockCount(), "the walk left nothing behind"); + } + + @Test + void keepsGoingPastAPageItCouldNotRevert() throws Exception { + for (int i = 0; i < 30; i++) { + insertBlock("world", i, 64, 0, false); + } + + // A page whose rows all fail to restore reverts nothing, so paging by id is the only thing moving the walk on. + List first = this.queries.nextActiveBlockPage(0L, 10); + assertEquals(10, first.size()); + long afterId = first.getLast().getId(); + + List second = this.queries.nextActiveBlockPage(afterId, 10); + assertEquals(10, second.size()); + assertFalse(second.stream().anyMatch(history -> history.getId() <= afterId), "no row is served twice"); + assertEquals(30, activeBlockCount(), "and nothing was reverted along the way"); + } + + @Test + void carriesEveryColumnThroughAPage() throws Exception { + insertBlock("world_the_end", -1234, 71, 5678, false); + + BlockHistory history = this.queries.nextActiveBlockPage(0L, 10).getFirst(); + assertEquals("world_the_end", history.getWorldName()); + assertEquals(-1234 >> 4, history.getChunkX()); + assertEquals(5678 >> 4, history.getChunkZ()); + assertEquals(-1234, history.getBlockX()); + assertEquals(71, history.getBlockY()); + assertEquals(5678, history.getBlockZ()); + assertEquals("minecraft:note_block[instrument=harp,note=5,powered=false]", history.getOriginalBlock()); + } + + @Test + void carriesEveryColumnThroughAnEntityPage() throws Exception { + insertEntity("{\"world\":\"world\",\"x\":1.5}", false); + + EntityHistory history = this.queries.nextActiveEntityPage(0L, 10).getFirst(); + assertEquals("{\"world\":\"world\",\"x\":1.5}", history.getLocationString()); + assertEquals("{id:\"minecraft:item_display\"}", history.getNbt()); + } + + @Test + void revertsAWholePageInOneStatement() throws Exception { + for (int i = 0; i < 5; i++) { + insertBlock("world", i, 64, 0, false); + } + + List page = this.queries.nextActiveBlockPage(0L, 5); + this.queries.markBlocksAsReverted(List.of(page.get(0).getId(), page.get(2).getId())); + + assertEquals(3, activeBlockCount(), "only the ids handed over are reverted"); + } + + @Test + void revertingNothingIsNotAnError() throws Exception { + insertBlock("world", 1, 64, 1, false); + + this.queries.markBlocksAsReverted(List.of()); + this.queries.markEntitiesAsReverted(List.of()); + + assertEquals(1, activeBlockCount()); + } + + @Test + void revertsEverythingLeftInOneSweep() throws Exception { + for (int i = 0; i < 20; i++) { + insertBlock("world", i, 64, 0, false); + } + insertEntity("{\"world\":\"world\"}", false); + + this.queries.markAllBlocksAsReverted(); + this.queries.markAllEntitiesAsReverted(); + + assertEquals(0, activeBlockCount()); + List remaining = new ArrayList<>(); + this.queries.forEachActiveEntityLocation(remaining::add); + assertTrue(remaining.isEmpty()); + } + + /** + * The whole of the startup path: rows in a real database, read through the real queries, into the real index - + * which is the only thing that shows the four columns come back out in the order the index expects them. + */ + @Test + void buildsTheConvertedBlockIndexFromWhatIsStored() throws Exception { + insertBlock("world", 10, 64, -20, false); + insertBlock("world", -1234, 71, 5678, false); + insertBlock("world_nether", 10, 64, -20, false); + insertBlock("world", 500, 12, 500, true); + + ConvertedBlockIndex index = new ConvertedBlockIndex(); + index.loadFrom(this.queries); + + assertEquals(3, index.size(), "a reverted row does not enter the index"); + assertTrue(index.contains("world", 10, 64, -20)); + assertTrue(index.contains("world", -1234, 71, 5678), "negative coordinates survive the round trip"); + assertTrue(index.contains("world_nether", 10, 64, -20), "the same position in another world is its own entry"); + assertFalse(index.contains("world", 500, 12, 500), "the reverted one is not converted any more"); + assertFalse(index.contains("world", 11, 64, -20), "a neighbour is not confused for it"); + assertFalse(index.contains("world_the_end", 10, 64, -20), "nor is an unknown world"); + } + + @Test + void forgettingABlockTakesItOutOfTheIndex() throws Exception { + insertBlock("world", 10, 64, -20, false); + + ConvertedBlockIndex index = new ConvertedBlockIndex(); + index.loadFrom(this.queries); + assertTrue(index.contains("world", 10, 64, -20)); + + index.remove("world", 10, 64, -20); + assertFalse(index.contains("world", 10, 64, -20)); + assertEquals(0, index.size()); + } + + @Test + void readsNothingFromAnEmptyTable() { + List seen = new ArrayList<>(); + this.queries.forEachActiveBlockPosition((world, x, y, z) -> seen.add(world)); + + assertTrue(seen.isEmpty()); + assertTrue(this.queries.nextActiveBlockPage(0L, 50).isEmpty()); + assertTrue(this.queries.nextActiveEntityPage(0L, 50).isEmpty()); + } +} diff --git a/README.md b/README.md index 591befc0..b9e84c59 100644 --- a/README.md +++ b/README.md @@ -325,7 +325,6 @@ CraftEngineConverter/ ├── API/ # Public API for other plugins ├── Common/ # Shared utilities and core logic ├── Hooks/ # Plugin integration modules -│ ├── BOM/ # Bill of Materials │ ├── Nexo/ # Nexo plugin integration │ ├── ItemsAdder/ # ItemsAdder plugin integration │ ├── PacketEvents/ # PacketEvents integration diff --git a/build-logic/build.gradle.kts b/build-logic/build.gradle.kts new file mode 100644 index 00000000..96833185 --- /dev/null +++ b/build-logic/build.gradle.kts @@ -0,0 +1,7 @@ +plugins { + `kotlin-dsl` +} + +kotlin { + jvmToolchain(21) +} diff --git a/build-logic/settings.gradle.kts b/build-logic/settings.gradle.kts new file mode 100644 index 00000000..116e2a02 --- /dev/null +++ b/build-logic/settings.gradle.kts @@ -0,0 +1,10 @@ +dependencyResolutionManagement { + repositoriesMode = RepositoriesMode.FAIL_ON_PROJECT_REPOS + + repositories { + gradlePluginPortal() + mavenCentral() + } +} + +rootProject.name = "build-logic" diff --git a/build-logic/src/main/kotlin/catalog.kt b/build-logic/src/main/kotlin/catalog.kt new file mode 100644 index 00000000..5e317d94 --- /dev/null +++ b/build-logic/src/main/kotlin/catalog.kt @@ -0,0 +1,24 @@ +import org.gradle.api.Project +import org.gradle.api.artifacts.MinimalExternalModuleDependency +import org.gradle.api.artifacts.VersionCatalog +import org.gradle.api.artifacts.VersionCatalogsExtension +import org.gradle.api.provider.Provider +import org.gradle.kotlin.dsl.getByType + +/** + * Type-safe `libs.*` accessors are not generated inside an included build, so convention plugins + * reach the consuming build's `gradle/libs.versions.toml` through the public + * [VersionCatalogsExtension] API instead. No reflection tricks, no `LibrariesForLibs` hack. + */ +internal val Project.libs: VersionCatalog + get() = extensions.getByType().named("libs") + +internal fun VersionCatalog.library(alias: String): Provider = + findLibrary(alias).orElseThrow { + IllegalStateException("No library '$alias' declared in gradle/libs.versions.toml") + } + +internal fun VersionCatalog.version(alias: String): String = + findVersion(alias).orElseThrow { + IllegalStateException("No version '$alias' declared in gradle/libs.versions.toml") + }.requiredVersion diff --git a/build-logic/src/main/kotlin/craftengineconverter.hook-conventions.gradle.kts b/build-logic/src/main/kotlin/craftengineconverter.hook-conventions.gradle.kts new file mode 100644 index 00000000..c2e5d3be --- /dev/null +++ b/build-logic/src/main/kotlin/craftengineconverter.hook-conventions.gradle.kts @@ -0,0 +1,11 @@ +plugins { + `java-library` + id("craftengineconverter.java-conventions") +} + +dependencies { + api(project(":Common")) + + compileOnly(libs.library("paper-api")) + compileOnly(libs.library("message-flow")) +} diff --git a/build-logic/src/main/kotlin/craftengineconverter.java-conventions.gradle.kts b/build-logic/src/main/kotlin/craftengineconverter.java-conventions.gradle.kts new file mode 100644 index 00000000..eac3412c --- /dev/null +++ b/build-logic/src/main/kotlin/craftengineconverter.java-conventions.gradle.kts @@ -0,0 +1,128 @@ +import org.gradle.api.tasks.testing.logging.TestExceptionFormat + +plugins { + `java-library` +} + +repositories { + mavenLocal { + content { includeModule("fr.robie", "yamllibrary") } + } + + mavenCentral() + + // Paper + maven("https://repo.papermc.io/repository/maven-public/") { + name = "papermc" + } + + // CraftEngine + maven("https://repo.momirealms.net/releases") { + name = "momirealmsReleases" + mavenContent { releasesOnly() } + content { includeGroup("net.momirealms") } + } + maven("https://repo.momirealms.net/snapshots") { + name = "momirealmsSnapshots" + mavenContent { snapshotsOnly() } + content { includeGroup("net.momirealms") } + } + + // PacketEvents + maven("https://repo.codemc.io/repository/maven-releases/") { + name = "codemcReleases" + mavenContent { releasesOnly() } + content { includeGroup("com.github.retrooper") } + } + + // PlaceholderAPI + maven("https://repo.extendedclip.com/releases/") { + name = "extendedclip" + mavenContent { releasesOnly() } + content { includeGroup("me.clip") } + } + + // Nexo + maven("https://repo.nexomc.com/releases") { + name = "nexo" + mavenContent { releasesOnly() } + content { + includeGroup("com.nexomc") + includeGroup("team.unnamed") + includeGroupByRegex("me\\.gabytm\\.util.*") + } + } + + // ItemsAdder + maven("https://maven.devs.beer/") { + name = "matteodev" + content { includeGroup("dev.lone") } + } + + // FoliaLib + maven("https://repo.tcoded.com/releases") { + name = "tcodedReleases" + mavenContent { releasesOnly() } + content { includeGroup("com.tcoded") } + } + + // Sarah (database library) + maven("https://repo.groupez.dev/releases") { + name = "groupez" + mavenContent { releasesOnly() } + content { includeGroupByRegex("fr\\.maxlego08.*") } + } + + // MessageFlow, paper-dispatch + maven("https://jitpack.io") { + name = "jitpack" + content { includeGroupByRegex("com\\.github\\.1robie.*") } + metadataSources { artifact() } + } + + maven("https://central.sonatype.com/repository/maven-snapshots/") { + name = "centralSnapshots" + mavenContent { snapshotsOnly() } + } +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(libs.version("java").toInt()) + } +} + +configurations { + testImplementation { + extendsFrom(compileOnly.get()) + } +} + +tasks.withType().configureEach { + options.encoding = "UTF-8" + options.release = libs.version("java").toInt() +} + +tasks.withType().configureEach { + (options as StandardJavadocDocletOptions).encoding = "UTF-8" +} + +tasks.withType().configureEach { + filteringCharset = "UTF-8" +} + +tasks.withType().configureEach { + useJUnitPlatform() + testLogging { + events("failed") + exceptionFormat = TestExceptionFormat.FULL + showStackTraces = true + } +} + +tasks.withType().configureEach { + isPreserveFileTimestamps = false + isReproducibleFileOrder = true + dirPermissions { unix("rwxr-xr-x") } + filePermissions { unix("rw-r--r--") } +} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..57379c63 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,17 @@ +// +// Root build script. +// +// Deliberately almost empty: there is no `allprojects {}` / `subprojects {}` block here. +// Cross-project configuration is what makes Gradle builds slow and un-cacheable, so shared +// setup lives in the convention plugins under `build-logic/` and each module applies the one +// it needs. `group` and `version` come from gradle.properties and are inherited by every project +// automatically, which is what the Maven section used to do. +// + +plugins { + base +} + +// Maven's clean package. `clean` is not part of it because Gradle is +// incremental - run `./gradlew clean build` explicitly if you really want a from-scratch build. +defaultTasks("build") diff --git a/docs/.gitbook/vars.yaml b/docs/.gitbook/vars.yaml deleted file mode 100644 index ccf016e8..00000000 --- a/docs/.gitbook/vars.yaml +++ /dev/null @@ -1,4 +0,0 @@ -PLUGIN_VERSION: "0.0.1" -CRAFTENGINE_VERSION: "0.0.65.0" -CODE_BLOCK_TRIPLEBACKTICKS: "```" -SINGLE_BACKTICK: "`" \ No newline at end of file diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index fb948cab..00000000 --- a/docs/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# 📖 Introduction - -Welcome to the complete documentation for **CraftEngineConverter**, the ultimate plugin to convert configuration files from other plugins into the CraftEngine format. - -## ⭐ Key Features - -### Conversion Support - -- **Multi-Plugin Compatibility**: Seamlessly convert configuration files from a variety of popular plugins into the CraftEngine format. Currently supporting **Nexo** and **ItemsAdder**, with more to come soon! -- **Automated Process**: Simplify your workflow with automated conversion processes that save you time and effort. - -### ⚡ Performance & Reliability - -- **Folia Compatible**: Fully supports Folia's regionized multithreading for maximum performance and stability. -- **Multi-Threaded Pack Conversion**: Leverage multi-threading capabilities to speed up the conversion process, ensuring efficient handling of large configuration files. - -## 🗺️ Quick Navigation - -### 🚀 Getting Started - -* [📋 Requirements](getting-started/requirements.md) -* [⚡ Quick Start](getting-started/quick-start.md) - Get running in 5 minutes! - -### ⚙️ Configuration - -* [🔧 Main Configuration](configuration/main-config.md) - -### 💻 Commands & Permissions - -* [⌨️ Commands](commands-permissions/commands.md) -* [🔐 Permissions](commands-permissions/permissions.md) - -### 🆘 Support - -* [❓ FAQ & Troubleshooting](troubleshooting/faq.md) -* [🐛 Common Issues](troubleshooting/common-issues.md) -* [📞 Contact & Support](support/contact.md) - -## 📄 License - -This project is licensed under the GNU License. See the [LICENSE](../LICENSE) file for details. - -*** - -**Version :** space.vars.PLUGIN_VERSION \ No newline at end of file diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md deleted file mode 100644 index c00290b2..00000000 --- a/docs/SUMMARY.md +++ /dev/null @@ -1,27 +0,0 @@ -# Table of contents - -## Getting Started - -* [📖 Introduction](README.md) -* [📋 Requirements](getting-started/requirements.md) -* [⚡ Quick Start](getting-started/quick-start.md) - -## Configuration - -* [🔧 Main Configuration](configuration/main-config.md) -* [Nexo Converter](converters/nexo-converter.md) -* [ItemsAdder Converter](converters/itemsadder-converter.md) - -## Commands & Permissions - -* [⌨️ Commands](commands-permissions/commands.md) -* [🔐 Permissions](commands-permissions/permissions.md) - -## Troubleshooting & Support - -* [❓ FAQ](troubleshooting/faq.md) -* [🐛 Common Issues](troubleshooting/common-issues.md) - -## Additional Resources - -* [📞 Contact & Support](support/contact.md) \ No newline at end of file diff --git a/docs/commands-permissions/commands.md b/docs/commands-permissions/commands.md deleted file mode 100644 index a80dad77..00000000 --- a/docs/commands-permissions/commands.md +++ /dev/null @@ -1,45 +0,0 @@ -# 📝 Commands Reference - -This page provides a comprehensive reference for all commands available in **CraftEngineConverter**. Each command is detailed with its syntax, description, and required permissions. - -## Main Command - -### `/craftengineconverter` or `/cec` -- **Description**: The primary command for accessing CraftEngineConverter functionalities. -- **Permissions**: `craftengineconverter.command.use` - -#### Subcommands - -1. `reload` - - **Description**: Reloads the plugin configuration without restarting the server. - - **Usage**: `/craftengineconverter reload` or `/cec reload` - - **Permissions**: `craftengineconverter.command.reload` - -2. `convert [] [] [--dryrun] [--threads=]` - - **Description**: Initiates the conversion process for supported plugin configuration files into the CraftEngine format. - - **Usage**: - Available plugin names: - - `nexo` - - `itemsadder` - Available types: - - `ALL` Default - Converts all supported configuration files. - - `ITEMS` - Converts only item configurations. - - `EMOJIS` - Converts only emoji configurations. - - `IMAGES` - Converts only image configurations. - - `LANGUAGES` - Converts only language files. - - `SOUNDS` - Converts only sound configurations. - - `PACKS` - Converts only resource packs. - Additional flags: - - `--dryrun`: Simulates the conversion process without making any changes. - - `--threads=`: Specifies the number of threads to use for multi-threaded pack conversion. Default is 1. - - `--force`: Stops any ongoing conversion process and immediately starts a new one. Use this to override and restart conversions that are currently running. - - **Usage Example**: `/craftengineconverter convert nexo ITEMS --dryrun --threads=4` or `/cec convert nexo ITEMS --dryrun --threads=4` - - **Permissions**: `craftengineconverter.command.convert` - -3. `clearfilescache` - - **Description**: Clears the internal cache of files used during the conversion process. - - **Usage**: - Aditional flags: - - `--all`: Clears all cached files. - - **Usage Example**: `/craftengineconverter clearfilescache --all` or `/cec clearfilescache`, clears only files outdated (modified since last access). - - **Permissions**: `craftengineconverter.command.clearfilescache` \ No newline at end of file diff --git a/docs/commands-permissions/permissions.md b/docs/commands-permissions/permissions.md deleted file mode 100644 index c623da7f..00000000 --- a/docs/commands-permissions/permissions.md +++ /dev/null @@ -1,20 +0,0 @@ -# 🔑 Permissions Reference - -This page provides a comprehensive reference for all permissions available in **CraftEngineConverter**. Each permission is detailed with its description and the commands it is associated with. - -## Available Permissions - -1. `craftengineconverter.command.use` - - **Description**: Grants access to the main CraftEngineConverter command. - - **Associated Command**: `/craftengineconverter` or `/cec` - -2. `craftengineconverter.command.reload` - - **Description**: Allows the user to reload the plugin configuration without restarting the server. - - **Associated Command**: `/craftengineconverter reload` or `/cec reload` - -3. `craftengineconverter.command.convert` - - **Description**: Permits the user to initiate the conversion process for supported plugin configuration files into the CraftEngine format. - - **Associated Command**: `/craftengineconverter convert [] [] [--dryrun] [--threads=]` - ---- -For more information on how to use these permissions, please refer to the [📝 Commands Reference](commands.md) page. \ No newline at end of file diff --git a/docs/configuration/main-config.md b/docs/configuration/main-config.md deleted file mode 100644 index cd5dec6d..00000000 --- a/docs/configuration/main-config.md +++ /dev/null @@ -1,227 +0,0 @@ -# 🛠️ Main Config (`config.yml`) Guide - -This guide provides a detailed overview of the main configuration file (`config.yml`) for **CraftEngineConverter**. Here, you'll find explanations for each configurable option, allowing you to customize the plugin to suit your server's needs. - -## 📁 Configuration File Location -The `config.yml` file is located in the `plugins/CraftEngineConverter/` directory of your Minecraft server. - -## ⚙️ Configuration Options - -```yaml -enable-debug: false - -# Language settings (available languages: EN, FR) -language: "EN" - -# Each block has a usage limit for a block-state. This setting controls how those limits are enforced when multiple plugins are installed: -# - "plugin": Each plugin gets its own separate limit. Different plugins can use the same block-states independently without affecting each other. -# - "global": All plugins share the same limit. Once any plugin uses up the limit for a block-state, other plugins cannot use it (prevents conflicts and duplicates). -# -# Choose "global" to prevent multiple plugins from using the same block-states; otherwise choose "plugin" to allow each plugin its own allocation. -# -# Note: -# - Block-states can have parent-child relationships. -# - A parent's limit automatically includes the limits of all its children. -# For example, if "note-block" (a child of "solid") has a limit of 10, then "solid" will have its own limit plus 10. -# -# Available block-state groups and their capacity: -# - SOLID (1338 available): Top-level group -# - MUSHROOM (189 available): Mushroom block variants -# - RED_MUSHROOM_BLOCK (63 available) -# - BROWN_MUSHROOM_BLOCK (63 available) -# - MUSHROOM_STEM (63 available) -# - NOTE_BLOCK (1149 available) -# -# - TRIPWIRE (126 available): Tripwire variants -# - LOWER_TRIPWIRE (63 available) -# - HIGHER_TRIPWIRE (63 available) -# -# - TINTABLE_LEAVES (65 available) -# - WATERLOGGED_TINTABLE_LEAVES (65 available) -# -# - NON_TINTABLE_LEAVES (234 available) -# - WATERLOGGED_NON_TINTABLE_LEAVES (234 available) -# -# - LEAVES (143 available) -# - WATERLOGGED_LEAVES (143 available) -# -# - Independent blocks (not part of any shared group): -# - CACTUS (15), SUGAR_CANE (15) -# - WEEPING_VINE (50), TWISTING_VINE (50), CAVE_VINE (100) -# - SAPLING (8), KELP (25), CHORUS (0) -block-state-limit: - type: PLUGIN - tintable-leaves: - start-limit: 0 - waterlogged-tintable-leaves: - start-limit: 0 - non-tintable-leaves: - start-limit: 0 - waterlogged-non-tintable-leaves: - start-limit: 0 - leaves: - start-limit: 0 - waterlogged-leaves: - start-limit: 0 - lower-tripwire: - start-limit: 0 - higher-tripwire: - start-limit: 0 - tripwire: - start-limit: 0 - mushroom-stem: - start-limit: 0 - red-mushroom-block: - start-limit: 0 - brown-mushroom-block: - start-limit: 0 - mushroom: - start-limit: 0 - note-block: - start-limit: 0 - solid: - start-limit: 0 - cactus: - start-limit: 0 - sugar-cane: - start-limit: 0 - weeping-vine: - start-limit: 0 - twisting-vine: - start-limit: 0 - cave-vine: - start-limit: 0 - sapling: - start-limit: 0 - kelp: - start-limit: 0 - chorus: - start-limit: 0 - -# Auto-convert items on plugin enable -auto-convert-on-startup: false - -# Select which converters and options should be used on startup -# If empty, all options for all converters will be used -# Available options: ITEMS, EMOJIS, IMAGES, LANGUAGES, SOUNDS, RECIPES, PACKS, ALL -# auto-convert-on-startup-types: -# nexo: -# - ITEMS -# - EMOJIS -# itemsadder: -# - ITEMS -# - IMAGES - -# Default material for items -default-material: "PAPER" - -# Disable italic formatting in item lore by adding tag -disable-default-italic: true - -# Armor converter settings -# Available types: COMPONENT, TRIM , BOTH -armor-converter-type: "COMPONENT" - -blacklisted-paths: - - "shaders/*" # Blacklist all files in shaders folder - # - "shaders/rendertype_text.fsh" # Example of how to blacklist a specific file - # - "minecraft:textures/shaders/" # Example of how to blacklist the entire shaders namespace - -formatting: - packet-events: true - boss-bar: true - action-bar: true - plugin-message: true - title: true - menu-title: true - -tag: - nexo-glyph: # - enabled: true - itemsadder-image: # :old_name: - enabled: true - placeholder-api: # or - enabled: true - -allow-block-conversion-propagation: true # When enabled, if a block is converted, the surrounding blocks will also be checked for conversion -max-block-conversion-propagation-depth: 64 # Maximum number of blocks to propagate conversion in one block interaction event - -nexo: - enable-hook: true # Enable Nexo integration if Nexo is installed - # Require this permission to allow Nexo block interaction conversion : craftengineconverter.nexo.block.interact.conversion - enable-block-interaction-conversion: true # When enabled, when you interact with a nexo block, it will convert the nexo block to their CE equivalent - # Require this permission to allow Nexo furniture interaction conversion : craftengineconverter.nexo.furniture.interact.conversion - enable-furniture-interaction-conversion: true # When enabled, when you interact with a nexo furniture, it will convert the furniture to their CE equivalent - enable-chunk-load-conversion: false # When enabled, when a chunk is loaded, it will convert all Nexo blocks and furnitures to CE equivalents - -itemsadder: - enable-hook: true # Enable ItemsAdder integration if ItemsAdder is installed - img-placeholderapi-support: true # Register a placeholder %img:old_name% to get the new image - # Require this permission to allow ItemsAdder block interaction conversion : craftengineconverter.itemsadder.block.interact.conversion - enable-block-interaction-conversion: true # When enabled, when you interact with an ItemsAdder block, it will convert the block to their CE equivalent - # Require this permission to allow ItemsAdder furniture interaction conversion : craftengineconverter.itemsadder.furniture.interact.conversion - enable-furniture-interaction-conversion: true # When enabled, when you interact with an ItemsAdder furniture, it will convert the furniture to their CE equivalent - enable-chunk-load-conversion: false # When enabled, when a chunk is loaded, it will convert all ItemsAdder blocks and furnitures to CE equivalents - blacklisted-content-folders-namespaces: [] # List of content folders or namespaces to ignore during conversion - -world-converter: - enable: false # Enable world conversion feature (Requires server restart to take effect) - nexo: - enable: true # Enable Nexo world conversion without nexo plugin installed ! Just explore and let the lugin convert Nexo blocks and furnitures to CE equivalents - itemsadder: - enable: true # Enable ItemsAdder world conversion without ItemsAdder plugin installed ! Just explore and let the lugin convert ItemsAdder blocks and furnitures to CE equivalents - progress-bar-options: - progress-color: GREEN - empty-color: DARK_GRAY - percent-color: YELLOW - progress-char: █ - empty-char: ░ - bar-width: 50 - -# Available colors: -# BLACK, DARK_BLUE, DARK_GREEN, DARK_AQUA, DARK_RED, DARK_PURPLE, -# GOLD, GRAY, DARK_GRAY, BLUE, GREEN, AQUA, RED, LIGHT_PURPLE, YELLOW, WHITE -progress-bar-options: - items: - progress-color: GREEN - empty-color: DARK_GRAY - percent-color: YELLOW - progress-char: █ - empty-char: ░ - bar-width: 50 - emojis: - progress-color: AQUA - empty-color: DARK_GRAY - percent-color: YELLOW - progress-char: █ - empty-char: ░ - bar-width: 50 - images: - progress-color: GOLD - empty-color: DARK_GRAY - percent-color: YELLOW - progress-char: █ - empty-char: ░ - bar-width: 50 - languages: - progress-color: BLUE - empty-color: DARK_GRAY - percent-color: YELLOW - progress-char: █ - empty-char: ░ - bar-width: 50 - sounds: - progress-color: LIGHT_PURPLE - empty-color: DARK_GRAY - percent-color: YELLOW - progress-char: █ - empty-char: ░ - bar-width: 50 - packs: - progress-color: RED - empty-color: DARK_GRAY - percent-color: YELLOW - progress-char: █ - empty-char: ░ - bar-width: 50 -``` \ No newline at end of file diff --git a/docs/converters/itemsadder-converter.md b/docs/converters/itemsadder-converter.md deleted file mode 100644 index b533fb50..00000000 --- a/docs/converters/itemsadder-converter.md +++ /dev/null @@ -1,48 +0,0 @@ -# ItemsAdder Converter - -This section provides instructions on how to use the **ItemsAdder Converter** feature of the **CraftEngineConverter** plugin to convert configuration files from the **ItemsAdder** plugin into the **CraftEngine** format. - -## 📋 Prerequisites - -Before proceeding with the conversion, ensure that you have the following prerequisites met: -- **CraftEngineConverter** plugin installed on your Minecraft server. Refer to the [🚀 Quick Start](../getting-started/quick-start.md) guide for installation instructions. -- **ItemsAdder** plugin installed on your Minecraft server (Recommended to convert existing blocks/furniture) -- **CraftEngine** plugin installed on your Minecraft server. - -If you have **ItemsAdder** installed, it is recommended to back up your server before performing any conversions and go to the config of ItemsAdder and disable the option to generate the resouce pack on server start to avoid conflicts with the resource pack generated by CraftEngine. - -## Command - -To convert ItemsAdder configuration files, use the following command in your Minecraft server console or in-game chat (if you have the necessary permissions): - -```bash -/ceconverter convert itemsadder -``` - -This command will initiate the conversion process for ItemsAdder configuration files. - -## Converted Files Location - -After the conversion is complete, the converted files will be saved in the following directory within your server: `plugins/CraftEngineConverter/converted/ItemsAdder/` - -## Upload Converted Files to CraftEngine - -For this you need to go to `plugins/CraftEngine/converted/ItemsAdder/` and copy all the files from there to your plugin's folder. -Or you can go to `plugins/CraftEngineConverter/converted/ItemsAdder/CraftEngine/resources/craftengineconverter` and copy the `configuration` and `resourcepack` folders to your `plugins/CraftEngine/resources/xxx` folder where `xxx` is a name you choose to organize your CraftEngine resources. - -## Usage - -If you want to convert in one click ItemsAdder blocks or furniture when you interact with them in-game, make sure to enable the following options in the `config.yml` file of **CraftEngineConverter**: -```yaml -itemsadder: - enable-hook: true # Enable ItemsAdder integration if ItemsAdder is installed - # Require this permission to allow ItemsAdder block interaction conversion : craftengineconverter.itemsadder.block.interact.conversion - enable-block-interaction-conversion: true # When enabled, when you interact with an ItemsAdder block, it will convert the block to their CE equivalent - # Require this permission to allow ItemsAdder furniture interaction conversion : craftengineconverter.itemsadder.furniture.interact.conversion - enable-furniture-interaction-conversion: true # When enabled, when you interact with an ItemsAdder furniture, it will convert the furniture to their CE equivalent -``` -Make sure that **ItemsAdder** plugin is installed on your server for these features to work. - -## Additional Information - -For more details on configuring **CraftEngineConverter**, please refer to the [🔧 Main Configuration](../configuration/main-config.md) page. \ No newline at end of file diff --git a/docs/converters/nexo-converter.md b/docs/converters/nexo-converter.md deleted file mode 100644 index afa2dacb..00000000 --- a/docs/converters/nexo-converter.md +++ /dev/null @@ -1,48 +0,0 @@ -# Nexo Converter - -This section provides instructions on how to convert configuration files from the **Nexo** plugin into the **CraftEngine** format using the **CraftEngineConverter** plugin. - -## 📋 Prerequisites - -Before proceeding with the conversion, ensure that you have the following prerequisites met: -- **CraftEngineConverter** plugin installed on your Minecraft server. Refer to the [🚀 Quick Start](../getting-started/quick-start.md) guide for installation instructions. -- **Nexo** plugin installed on your Minecraft server (Recommended to convert existing blocks/furniture). -- **CraftEngine** plugin installed on your Minecraft server. - -## Command - -To convert Nexo configuration files, use the following command in your Minecraft server console or in-game chat (if you have the necessary permissions): - -```bash -/ceconverter convert nexo -``` - -This command will initiate the conversion process for Nexo configuration files. - -## Converted Files Location - -After the conversion is complete, the converted files will be saved in the following directory within your server:`plugins/CraftEngineConverter/converted/Nexo/` - -## Upload Converted Files to CraftEngine - -For this you need to go to `plugins/CraftEngine/converted/Nexo/` and copy all the files from there to your plugin's folder. -Or you can go to `plugins/CraftEngineConverter/converted/Nexo/CraftEngine/resources/craftengineconverter` and copy the `configuration` and `resourcepack` folders to your `plugins/CraftEngine/resources/xxx` folder where `xxx` is a name you choose to organize your CraftEngine resources. - -## Usage - -If you want to convert in one click nexo blocks or furniture when you interact with them in-game, make sure to enable the following options in the `config.yml` file of **CraftEngineConverter**: - -```yaml -nexo: - enable-hook: true # Enable Nexo integration if Nexo is installed - # Require this permission to allow Nexo block interaction conversion : craftengineconverter.nexo.block.interact.conversion - enable-block-interaction-conversion: true # When enabled, when you interact with a nexo block, it will convert the nexo block to their CE equivalent - # Require this permission to allow Nexo furniture interaction conversion : craftengineconverter.nexo.furniture.interact.conversion - enable-furniture-interaction-conversion: true # When enabled, when you interact with a nexo furniture, it will convert the furniture to their CE equivalent -``` - -Make sure that **Nexo** plugin is installed on your server for these features to work. - -## Additional Information - -For more details on configuring **CraftEngineConverter**, please refer to the [🔧 Main Configuration](../configuration/main-config.md) page. \ No newline at end of file diff --git a/docs/getting-started/quick-start.md b/docs/getting-started/quick-start.md deleted file mode 100644 index 434b0af3..00000000 --- a/docs/getting-started/quick-start.md +++ /dev/null @@ -1,45 +0,0 @@ -# 🚀 Quick Start - -This guide will help you get **CraftEngineConverter** up and running in just a few minutes. - -## 📋 Prerequisites - -Please check the [📋 Requirements](requirements.md) page to ensure your server meets all necessary requirements. - -## 📥 Download - -Download the latest version of **CraftEngineConverter** from one of the following sources: -- [Modrinth](https://modrinth.com/plugin/craftengineconverter) :x: -- [Polymart](https://polymart.org/product/XXXX/craftengineconverter) :x: -- [SpigotMC](https://www.spigotmc.org/resources/craftengineconverter.XXXX/) :x: -- [GitHub Releases](https://github.com/1robie/CraftEngineConverter/releases) :white_check_mark: - -:x: Note: The plugin is currently only available on GitHub Releases. Other platforms will be supported in future updates. - -## 🔧 Installation - -### Step 1: Install Plugins - -1. **Stop your Minecraft server** if it is running. -2. **Download the CraftEngineConverter.jar** file from the link above. -3. **Place the space.vars.SINGLE_BACKTICKCraftEngineConverter.space.vars.PLUGIN_VERSION.jarspace.vars.SINGLE_BACKTICK file** into your server's `plugins` directory. -4. **Ensure that the required dependency, CraftEngine**, is also installed in the `plugins` directory. -5. **Start your Minecraft server.** - -### Step 2: Verification - -After starting your server, check the console logs for messages indicating that **CraftEngineConverter** has been enabled successfully. You should see output similar to the following: -``` bash -[xx:xx:xx INFO]: [CraftEngineConverter v0.0.1] Enabling plugin ... -[xx:xx:xx INFO]: [CraftEngineConverter v0.0.1] Loading 1 commands -[xx:xx:xx INFO]: [CraftEngineConverter v0.0.1] Auto-conversion is enabled, starting conversion... -[xx:xx:xx INFO]: [CraftEngineConverter v0.0.1] Plugin enabled ! -``` - -If you see any errors, please refer to the [🐛 Common Issues](../troubleshooting/common-issues.md) page for troubleshooting tips. - -## 🎉 You're All Set! - -You have successfully installed and set up **CraftEngineConverter**! You can now start converting configuration files from supported plugins into the CraftEngine format. -All configuration files will be generated in the `plugins/CraftEngineConverter/converted/` directory. See [Nexo Converter](../converters/nexo-converter.md) or [ItemsAdder Converter](../converters/itemsadder-converter.md) for specific plugin conversion instructions. -For more information on how to use the plugin, please refer to the [🔧 Main Configuration](../configuration/main-config.md) and [⌨️ Commands](../commands-permissions/commands.md) pages. \ No newline at end of file diff --git a/docs/getting-started/requirements.md b/docs/getting-started/requirements.md deleted file mode 100644 index a04b94eb..00000000 --- a/docs/getting-started/requirements.md +++ /dev/null @@ -1,40 +0,0 @@ -# 📋 Requirements - -To ensure a smooth experience with **CraftEngineConverter**, please make sure your server meets the following requirements: - -## 🖥️ Server Requirements - -### Minecraft Server Software -CraftEngineConverter is compatible with the following server software: - -#### ✅ Fully Supported -- **Paper** - **Recommended** for best performance -- **Spigot** -- **Purpur** - -### Java Version -- **Java 21** required -- Verify your Java version with: `java -version` - -## 🔌 Required Dependencies - -These plugins **must** be installed on your server for CraftEngineConverter to function properly: - -### CraftEngine (Required) -- **Minimum Version**: space.vars.CRAFTENGINE_VERSION -- **Download**: [Modrinth](https://modrinth.com/plugin/craftengine) [Polymart](https://polymart.org/product/7624/craftengine) [SpigotMC - Free Version](https://www.spigotmc.org/resources/craftengine-free-version.128871/) - -## ⚙️ Optional Dependencies - -The following plugins are **optional** but enhance the functionality of CraftEngineConverter: - -### PlaceholderAPI (Optional) -- **Minimum Version**: 2.11.7 -- **Download**: [SpigotMC](https://www.spigotmc.org/resources/placeholderapi.6245/) - -### PacketEvents (Optional) -- **Minimum Version**: 2.11.0 -- **Download**: [Modrinth](https://modrinth.com/plugin/packetevents) - ---- -Ensure your server meets these requirements to take full advantage of CraftEngineConverter's features! \ No newline at end of file diff --git a/docs/support/contact.md b/docs/support/contact.md deleted file mode 100644 index ae8536c4..00000000 --- a/docs/support/contact.md +++ /dev/null @@ -1,18 +0,0 @@ -# 📞 Contact & Support - -If you need help, have questions, or want to report a bug or security issue, please use one of the following methods: - -## 💬 Discord (Preferred) -- **Contact:** kyubi8319 -- Please send a clear and detailed message. If your message is unclear or looks like spam, it may be ignored. -- **Security:** If you discover a critical vulnerability, do **not** open a public issue. Contact me directly and privately on Discord. - -## 🐛 GitHub Issues -- For general bugs and feature requests, you can open an issue on the [GitHub repository](https://github.com/1robie/CraftEngineConverter/issues). -- Please do **not** report security vulnerabilities publicly. - -## 📚 Documentation -- Check the [FAQ & Troubleshooting](../troubleshooting/faq.md) and [Common Issues](../troubleshooting/common-issues.md) pages for quick help. - ---- -Thank you for using CraftEngineConverter! \ No newline at end of file diff --git a/docs/troubleshooting/faq.md b/docs/troubleshooting/faq.md deleted file mode 100644 index e69de29b..00000000 diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 00000000..bac98aac --- /dev/null +++ b/gradle.properties @@ -0,0 +1,47 @@ +group = fr.robie.craftengineconverter +version = 0.0.3-SNAPSHOT + + +plugin.author = 1robie +plugin.description = A plugin to convert configurations to CraftEngine format +plugin.apiVersion = 1.21 +plugin.mainClass = fr.robie.craftengineconverter.CraftEngineConverter +plugin.bootstrapper = fr.robie.craftengineconverter.CraftEngineConverterBootstrapper +plugin.loader = fr.robie.craftengineconverter.CraftEngineConverterLoader + +runServer.jvmArgs = -Xms2G -Xmx2G -Dfile.encoding=UTF-8 + +# --- HotSwap / DCEVM ------------------------------------------------------------------------------ +# Nothing here is bundled - see DEVELOPMENT.md for the three levels of HotSwap. +# +# Level 1 (method bodies) needs none of this: just Debug 'runServer' and press Ctrl+F9. +# +# Level 2 (add/remove methods and fields) needs a JVM with enhanced class redefinition. IntelliJ's +# bundled JetBrains Runtime is one. All of this is per-user and never committed - put it in your own +# ~/.gradle/gradle.properties (outside the repo): +# org.gradle.java.installations.paths = /jbr +# runServer.javaVersion = 25 +# runServer.javaVendor = JetBrains +# runServer.jvmArgsExtra = -XX:+AllowEnhancedClassRedefinition +# `runServer.jvmArgs` is committed, so JBR-only flags (which crash stock JVMs) go in the per-user +# `runServer.jvmArgsExtra` instead, which the build appends. +# +# Level 3 (HotswapAgent) is optional and rarely worth it for a Paper plugin. The agent path is +# per-user and never committed - put these two in your own ~/.gradle/gradle.properties (outside the +# repo) and the build attaches the agent to the server JVM automatically: +# runServer.javaAgent = C:/Users//.hotswap/hotswap-agent.jar +# runServer.javaAgentArgs = disablePlugin=Log4j2 +# `disablePlugin` is required: HotswapAgent's Log4j2 plugin cannot instrument Paper's log4j (Paper +# loads it in a separate URLClassLoader) and floods the console with CannotCompileException stack +# traces. + +#################################################################################################### +# Gradle +#################################################################################################### +org.gradle.jvmargs = -Xmx3G -XX:MaxMetaspaceSize=1G -Dfile.encoding=UTF-8 +org.gradle.parallel = true +org.gradle.caching = true + +# Verified on this project against `build` and `runServer`, including the paperweight-userdev +# setup pipeline. Turn it off with `--no-configuration-cache` if a plugin upgrade regresses it. +org.gradle.configuration-cache = true diff --git a/gradle/gradle-daemon-jvm.properties b/gradle/gradle-daemon-jvm.properties new file mode 100644 index 00000000..004a0fae --- /dev/null +++ b/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,12 @@ +#This file is generated by updateDaemonJvm +toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/bc7c5a81f3d680de7b32b5671550e6fa/redirect +toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/06a33bd735fe2a3eaad523052759de91/redirect +toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/bc7c5a81f3d680de7b32b5671550e6fa/redirect +toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/06a33bd735fe2a3eaad523052759de91/redirect +toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1963e5739fd691761c528d9c9417be8d/redirect +toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/0c90b78f3825f6e979da37db7c92ebaa/redirect +toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/bc7c5a81f3d680de7b32b5671550e6fa/redirect +toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/06a33bd735fe2a3eaad523052759de91/redirect +toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/476d3c08f4989328dee56d22e202d98d/redirect +toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/4170a8049ea45591acc1d566ebcb3193/redirect +toolchainVersion=21 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 00000000..87d46403 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,74 @@ +# +# Central version catalog. +# +# This replaces the / block of the old root pom.xml. +# Every version used by the build lives here and nowhere else. +# +[versions] +# Toolchain / language level (was maven.compiler.release) +java = "21" + +# Paper. `paper` is used both for `paper-api` (non-paperweight modules) and for the +# paperweight dev-bundle (the :Plugin module). Keep the two in sync. +paper = "1.21.11-R0.1-SNAPSHOT" +# Plain Minecraft version, used by the `runServer` development server. +minecraft = "1.21.11" + +craftengine = "26.10" + +adventure = "5.2.0" +bstats = "3.2.1" +folialib = "0.5.2" +itemsadder = "4.0.18-beta-10" +junit = "6.1.3" +messageflow = "1.1.2" +nexo = "1.29.1" +packetevents = "2.14.0" +paperdispatch = "1.1.0" +placeholderapi = "2.12.3" +reflections = "0.10.2" +sarah = "1.27" +snakeyaml = "2.7" +yamllibrary = "-SNAPSHOT" + +# Build plugins +paperweight = "2.0.0-beta.21" +runPaper = "3.1.0" +shadow = "9.6.1" + +[libraries] +# --- Paper ------------------------------------------------------------------- +paper-api = { module = "io.papermc.paper:paper-api", version.ref = "paper" } + +# --- CraftEngine ------------------------------------------------------------- +craftengine-core = { module = "net.momirealms:craft-engine-core", version.ref = "craftengine" } +craftengine-bukkit = { module = "net.momirealms:craft-engine-bukkit", version.ref = "craftengine" } + +# --- Shaded at build time (relocated into the final jar) ---------------------- +bstats-base = { module = "org.bstats:bstats-base", version.ref = "bstats" } +bstats-bukkit = { module = "org.bstats:bstats-bukkit", version.ref = "bstats" } +folialib = { module = "com.tcoded:FoliaLib", version.ref = "folialib" } +message-flow = { module = "com.github.1robie.MessageFlow:message-flow", version.ref = "messageflow" } +paper-dispatch = { module = "com.github.1robie.paper-dispatch:paper-dispatch", version.ref = "paperdispatch" } +sarah = { module = "fr.maxlego08.sarah:sarah", version.ref = "sarah" } +yamllibrary = { module = "com.github.1robie.YamlLibrary:yamllibrary-paper", version.ref = "yamllibrary" } +yamllibrary-core = { module = "com.github.1robie.YamlLibrary:yamllibrary-core", version.ref = "yamllibrary" } + +# --- Provided by the server / by CraftEngine at runtime ---------------------- +adventure-api = { module = "net.kyori:adventure-api", version.ref = "adventure" } +itemsadder = { group = "beer.devs", name = "itemsadder-api", version.ref = "itemsadder" } +nexo = { module = "com.nexomc:nexo", version.ref = "nexo" } +packetevents-spigot = { module = "com.github.retrooper:packetevents-spigot", version.ref = "packetevents" } +placeholderapi = { module = "me.clip:placeholderapi", version.ref = "placeholderapi" } +reflections = { module = "org.reflections:reflections", version.ref = "reflections" } +snakeyaml = { module = "org.yaml:snakeyaml", version.ref = "snakeyaml" } + +# --- Test -------------------------------------------------------------------- +junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" } +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" } +junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher" } + +[plugins] +paperweight-userdev = { id = "io.papermc.paperweight.userdev", version.ref = "paperweight" } +run-paper = { id = "xyz.jpenilla.run-paper", version.ref = "runPaper" } +shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..b1b8ef56 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..9ed96af2 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionSha256Sum=0b00b0ffe07c4d4789c12d4935a44a7057d55774b7540bd4a3f76f336deb177a diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..203529cb --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..7e60b729 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/pom.xml b/pom.xml deleted file mode 100644 index d364b66e..00000000 --- a/pom.xml +++ /dev/null @@ -1,317 +0,0 @@ - - - 4.0.0 - - fr.robie.craftengineconverter - CraftEngineConverter - 0.0.2 - pom - - CraftEngineConverter - - API - Common - Hooks - Plugin - - - - - dev-build - - -Dev - - - - - - UTF-8 - UTF-8 - UTF-8 - 21 - 21 - 21 - - 1robie - A plugin to convert configurations to CraftEngine format - 1.21 - fr.robie.craftengineconverter.CraftEngineConverter - - ${project.version}${dev.suffix} - - - 26.5-SNAPSHOT - - - - - - - fr.robie.craftengineconverter - API - ${project.version} - - - fr.robie.craftengineconverter - Common - ${project.version} - - - fr.robie.craftengineconverter - BOM - ${project.version} - - - - com.github.1robie.MessageFlow - message-flow - 1.1.2 - compile - - - - - io.papermc.paper - paper-api - 1.21.11-R0.1-SNAPSHOT - provided - - - - - org.bstats - bstats-bukkit - 3.2.1 - - - - - org.bstats - bstats-base - 3.2.1 - - - - - com.github.retrooper - packetevents-spigot - 2.11.2 - provided - - - - - net.momirealms - craft-engine-core - ${dependency.craftengine.version} - provided - - - net.momirealms - craft-engine-bukkit - ${dependency.craftengine.version} - provided - - - - - me.clip - placeholderapi - 2.12.2 - provided - - - - - com.nexomc - nexo - 1.24.0 - - - dev.triumphteam - triumph-gui - - - provided - - - - - dev.lone - api-itemsadder - 4.0.10 - provided - - - - - net.kyori - adventure-api - 4.26.1 - provided - - - - - fr.maxlego08.sarah - sarah - 1.23 - compile - - - - - com.tcoded - FoliaLib - 0.5.1 - compile - - - - - org.junit.jupiter - junit-jupiter - 6.1.3 - test - - - - - org.yaml - snakeyaml - 2.6 - provided - - - - - - clean package - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.15.0 - - ${maven.compiler.source} - ${maven.compiler.target} - ${maven.compiler.release} - ${project.build.sourceEncoding} - - - - - org.apache.maven.plugins - maven-resources-plugin - 3.5.0 - - ${project.build.sourceEncoding} - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.5.0 - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.5.5 - - - - org.apache.maven.plugins - maven-install-plugin - 3.1.4 - - - - org.apache.maven.plugins - maven-shade-plugin - 3.6.2 - - - - - - - src/main/resources - true - - - - - - - - papermc-repo - https://repo.papermc.io/repository/maven-public/ - - - - - tcoded-releases - https://repo.tcoded.com/releases - - - - - placeholderapi - https://repo.extendedclip.com/releases/ - - - - - codemc-releases - https://repo.codemc.io/repository/maven-releases/ - - - - - nexo-repo - https://repo.nexomc.com/releases - - - - - matteodev - https://maven.devs.beer/ - - - - - xiaomomi's plugins-releases - XiaoMoMi's Plugin Repository - https://repo.momirealms.net/releases - - - xiaomomi's plugins-snapshots - XiaoMoMi's Plugin Repository - https://repo.momirealms.net/snapshots - - - - - groupez - https://repo.groupez.dev/releases - - - - - central-snapshots - https://central.sonatype.com/repository/maven-snapshots/ - - - - - jitpack.io - https://jitpack.io - - - diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 00000000..08a82714 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,49 @@ +// +// Settings for the CraftEngineConverter multi-module build. +// +// Replaces the and sections of the old root pom.xml. +// +// Repositories are NOT declared here. paperweight-userdev registers extra repositories +// (mache, the plugin remapper, and the decompiler/param-mapping repos named by the dev bundle's +// own metadata) directly on the :Plugin project. Gradle cannot merge settings repositories with +// project repositories - whichever `RepositoriesMode` is chosen, one side is discarded - so a +// settings-level repository block would either be ignored for :Plugin or would silently break +// paperweight's setup pipeline. They therefore live in the `craftengineconverter.java-conventions` +// convention plugin, which is still a single declaration site for the whole build. +// + +pluginManagement { + repositories { + gradlePluginPortal() + // paperweight (and Paper plugin markers) are published here too. + maven("https://repo.papermc.io/repository/maven-public/") { + name = "papermc" + } + } + + // Convention plugins live in their own included build instead of buildSrc: editing one then + // only re-runs what actually depends on it, and IntelliJ imports it as a separate, + // properly-typed Gradle project. + includeBuild("build-logic") +} + +plugins { + // Lets Gradle download a matching JDK on its own when the required toolchain (Java 21) is not + // installed locally. Without this, a machine with only a newer JDK fails with + // "No matching toolchain found". + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} + +rootProject.name = "CraftEngineConverter" + +// Module layout is identical to the Maven one; Gradle derives the directories from the paths. +include( + ":API", + ":Common", + ":Hooks", + ":Hooks:PacketEvent", + ":Hooks:PlaceholderAPI", + ":Hooks:Nexo", + ":Hooks:ItemsAdder", + ":Plugin", +)