diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c04b98e..5840389 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,6 +33,7 @@ jobs: shell: bash - run: ./gradlew :cli:run --args=doctor --no-daemon -q shell: bash + - run: node --test scripts/test-bedrock-machine-menus.mjs fixture: name: fixture MOD と Fabric サーバー用 MOD (Fabric MC 26.3) @@ -56,6 +57,7 @@ jobs: [ "$(sp_val LOADER)" = "$(cat_val fabric-loader)" ] || { echo "不一致: spike LOADER"; fail=1; } root_ver="$(sed -n 's/^version=//p' gradle.properties)" [ "$(prop_val platform-fabric core_version)" = "$root_ver" ] || { echo "不一致: core_version と version"; fail=1; } + [ "$(prop_val platform-fabric mod_version)" = "$root_ver" ] || { echo "不一致: mod_version と version"; fail=1; } exit $fail - uses: actions/setup-java@v4 with: diff --git a/README.md b/README.md index f5f8300..6f153f4 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,15 @@ Java Edition の MOD を、Bedrock Edition のプレイヤーが改造なしのクライアントで遊べるようにする OSS 互換エンジンです。サーバーでの利用を必須要件にしています。設計方針は [Epic #1](https://github.com/Pui-core/pui-core_java-to-bedrock-mods_engine/issues/1) にあります。 -> **現在の状態: v0.0.1 → v0.1.0 開発中** -> Windows 版 Bedrock のローカルワールドで単純なブロック素材の描画を確認しました。ビルド基盤、MOD の静的解析と診断(`scan` / `validate` / `report`)、アドオン生成の試作(`compile`)、検証用の fixture MOD、接続スパイク用スクリプトを提供しています。任意の MOD の互換は保証しません。 +> **v0.4.0 開発版** +> Fabric/Geyser と Bedrock のローカルワールドで、自作 fixture と Compressed Blocks の加工を確認しました。公式 BDS での受け入れ試験が残っています。 ## 対応モード | モード | 実行主体 | 状態 | |---|---|---| | A: Java MOD サーバー接続 | Fabric サーバー + Geyser + Hydraulic | Bedrock 2人の同時入場と試験用ブロックの設置・破壊の同期を確認([試験結果](docs/adr/0005-mode-a-connection-gate.md#v010-の認証実機検証)) | -| B: Bedrock ネイティブ変換 | BDS / ローカルワールド | Windows のローカルワールドで基本素材の描画と作業台のレシピを確認。公式 BDS は未検証([ADR-0006](docs/adr/0006-mode-b-behavior-pack.md)) | +| B: Bedrock ネイティブ変換 | BDS / ローカルワールド | Windows のローカルワールドで基本素材の描画、作業台のレシピ、フォームでの加工を確認。公式 BDS は未検証([ADR-0006](docs/adr/0006-mode-b-behavior-pack.md)) | | C: プロキシ・複数サーバー | 各 Java バックエンド | 未着手(v0.6.0) | ## 必要なもの @@ -47,7 +47,7 @@ modbridge compile mods/ --out build/pack --cache .modbridge-cache # build/pack/ に modbridge-rp.mcpack(見た目)、modbridge-bp.mcpack(定義)、modbridge.mcaddon(両方)、mapping.json(対応表) ``` -単純なモデル(平面アイテム、立方体のブロック)と、作業台のレシピだけを変換します。それ以外は、理由を付けて対応表(`mapping.json`)で SKIPPED にします。Java のコードで決まる性質(スタック数・硬さなど)と Java のロジックは変換せず、そのことを対応表と診断に書きます。解析に ERROR があるときや、ID が衝突したときは何も作らず、出力フォルダーも変更しません。Windows 版 26.65 のローカルワールドで、立方体ブロックの面の向き・透過・日本語名を確認済みです。BDS の動作は未検証です。詳しくは [ADR-0004](docs/adr/0004-asset-compiler-and-mapping.md) と [ADR-0006](docs/adr/0006-mode-b-behavior-pack.md) にあります。 +平面アイテムと立方体のブロックに加え、作業台、かまど、溶鉱炉、燻製器、焚き火の単純なレシピを変換します。加熱レシピは材料1種と結果1個に対応し、時間と経験値には Bedrock 側の仕様を使います。非対応の定義と Java のコードで決まる性質は、対応表(`mapping.json`)と診断に理由を出します。解析に ERROR がある場合や ID が衝突した場合は、出力フォルダーを変更しません。Windows 版 26.65 のローカルワールドで、立方体ブロックの面の向き・透過・日本語名を確認済みです。詳しくは [ADR-0004](docs/adr/0004-asset-compiler-and-mapping.md) と [ADR-0006](docs/adr/0006-mode-b-behavior-pack.md) にあります。 ### BDS への配置 @@ -61,10 +61,10 @@ modbridge bds-rollback --bds /path/to/bedrock-server --backup --confirm-sto ## fixture MOD -`fixtures/fabric-fixture` は検証用の自作 MOD です。独自アイテム `pmb_fixture:test_ingot`、独自ブロック `pmb_fixture:test_block`、素材を持たないコード専用のアイテム `pmb_fixture:code_only_marker` と、レシピ 2 つ(インゴット 9 個 ⇔ ブロック)を登録します。Minecraft 本体を取得するので、ルートとは別のビルドにしています。 +`fixtures/fabric-fixture` は検証用の自作 MOD です。独自アイテム `pmb_fixture:test_ingot`、独自ブロック `pmb_fixture:test_block`、素材を持たないコード専用のアイテム `pmb_fixture:code_only_marker` を登録します。作業台ではインゴット9個とブロック1個を相互に変換し、かまど・溶鉱炉・燻製器・焚き火ではブロック1個をインゴット1個に変換できます。Minecraft 本体を取得するので、ルートとは別のビルドにしています。 ```sh -cd fixtures/fabric-fixture && ./gradlew build # build/libs/pmb-fabric-fixture-0.0.3.jar +cd fixtures/fabric-fixture && ./gradlew build # build/libs/pmb-fabric-fixture-0.0.4.jar ``` ## Fabric サーバー用 MOD(Mode A) @@ -75,11 +75,39 @@ cd fixtures/fabric-fixture && ./gradlew build # build/libs/pmb-fabric-fixture- - **実行時レジストリの取得**: JVM 引数 `-Dmodbridge.registryDump=` を付けると、MOD が実際に登録したアイテム・ブロック・レシピを JSON に書き出します(`-Dmodbridge.registryDump.stop=true` を足すと、書き出した後にサーバーを止めます)。 ```sh -cd platform-fabric && ./gradlew build # build/libs/modbridge-fabric-0.2.0.jar(Geyser の API を取得するため、初回はネットワークが要る) +cd platform-fabric && ./gradlew build # build/libs/modbridge-fabric-0.4.0-SNAPSHOT.jar(初回は Geyser の API を取得) ``` ビルド済みなら、接続スパイクのスクリプトが自動で組み込み、`local/spike-server/registry-dump.json` に書き出します。 +### Mode A の加工アダプター + +Fabric の `fabric.mod.json` に `modbridge-adapter` エントリーポイントを登録し、`Adapter` を実装します。運用者が JVM 引数 `-Dmodbridge.adapters.trusted=<提供元MODのID>` で許可した提供元から、対象 MOD の版とモードが一致するものを読み込みます。複数の提供元はカンマで区切ります。 + +アダプターのビルドでは PuiModBridge のチェックアウトを Gradle の `includeBuild` で参照し、`dev.puicore.modbridge:core:0.4.0-SNAPSHOT` を `compileOnly` にします。実行時の `core` は `modbridge-fabric` が供給します。 [fixture の設定](fixtures/fabric-fixture/settings.gradle) · [fixture の依存指定](fixtures/fabric-fixture/build.gradle) · [エントリーポイント](fixtures/fabric-fixture/src/main/resources/fabric.mod.json) + +`descriptor()` で API 版、対象 MOD ID、対応する版の文字列、`Mode.A`、`MACHINE_MENU` を宣言し、起動時の `register()` でメニューを登録します。終了処理が必要な場合は `shutdown()` を実装します。メニューとレシピには名前空間付き ID を付け、加工台・材料・結果は Java の登録 ID で指定します。 [Adapter API](core/src/main/java/dev/puicore/modbridge/core/adapter/Adapter.java) · [動作するサンプル](fixtures/fabric-fixture/src/main/java/dev/puicore/modbridge/fixture/FixtureMachineAdapter.java) + +fixture の `pmb_fixture` を許可すると、`pmb_fixture:test_block` が加工台になり、銅インゴット2個を試験用インゴット1個に交換できます。応答は30秒以内に1回使えます。加工時に距離、権限、ブロック、材料、出力先の空きを確認し、結果をアクションバーで知らせます。スニーク中は通常どおりブロックを操作できます。 + +`-Dmodbridge.adapters.rules=` では、対象の MOD・版・モードと加工内容を宣言できます。[Compressed Blocks 1.0.3 用の例](fixtures/adapter-rules/compressed-blocks.json)を指定すると、Bedrock から鍛冶台を操作して丸石9個を圧縮できます。ルールはサーバーの運用者が指定します。 + +Minecraft for Windows 26.65 で、認証付きの隔離 Fabric/Geyser に参加し、両方の加工画面と所持品・アクションバーへの反映を確認済みです。フォームを開いてから加工台の操作範囲を離れると、加工は行われず所持品が維持されました。 + +### Mode B の加工ルール + +```sh +modbridge compile pmb-fabric-fixture.jar fabric-api.jar --out build/machine-pack --adapter-rules fixtures/adapter-rules/fixture-mode-b.json +``` + +運用者が指定した JSON のうち、入力 JAR の MOD ID・版と Mode B に一致するルールを使います。加工台と材料・結果は Java 側の ID で指定します。任意の `mappings` で、カスタムアイテム・ブロック・レシピの生成先 ID を変更できます。対応するパック定義・レシピ・加工メニューにも変更が反映されます。Bedrock で未変換のカスタム ID を加工で参照すると、コンパイルを中止します。 + +[Compressed Blocks 1.0.3 用の例](fixtures/adapter-rules/compressed-blocks.json)は Mode B でも使えます。複数の MOD のルールを使う場合は、1ファイルの `adapters` 配列にまとめます。 + +サバイバルのメンバーとオペレーターが加工台を操作できます。スクリプトは画面を開くときと選択を受け付けるときにこの権限を確認します。スニーク中は通常のブロック操作ができます。選択の有効期間は600サーバーティックで、処理結果はアクションバーに出ます。既定のスタックと結合できる材料を使います。必要な個数または出力先が足りなければ、所持品を変更しません。 + +加工メニューを含むパックは Bedrock 1.21.100 以上と安定版の `@minecraft/server` 2.1.0、`@minecraft/server-ui` 2.0.0 を要求します。加工台には Bedrock 標準のプレイヤー権限が適用されます。他のアドオンが領域ごとに設ける操作制限との連携は未対応です。Minecraft for Windows 26.65 のローカルワールドで、両方の加工画面、材料の消費と結果の追加、ワールド再読込後の保存を確認済みです。公式 BDS での動作は実機確認待ちです。[Bedrock 1.21.100 の変更履歴](https://feedback.minecraft.net/hc/en-us/articles/38581287884557-Minecraft-1-21-100-Bedrock) + ## 接続スパイク(Mode A) Fabric 専用サーバー、Geyser-Fabric、Hydraulic、fixture MOD を `local/spike-server` に組んで起動します。取得物はすべて固定版で、SHA-256 照合が通ったものだけを使います。 diff --git a/cli/src/main/java/dev/puicore/modbridge/cli/Main.java b/cli/src/main/java/dev/puicore/modbridge/cli/Main.java index 6e1a9f4..a1c02e1 100644 --- a/cli/src/main/java/dev/puicore/modbridge/cli/Main.java +++ b/cli/src/main/java/dev/puicore/modbridge/cli/Main.java @@ -1,6 +1,7 @@ package dev.puicore.modbridge.cli; import dev.puicore.modbridge.core.Doctor; +import dev.puicore.modbridge.core.adapter.AdapterRules; import dev.puicore.modbridge.core.bds.BdsInstaller; import dev.puicore.modbridge.core.compile.PackCompiler; import dev.puicore.modbridge.core.compile.PackPublisher; @@ -151,7 +152,7 @@ private static int compile(List args, PrintStream out, PrintStream err) String a = args.get(i); if (!onlyFiles && a.equals("--")) { onlyFiles = true; - } else if (!onlyFiles && List.of("--out", "--runtime", "--cache", "--pack-name", "--pack-id").contains(a)) { + } else if (!onlyFiles && List.of("--out", "--runtime", "--cache", "--pack-name", "--pack-id", "--adapter-rules").contains(a)) { if (i + 1 >= args.size()) { err.println(a + " には値が必要"); return USAGE; @@ -168,13 +169,19 @@ private static int compile(List args, PrintStream out, PrintStream err) } } if (inputs.isEmpty() || !opts.containsKey("--out")) { - err.println("使い方: modbridge compile ... --out DIR [--runtime FILE] [--cache DIR] [--pack-name NAME] [--pack-id ID]"); + err.println("使い方: modbridge compile ... --out DIR [--runtime FILE] [--cache DIR] " + + "[--pack-name NAME] [--pack-id ID] [--adapter-rules FILE]"); return USAGE; } PackCompiler.Settings settings; try { + AdapterRules rules = opts.containsKey("--adapter-rules") + ? AdapterRules.readDocument(Path.of(opts.get("--adapter-rules"))) : AdapterRules.EMPTY; settings = new PackCompiler.Settings(opts.getOrDefault("--pack-name", PackCompiler.Settings.DEFAULT.packName()), - opts.getOrDefault("--pack-id", PackCompiler.Settings.DEFAULT.packId())); + opts.getOrDefault("--pack-id", PackCompiler.Settings.DEFAULT.packId()), rules); + } catch (IOException e) { + err.println("アダプタールールを読めない: " + e.getMessage()); + return IO; } catch (IllegalArgumentException e) { err.println(e.getMessage()); return USAGE; @@ -420,7 +427,7 @@ private static void usage(PrintStream out) { validate ... [--runtime FILE] 解析して診断だけを表示する report IR から互換性レポートを表示する - compile ... --out DIR [--runtime FILE] [--cache DIR] [--pack-name NAME] [--pack-id ID] + compile ... --out DIR [--runtime FILE] [--cache DIR] [--pack-name NAME] [--pack-id ID] [--adapter-rules FILE] Bedrock のアドオン(RP・BP・.mcaddon)と対応表を作り、DIR に公開する bds-install --bds BDS [--world NAME] [--apply --confirm-stopped] compile の出力を BDS のワールドに配置する(既定は dry-run) diff --git a/core/src/main/java/dev/puicore/modbridge/core/adapter/Adapter.java b/core/src/main/java/dev/puicore/modbridge/core/adapter/Adapter.java new file mode 100644 index 0000000..1de890f --- /dev/null +++ b/core/src/main/java/dev/puicore/modbridge/core/adapter/Adapter.java @@ -0,0 +1,99 @@ +package dev.puicore.modbridge.core.adapter; + +import dev.puicore.modbridge.core.ir.BridgeIr.Kind; +import dev.puicore.modbridge.core.ir.BridgeIr.Mode; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; + +/** 信頼済み MOD が提供する、プラットフォームから独立したアダプターの契約。 */ +public interface Adapter { + int API_VERSION = 1; + + Descriptor descriptor(); + + void register(Registrar registrar); + + default void shutdown() {} + + enum Capability { IDENTIFIER_MAPPING, MACHINE_MENU } + + record Descriptor(String id, int apiVersion, String targetMod, Set versions, Set modes, + Set capabilities) { + public Descriptor { + Ids.require(id); + if (apiVersion <= 0 || Objects.requireNonNull(targetMod).isBlank()) { + throw new IllegalArgumentException("API 版または対象 MOD が不正"); + } + versions = Set.copyOf(versions); + modes = Set.copyOf(modes); + capabilities = Set.copyOf(capabilities); + if (versions.isEmpty() || versions.stream().anyMatch(String::isBlank) || modes.isEmpty() || capabilities.isEmpty()) { + throw new IllegalArgumentException("対象の版、モード、機能を指定する"); + } + } + } + + interface Registrar { + void mapping(Kind kind, String source, String destination); + + void menu(Menu menu); + } + + record ItemAmount(String item, int count) { + public ItemAmount { + Ids.require(item); + if (count < 1 || count > 4096) { + throw new IllegalArgumentException("加工する個数は 1〜4096"); + } + } + } + + record Recipe(String id, String label, ItemAmount input, ItemAmount output) { + public Recipe { + Ids.require(id); + Ids.requireLabel(label); + Objects.requireNonNull(input); + Objects.requireNonNull(output); + } + } + + record Menu(String id, String title, Set blocks, double maxDistance, List recipes) { + public Menu { + Ids.require(id); + Ids.requireLabel(title); + blocks = Set.copyOf(blocks); + blocks.forEach(Ids::require); + recipes = List.copyOf(recipes); + if (blocks.isEmpty() || !Double.isFinite(maxDistance) || maxDistance <= 0 || maxDistance > 64 + || recipes.isEmpty() || recipes.size() > 32) { + throw new IllegalArgumentException("ブロック、操作距離(64 以下)、レシピ(1〜32 件)を指定する"); + } + Set recipeIds = new HashSet<>(); + for (Recipe recipe : recipes) { + if (!recipeIds.add(recipe.id())) { + throw new IllegalArgumentException("同じレシピ ID が重複: " + recipe.id()); + } + } + } + } + final class Ids { + private static final Pattern ID = Pattern.compile("[a-z0-9_.-]+:[a-z0-9_./-]+"); + + private Ids() {} + + static void require(String id) { + if (!ID.matcher(Objects.requireNonNull(id)).matches()) { + throw new IllegalArgumentException("名前空間付きの識別子を指定する: " + id); + } + } + + static void requireLabel(String label) { + if (Objects.requireNonNull(label).isBlank()) { + throw new IllegalArgumentException("画面に表示する名前を指定する"); + } + } + } +} diff --git a/core/src/main/java/dev/puicore/modbridge/core/adapter/AdapterRegistry.java b/core/src/main/java/dev/puicore/modbridge/core/adapter/AdapterRegistry.java new file mode 100644 index 0000000..cd1a1a0 --- /dev/null +++ b/core/src/main/java/dev/puicore/modbridge/core/adapter/AdapterRegistry.java @@ -0,0 +1,170 @@ +package dev.puicore.modbridge.core.adapter; + +import dev.puicore.modbridge.core.adapter.Adapter.Capability; +import dev.puicore.modbridge.core.adapter.Adapter.Descriptor; +import dev.puicore.modbridge.core.adapter.Adapter.Ids; +import dev.puicore.modbridge.core.adapter.Adapter.Menu; +import dev.puicore.modbridge.core.ir.BridgeIr.Kind; +import dev.puicore.modbridge.core.ir.BridgeIr.Mode; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; + +/** 起動時にアダプターを選び、対応付け・加工メニューを登録する。 */ +public final class AdapterRegistry implements AutoCloseable { + /** ローダーの MOD ID と、信頼判定後にだけ参照する入口。 */ + public record Candidate(String provider, Supplier factory) { + public Candidate { + Objects.requireNonNull(provider); + Objects.requireNonNull(factory); + } + } + + private record Mapping(Kind kind, String source) {} + + private final List adapters = new ArrayList<>(); + private final List descriptors = new ArrayList<>(); + private final Map mappings = new HashMap<>(); + private final Map machines = new HashMap<>(); + private final Set menuIds = new HashSet<>(); + private boolean closed; + + private AdapterRegistry() {} + + public static AdapterRegistry load(List candidates, Set trustedProviders, Map loadedMods, + Mode mode) { + return load(candidates, trustedProviders, loadedMods, mode, List.of()); + } + + public static AdapterRegistry load(List candidates, Set trustedProviders, Map loadedMods, + Mode mode, List declaredRules) { + AdapterRegistry registry = new AdapterRegistry(); + try { + for (Candidate candidate : candidates) { + if (!trustedProviders.contains(candidate.provider())) { + continue; + } + registry.registerIfSupported(candidate.factory().get(), loadedMods, mode); + } + for (Adapter rule : declaredRules) { + registry.registerIfSupported(rule, loadedMods, mode); + } + return registry; + } catch (RuntimeException | Error failure) { + try { + registry.close(); + } catch (RuntimeException cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + private void registerIfSupported(Adapter adapter, Map loadedMods, Mode mode) { + Descriptor descriptor = Objects.requireNonNull(adapter.descriptor()); + String version = loadedMods.get(descriptor.targetMod()); + if (version != null && descriptor.versions().contains(version) && descriptor.modes().contains(mode)) { + register(adapter, descriptor); + } + } + + private void register(Adapter adapter, Descriptor descriptor) { + if (descriptor.apiVersion() != Adapter.API_VERSION) { + throw new IllegalArgumentException("アダプターの API 版が非対応: " + descriptor.id()); + } + if (descriptors.stream().anyMatch(d -> d.id().equals(descriptor.id()))) { + throw new IllegalArgumentException("アダプター ID が重複: " + descriptor.id()); + } + adapters.add(adapter); + Registration registration = new Registration(descriptor); + try { + adapter.register(registration); + } finally { + registration.finished = true; + } + descriptors.add(descriptor); + } + + public List activeAdapters() { + return List.copyOf(descriptors); + } + + public Optional mapping(Kind kind, String source) { + return Optional.ofNullable(mappings.get(new Mapping(kind, source))); + } + + public Optional menuForBlock(String block) { + return Optional.ofNullable(machines.get(block)); + } + + public List menus() { + return machines.values().stream().distinct().sorted(java.util.Comparator.comparing(Menu::id)).toList(); + } + + @Override + public void close() { + if (closed) { + return; + } + closed = true; + RuntimeException problem = null; + for (Adapter adapter : adapters.reversed()) { + try { + adapter.shutdown(); + } catch (RuntimeException failure) { + if (problem == null) { + problem = new IllegalStateException("アダプターの停止に失敗"); + } + problem.addSuppressed(failure); + } + } + if (problem != null) { + throw problem; + } + } + + private final class Registration implements Adapter.Registrar { + private final Descriptor descriptor; + private final Thread registering = Thread.currentThread(); + private boolean finished; + + Registration(Descriptor descriptor) { + this.descriptor = descriptor; + } + + @Override + public void mapping(Kind kind, String source, String destination) { + require(Capability.IDENTIFIER_MAPPING); + Ids.require(source); + Ids.require(destination); + if (mappings.putIfAbsent(new Mapping(Objects.requireNonNull(kind), source), destination) != null) { + throw new IllegalArgumentException("同じ識別子の対応付けが重複: " + source); + } + } + + @Override + public void menu(Menu menu) { + require(Capability.MACHINE_MENU); + if (!menuIds.add(menu.id())) { + throw new IllegalArgumentException("メニュー ID が重複: " + menu.id()); + } + for (String block : menu.blocks()) { + if (machines.putIfAbsent(block, menu) != null) { + throw new IllegalArgumentException("同じブロックのメニューが重複: " + block); + } + } + } + + private void require(Capability capability) { + if (Thread.currentThread() != registering || finished || !descriptor.capabilities().contains(capability)) { + throw new IllegalStateException("登録フェーズまたは宣言した機能を確認する: " + capability); + } + } + } +} diff --git a/core/src/main/java/dev/puicore/modbridge/core/adapter/AdapterRules.java b/core/src/main/java/dev/puicore/modbridge/core/adapter/AdapterRules.java new file mode 100644 index 0000000..d9a3af5 --- /dev/null +++ b/core/src/main/java/dev/puicore/modbridge/core/adapter/AdapterRules.java @@ -0,0 +1,119 @@ +package dev.puicore.modbridge.core.adapter; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.Strictness; +import dev.puicore.modbridge.core.adapter.Adapter.Capability; +import dev.puicore.modbridge.core.adapter.Adapter.Descriptor; +import dev.puicore.modbridge.core.adapter.Adapter.Ids; +import dev.puicore.modbridge.core.adapter.Adapter.Menu; +import dev.puicore.modbridge.core.adapter.Adapter.Registrar; +import dev.puicore.modbridge.core.ir.BridgeIr.Kind; +import dev.puicore.modbridge.core.ir.BridgeIr.Mode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.EnumSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +/** 運用者が明示した JSON を、クラス名やコード実行を伴わない登録ルールとして読む。 */ +public final class AdapterRules { + private static final String SCHEMA = "modbridge.adapter-rules"; + private static final int MAX_BYTES = 1 << 20; + public static final AdapterRules EMPTY = new AdapterRules(List.of(), ""); + + private final List adapters; + private final String sha256; + + private AdapterRules(List adapters, String sha256) { + this.adapters = adapters; + this.sha256 = sha256; + } + + public static List read(Path path) throws IOException { + return readDocument(path).adapters(); + } + + public List adapters() { + return adapters; + } + + public String sha256() { + return sha256; + } + + /** 読み取った内容とキャッシュ用のハッシュを同じスナップショットにまとめる。 */ + public static AdapterRules readDocument(Path path) throws IOException { + try (var stream = Files.newInputStream(path)) { + byte[] data = stream.readNBytes(MAX_BYTES + 1); + if (data.length > MAX_BYTES) { + throw new IOException("アダプタールールは 1 MiB まで"); + } + List adapters = parse(new String(data, StandardCharsets.UTF_8)); + String digest = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(data)); + return new AdapterRules(adapters, digest); + } catch (JsonParseException | IllegalArgumentException | NullPointerException failure) { + throw new IOException("アダプタールールを読めない: " + failure.getMessage(), failure); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException(failure); + } + } + + private static List parse(String json) { + var document = new GsonBuilder().setStrictness(Strictness.STRICT).create().fromJson(json, Document.class); + if (document == null || !SCHEMA.equals(document.schema()) || document.schemaVersion() != 1) { + throw new IllegalArgumentException("スキーマと版 modbridge.adapter-rules/1 を指定する"); + } + return document.adapters().stream().map(Rule::asAdapter).toList(); + } + + private record Document(String schema, int schemaVersion, List adapters) { + Document { + adapters = List.copyOf(adapters); + } + } + + private record Mapping(Kind kind, String source, String destination) { + Mapping { + Objects.requireNonNull(kind); + Ids.require(source); + Ids.require(destination); + } + } + + private record Rule(String id, String targetMod, Set versions, Set modes, List mappings, List menus) { + Rule { + mappings = mappings == null ? List.of() : List.copyOf(mappings); + menus = menus == null ? List.of() : List.copyOf(menus); + } + + Adapter asAdapter() { + var capabilities = EnumSet.noneOf(Capability.class); + if (!mappings.isEmpty()) { + capabilities.add(Capability.IDENTIFIER_MAPPING); + } + if (!menus.isEmpty()) { + capabilities.add(Capability.MACHINE_MENU); + } + var descriptor = new Descriptor(id, Adapter.API_VERSION, targetMod, versions, modes, capabilities); + return new Adapter() { + @Override + public Descriptor descriptor() { + return descriptor; + } + + @Override + public void register(Registrar registrar) { + mappings.forEach(mapping -> registrar.mapping(mapping.kind(), mapping.source(), mapping.destination())); + menus.forEach(registrar::menu); + } + }; + } + } +} diff --git a/core/src/main/java/dev/puicore/modbridge/core/adapter/MachineSessions.java b/core/src/main/java/dev/puicore/modbridge/core/adapter/MachineSessions.java new file mode 100644 index 0000000..94a0394 --- /dev/null +++ b/core/src/main/java/dev/puicore/modbridge/core/adapter/MachineSessions.java @@ -0,0 +1,200 @@ +package dev.puicore.modbridge.core.adapter; + +import dev.puicore.modbridge.core.adapter.Adapter.Ids; +import dev.puicore.modbridge.core.adapter.Adapter.Menu; +import dev.puicore.modbridge.core.adapter.Adapter.Recipe; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.LongSupplier; + +/** 加工画面の応答を一度だけ受け付け、サーバーの状態から在庫の変更を計算する。 */ +public final class MachineSessions { + public enum Result { + APPLIED, STALE, EXPIRED, INVALID_SELECTION, OUT_OF_REACH, DENIED, BLOCK_CHANGED, + INPUT_MISSING, OUTPUT_FULL, RECIPE_UNAVAILABLE, INVENTORY_CHANGED + } + + public record Target(String dimension, int x, int y, int z, String block) { + public Target { + Ids.require(dimension); + Ids.require(block); + } + } + + public record Position(String dimension, double x, double y, double z) {} + + public record Stack(String item, int count, int limit, boolean plain) { + public static final Stack EMPTY = new Stack("", 0, 0, false); + + public Stack { + if (count == 0) { + if (!"".equals(item) || limit != 0 || plain) { + throw new IllegalArgumentException("空きスロットは Stack.EMPTY で表す"); + } + } else { + Ids.require(item); + if (count < 0 || limit < 1 || count > limit) { + throw new IllegalArgumentException("スロットの個数か上限が不正"); + } + } + } + + public boolean matches(String id) { + return plain && item.equals(id); + } + + private Stack withCount(int newCount) { + return newCount == 0 ? EMPTY : new Stack(item, newCount, limit, plain); + } + } + + /** 接続中のプレイヤーをサーバー上で解決し、検証・反映する。 */ + public interface PlayerAccess { + Position position(); + + boolean mayOperate(Target target); + + String blockAt(Target target); + + List inventory(); + + /** 利用できないアイテムは 0。 */ + int stackLimit(String item); + + /** 現在のスロットが expected と一致する場合のみ、変更した全スロットを反映する。 */ + boolean replaceInventory(List expected, List updated); + } + + public record View(UUID token, Menu menu) {} + + private record Session(UUID token, Target target, Menu menu, long opened) {} + + private final Map active = new HashMap<>(); + private final long lifetime; + private final LongSupplier clock; + + public MachineSessions(Duration lifetime) { + this(lifetime, System::nanoTime); + } + + MachineSessions(Duration lifetime, LongSupplier clock) { + this.lifetime = lifetime.toNanos(); + this.clock = Objects.requireNonNull(clock); + if (this.lifetime <= 0) { + throw new IllegalArgumentException("セッションの有効時間は正の値にする"); + } + } + + public Optional open(UUID player, Target target, Menu menu, PlayerAccess access) { + Objects.requireNonNull(player); + if (!menu.blocks().contains(target.block()) || checkTarget(target, menu, access) != null) { + return Optional.empty(); + } + UUID token = UUID.randomUUID(); + synchronized (active) { + long now = clock.getAsLong(); + active.values().removeIf(session -> now - session.opened() >= lifetime); + active.put(player, new Session(token, target, menu, now)); + } + return Optional.of(new View(token, menu)); + } + + public Result select(UUID player, UUID token, int selection, PlayerAccess access) { + Session session = take(player, token); + if (session == null) { + return Result.STALE; + } + if (clock.getAsLong() - session.opened() >= lifetime) { + return Result.EXPIRED; + } + Menu menu = session.menu(); + if (selection < 0 || selection >= menu.recipes().size()) { + return Result.INVALID_SELECTION; + } + Result denied = checkTarget(session.target(), menu, access); + return denied == null ? process(menu.recipes().get(selection), access) : denied; + } + + public void cancel(UUID player, UUID token) { + take(player, token); + } + + public void disconnect(UUID player) { + synchronized (active) { + active.remove(player); + } + } + + private Session take(UUID player, UUID token) { + synchronized (active) { + Session session = active.get(player); + if (session == null || !session.token().equals(token)) { + return null; + } + active.remove(player); + return session; + } + } + + private static Result checkTarget(Target target, Menu menu, PlayerAccess access) { + Position player = access.position(); + double dx = player.x() - (target.x() + 0.5); + double dy = player.y() - (target.y() + 0.5); + double dz = player.z() - (target.z() + 0.5); + double distance = dx * dx + dy * dy + dz * dz; + if (!target.dimension().equals(player.dimension()) || !(distance <= menu.maxDistance() * menu.maxDistance())) { + return Result.OUT_OF_REACH; + } + if (!access.mayOperate(target)) { + return Result.DENIED; + } + return target.block().equals(access.blockAt(target)) ? null : Result.BLOCK_CHANGED; + } + + private static Result process(Recipe recipe, PlayerAccess access) { + int limit = access.stackLimit(recipe.output().item()); + if (limit <= 0) { + return Result.RECIPE_UNAVAILABLE; + } + List before = List.copyOf(access.inventory()); + List after = new ArrayList<>(before); + int input = recipe.input().count(); + for (int slot = 0; slot < after.size() && input > 0; slot++) { + Stack stack = after.get(slot); + if (stack.matches(recipe.input().item())) { + int used = Math.min(input, stack.count()); + after.set(slot, stack.withCount(stack.count() - used)); + input -= used; + } + } + if (input > 0) { + return Result.INPUT_MISSING; + } + int output = recipe.output().count(); + for (int slot = 0; slot < after.size() && output > 0; slot++) { + Stack stack = after.get(slot); + if (stack.matches(recipe.output().item())) { + int added = Math.min(output, stack.limit() - stack.count()); + after.set(slot, stack.withCount(stack.count() + added)); + output -= added; + } + } + for (int slot = 0; slot < after.size() && output > 0; slot++) { + if (after.get(slot).count() == 0) { + int added = Math.min(output, limit); + after.set(slot, new Stack(recipe.output().item(), added, limit, true)); + output -= added; + } + } + if (output > 0) { + return Result.OUTPUT_FULL; + } + return access.replaceInventory(before, List.copyOf(after)) ? Result.APPLIED : Result.INVENTORY_CHANGED; + } +} diff --git a/core/src/main/java/dev/puicore/modbridge/core/compile/BedrockMachineMenus.java b/core/src/main/java/dev/puicore/modbridge/core/compile/BedrockMachineMenus.java new file mode 100644 index 0000000..637e6c3 --- /dev/null +++ b/core/src/main/java/dev/puicore/modbridge/core/compile/BedrockMachineMenus.java @@ -0,0 +1,98 @@ +package dev.puicore.modbridge.core.compile; + +import dev.puicore.modbridge.core.adapter.Adapter.ItemAmount; +import dev.puicore.modbridge.core.adapter.Adapter.Menu; +import dev.puicore.modbridge.core.adapter.Adapter.Recipe; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** Mode B の加工メニューを、固定の実行コードと検証済みの宣言データにする。 */ +final class BedrockMachineMenus { + static final String ENTRY = "scripts/modbridge-machine-menus.js"; + static final List MIN_ENGINE_VERSION = List.of(1, 21, 100); + + private BedrockMachineMenus() {} + + static List> dependencies() { + return List.of(dependency("@minecraft/server", "2.1.0"), dependency("@minecraft/server-ui", "2.0.0")); + } + + private static Map dependency(String name, String version) { + Map dependency = new LinkedHashMap<>(); + dependency.put("module_name", name); + dependency.put("version", version); + return dependency; + } + + static Map module(UUID header) { + UUID uuid = UUID.nameUUIDFromBytes(("modbridge:bp:script:" + header).getBytes(StandardCharsets.UTF_8)); + Map module = new LinkedHashMap<>(); + module.put("type", "script"); + module.put("language", "javascript"); + module.put("uuid", uuid.toString()); + module.put("version", List.of(1, 0, 0)); + module.put("entry", ENTRY); + return module; + } + + static void addScript(List menus, Map entries, Map files, + List behavior) { + List resolved = menus.stream().map(menu -> resolve(menu, entries)).toList(); + Map stations = new LinkedHashMap<>(); + for (Menu menu : resolved) { + for (String block : menu.blocks().stream().sorted().toList()) { + if (stations.putIfAbsent(block, menu) != null) { + throw new IllegalArgumentException("同じ Bedrock ブロックの加工メニューが重複: " + block); + } + } + } + // 各ブロックを配列として渡し、プレーンな JSON だけを実行コードに埋め込む。 + var rules = stations.entrySet().stream().map(e -> new Station(e.getKey(), e.getValue().title(), + e.getValue().maxDistance(), e.getValue().recipes())).toList(); + try (var script = BedrockMachineMenus.class.getResourceAsStream("bedrock-machine-menus.js")) { + if (script == null) { + throw new IllegalStateException("Mode B の加工スクリプトが同梱されていない"); + } + String source = new String(script.readAllBytes(), StandardCharsets.UTF_8); + String data = new String(PackCompiler.json(rules), StandardCharsets.UTF_8); + files.put(ENTRY, (source + "\nregisterMachineMenus(" + data.stripTrailing() + ");\n").getBytes(StandardCharsets.UTF_8)); + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + behavior.add(new BehaviorPack.Entry("modbridge:machine_menus", "SCRIPT", "modbridge:machine_menus", "GENERATED", + ENTRY, resolved.stream().map(Menu::id).toList())); + } + + private static Menu resolve(Menu menu, Map entries) { + var blocks = new java.util.TreeSet(); + menu.blocks().forEach(block -> blocks.add(resolve("block", block, entries))); + List recipes = menu.recipes().stream() + .map(recipe -> new Recipe(recipe.id(), recipe.label(), resolveItem(recipe.input(), entries), + resolveItem(recipe.output(), entries))).toList(); + return new Menu(menu.id(), menu.title(), blocks, menu.maxDistance(), recipes); + } + + private static ItemAmount resolveItem(ItemAmount amount, Map entries) { + // Mode B では変換済みのブロック自体にも同じ ID のブロックアイテムが付く。 + String kind = entries.containsKey("block:" + amount.item()) ? "block" : "item"; + return new ItemAmount(resolve(kind, amount.item(), entries), amount.count()); + } + + private static String resolve(String kind, String id, Map entries) { + if (id.startsWith("minecraft:")) { + return id; + } + PackCompiler.Entry entry = entries.get(kind + ":" + id); + if (entry == null || entry.status().equals("SKIPPED")) { + throw new IllegalArgumentException("加工ルールの参照先を Mode B に変換できない: " + id); + } + return entry.bedrock(); + } + + private record Station(String block, String title, double maxDistance, List recipes) {} +} diff --git a/core/src/main/java/dev/puicore/modbridge/core/compile/BehaviorPack.java b/core/src/main/java/dev/puicore/modbridge/core/compile/BehaviorPack.java index 4d8e5c3..97c0d36 100644 --- a/core/src/main/java/dev/puicore/modbridge/core/compile/BehaviorPack.java +++ b/core/src/main/java/dev/puicore/modbridge/core/compile/BehaviorPack.java @@ -21,7 +21,7 @@ *
  • アイテム: {@code minecraft:item}。アイコンは item_texture.json の短縮名
  • *
  • ブロック: {@code minecraft:block}。形は {@code minecraft:geometry.full_block}、面は {@code material_instances}
  • *
  • ブロックアイテム: Bedrock がブロックから自動で作るので、ファイルは作らない
  • - *
  • レシピ: {@code crafting_shaped} と {@code crafting_shapeless} のうち、材料と結果が単一のアイテムのものだけ
  • + *
  • レシピ: 単一アイテムを材料とする定形・不定形および加熱レシピ
  • * * *

    Java のコードで決まる性質(スタック数・硬さ・道具の条件・ドロップ数など)は静的には分からないので、 @@ -32,6 +32,7 @@ public final class BehaviorPack { static final String FORMAT_VERSION = "1.21.80"; static final String RECIPE_FORMAT_VERSION = "1.20.10"; private static final String MIRRORED_RECIPE_FORMAT_VERSION = "1.20.80"; + private static final String FURNACE_RECIPE_FORMAT_VERSION = "1.12"; static final String CODE_PROPERTIES_NOTE = "スタック数・硬さ・道具の条件・ドロップなど、Java のコードで決まる性質は変換していない(Bedrock の既定値になる)"; /** ビヘイビアパックでの定義 1 件の変換結果。{@code status} は GENERATED / PARTIAL / SKIPPED。 */ @@ -45,11 +46,12 @@ private BehaviorPack() {} * @param rp リソースパックの変換結果(Java のサブジェクト → 結果) * @param recipes レシピの Java 識別子 → レシピの JSON(読めなかったものは null) */ - static Result build(Map rp, Map recipes, Map recipeSkips) { + static Result build(Map rp, Map recipes, Map recipeSkips, + Map recipeIdentifiers) { Map files = new TreeMap<>(); Map entries = new TreeMap<>(); List diags = new ArrayList<>(); - Set available = new TreeSet<>(); // レシピで使える Java の識別子(変換できたアイテムとブロック) + Map available = new TreeMap<>(); // レシピで使える Java → Bedrock の識別子 for (PackCompiler.Entry e : rp.values()) { String subject = e.kind().toLowerCase() + ":" + e.java(); @@ -57,7 +59,7 @@ static Result build(Map rp, Map entries.put(subject, new Entry(e.java(), e.kind(), e.bedrock(), "SKIPPED", null, List.of("リソースパックで変換していない"))); continue; } - available.add(e.java()); + available.put(e.java(), e.bedrock()); String file = (e.kind().equals("BLOCK") ? "blocks/" : "items/") + e.bedrock().replace(':', '/') + ".json"; if (e.kind().equals("BLOCK")) { files.put(file, PackCompiler.json(block(e))); @@ -73,10 +75,10 @@ static Result build(Map rp, Map } recipeSkips.forEach((id, reason) -> entries.put("recipe:" + id, - new Entry(id, "RECIPE", BedrockIds.identifier(id), "SKIPPED", null, List.of(reason)))); + new Entry(id, "RECIPE", PackCompiler.bedrockId(recipeIdentifiers, id), "SKIPPED", null, List.of(reason)))); for (var r : new TreeMap<>(recipes).entrySet()) { String subject = "recipe:" + r.getKey(); - String bid = BedrockIds.identifier(r.getKey()); + String bid = PackCompiler.bedrockId(recipeIdentifiers, r.getKey()); Recipe converted = r.getValue() == null ? Recipe.fail("レシピの JSON を読めない") : recipe(bid, r.getValue(), available); if (converted.json == null) { diags.add(new Diagnostic(Severity.WARN, "RECIPE_UNSUPPORTED", r.getKey(), converted.reason)); @@ -85,11 +87,9 @@ static Result build(Map rp, Map } String file = "recipes/" + bid.replace(':', '/') + ".json"; files.put(file, PackCompiler.json(converted.json)); - List notes = new ArrayList<>(converted.notes); - entries.put(subject, new Entry(r.getKey(), "RECIPE", bid, notes.isEmpty() ? "GENERATED" : "PARTIAL", file, List.copyOf(notes))); - if (!notes.isEmpty()) { - diags.add(new Diagnostic(Severity.WARN, "VANILLA_ID_ASSUMED", r.getKey(), String.join("。", notes))); - } + List notes = converted.notes().stream().map(RecipeNote::message).toList(); + entries.put(subject, new Entry(r.getKey(), "RECIPE", bid, notes.isEmpty() ? "GENERATED" : "PARTIAL", file, notes)); + converted.notes().forEach(note -> diags.add(new Diagnostic(Severity.WARN, note.code(), r.getKey(), note.message()))); } return new Result(files, List.copyOf(entries.values()), diags); } @@ -151,15 +151,26 @@ private static Map material(String texture, String render) { // ---- レシピ ---- - private record Recipe(Map json, List notes, String reason) { + private record RecipeNote(String code, String message) {} + + private record Recipe(Map json, List notes, String reason) { static Recipe fail(String reason) { return new Recipe(null, List.of(), reason); } } - private static Recipe recipe(String bid, JsonObject r, Set available) { + private static Recipe recipe(String bid, JsonObject r, Map available) { String type = str(r.get("type")); - List notes = new ArrayList<>(); + List stations = switch (type) { + case "minecraft:smelting" -> List.of("furnace"); + case "minecraft:blasting" -> List.of("blast_furnace"); + case "minecraft:smoking" -> List.of("smoker"); + case "minecraft:campfire_cooking" -> List.of("campfire", "soul_campfire"); + case null, default -> List.of(); + }; + if (!stations.isEmpty()) { + return furnaceRecipe(bid, r, available, stations); + } Set vanilla = new TreeSet<>(); Set ingredientsForUnlock = new TreeSet<>(); Map result = result(r.get("result"), available, vanilla); @@ -230,27 +241,57 @@ private static Recipe recipe(String bid, JsonObject r, Set available) { body.put("ingredients", outIngredients); key = "minecraft:recipe_shapeless"; } else { - return Recipe.fail("レシピの種類 " + type + " は非対応(作業台のレシピだけ。かまどなどは v0.4.0)"); + return Recipe.fail("レシピの種類 " + type + " は非対応"); } // Bedrock の 1.20 以降の書式には発見条件が必要なので、変換した材料を使う。 body.put("unlock", ingredientsForUnlock.stream().map(id -> Map.of("item", id)).toList()); body.put("result", result); + return finishRecipe(formatVersion, key, body, vanilla, new ArrayList<>()); + } + + private static Recipe furnaceRecipe(String bid, JsonObject r, Map available, List stations) { + Set vanilla = new TreeSet<>(); + JsonElement material = r.get("ingredient"); + if (material instanceof JsonObject object && !object.keySet().equals(Set.of("item"))) { + return Recipe.fail("加熱材料の指定が単一のアイテムに限定されていない"); + } + String input = ingredient(material, available, vanilla); + if (input == null) { + return Recipe.fail("加熱材料がタグ・複数候補・変換していないアイテムのどれか(非対応)"); + } + Map output = result(r.get("result"), available, vanilla); + if (output == null || !output.get("count").equals(1)) { + return Recipe.fail("加熱の結果は、成分のない変換済みアイテム1個に対応する"); + } + Map body = new LinkedHashMap<>(); + body.put("description", Map.of("identifier", bid)); + body.put("tags", stations); + body.put("input", input); + body.put("output", output.get("item")); + List notes = new ArrayList<>(); + notes.add(new RecipeNote("RECIPE_COOKING_DEFAULTS", "Java の加熱時間と経験値は変換せず、Bedrock 側の仕様で動作する")); + return finishRecipe(FURNACE_RECIPE_FORMAT_VERSION, "minecraft:recipe_furnace", body, vanilla, notes); + } + + private static Recipe finishRecipe(String format, String key, Map body, Set vanilla, + List notes) { if (!vanilla.isEmpty()) { - notes.add("バニラのアイテム ID は Java と同じとみなした(Bedrock で名前が違うものがある): " + String.join(", ", vanilla)); + notes.add(new RecipeNote("VANILLA_ID_ASSUMED", + "バニラのアイテム ID は Java と同じとみなした(Bedrock で名前が違うものがある): " + String.join(", ", vanilla))); } Map root = new LinkedHashMap<>(); - root.put("format_version", formatVersion); + root.put("format_version", format); root.put(key, body); - return new Recipe(root, notes, null); + return new Recipe(root, List.copyOf(notes), null); } /** 材料を Bedrock の識別子にする。タグ・複数候補・変換していないアイテムは null。 */ - private static String ingredient(JsonElement e, Set available, Set vanilla) { + private static String ingredient(JsonElement e, Map available, Set vanilla) { String id = e instanceof JsonObject o ? str(o.get("item")) : str(e); return itemId(id, available, vanilla); } - private static Map result(JsonElement e, Set available, Set vanilla) { + private static Map result(JsonElement e, Map available, Set vanilla) { if (!(e instanceof JsonObject o)) { return null; } @@ -259,8 +300,15 @@ private static Map result(JsonElement e, Set available, return null; // 成分付きの結果(NBT 相当)は非対応 } int count = 1; - if (o.get("count") instanceof JsonPrimitive p && p.isNumber()) { - count = p.getAsInt(); + if (o.has("count")) { + if (!(o.get("count") instanceof JsonPrimitive p) || !p.isNumber()) { + return null; + } + try { + count = p.getAsBigDecimal().intValueExact(); + } catch (ArithmeticException | NumberFormatException e1) { + return null; + } } if (count < 1 || count > 64) { return null; @@ -271,7 +319,7 @@ private static Map result(JsonElement e, Set available, return m; } - private static String itemId(String id, Set available, Set vanilla) { + private static String itemId(String id, Map available, Set vanilla) { if (id == null || id.startsWith("#")) { return null; } @@ -283,7 +331,7 @@ private static String itemId(String id, Set available, Set vanil vanilla.add(n); return n; } - return available.contains(n) ? BedrockIds.identifier(n) : null; + return available.get(n); } private static String str(JsonElement e) { diff --git a/core/src/main/java/dev/puicore/modbridge/core/compile/PackCompiler.java b/core/src/main/java/dev/puicore/modbridge/core/compile/PackCompiler.java index 5741cd2..91653ec 100644 --- a/core/src/main/java/dev/puicore/modbridge/core/compile/PackCompiler.java +++ b/core/src/main/java/dev/puicore/modbridge/core/compile/PackCompiler.java @@ -7,6 +7,8 @@ import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import dev.puicore.modbridge.core.TargetVersions; +import dev.puicore.modbridge.core.adapter.AdapterRegistry; +import dev.puicore.modbridge.core.adapter.AdapterRules; import dev.puicore.modbridge.core.ir.BridgeIr; import dev.puicore.modbridge.core.ir.BridgeIr.Definition; import dev.puicore.modbridge.core.ir.BridgeIr.Diagnostic; @@ -30,6 +32,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; @@ -60,7 +63,7 @@ public final class PackCompiler { /** 公開する成果物(キャッシュもこの 4 つが揃っているときだけ使う)。 */ public static final List OUTPUT_FILES = List.of(PACK_FILE, BEHAVIOR_PACK_FILE, ADDON_FILE, MAPPING_FILE); /** 生成器の版。出力の形式を変えたら上げる(キャッシュの鍵に入る)。 */ - static final String COMPILER_VERSION = "pack-compiler/10"; + static final String COMPILER_VERSION = "pack-compiler/13"; static final long MAX_PACK_BYTES = 256L << 20; static final int MAX_TEXTURES = 16_384; /** パックが要求する Bedrock の最低版。1.21.80 以降の書式(ブロックの geometry と material_instances)に合わせる(ADR-0006)。 */ @@ -74,10 +77,15 @@ public final class PackCompiler { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); /** 生成の設定。{@code packId} はヘッダーの UUID を決める(同じ ID なら、内容が変わっても同じパックとして更新される)。 */ - public record Settings(String packName, String packId) { + public record Settings(String packName, String packId, AdapterRules adapterRules) { public static final Settings DEFAULT = new Settings("PuiModBridge Resources", "modbridge"); + public Settings(String packName, String packId) { + this(packName, packId, AdapterRules.EMPTY); + } + public Settings { + Objects.requireNonNull(adapterRules); if (packName == null || packName.isBlank() || packName.length() > 64) { throw new IllegalArgumentException("パック名は 1〜64 文字にする"); } @@ -147,14 +155,47 @@ private Result run() { diag(Severity.ERROR, "IR_HAS_ERRORS", "-", "解析に ERROR 診断があるので、パックを作らない(fail closed)"); return fail(); } + Map versions = new TreeMap<>(); + ir.mods().forEach(mod -> versions.put(mod.id(), mod.version())); + AdapterRegistry adapters; + try { + adapters = AdapterRegistry.load(List.of(), Set.of(), versions, Mode.B, settings.adapterRules().adapters()); + } catch (IllegalArgumentException failure) { + diag(Severity.ERROR, "ADAPTER_RULES_INVALID", "-", failure.getMessage()); + return fail(); + } + try (adapters) { + return run(adapters); + } + } + + private Result run(AdapterRegistry adapters) { List targets = ir.definitions().stream().filter(d -> d.kind() == Kind.ITEM || d.kind() == Kind.BLOCK).toList(); Map recipes = new TreeMap<>(); Map> unconvertedContent = new TreeMap<>(); // MOD → 変換しないカテゴリ → ファイル数 Map recipeSkips = new TreeMap<>(); + Map identifiers = new TreeMap<>(); + Map recipeIdentifiers = new TreeMap<>(); + for (Definition d : ir.definitions()) { + var mapping = adapters.mapping(d.kind(), d.id()); + if (mapping.isEmpty()) { + continue; + } + String destination = mapping.get(); + if (!BedrockIds.identifier(destination).equals(destination) || destination.startsWith("minecraft:")) { + diag(Severity.ERROR, "ADAPTER_RULES_INVALID", d.id(), "Bedrock のカスタム識別子を指定する: " + destination); + continue; + } + Map selected = d.kind() == Kind.RECIPE ? recipeIdentifiers : identifiers; + String previous = selected.putIfAbsent(d.id(), destination); + if (previous != null && !previous.equals(destination)) { + diag(Severity.ERROR, "ADAPTER_RULES_INVALID", d.id(), "ブロックと同名のアイテムは同じ識別子にする"); + } + } // Bedrock 識別子の衝突(アイテムとブロックは同じ名前空間。同じ Java ID のアイテムとブロックはブロックアイテムなので可) Map> byBedrock = new TreeMap<>(); - targets.forEach(d -> byBedrock.computeIfAbsent(BedrockIds.identifier(d.id()), k -> new TreeSet<>()).add(d.id())); + targets.forEach(d -> byBedrock.computeIfAbsent(bedrockId(identifiers, d.id()), k -> new TreeSet<>()).add(d.id())); byBedrock.forEach((bid, javaIds) -> { if (javaIds.size() > 1) { diag(Severity.ERROR, "ID_COLLISION", bid, "別々の Java 識別子が同じ Bedrock 識別子になる: " + String.join(", ", javaIds)); @@ -163,7 +204,7 @@ private Result run() { // レシピの識別子の衝突(レシピはアイテム・ブロックとは別の名前空間) Map> recipeIds = new TreeMap<>(); ir.definitions().stream().filter(d -> d.kind() == Kind.RECIPE) - .forEach(d -> recipeIds.computeIfAbsent(BedrockIds.identifier(d.id()), k -> new TreeSet<>()).add(d.id())); + .forEach(d -> recipeIds.computeIfAbsent(bedrockId(recipeIdentifiers, d.id()), k -> new TreeSet<>()).add(d.id())); recipeIds.forEach((bid, javaIds) -> { if (javaIds.size() > 1) { diag(Severity.ERROR, "ID_COLLISION", bid, "別々の Java のレシピが同じ Bedrock 識別子になる: " + String.join(", ", javaIds)); @@ -218,7 +259,7 @@ private Result run() { defs.sort((a, b) -> a.kind() == b.kind() ? a.id().compareTo(b.id()) : b.kind().compareTo(a.kind())); // BLOCK を先に for (Definition d : defs) { String subject = d.kind().name().toLowerCase() + ":" + d.id(); - String bid = BedrockIds.identifier(d.id()); + String bid = bedrockId(identifiers, d.id()); String skip = skipReason(d, modeB.get(subject)); if (d.kind() == Kind.RECIPE) { if (skip != null) { @@ -277,7 +318,7 @@ private Result run() { UUID header = UUID.nameUUIDFromBytes(("modbridge:rp:header:" + settings.packId()).getBytes(StandardCharsets.UTF_8)); UUID module = UUID.nameUUIDFromBytes(("modbridge:rp:module:" + settings.packId()).getBytes(StandardCharsets.UTF_8)); List version = packVersion(contentSha); - files.put("manifest.json", json(manifest(header, module, version, "resources", settings.packName()))); + files.put("manifest.json", json(manifest(header, module, version, "resources", settings.packName(), false))); byte[] pack = zip(files); if (pack.length > MAX_PACK_BYTES) { @@ -285,7 +326,7 @@ private Result run() { return fail(); } // ---- ビヘイビアパック ---- - BehaviorPack.Result bp = BehaviorPack.build(entries, recipes, recipeSkips); + BehaviorPack.Result bp = BehaviorPack.build(entries, recipes, recipeSkips, recipeIdentifiers); diags.addAll(bp.diagnostics()); List notConverted = new ArrayList<>(); unconvertedContent.forEach((mod, cats) -> { @@ -307,16 +348,33 @@ private Result run() { } } Map bpFiles = new TreeMap<>(bp.files()); + List behavior = new ArrayList<>(bp.entries()); + var menus = adapters.menus(); + boolean hasScript = !menus.isEmpty(); + if (hasScript) { + try { + BedrockMachineMenus.addScript(menus, entries, bpFiles, behavior); + } catch (IllegalArgumentException failure) { + diag(Severity.ERROR, "ADAPTER_RULES_INVALID", "-", failure.getMessage()); + return fail(); + } + } + List bpMinEngine = hasScript ? BedrockMachineMenus.MIN_ENGINE_VERSION : MIN_ENGINE_VERSION; String bpSha = contentHash(withDependency(bpFiles, header.toString(), version)); UUID bpHeader = UUID.nameUUIDFromBytes(("modbridge:bp:header:" + settings.packId()).getBytes(StandardCharsets.UTF_8)); UUID bpModule = UUID.nameUUIDFromBytes(("modbridge:bp:module:" + settings.packId()).getBytes(StandardCharsets.UTF_8)); List bpVersion = packVersion(bpSha); - Map bpManifest = manifest(bpHeader, bpModule, bpVersion, "data", settings.packName() + " (behavior)"); + Map bpManifest = manifest(bpHeader, bpModule, bpVersion, "data", settings.packName() + " (behavior)", hasScript); // Map.of は要素が 2 つ以上だと反復の順序が実行ごとに変わりうるので、順序を固定する Map dependency = new LinkedHashMap<>(); dependency.put("uuid", header.toString()); dependency.put("version", version); - bpManifest.put("dependencies", List.of(dependency)); + List> dependencies = new ArrayList<>(); + dependencies.add(dependency); + if (hasScript) { + dependencies.addAll(BedrockMachineMenus.dependencies()); + } + bpManifest.put("dependencies", dependencies); bpFiles.put("manifest.json", json(bpManifest)); byte[] bpPack = zip(bpFiles); if (bpPack.length > MAX_PACK_BYTES) { @@ -327,8 +385,8 @@ private Result run() { Mapping mapping = new Mapping(MAPPING_SCHEMA, MAPPING_SCHEMA_VERSION, "modbridge " + TargetVersions.get("modbridge"), new PackInfo(settings.packName(), header.toString(), module.toString(), version, MIN_ENGINE_VERSION, contentSha), List.copyOf(entries.values()), List.copyOf(textures.values()), - new PackInfo(settings.packName() + " (behavior)", bpHeader.toString(), bpModule.toString(), bpVersion, MIN_ENGINE_VERSION, bpSha), - bp.entries(), List.copyOf(notConverted), List.copyOf(diags)); + new PackInfo(settings.packName() + " (behavior)", bpHeader.toString(), bpModule.toString(), bpVersion, bpMinEngine, bpSha), + List.copyOf(behavior), List.copyOf(notConverted), List.copyOf(diags)); Map outputs = new LinkedHashMap<>(); outputs.put(PACK_FILE, pack); outputs.put(BEHAVIOR_PACK_FILE, bpPack); @@ -608,13 +666,18 @@ private static JsonObject recipeJson(SafeArchive jar, Definition d) { return null; } - private Map manifest(UUID header, UUID module, List version, String moduleType, String name) { + static String bedrockId(Map mappings, String javaId) { + String mapped = mappings.get(javaId); + return mapped == null ? BedrockIds.identifier(javaId) : mapped; + } + + private Map manifest(UUID header, UUID module, List version, String moduleType, String name, boolean hasScript) { Map h = new LinkedHashMap<>(); h.put("name", name); h.put("description", "modbridge " + TargetVersions.get("modbridge") + " で生成(Java " + TargetVersions.get("minecraft") + " の MOD から)"); h.put("uuid", header.toString()); h.put("version", version); - h.put("min_engine_version", MIN_ENGINE_VERSION); + h.put("min_engine_version", hasScript ? BedrockMachineMenus.MIN_ENGINE_VERSION : MIN_ENGINE_VERSION); Map mod = new LinkedHashMap<>(); mod.put("type", moduleType); mod.put("uuid", module.toString()); @@ -622,7 +685,7 @@ private Map manifest(UUID header, UUID module, List ver Map root = new LinkedHashMap<>(); root.put("format_version", 2); root.put("header", h); - root.put("modules", List.of(mod)); + root.put("modules", hasScript ? List.of(mod, BedrockMachineMenus.module(header)) : List.of(mod)); return root; } @@ -672,12 +735,21 @@ private static boolean checkConsistent(Map outputs, Mapping m) { return false; } // BP の依存先は RP のヘッダー - if (!(bpManifest.get("dependencies") instanceof com.google.gson.JsonArray deps) || deps.size() != 1 + boolean hasScript = bpFiles.containsKey(BedrockMachineMenus.ENTRY); + if (!(bpManifest.get("dependencies") instanceof com.google.gson.JsonArray deps) || deps.size() != (hasScript ? 3 : 1) || !(deps.get(0) instanceof JsonObject dep) || !m.pack().headerUuid().equals(dep.has("uuid") ? dep.get("uuid").getAsString() : null) || !GSON.toJsonTree(m.pack().version()).equals(dep.get("version"))) { return false; } + if (!(bpManifest.get("modules") instanceof com.google.gson.JsonArray modules) || modules.size() != (hasScript ? 2 : 1)) { + return false; + } + if (hasScript && (!GSON.toJsonTree(BedrockMachineMenus.dependencies().get(0)).equals(deps.get(1)) + || !GSON.toJsonTree(BedrockMachineMenus.dependencies().get(1)).equals(deps.get(2)) + || !GSON.toJsonTree(BedrockMachineMenus.module(UUID.fromString(m.behaviorPack().headerUuid()))).equals(modules.get(1)))) { + return false; + } // 対応表の BP のファイルと、BP の中身が一致する Set listed = new TreeSet<>(); m.behavior().forEach(e -> { @@ -696,7 +768,8 @@ private static boolean headerMatches(JsonObject manifest, PackInfo info) { if (manifest == null || !(manifest.get("header") instanceof JsonObject h) || !h.has("uuid")) { return false; } - return info.headerUuid().equals(h.get("uuid").getAsString()) && GSON.toJsonTree(info.version()).equals(h.get("version")); + return info.headerUuid().equals(h.get("uuid").getAsString()) && GSON.toJsonTree(info.version()).equals(h.get("version")) + && GSON.toJsonTree(info.minEngineVersion()).equals(h.get("min_engine_version")); } private static JsonObject parseObject(byte[] b) { @@ -717,6 +790,9 @@ private static JsonObject parseObject(byte[] b) { static Map withDependency(Map files, String rpUuid, List rpVersion) { Map m = new TreeMap<>(files); m.put("\0dependency", (rpUuid + " " + rpVersion).getBytes(StandardCharsets.UTF_8)); + if (files.containsKey(BedrockMachineMenus.ENTRY)) { + m.put("\0script_dependencies", json(BedrockMachineMenus.dependencies())); + } return m; } diff --git a/core/src/main/java/dev/puicore/modbridge/core/compile/PackPublisher.java b/core/src/main/java/dev/puicore/modbridge/core/compile/PackPublisher.java index 746d7a3..1220087 100644 --- a/core/src/main/java/dev/puicore/modbridge/core/compile/PackPublisher.java +++ b/core/src/main/java/dev/puicore/modbridge/core/compile/PackPublisher.java @@ -40,16 +40,13 @@ public final class PackPublisher { private PackPublisher() {} - /** アダプターはまだ無い(#7)。将来はアダプターの ID と版をここに入れる。 */ - static final List ADAPTERS = List.of(); - public static String cacheKey(BridgeIr ir, PackCompiler.Settings settings) { StringBuilder b = new StringBuilder(); b.append(PackCompiler.COMPILER_VERSION).append('\n'); TargetVersions.all().forEach((k, v) -> b.append(k).append('=').append(v).append('\n')); b.append("packName=").append(settings.packName()).append('\n'); b.append("packId=").append(settings.packId()).append('\n'); - b.append("adapters=").append(ADAPTERS).append('\n'); + b.append("adapterRules=").append(settings.adapterRules().sha256()).append('\n'); b.append(IrJson.write(ir)); return HexFormat.of().formatHex(PackCompiler.sha256().digest(b.toString().getBytes(StandardCharsets.UTF_8))); } diff --git a/core/src/main/resources/dev/puicore/modbridge/core/compile/bedrock-machine-menus.js b/core/src/main/resources/dev/puicore/modbridge/core/compile/bedrock-machine-menus.js new file mode 100644 index 0000000..67bb510 --- /dev/null +++ b/core/src/main/resources/dev/puicore/modbridge/core/compile/bedrock-machine-menus.js @@ -0,0 +1,131 @@ +import { GameMode, ItemStack, PlayerPermissionLevel, system, world } from "@minecraft/server"; +import { ActionFormData } from "@minecraft/server-ui"; + +const sessionTicks = 600; + +function mayUseMachine(player) { + if (!player.isValid || player.getGameMode() !== GameMode.Survival) return false; + const role = player.playerPermissionLevel; + return role === PlayerPermissionLevel.Member || role === PlayerPermissionLevel.Operator; +} + +function canOperate(player, target) { + if (!mayUseMachine(player) || + (player.getComponent("minecraft:health")?.currentValue ?? 0) <= 0 || + player.dimension.id !== target.dimension) { + return false; + } + const { x, y, z } = player.location; + const at = target.location; + const distanceSquared = (x - at.x - 0.5) ** 2 + (y - at.y - 0.5) ** 2 + (z - at.z - 0.5) ** 2; + return distanceSquared <= target.station.maxDistance ** 2 && + player.dimension.getBlock(at)?.typeId === target.station.block; +} + +function transfer(container, recipe) { + const source = new ItemStack(recipe.input.item); + const result = new ItemStack(recipe.output.item); + const before = Array.from({ length: container.size }, (_, slot) => container.getItem(slot)); + const after = before.slice(); + let required = recipe.input.count; + for (let slot = 0; slot < after.length && required > 0; slot++) { + const stack = after[slot]; + if (!stack?.isStackableWith(source)) continue; + const taken = Math.min(required, stack.amount); + if (taken === stack.amount) { + after[slot] = undefined; + } else { + after[slot] = stack.clone(); + after[slot].amount -= taken; + } + required -= taken; + } + if (required !== 0) return false; + + let remaining = recipe.output.count; + // まず同じアイテムのスタックに入りきる分を入れる。次に空きスロットを使う。 + for (let slot = 0; slot < after.length && remaining > 0; slot++) { + const stack = after[slot]; + if (!stack?.isStackableWith(result) || stack.amount >= stack.maxAmount) continue; + const added = Math.min(remaining, stack.maxAmount - stack.amount); + after[slot] = stack.clone(); + after[slot].amount += added; + remaining -= added; + } + for (let slot = 0; slot < after.length && remaining > 0; slot++) { + if (after[slot]) continue; + const added = Math.min(remaining, result.maxAmount); + after[slot] = result.clone(); + after[slot].amount = added; + remaining -= added; + } + if (remaining !== 0) return false; + + const written = []; + try { + for (let slot = 0; slot < after.length; slot++) { + if (before[slot] === after[slot]) continue; + written.push(slot); + container.setItem(slot, after[slot]); + } + } catch (failure) { + const errors = [failure]; + for (const slot of written.reverse()) { + try { + container.setItem(slot, before[slot]); + } catch (restoreFailure) { + errors.push(restoreFailure); + } + } + if (errors.length > 1) throw new AggregateError(errors, "inventory rollback failed"); + throw failure; + } + return true; +} + +function registerMachineMenus(rules) { + const stations = new Map(rules.map(station => [station.block, station])); + const sessions = new Map(); + world.afterEvents.playerLeave.subscribe(({ playerId }) => sessions.delete(playerId)); + + async function open(player, target) { + const playerId = player.id; + if (sessions.has(playerId) || !canOperate(player, target)) return; + const expiresAt = system.currentTick + sessionTicks; + // このオブジェクトの同一性をセッション ID として使う。クライアントから受け取るのは選択番号だけ。 + sessions.set(playerId, target); + const timer = system.runTimeout(() => { + if (sessions.get(playerId) === target) sessions.delete(playerId); + }, sessionTicks); + try { + const form = new ActionFormData().title(target.station.title); + target.station.recipes.forEach(recipe => form.button(recipe.label)); + const response = await form.show(player); + if (sessions.get(playerId) !== target) return; + sessions.delete(playerId); + if (system.currentTick >= expiresAt || response.canceled || !Number.isInteger(response.selection) || + !canOperate(player, target)) return; + const recipe = target.station.recipes[response.selection]; + const container = player.getComponent("minecraft:inventory")?.container; + if (recipe && container) { + const applied = transfer(container, recipe); + player.onScreenDisplay.setActionBar(applied ? "加工が完了しました" : "材料かインベントリの空きが不足しています"); + } + } finally { + system.clearRun(timer); + if (sessions.get(playerId) === target) sessions.delete(playerId); + } + } + + world.beforeEvents.playerInteractWithBlock.subscribe(event => { + const station = stations.get(event.block.typeId); + if (!station || event.cancel || !mayUseMachine(event.player) || event.player.isSneaking) return; + event.cancel = true; + if (!event.isFirstEvent) return; + const { player, block } = event; + const target = { station, dimension: block.dimension.id, location: block.location }; + system.run(() => { + open(player, target).catch(failure => console.warn("ModBridge machine menu: " + failure)); + }); + }); +} diff --git a/core/src/test/java/dev/puicore/modbridge/core/adapter/MachineSessionsTest.java b/core/src/test/java/dev/puicore/modbridge/core/adapter/MachineSessionsTest.java new file mode 100644 index 0000000..50eb35d --- /dev/null +++ b/core/src/test/java/dev/puicore/modbridge/core/adapter/MachineSessionsTest.java @@ -0,0 +1,222 @@ +package dev.puicore.modbridge.core.adapter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import dev.puicore.modbridge.core.adapter.Adapter.Capability; +import dev.puicore.modbridge.core.adapter.Adapter.Descriptor; +import dev.puicore.modbridge.core.adapter.Adapter.ItemAmount; +import dev.puicore.modbridge.core.adapter.Adapter.Menu; +import dev.puicore.modbridge.core.adapter.Adapter.Recipe; +import dev.puicore.modbridge.core.adapter.Adapter.Registrar; +import dev.puicore.modbridge.core.adapter.MachineSessions.PlayerAccess; +import dev.puicore.modbridge.core.adapter.MachineSessions.Position; +import dev.puicore.modbridge.core.adapter.MachineSessions.Result; +import dev.puicore.modbridge.core.adapter.MachineSessions.Stack; +import dev.puicore.modbridge.core.adapter.MachineSessions.Target; +import dev.puicore.modbridge.core.ir.BridgeIr.Kind; +import dev.puicore.modbridge.core.ir.BridgeIr.Mode; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class MachineSessionsTest { + private static final String DIMENSION = "minecraft:overworld"; + private static final String MACHINE = "pmb_fixture:bench"; + private static final String INPUT = "minecraft:copper_ingot"; + private static final String OUTPUT = "pmb_fixture:test_ingot"; + private static final Target TARGET = new Target(DIMENSION, 0, 80, 0, MACHINE); + private static final Menu MENU = new Menu("pmb_fixture:bench", "加工台", Set.of(MACHINE), 5, + List.of(new Recipe("pmb_fixture:refine", "加工", new ItemAmount(INPUT, 2), new ItemAmount(OUTPUT, 2)))); + private final AtomicLong clock = new AtomicLong(); + private final MachineSessions sessions = new MachineSessions(Duration.ofSeconds(1), clock::get); + private final UUID player = UUID.randomUUID(); + + @Test + void 信頼済みで対象の版とモードに合うアダプターだけが登録する() { + AtomicInteger closed = new AtomicInteger(); + AtomicReference savedRegistrar = new AtomicReference<>(); + Adapter adapter = new Adapter() { + @Override + public Descriptor descriptor() { + return new Descriptor("pmb_fixture:adapter", API_VERSION, "pmb_fixture", Set.of("1.0"), Set.of(Mode.A), + Set.of(Capability.MACHINE_MENU, Capability.IDENTIFIER_MAPPING)); + } + + @Override + public void register(Registrar registrar) { + savedRegistrar.set(registrar); + registrar.menu(MENU); + registrar.mapping(Kind.ITEM, INPUT, OUTPUT); + } + + @Override + public void shutdown() { + closed.incrementAndGet(); + } + }; + var candidates = List.of(new AdapterRegistry.Candidate("other_mod", () -> { + throw new AssertionError("信頼されていない提供元の入口を呼んだ"); + }), new AdapterRegistry.Candidate("pmb_fixture", () -> adapter)); + Set trusted = Set.of("pmb_fixture"); + try (var mismatch = AdapterRegistry.load(candidates, trusted, Map.of("pmb_fixture", "2.0"), Mode.A); + var otherMode = AdapterRegistry.load(candidates, trusted, Map.of("pmb_fixture", "1.0"), Mode.B); + var registry = AdapterRegistry.load(candidates, trusted, Map.of("pmb_fixture", "1.0"), Mode.A)) { + assertEquals(0, mismatch.activeAdapters().size()); + assertEquals(0, otherMode.activeAdapters().size()); + assertEquals(List.of(adapter.descriptor()), registry.activeAdapters()); + assertEquals(MENU, registry.menuForBlock(MACHINE).orElseThrow()); + assertEquals(OUTPUT, registry.mapping(Kind.ITEM, INPUT).orElseThrow()); + assertThrows(IllegalStateException.class, () -> savedRegistrar.get().menu(MENU)); + } + assertEquals(1, closed.get()); + } + + @Test + void 宣言ルールを登録し未知のスキーマは拒否する(@TempDir Path temp) throws IOException { + Path rules = temp.resolve("rules.json"); + String json = """ + { + "schema": "modbridge.adapter-rules", + "schemaVersion": 1, + "adapters": [{ + "id": "fixtures:rules", + "targetMod": "test_mod", + "versions": ["1.0"], + "modes": ["A"], + "mappings": [{"kind":"ITEM","source":"test_mod:input","destination":"test_mod:output"}] + }] + } + """; + Files.writeString(rules, json); + try (var registry = AdapterRegistry.load(List.of(), Set.of(), Map.of("test_mod", "1.0"), Mode.A, AdapterRules.read(rules))) { + assertEquals("test_mod:output", registry.mapping(Kind.ITEM, "test_mod:input").orElseThrow()); + } + Files.writeString(rules, json.replace("\"schemaVersion\": 1", "\"schemaVersion\": 2")); + assertThrows(IOException.class, () -> AdapterRules.read(rules)); + } + + @Test + void 応答で位置権限とブロックを再検証する() { + Player access = new Player(List.of(input(3), Stack.EMPTY)); + var tooFar = sessions.open(player, TARGET, MENU, access).orElseThrow(); + access.position = new Position(DIMENSION, 20, 80, 0); + assertEquals(Result.OUT_OF_REACH, sessions.select(player, tooFar.token(), 0, access)); + assertFalse(sessions.open(player, TARGET, MENU, access).isPresent()); + access.position = new Position(DIMENSION, 0, 80, 0); + var denied = sessions.open(player, TARGET, MENU, access).orElseThrow(); + access.allowed = false; + assertEquals(Result.DENIED, sessions.select(player, denied.token(), 0, access)); + access.allowed = true; + var blockChanged = sessions.open(player, TARGET, MENU, access).orElseThrow(); + access.block = "minecraft:air"; + assertEquals(Result.BLOCK_CHANGED, sessions.select(player, blockChanged.token(), 0, access)); + assertEquals(List.of(input(3), Stack.EMPTY), access.inventory()); + } + + @Test + void 別プレイヤー古い画面切断期限切れおよび不正な選択を拒否する() { + Player access = new Player(List.of(input(3), Stack.EMPTY)); + var replaced = sessions.open(player, TARGET, MENU, access).orElseThrow(); + var current = sessions.open(player, TARGET, MENU, access).orElseThrow(); + sessions.cancel(player, replaced.token()); + assertEquals(Result.STALE, sessions.select(player, replaced.token(), 0, access)); + assertEquals(Result.STALE, sessions.select(UUID.randomUUID(), current.token(), 0, access)); + assertEquals(Result.INVALID_SELECTION, sessions.select(player, current.token(), 1, access)); + assertEquals(Result.STALE, sessions.select(player, current.token(), 0, access)); + var dropped = sessions.open(player, TARGET, MENU, access).orElseThrow(); + sessions.disconnect(player); + assertEquals(Result.STALE, sessions.select(player, dropped.token(), 0, access)); + var expired = sessions.open(player, TARGET, MENU, access).orElseThrow(); + clock.set(Duration.ofSeconds(1).toNanos()); + assertEquals(Result.EXPIRED, sessions.select(player, expired.token(), 0, access)); + assertEquals(List.of(input(3), Stack.EMPTY), access.inventory()); + } + + @Test + void 入力不足出力満杯および変更済み在庫でアイテムを失わない() { + var modified = new Stack(INPUT, 2, 64, false); + Player wrongInput = new Player(List.of(modified, Stack.EMPTY)); + assertEquals(Result.INPUT_MISSING, select(wrongInput)); + assertEquals(List.of(modified, Stack.EMPTY), wrongInput.inventory()); + + Player full = new Player(List.of(input(3), new Stack(OUTPUT, 15, 16, true))); + assertEquals(Result.OUTPUT_FULL, select(full)); + assertEquals(List.of(input(3), new Stack(OUTPUT, 15, 16, true)), full.inventory()); + + Player stale = new Player(List.of(input(3), Stack.EMPTY)); + stale.refuseCommit = true; + assertEquals(Result.INVENTORY_CHANGED, select(stale)); + assertEquals(List.of(input(3), Stack.EMPTY), stale.inventory()); + } + + @Test + void 同時に同じ応答が届いても加工は一度しか成立しない() throws Exception { + Player access = new Player(List.of(input(4), Stack.EMPTY)); + var view = sessions.open(player, TARGET, MENU, access).orElseThrow(); + CountDownLatch start = new CountDownLatch(1); + try (var workers = Executors.newFixedThreadPool(2)) { + var first = workers.submit(() -> { + start.await(); + return sessions.select(player, view.token(), 0, access); + }); + var second = workers.submit(() -> { + start.await(); + return sessions.select(player, view.token(), 0, access); + }); + start.countDown(); + assertEquals(Set.of(Result.APPLIED, Result.STALE), + Set.of(first.get(5, TimeUnit.SECONDS), second.get(5, TimeUnit.SECONDS))); + } + assertEquals(List.of(input(2), new Stack(OUTPUT, 2, 16, true)), access.inventory()); + } + + private Result select(Player access) { + return sessions.select(player, sessions.open(player, TARGET, MENU, access).orElseThrow().token(), 0, access); + } + + private static Stack input(int count) { + return new Stack(INPUT, count, 64, true); + } + + private static final class Player implements PlayerAccess { + private Position position = new Position(DIMENSION, 0, 80, 0); + private String block = MACHINE; + private boolean allowed = true; + private boolean refuseCommit; + private List inventory; + + Player(List inventory) { + this.inventory = inventory; + } + + @Override public Position position() { return position; } + @Override public String blockAt(Target target) { return block; } + @Override public boolean mayOperate(Target target) { return allowed; } + @Override public List inventory() { return inventory; } + @Override public int stackLimit(String item) { return item.equals(OUTPUT) ? 16 : 0; } + + @Override + public boolean replaceInventory(List expected, List updated) { + if (refuseCommit || !inventory.equals(expected)) { + return false; + } + inventory = updated; + return true; + } + } +} diff --git a/core/src/test/java/dev/puicore/modbridge/core/compile/PackCompilerTest.java b/core/src/test/java/dev/puicore/modbridge/core/compile/PackCompilerTest.java index 34bf73f..42d47cc 100644 --- a/core/src/test/java/dev/puicore/modbridge/core/compile/PackCompilerTest.java +++ b/core/src/test/java/dev/puicore/modbridge/core/compile/PackCompilerTest.java @@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.gson.JsonParser; +import dev.puicore.modbridge.core.adapter.AdapterRules; import dev.puicore.modbridge.core.ir.BridgeIr; import dev.puicore.modbridge.core.scan.Analyzer; import java.awt.image.BufferedImage; @@ -512,6 +513,57 @@ private static dev.puicore.modbridge.core.compile.BehaviorPack.Entry bpEntry(Pac assertEquals(1, mapping(r).notConverted().size()); } + @Test + void 対象版の加工ルールからスクリプトと識別子を反映しキャッシュでも復元する() throws IOException { + Path fixture = jar("fixture.jar", fixture("pmb_fixture")); + List inputs = List.of(fixture); + BridgeIr ir = Analyzer.analyzePaths(inputs); + Path ruleFile = dir.resolve("rules.json"); + String declaration = """ + {"schema":"modbridge.adapter-rules","schemaVersion":1,"adapters":[{ + "id":"test:machine","targetMod":"pmb_fixture","versions":["1.0.0"],"modes":["B"], + "mappings":[{"kind":"BLOCK","source":"pmb_fixture:test_block","destination":"test:machine"}, + {"kind":"ITEM","source":"pmb_fixture:test_ingot","destination":"test:ingot"}], + "menus":[{"id":"test:menu","title":"加工台","blocks":["pmb_fixture:test_block"],"maxDistance":5, + "recipes":[{"id":"test:recipe","label":"加工","input":{"item":"minecraft:copper_ingot","count":2}, + "output":{"item":"pmb_fixture:test_ingot","count":1}}]}] + }]} + """; + Files.writeString(ruleFile, declaration); + var settings = new PackCompiler.Settings("Fixture", "fixture", AdapterRules.readDocument(ruleFile)); + var result = PackCompiler.compile(ir, Analyzer.jarFiles(inputs), settings); + assertTrue(result.ok(), result.diagnostics().toString()); + var bp = unzip(result.outputs().get(PackCompiler.BEHAVIOR_PACK_FILE)); + assertTrue(bp.containsKey("blocks/test/machine.json")); + assertFalse(bp.containsKey("items/test/machine.json")); + assertTrue(bp.containsKey("items/test/ingot.json")); + assertTrue(text(bp, "recipes/pmb_fixture/test_block.json").contains("\"item\": \"test:ingot\"")); + assertTrue(text(bp, "recipes/pmb_fixture/test_block.json").contains("\"item\": \"test:machine\"")); + assertTrue(text(bp, BedrockMachineMenus.ENTRY).contains("\"block\": \"test:machine\"")); + assertTrue(text(bp, BedrockMachineMenus.ENTRY).contains("\"item\": \"test:ingot\"")); + assertTrue(text(bp, "manifest.json").contains("\"module_name\": \"@minecraft/server-ui\"")); + assertEquals(List.of(1, 21, 100), result.mapping().behaviorPack().minEngineVersion()); + String key = PackPublisher.cacheKey(ir, settings); + Path cache = dir.resolve("cache"); + PackPublisher.writeCache(cache, key, result.outputs()); + assertEquals(result.mapping(), PackPublisher.readCachedResult(cache, key).mapping()); + + Files.writeString(ruleFile, declaration.replace("1.0.0", "0.9.0")); + var inactiveSettings = new PackCompiler.Settings("Fixture", "fixture", AdapterRules.readDocument(ruleFile)); + assertNotEquals(key, PackPublisher.cacheKey(ir, inactiveSettings)); + var inactive = PackCompiler.compile(ir, Analyzer.jarFiles(inputs), inactiveSettings); + assertTrue(inactive.ok(), inactive.diagnostics().toString()); + assertFalse(unzip(inactive.outputs().get(PackCompiler.BEHAVIOR_PACK_FILE)).containsKey(BedrockMachineMenus.ENTRY)); + + Files.writeString(ruleFile, declaration.replace( + "\"output\":{\"item\":\"pmb_fixture:test_ingot\"", "\"output\":{\"item\":\"pmb_fixture:missing\"")); + var invalidSettings = new PackCompiler.Settings("Fixture", "fixture", AdapterRules.readDocument(ruleFile)); + var invalid = PackCompiler.compile(ir, Analyzer.jarFiles(inputs), invalidSettings); + assertFalse(invalid.ok()); + assertTrue(invalid.outputs().isEmpty()); + assertTrue(invalid.diagnostics().stream().anyMatch(d -> d.code().equals("ADAPTER_RULES_INVALID"))); + } + private static String unlockedBy(String recipe, String kind) { return JsonParser.parseString(recipe).getAsJsonObject().getAsJsonObject(kind) .getAsJsonArray("unlock").get(0).getAsJsonObject().get("item").getAsString(); @@ -523,7 +575,11 @@ private static String unlockedBy(String recipe, String kind) { m.put("data/rec/recipe/tagged.json", u("{\"type\":\"minecraft:crafting_shapeless\",\"ingredients\":[\"#c:ingots\"]," + "\"result\":{\"id\":\"rec:test_ingot\"}}")); m.put("data/rec/recipe/smelt.json", u("{\"type\":\"minecraft:smelting\",\"ingredient\":\"rec:test_block\"," + + "\"result\":{\"id\":\"rec:test_ingot\",\"count\":2}}")); + m.put("data/rec/recipe/smelt_tagged.json", u("{\"type\":\"minecraft:smelting\",\"ingredient\":\"#c:ingots\"," + "\"result\":{\"id\":\"rec:test_ingot\"}}")); + m.put("data/rec/recipe/smelt_fractional.json", u("{\"type\":\"minecraft:smelting\",\"ingredient\":\"rec:test_block\"," + + "\"result\":{\"id\":\"rec:test_ingot\",\"count\":1.5}}")); m.put("data/rec/recipe/vanilla.json", u("{\"type\":\"minecraft:crafting_shapeless\",\"ingredients\":[\"minecraft:iron_ingot\"," + "\"rec:test_ingot\"],\"result\":{\"id\":\"rec:test_block\"}}")); m.put("data/rec/recipe/unknown_result.json", u("{\"type\":\"minecraft:crafting_shapeless\",\"ingredients\":[\"rec:test_ingot\"]," @@ -533,12 +589,60 @@ private static String unlockedBy(String recipe, String kind) { assertEquals("SKIPPED", bpEntry(r, "RECIPE", "rec:tagged").status()); assertTrue(bpEntry(r, "RECIPE", "rec:tagged").notes().get(0).contains("タグ")); assertEquals("SKIPPED", bpEntry(r, "RECIPE", "rec:smelt").status()); + assertEquals("SKIPPED", bpEntry(r, "RECIPE", "rec:smelt_tagged").status()); + assertEquals("SKIPPED", bpEntry(r, "RECIPE", "rec:smelt_fractional").status()); assertEquals("SKIPPED", bpEntry(r, "RECIPE", "rec:unknown_result").status()); assertEquals("PARTIAL", bpEntry(r, "RECIPE", "rec:vanilla").status()); assertTrue(r.diagnostics().stream().anyMatch(d -> d.code().equals("VANILLA_ID_ASSUMED") && d.subject().equals("rec:vanilla"))); assertTrue(r.diagnostics().stream().filter(d -> d.code().equals("RECIPE_UNSUPPORTED")).count() >= 3); } + @Test + void 加熱レシピを機器別に生成し_材料と結果の対応付けを使う() throws IOException { + Map m = fixture("cook"); + Map> stations = Map.of( + "smelting", List.of("furnace"), + "blasting", List.of("blast_furnace"), + "smoking", List.of("smoker"), + "campfire_cooking", List.of("campfire", "soul_campfire")); + for (String type : stations.keySet()) { + m.put("data/cook/recipe/" + type + ".json", u(""" + {"type":"minecraft:%s","ingredient":"cook:test_block","result":{"id":"cook:test_ingot"}, + "cookingtime":200,"experience":0.7} + """.formatted(type))); + } + m.put("data/cook/recipe/vanilla_input.json", u(""" + {"type":"minecraft:blasting","ingredient":"minecraft:raw_gold","result":{"id":"cook:test_ingot"}} + """)); + List inputs = List.of(jar("cook.jar", m)); + Path rules = Files.writeString(dir.resolve("cook-rules.json"), """ + {"schema":"modbridge.adapter-rules","schemaVersion":1,"adapters":[{ + "id":"cook:rules","targetMod":"cook","versions":["1.0.0"],"modes":["B"], + "mappings":[{"kind":"BLOCK","source":"cook:test_block","destination":"cook:raw"}, + {"kind":"ITEM","source":"cook:test_ingot","destination":"cook:cooked"}] + }]} + """); + var settings = new PackCompiler.Settings("Fixture", "fixture", AdapterRules.readDocument(rules)); + PackCompiler.Result r = PackCompiler.compile(Analyzer.analyzePaths(inputs), Analyzer.jarFiles(inputs), settings); + assertTrue(r.ok(), r.diagnostics().toString()); + Map bp = unzip(r.outputs().get(PackCompiler.BEHAVIOR_PACK_FILE)); + for (var station : stations.entrySet()) { + String id = "cook:" + station.getKey(); + BehaviorPack.Entry entry = bpEntry(r, "RECIPE", id); + assertEquals("PARTIAL", entry.status()); + var recipe = JsonParser.parseString(text(bp, entry.file())).getAsJsonObject(); + var furnace = recipe.getAsJsonObject("minecraft:recipe_furnace"); + assertEquals(id, furnace.getAsJsonObject("description").get("identifier").getAsString()); + assertEquals(station.getValue(), furnace.getAsJsonArray("tags").asList().stream().map(e -> e.getAsString()).toList()); + assertEquals("cook:raw", furnace.get("input").getAsString()); + assertEquals("cook:cooked", furnace.get("output").getAsString()); + assertFalse(furnace.has("unlock")); + assertTrue(r.diagnostics().stream().anyMatch(d -> d.subject().equals(id) && d.code().equals("RECIPE_COOKING_DEFAULTS"))); + assertFalse(r.diagnostics().stream().anyMatch(d -> d.subject().equals(id) && d.code().equals("VANILLA_ID_ASSUMED"))); + } + assertEquals(2, bpEntry(r, "RECIPE", "cook:vanilla_input").notes().size()); + } + @Test void レシピの識別子が衝突したら何も作らない() throws IOException { Map m = fixture("rc"); diff --git a/docs/adr/0006-mode-b-behavior-pack.md b/docs/adr/0006-mode-b-behavior-pack.md index ced976f..e2f2994 100644 --- a/docs/adr/0006-mode-b-behavior-pack.md +++ b/docs/adr/0006-mode-b-behavior-pack.md @@ -1,6 +1,6 @@ # ADR-0006: Mode B のビヘイビアパック生成と .mcaddon -- 状態: 採用(Minecraft for Windows 26.65 で素材とレシピを確認、公式 BDS は未検証) +- 状態: 採用(Minecraft for Windows 26.65 のローカルワールドで素材・作業台・加工を確認、公式 BDS は未検証) - 日付: 2026-11-27 - 関連: #6, #4, #1、前提は ADR-0004 @@ -28,7 +28,8 @@ Mode B では、Java の MOD のコードを BDS で動かさず、宣言デー | アイテム | `minecraft:item`。`minecraft:icon` の `textures.default` に、item_texture.json の短縮名を書く。名前は `minecraft:display_name` で `item..name` を参照する | | ブロック | `minecraft:block`。形は `minecraft:geometry.full_block`。面は `material_instances` で、全面が同じなら `*` だけ、違う面があれば側面(north)を `*` にして違う面だけを書く。描画方法はリソースパックで判定した `render`(opaque / alpha_test / blend) | | ブロックアイテム | ファイルを作らない(Bedrock がブロックから自動で作る) | - | レシピ | `crafting_shaped` → `minecraft:recipe_shaped`、`crafting_shapeless` → `minecraft:recipe_shapeless`(`tags` は `crafting_table`)。材料と結果は、単一のアイテムのものだけ | + | 作業台のレシピ | `crafting_shaped` → `minecraft:recipe_shaped`、`crafting_shapeless` → `minecraft:recipe_shapeless`(`tags` は `crafting_table`)。材料と結果は、単一のアイテムのものだけ | + | 加熱レシピ(v0.4.0) | `smelting`、`blasting`、`smoking`、`campfire_cooking` → `minecraft:recipe_furnace`。機器に合わせて `furnace`、`blast_furnace`、`smoker`、`campfire` と `soul_campfire` のタグを使う。材料1種と結果1個に対応する | - 左右非対称の定形レシピは書式 `1.20.80` の `assume_symmetry: true` で、Java と同じく左右両方の配置を受け付ける。[Bedrock の定形レシピ](https://learn.microsoft.com/en-us/minecraft/creator/reference/content/recipereference/examples/recipedefinitions/recipe_shaped?view=minecraft-bedrock-stable) @@ -37,7 +38,8 @@ Mode B では、Java の MOD のコードを BDS で動かさず、宣言デー - タグ(`#c:ingots` など)や、複数候補の材料 - 成分付きの結果 - このパックで変換していない MOD のアイテム - - 作業台以外の種類(かまどなど。v0.4.0) + - 加熱レシピの複数個の結果、醸造・鍛冶などの非対応の種類 +- **加熱時間と経験値**: Bedrock の加熱レシピでは指定できないので、Bedrock 側の仕様を使う。対応表は PARTIAL とし、`RECIPE_COOKING_DEFAULTS`(WARN)を出す。 [Bedrock の加熱レシピ仕様](https://learn.microsoft.com/en-us/minecraft/creator/reference/content/recipereference/examples/recipedefinitions/recipe_furnace?view=minecraft-bedrock-stable) - **バニラのアイテム**: 材料・結果にバニラのアイテムがあるレシピは、ID が Java と同じとみなして変換する。ただし PARTIAL にし、`VANILLA_ID_ASSUMED`(WARN)で該当する ID を示す。Bedrock では名前が違うバニラのアイテムがあるため。 ### 黙って欠落させない @@ -79,7 +81,7 @@ Mode B では、Java の MOD のコードを BDS で動かさず、宣言デー - ブロックアイテムのファイルを作らないこと - RP への依存と `.mcaddon` の中身 - `JAVA_LOGIC_NOT_CONVERTED` が出ること - - タグ・かまど・未変換の結果を SKIPPED にすること + - v0.3.0 で非対応だったタグ・かまど・未変換の結果を SKIPPED にすること - バニラの ID を PARTIAL にすること - 4 つの成果物でのキャッシュの検証と、対応表を書き換えたキャッシュを使わないこと - レシピの識別子の衝突で何も作らないこと @@ -94,12 +96,16 @@ Mode B では、Java の MOD のコードを BDS で動かさず、宣言デー ## Minecraft for Windows 26.65 のローカル実測(2026-11-28) -- Bedrock のコンテンツログで、`unlock` がない 1.20 以降のレシピが読み込まれないことを確認した。 -- 変換後の材料 ID を解放条件に入れた定形・不定形レシピは、純正クライアントで読み込みエラーがなく、作業台で fixture のブロック1個からインゴット9個を得て、ブロック1個へ戻せた。Java の進捗に基づく解放条件の変換は対象外。 +- fixture 0.0.4 と Compressed Blocks 1.0.3 の生成済み RP・BP を隔離ワールドに同梱してインポートした。fixture のブロック・アイテムの描画と、サバイバルで試験用加工台と鍛冶台からフォームが開くことを確認した。 +- 試験用加工台で銅インゴット4個のうち2個を消費し、試験用インゴット1個を得た。鍛冶台では丸石18個のうち9個を消費し、圧縮丸石1個を得た。 +- ワールドを保存して開き直した後、加工台と鍛冶台が同じ場所にあり、残った材料と加工結果が所持品に保持された。 +- Bedrock のコンテンツログで、`unlock` がない 1.20 以降のレシピを読み込めないことを確認した。変換後の材料 ID を解放条件に登録すると、レシピブックに表示される。作業台でブロック1個からインゴット9個を取得し、定形レシピでブロック1個に戻せることを確認した。Java の進捗に基づく解放条件の変換は対象外。 +- レシピ修正は PR #25 で先に取り込んだ。加工ルールを含まない PR #25 単体のパックでも、純正クライアントで作業台の両方向のレシピを確認した。 +- v0.4.0 の fixture の加熱レシピ4種は Java 26.3 の実行時レジストリに登録された。生成パックを入れた Windows の隔離ワールドでは、かまど・溶鉱炉・燻製器の出力欄にテストインゴットが入り、通常の焚き火と魂の焚き火からも同じアイテムを回収できた。 ## 未検証・既知の制約 -- 公式 BDS でのパック読込、複数人参加、再起動後の保存は未確認。 +- 公式 BDS でのパックの読込、複数人参加、再起動後の保存は未確認。BDS の起動には、Minecraft の EULA とプライバシーポリシーへの同意が要る。 - BDS への配置と復旧の設計は [ADR-0007](0007-bds-install-and-rollback.md) を参照。 - Java のコードで決まる性質は、Mode A で取得した実行時レジストリから補える見込み。実行時レジストリにスタック数・硬さなどを足すのは、将来の課題。 - レシピのバニラのアイテム ID の対応表は無い。 diff --git a/fixtures/adapter-rules/compressed-blocks.json b/fixtures/adapter-rules/compressed-blocks.json new file mode 100644 index 0000000..28fc2a7 --- /dev/null +++ b/fixtures/adapter-rules/compressed-blocks.json @@ -0,0 +1,28 @@ +{ + "schema": "modbridge.adapter-rules", + "schemaVersion": 1, + "adapters": [ + { + "id": "modbridge_examples:compressed_blocks", + "targetMod": "compressed_blocks", + "versions": ["1.0.3"], + "modes": ["A", "B"], + "menus": [ + { + "id": "modbridge_examples:compression_bench", + "title": "丸石の圧縮", + "blocks": ["minecraft:smithing_table"], + "maxDistance": 5, + "recipes": [ + { + "id": "modbridge_examples:compress_cobblestone", + "label": "丸石9個を圧縮", + "input": {"item": "minecraft:cobblestone", "count": 9}, + "output": {"item": "compressed_blocks:compressed_cobblestone", "count": 1} + } + ] + } + ] + } + ] +} diff --git a/fixtures/adapter-rules/fixture-mode-b.json b/fixtures/adapter-rules/fixture-mode-b.json new file mode 100644 index 0000000..878db69 --- /dev/null +++ b/fixtures/adapter-rules/fixture-mode-b.json @@ -0,0 +1,28 @@ +{ + "schema": "modbridge.adapter-rules", + "schemaVersion": 1, + "adapters": [ + { + "id": "pmb_fixture:machines", + "targetMod": "pmb_fixture", + "versions": ["0.0.4"], + "modes": ["B"], + "menus": [ + { + "id": "pmb_fixture:test_machine", + "title": "試験用加工台", + "blocks": ["pmb_fixture:test_block"], + "maxDistance": 5, + "recipes": [ + { + "id": "pmb_fixture:copper_to_ingot", + "label": "銅インゴット2個を加工", + "input": {"item": "minecraft:copper_ingot", "count": 2}, + "output": {"item": "pmb_fixture:test_ingot", "count": 1} + } + ] + } + ] + } + ] +} diff --git a/fixtures/fabric-fixture/build.gradle b/fixtures/fabric-fixture/build.gradle index 446174c..b83c1f7 100644 --- a/fixtures/fabric-fixture/build.gradle +++ b/fixtures/fabric-fixture/build.gradle @@ -8,10 +8,14 @@ version = project.mod_version group = 'dev.puicore.modbridge' base { archivesName = 'pmb-fabric-fixture' } +def rootProperties = new Properties() +file('../../gradle.properties').withInputStream { rootProperties.load(it) } + dependencies { minecraft "com.mojang:minecraft:${project.minecraft_version}" implementation "net.fabricmc:fabric-loader:${project.loader_version}" implementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_api_version}" + compileOnly('dev.puicore.modbridge:core:' + rootProperties.getProperty('version')) { transitive = false } } processResources { diff --git a/fixtures/fabric-fixture/gradle.properties b/fixtures/fabric-fixture/gradle.properties index 098199c..d153b0c 100644 --- a/fixtures/fabric-fixture/gradle.properties +++ b/fixtures/fabric-fixture/gradle.properties @@ -7,4 +7,4 @@ loader_version=0.20.1 loom_version=1.19.4 fabric_api_version=0.166.2+26.3 -mod_version=0.0.3 +mod_version=0.0.4 diff --git a/fixtures/fabric-fixture/settings.gradle b/fixtures/fabric-fixture/settings.gradle index f9e6a87..a51ff0b 100644 --- a/fixtures/fabric-fixture/settings.gradle +++ b/fixtures/fabric-fixture/settings.gradle @@ -10,3 +10,4 @@ pluginManagement { } rootProject.name = 'pmb-fabric-fixture' +includeBuild('../..') diff --git a/fixtures/fabric-fixture/src/main/java/dev/puicore/modbridge/fixture/FixtureMachineAdapter.java b/fixtures/fabric-fixture/src/main/java/dev/puicore/modbridge/fixture/FixtureMachineAdapter.java new file mode 100644 index 0000000..ffaa94c --- /dev/null +++ b/fixtures/fabric-fixture/src/main/java/dev/puicore/modbridge/fixture/FixtureMachineAdapter.java @@ -0,0 +1,23 @@ +package dev.puicore.modbridge.fixture; + +import dev.puicore.modbridge.core.adapter.Adapter; +import dev.puicore.modbridge.core.ir.BridgeIr.Mode; +import java.util.List; +import java.util.Set; + +/** fixture のブロックを加工台にする最小アダプター。 */ +public final class FixtureMachineAdapter implements Adapter { + @Override + public Descriptor descriptor() { + return new Descriptor("pmb_fixture:machines", API_VERSION, "pmb_fixture", Set.of("0.0.4"), + Set.of(Mode.A), Set.of(Capability.MACHINE_MENU)); + } + + @Override + public void register(Registrar registrar) { + var recipe = new Recipe("pmb_fixture:refine_copper", "銅2個で試験用インゴット1個", + new ItemAmount("minecraft:copper_ingot", 2), new ItemAmount("pmb_fixture:test_ingot", 1)); + registrar.menu(new Menu("pmb_fixture:processing_bench", "試験用加工台", Set.of("pmb_fixture:test_block"), 5, + List.of(recipe))); + } +} diff --git a/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_blasting.json b/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_blasting.json new file mode 100644 index 0000000..fab0f04 --- /dev/null +++ b/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_blasting.json @@ -0,0 +1,9 @@ +{ + "type": "minecraft:blasting", + "ingredient": "pmb_fixture:test_block", + "result": { + "id": "pmb_fixture:test_ingot" + }, + "cookingtime": 200, + "experience": 0.3 +} diff --git a/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_campfire_cooking.json b/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_campfire_cooking.json new file mode 100644 index 0000000..43f3945 --- /dev/null +++ b/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_campfire_cooking.json @@ -0,0 +1,9 @@ +{ + "type": "minecraft:campfire_cooking", + "ingredient": "pmb_fixture:test_block", + "result": { + "id": "pmb_fixture:test_ingot" + }, + "cookingtime": 600, + "experience": 0.3 +} diff --git a/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_smelting.json b/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_smelting.json new file mode 100644 index 0000000..18ab63c --- /dev/null +++ b/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_smelting.json @@ -0,0 +1,9 @@ +{ + "type": "minecraft:smelting", + "ingredient": "pmb_fixture:test_block", + "result": { + "id": "pmb_fixture:test_ingot" + }, + "cookingtime": 200, + "experience": 0.3 +} diff --git a/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_smoking.json b/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_smoking.json new file mode 100644 index 0000000..745f634 --- /dev/null +++ b/fixtures/fabric-fixture/src/main/resources/data/pmb_fixture/recipe/test_ingot_from_smoking.json @@ -0,0 +1,9 @@ +{ + "type": "minecraft:smoking", + "ingredient": "pmb_fixture:test_block", + "result": { + "id": "pmb_fixture:test_ingot" + }, + "cookingtime": 200, + "experience": 0.3 +} diff --git a/fixtures/fabric-fixture/src/main/resources/fabric.mod.json b/fixtures/fabric-fixture/src/main/resources/fabric.mod.json index 4e1a95d..3bfbdda 100644 --- a/fixtures/fabric-fixture/src/main/resources/fabric.mod.json +++ b/fixtures/fabric-fixture/src/main/resources/fabric.mod.json @@ -8,7 +8,8 @@ "license": "LicenseRef-Undecided", "environment": "*", "entrypoints": { - "main": ["dev.puicore.modbridge.fixture.FixtureMod"] + "main": ["dev.puicore.modbridge.fixture.FixtureMod"], + "modbridge-adapter": ["dev.puicore.modbridge.fixture.FixtureMachineAdapter"] }, "depends": { "fabricloader": ">=0.20.1", diff --git a/gradle.properties b/gradle.properties index 9f1e347..7c66119 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,4 +2,4 @@ org.gradle.jvmargs=-Xmx1G -Dfile.encoding=UTF-8 org.gradle.parallel=true org.gradle.caching=true group=dev.puicore.modbridge -version=0.0.1-SNAPSHOT +version=0.4.0-SNAPSHOT diff --git a/platform-fabric/build.gradle b/platform-fabric/build.gradle index 832b2e8..72b989b 100644 --- a/platform-fabric/build.gradle +++ b/platform-fabric/build.gradle @@ -17,7 +17,7 @@ base { archivesName = 'modbridge-fabric' } // コンパイル時だけ参照する(実行時は、サーバーに入っている Geyser を使う)。値は scripts/spike-server.sh と同じ。 def geyserUrl = 'https://download.geysermc.org/v2/projects/geyser/versions/2.12.1/builds/1312/downloads/fabric' def geyserSha = '9c059b51af0bd534922ca9633996fd124543291d137b9373edc95fc1a0d59276' -def geyserNested = ['META-INF/jars/events-1.1-SNAPSHOT.jar', 'META-INF/jars/base-api-1.0.3.jar'] +def geyserNested = ['META-INF/jars/events-1.1-SNAPSHOT.jar', 'META-INF/jars/base-api-1.0.3.jar', 'META-INF/jars/cumulus-1.1.2.jar'] def geyserDir = layout.buildDirectory.dir('geyser-api') def fetchGeyserApi = tasks.register('fetchGeyserApi') { @@ -66,7 +66,7 @@ dependencies { include('dev.puicore.modbridge:core:' + project.core_version) compileOnly files(geyserDir.map { it.file('Geyser-Fabric.jar') }, geyserDir.map { it.file('events-1.1-SNAPSHOT.jar') }, - geyserDir.map { it.file('base-api-1.0.3.jar') }).builtBy(fetchGeyserApi) + geyserDir.map { it.file('base-api-1.0.3.jar') }, geyserDir.map { it.file('cumulus-1.1.2.jar') }).builtBy(fetchGeyserApi) } processResources { diff --git a/platform-fabric/gradle.properties b/platform-fabric/gradle.properties index 3e28ac6..17f89b0 100644 --- a/platform-fabric/gradle.properties +++ b/platform-fabric/gradle.properties @@ -7,7 +7,7 @@ loader_version=0.20.1 loom_version=1.19.4 fabric_api_version=0.166.2+26.3 -mod_version=0.2.0 +mod_version=0.4.0-SNAPSHOT # ルートの gradle.properties の version と同じ値を保つ(composite build で core を取り込む) -core_version=0.0.1-SNAPSHOT +core_version=0.4.0-SNAPSHOT diff --git a/platform-fabric/src/main/java/dev/puicore/modbridge/platform/fabric/ModBridgeFabric.java b/platform-fabric/src/main/java/dev/puicore/modbridge/platform/fabric/ModBridgeFabric.java index 0a9795b..a3c2d3c 100644 --- a/platform-fabric/src/main/java/dev/puicore/modbridge/platform/fabric/ModBridgeFabric.java +++ b/platform-fabric/src/main/java/dev/puicore/modbridge/platform/fabric/ModBridgeFabric.java @@ -41,6 +41,9 @@ public void onInitializeServer() { String dumpTarget = System.getProperty("modbridge.registryDump"); boolean stop = Boolean.getBoolean("modbridge.registryDump.stop"); boolean geyser = FabricLoader.getInstance().isModLoaded("geyser-fabric"); + if (geyser) { + new ServerMachineMenus().install(); + } boolean permissive = policy == Policy.PERMISSIVE && geyser; if (permissive) { diff --git a/platform-fabric/src/main/java/dev/puicore/modbridge/platform/fabric/ServerMachineMenus.java b/platform-fabric/src/main/java/dev/puicore/modbridge/platform/fabric/ServerMachineMenus.java new file mode 100644 index 0000000..d9117c6 --- /dev/null +++ b/platform-fabric/src/main/java/dev/puicore/modbridge/platform/fabric/ServerMachineMenus.java @@ -0,0 +1,216 @@ +package dev.puicore.modbridge.platform.fabric; + +import dev.puicore.modbridge.core.adapter.Adapter; +import dev.puicore.modbridge.core.adapter.AdapterRegistry; +import dev.puicore.modbridge.core.adapter.AdapterRules; +import dev.puicore.modbridge.core.adapter.MachineSessions; +import dev.puicore.modbridge.core.adapter.MachineSessions.PlayerAccess; +import dev.puicore.modbridge.core.adapter.MachineSessions.Position; +import dev.puicore.modbridge.core.adapter.MachineSessions.Result; +import dev.puicore.modbridge.core.adapter.MachineSessions.Stack; +import dev.puicore.modbridge.core.adapter.MachineSessions.Target; +import dev.puicore.modbridge.core.ir.BridgeIr.Mode; +import java.io.IOException; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; +import net.fabricmc.fabric.api.event.player.UseBlockCallback; +import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.core.BlockPos; +import net.minecraft.core.SectionPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import org.geysermc.cumulus.form.SimpleForm; +import org.geysermc.geyser.api.GeyserApi; + +/** Geyser のフォーム応答を Fabric のサーバースレッドへ渡す。 */ +final class ServerMachineMenus { + private final MachineSessions sessions = new MachineSessions(Duration.ofSeconds(30)); + private AdapterRegistry adapters; + + void install() { + ServerLifecycleEvents.SERVER_STARTING.register(server -> loadAdapters()); + ServerLifecycleEvents.SERVER_STOPPED.register(server -> { + if (adapters != null) { + try { + adapters.close(); + } finally { + adapters = null; + } + } + }); + ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> sessions.disconnect(handler.getPlayer().getUUID())); + UseBlockCallback.EVENT.register((player, level, hand, hit) -> player instanceof ServerPlayer serverPlayer + && hand == InteractionHand.MAIN_HAND ? open(serverPlayer, hit.getBlockPos()) : InteractionResult.PASS); + } + + private void loadAdapters() { + var trusted = Arrays.stream(System.getProperty("modbridge.adapters.trusted", "").split(",")) + .map(String::strip).filter(id -> !id.isEmpty()).collect(Collectors.toUnmodifiableSet()); + FabricLoader loader = FabricLoader.getInstance(); + var mods = loader.getAllMods().stream() + .map(mod -> mod.getMetadata()) + .collect(Collectors.toMap(m -> m.getId(), m -> m.getVersion().getFriendlyString())); + var candidates = loader.getEntrypointContainers("modbridge-adapter", Adapter.class).stream() + .map(entry -> new AdapterRegistry.Candidate(entry.getProvider().getMetadata().getId(), entry::getEntrypoint)) + .toList(); + adapters = AdapterRegistry.load(candidates, trusted, mods, Mode.A, rules()); + adapters.activeAdapters().forEach(adapter -> ModBridgeFabric.LOG.info("[modbridge] adapter active: {}", adapter.id())); + } + + private static List rules() { + String file = System.getProperty("modbridge.adapters.rules"); + if (file == null || file.isBlank()) { + return List.of(); + } + try { + return AdapterRules.read(Path.of(file)); + } catch (IOException failure) { + throw new IllegalStateException("modbridge: 加工アダプターのルールを読み込めません", failure); + } + } + + private InteractionResult open(ServerPlayer player, BlockPos pos) { + if (adapters == null || player.isShiftKeyDown()) { + return InteractionResult.PASS; + } + var level = player.level(); + String block = blockId(level, pos); + var menu = adapters.menuForBlock(block).orElse(null); + if (menu == null) { + return InteractionResult.PASS; + } + UUID playerId = player.getUUID(); + var connection = GeyserApi.api().connectionByUuid(playerId); + if (connection == null) { + return InteractionResult.PASS; + } + var target = new Target(level.dimension().identifier().toString(), pos.getX(), pos.getY(), pos.getZ(), block); + var view = sessions.open(playerId, target, menu, new ServerAccess(player)).orElse(null); + if (view == null) { + return InteractionResult.PASS; + } + MinecraftServer server = level.getServer(); + UUID token = view.token(); + var form = SimpleForm.builder().title(view.menu().title()); + view.menu().recipes().forEach(recipe -> form.button(recipe.label())); + form.validResultHandler(response -> server.execute(() -> handle(server, playerId, token, response.clickedButtonId()))); + form.closedOrInvalidResultHandler(() -> server.execute(() -> sessions.cancel(playerId, token))); + if (!connection.sendForm(form)) { + sessions.cancel(playerId, token); + return InteractionResult.PASS; + } + return InteractionResult.SUCCESS_SERVER; + } + + private void handle(MinecraftServer server, UUID playerId, UUID token, int choice) { + ServerPlayer current = server.getPlayerList().getPlayer(playerId); + if (current == null) { + sessions.disconnect(playerId); + return; + } + Result result = sessions.select(playerId, token, choice, new ServerAccess(current)); + if (result == Result.STALE) { + return; + } + current.sendOverlayMessage(Component.literal(switch (result) { + case APPLIED -> "加工しました"; + case INPUT_MISSING -> "加工に必要な材料が足りません"; + case OUTPUT_FULL -> "加工結果を入れる空きがありません"; + case EXPIRED -> "加工画面の期限が切れました"; + default -> "加工できませんでした。ブロックを操作して開き直してください"; + })); + } + + private static String blockId(ServerLevel level, BlockPos pos) { + return level.getChunkSource().hasChunk(SectionPos.blockToSectionCoord(pos.getX()), SectionPos.blockToSectionCoord(pos.getZ())) + ? BuiltInRegistries.BLOCK.getKey(level.getBlockState(pos).getBlock()).toString() : ""; + } + + private record ServerAccess(ServerPlayer player) implements PlayerAccess { + @Override + public Position position() { + return new Position(player.level().dimension().identifier().toString(), player.getX(), player.getY(), player.getZ()); + } + + @Override + public boolean mayOperate(Target target) { + return player.isAlive() && !player.isSpectator() && player.getAbilities().mayBuild + && player.mayInteract(player.level(), position(target)); + } + + @Override + public String blockAt(Target target) { + return blockId(player.level(), position(target)); + } + + private static BlockPos position(Target target) { + return new BlockPos(target.x(), target.y(), target.z()); + } + + @Override + public List inventory() { + Inventory inventory = player.getInventory(); + return IntStream.range(0, inventory.getNonEquipmentItems().size()).mapToObj(slot -> { + ItemStack stack = inventory.getItem(slot); + return stack.isEmpty() ? Stack.EMPTY : new Stack(BuiltInRegistries.ITEM.getKey(stack.getItem()).toString(), + stack.getCount(), Math.max(stack.getCount(), stack.getMaxStackSize()), + stack.getComponentsPatch().isEmpty() && stack.getCount() <= stack.getMaxStackSize()); + }).toList(); + } + + @Override + public int stackLimit(String itemId) { + Item item = item(itemId); + return item == null ? 0 : new ItemStack(item).getMaxStackSize(); + } + + @Override + public boolean replaceInventory(List expected, List updated) { + if (!inventory().equals(expected) || expected.size() != updated.size()) { + return false; + } + var changes = new LinkedHashMap(); + for (int slot = 0; slot < updated.size(); slot++) { + Stack next = updated.get(slot); + if (expected.get(slot).equals(next)) { + continue; + } + if (next.count() == 0) { + changes.put(slot, ItemStack.EMPTY); + } else { + Item item = item(next.item()); + if (item == null) { + return false; + } + changes.put(slot, new ItemStack(item, next.count())); + } + } + Inventory inventory = player.getInventory(); + changes.forEach(inventory::setItem); + inventory.setChanged(); + player.containerMenu.broadcastChanges(); + return true; + } + + private static Item item(String id) { + return BuiltInRegistries.ITEM.getOptional(Identifier.parse(id)).orElse(null); + } + } +} diff --git a/platform-fabric/src/main/resources/fabric.mod.json b/platform-fabric/src/main/resources/fabric.mod.json index 917f55a..87056e3 100644 --- a/platform-fabric/src/main/resources/fabric.mod.json +++ b/platform-fabric/src/main/resources/fabric.mod.json @@ -15,7 +15,9 @@ "fabricloader": ">=0.20.1", "minecraft": "~26.3", "java": ">=25", - "fabric-lifecycle-events-v1": "*" + "fabric-lifecycle-events-v1": "*", + "fabric-events-interaction-v0": "*", + "fabric-networking-api-v1": "*" }, "suggests": { "geyser-fabric": "*" diff --git a/scripts/test-bedrock-machine-menus.mjs b/scripts/test-bedrock-machine-menus.mjs new file mode 100644 index 0000000..e255c7d --- /dev/null +++ b/scripts/test-bedrock-machine-menus.mjs @@ -0,0 +1,202 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import { runInNewContext } from "node:vm"; + +const source = readFileSync(new URL( + "../core/src/main/resources/dev/puicore/modbridge/core/compile/bedrock-machine-menus.js", import.meta.url), "utf8") + .replace(/^import .+;\r?\n/gm, ""); +const location = { x: 0, y: 64, z: 0 }; +const recipe = { + label: "Process copper", + input: { item: "minecraft:copper_ingot", count: 2 }, + output: { item: "fixture:test_ingot", count: 1 } +}; +const station = { block: "fixture:machine", title: "Machine", maxDistance: 5, recipes: [recipe] }; + +class ItemStack { + constructor(typeId, amount = 1, custom = false) { + this.typeId = typeId; + this.amount = amount; + this.custom = custom; + this.maxAmount = 64; + } + + isStackableWith(other) { + return this.typeId === other.typeId && this.custom === other.custom; + } + + clone() { + return new ItemStack(this.typeId, this.amount, this.custom); + } +} + +function player(id, slots = [new ItemStack(recipe.input.item, 2), undefined]) { + const inventory = { + size: slots.length, + getItem: slot => slots[slot]?.clone(), + setItem(slot, item) { + slots[slot] = item?.clone(); + if (slot === this.failOnceAt) { + delete this.failOnceAt; + throw new Error("slot write failed"); + } + } + }; + return { + id, location: { ...location }, mode: "survival", playerPermissionLevel: 1, isValid: true, inventory, slots, + dimension: { id: "overworld", block: station.block, getBlock() { return { typeId: this.block }; } }, + getGameMode() { return this.mode; }, + getComponent(type) { + return type === "minecraft:health" ? { currentValue: 20 } : { container: inventory }; + }, + onScreenDisplay: { setActionBar() {} } + }; +} + +function harness() { + const forms = []; + const timers = new Set(); + const warnings = []; + let currentTick = 1000; + let beforeInteract; + let onLeave; + class ActionFormData { + title() { return this; } + button() { return this; } + show(player) { + return new Promise(resolve => forms.push({ player, resolve })); + } + } + runInNewContext(source + "\nregisterMachineMenus(stations);", { + ItemStack, ActionFormData, stations: [station], + GameMode: { Survival: "survival" }, + PlayerPermissionLevel: { Visitor: 0, Member: 1, Operator: 2, Custom: 3 }, + world: { + beforeEvents: { playerInteractWithBlock: { subscribe: listener => { beforeInteract = listener; } } }, + afterEvents: { playerLeave: { subscribe: listener => { onLeave = listener; } } } + }, + system: { + get currentTick() { return currentTick; }, + run: callback => callback(), + runTimeout: callback => { timers.add(callback); return callback; }, + clearRun: callback => timers.delete(callback) + }, + console: { warn: message => warnings.push(message) } + }); + return { + forms, warnings, + click(player, isFirstEvent = true, cancel = false) { + const event = { + player, isFirstEvent, cancel, + block: { typeId: station.block, dimension: player.dimension, location } + }; + beforeInteract(event); + return event.cancel; + }, + leave: player => onLeave({ playerId: player.id }), + advanceTicks: ticks => { currentTick += ticks; }, + expire: () => timers.forEach(callback => callback()) + }; +} + +function inventory(player) { + return player.slots.flatMap(stack => stack ? [[stack.typeId, stack.amount, stack.custom]] : []); +} + +const settleForms = () => new Promise(resolve => setImmediate(resolve)); + +test("overlapping responses only update their own inventories and consume each selection once", async () => { + const { click, forms } = harness(); + const first = player("first"); + const second = player("second"); + click(first); + click(first, false); + click(first); + click(second); + assert.deepEqual(forms.map(form => form.player.id), ["first", "second"]); + forms[1].resolve({ selection: 0 }); + forms[0].resolve({ selection: 0 }); + forms[0].resolve({ selection: 0 }); + await settleForms(); + for (const who of [first, second]) assert.deepEqual(inventory(who), [[recipe.output.item, 1, false]]); +}); + +test("expiry, leaving, distance, permissions, changed block and invalid choices prevent processing", async () => { + const reject = [ + (qa) => { qa.expire(); }, + (qa, who) => { qa.leave(who); }, + (qa, who) => { who.location.x = 20; }, + (qa, who) => { who.mode = "creative"; }, + (qa, who) => { who.playerPermissionLevel = 0; }, + (qa, who) => { who.dimension.id = "nether"; }, + (qa, who) => { who.dimension.block = "minecraft:air"; } + ]; + for (const change of reject) { + const qa = harness(); + const who = player("first"); + qa.click(who); + change(qa, who); + qa.forms[0].resolve({ selection: 0 }); + await settleForms(); + assert.deepEqual(inventory(who), [[recipe.input.item, 2, false]]); + } + for (const response of [{ selection: -1 }, { selection: 0, canceled: true }, { selection: "0" }]) { + const qa = harness(); + const who = player("first"); + qa.click(who); + qa.forms[0].resolve(response); + await settleForms(); + assert.deepEqual(inventory(who), [[recipe.input.item, 2, false]]); + } +}); + +test("visitors, custom roles and interactions already canceled do not open forms", () => { + const qa = harness(); + const who = player("first"); + for (const role of [0, 3]) { + who.playerPermissionLevel = role; + assert.equal(qa.click(who), false); + } + who.playerPermissionLevel = 1; + assert.equal(qa.click(who, true, true), true); + assert.equal(qa.forms.length, 0); +}); + +test("selection observes the server deadline even before the cleanup callback runs", async () => { + const qa = harness(); + const onTime = player("on-time"); + const expired = player("expired"); + qa.click(onTime); + qa.click(expired); + qa.advanceTicks(599); + qa.forms[0].resolve({ selection: 0 }); + await settleForms(); + assert.deepEqual(inventory(onTime), [[recipe.output.item, 1, false]]); + + qa.advanceTicks(1); + qa.forms[1].resolve({ selection: 0 }); + await settleForms(); + assert.deepEqual(inventory(expired), [[recipe.input.item, 2, false]]); + + qa.click(expired); + qa.forms[2].resolve({ selection: 0 }); + await settleForms(); + assert.deepEqual(inventory(expired), [[recipe.output.item, 1, false]]); +}); + +test("full inventories, custom materials and a failed slot write preserve the inventory", async () => { + const qa = harness(); + const full = player("full", [new ItemStack(recipe.input.item, 3), new ItemStack("minecraft:stone", 64)]); + const custom = player("custom", [new ItemStack(recipe.input.item, 2, true), undefined]); + const failure = player("failure", [new ItemStack(recipe.input.item, 3), undefined]); + failure.inventory.failOnceAt = 1; + for (const [i, who] of [full, custom, failure].entries()) { + const original = inventory(who); + qa.click(who); + qa.forms[i].resolve({ selection: 0 }); + await settleForms(); + assert.deepEqual(inventory(who), original); + } + assert.deepEqual(qa.warnings, ["ModBridge machine menu: Error: slot write failed"]); +});