diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 97aafc8..095fd35 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -51,6 +51,7 @@ The following is the public MCP tool surface; the companion may perform several | `list_asset_categories` | — | | `list_asset_packs` | — | | `prepare_map_with_packs` | `filename`, `packs` | +| `create_image_pack` | `filename`, `name`, `images`, `pack_id`, `author` | | `list_assets` | `category`, `search`, `limit`, `vanilla_only`, `match_mode`, `min_score`, `searches` | | `preview_assets` | `assets`, `category`, `columns`, `cell_px` | | `repair_terrain` | `force` | diff --git a/docs/README.md b/docs/README.md index 7836457..09d0d86 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,4 +7,5 @@ Contributor references in this folder: - [Developer installation](developer-installation.md) - [Bridge protocol](PROTOCOL.md) - [Build release packages](releases.md) +- [Generated tagged asset packs](image-pack.md) - [Contributing](../CONTRIBUTING.md) diff --git a/docs/image-pack.md b/docs/image-pack.md new file mode 100644 index 0000000..8902c41 --- /dev/null +++ b/docs/image-pack.md @@ -0,0 +1,36 @@ +# Generated tagged asset packs + +`create_image_pack(filename, name, images, pack_id="", author="")` writes a +native `.dungeondraft_pack` of named, tagged PNG objects into Dungeondraft's +configured asset folder only (Settings > Assets, or `BATTLEMAP_MCP_ASSETS_DIR`). +`filename` is a bare new pack name in that folder; existing files are never +overwritten. Publication opens the destination with `O_CREAT|O_EXCL`, so it +works on exFAT, FAT32, and network shares that do not support hard links. + +Each image needs an absolute PNG path, a library name, and descriptive tags. +PNG alpha is preserved. Limits match embedded import: 32 MiB per PNG, 8192 px +per side, 16 million pixels; packs at most 100 images and 256 MiB of image +bytes. The reserved Colorable tag is refused. + +## Workflow + +1. Call `create_image_pack` with a project-related pack name and its images. +2. In Dungeondraft, rescan packs from the Assets window, or restart the editor. + This companion does **not** call `Assets.UpdateTree` / `refresh_asset_packs`. +3. Save the map, then `prepare_map_with_packs(new_map_name, [pack_id])`. +4. Find assets with `list_assets` or `search_pack_contents` and `place_object`. + +`search_pack_contents` can already see the new archive on disk before a rescan. +`list_asset_packs` and `prepare_map_with_packs` need the editor to have mounted +it. Prefer a new pack id during a live session; Dungeondraft caches loaded ids. +Never move or remove a mounted pack while the editor is running. + +Embedded `import_image` objects stay self-contained in the map and do not join +the library. Use a pack when you need searchable, reusable library entries. + +## Validation + +Offline coverage: `server/tests/test_image_import.py`. + +Maintainer documentation needing a matching update: the public tool reference +and asset-pack workflow pages at https://knownframe.com/battlemap-mcp/docs/. diff --git a/server/battlemap_mcp/bridge_client.py b/server/battlemap_mcp/bridge_client.py index d9de4a0..e5d7f80 100644 --- a/server/battlemap_mcp/bridge_client.py +++ b/server/battlemap_mcp/bridge_client.py @@ -45,6 +45,7 @@ { "arrange_objects", "clear_captures", + "create_image_pack", "crop_map", "export_dd2vtt", "get_export", diff --git a/server/battlemap_mcp/image_import.py b/server/battlemap_mcp/image_import.py index ea30dfd..52b83c9 100644 --- a/server/battlemap_mcp/image_import.py +++ b/server/battlemap_mcp/image_import.py @@ -1,16 +1,27 @@ -"""Check a local PNG before the bridge embeds it in the map (import_image).""" +"""Local PNG checks for import_image, and building tagged asset packs.""" from __future__ import annotations +import hashlib import io +import json +import os +import re +import struct from pathlib import Path +from uuid import uuid4 +from . import pack_contents from .errors import ValidationError +from .validation import require_bare_filename # The bridge refuses the same limits before it decodes anything. MAX_BYTES = 32 * 1024 * 1024 MAX_SIDE = 8192 MAX_PIXELS = 16_000_000 +MAX_PACK_IMAGES = 100 +MAX_PACK_IMAGE_BYTES = 256 * 1024 * 1024 +PACK_SUFFIX = pack_contents.PACK_SUFFIX def read_png(path: str) -> bytes: @@ -38,3 +49,137 @@ def read_png(path: str) -> bytes: except (OSError, ValueError, Image.DecompressionBombError) as exc: raise ValidationError(f"invalid or oversized PNG: {exc}") from exc return data + + +def _pack_destination(filename: str) -> Path: + """Resolve a bare pack filename inside Dungeondraft's configured asset folder.""" + folder = pack_contents.assets_directory() + bare = require_bare_filename(filename) + if not bare.endswith(PACK_SUFFIX): + bare += PACK_SUFFIX + # require_bare_filename already forbids separators; keep the join closed. + root = folder.resolve() + destination = (folder / bare).resolve() + if destination.parent != root or not destination.name.endswith(PACK_SUFFIX): + raise ValidationError( + f"filename resolves outside the asset pack folder ({destination}); refusing" + ) + return destination + + +def _open_new_pack(destination: Path): + """Open destination for exclusive create; never replace an existing file. + + Uses O_CREAT|O_EXCL so publication works on filesystems that lack hard + links (exFAT, FAT32, many network shares). A competing writer that claimed + the name first becomes FileExistsError. + """ + flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY + if hasattr(os, "O_BINARY"): + flags |= os.O_BINARY + try: + fd = os.open(destination, flags, 0o644) + except FileExistsError as exc: + raise ValidationError(f"{destination.name} already exists; choose a new filename") from exc + return os.fdopen(fd, "wb") + + +def build_pack( + filename: str, name: str, images: list[dict], pack_id: str = "", author: str = "" +) -> dict: + """Write a new tagged .dungeondraft_pack into the configured asset folder.""" + destination = _pack_destination(filename) + if destination.exists() or destination.is_symlink(): + raise ValidationError(f"{destination.name} already exists; choose a new filename") + if not name.strip() or len(name) > 120: + raise ValidationError("name must contain 1-120 characters") + pack_id = pack_id or uuid4().hex[:8] + if not re.fullmatch(r"[A-Za-z0-9]{8}", pack_id): + raise ValidationError("pack_id must be eight letters or digits") + if not 1 <= len(images) <= MAX_PACK_IMAGES: + raise ValidationError(f"provide 1-{MAX_PACK_IMAGES} images") + files: dict[str, bytes] = {} + tags: dict[str, list[str]] = {} + assets = [] + total = 0 + for item in images: + asset_name = item["name"] + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9 _-]{0,99}", asset_name): + raise ValidationError("image name must be 1-100 letters, digits, spaces, _ or -") + relative = f"textures/objects/{asset_name}.png" + if relative.casefold() in {key.casefold() for key in files}: + raise ValidationError("image names must be unique ignoring case") + asset_tags = item["tags"] + if not 1 <= len(asset_tags) <= 32 or any( + not tag.strip() or len(tag) > 80 or any(ord(c) < 32 for c in tag) for tag in asset_tags + ): + raise ValidationError("each image needs 1-32 nonempty tags, at most 80 characters each") + # Colorable is an engine instruction, not descriptive metadata. + asset_tags = list(dict.fromkeys(tag.strip() for tag in asset_tags)) + if any(tag.casefold() == "colorable" for tag in asset_tags): + raise ValidationError("Colorable is reserved; it would recolor the imported artwork") + data = read_png(item["path"]) + total += len(data) + if total > MAX_PACK_IMAGE_BYTES: + raise ValidationError("pack images must total at most 256 MiB") + files[relative] = data + for tag in dict.fromkeys(tag.strip() for tag in asset_tags): + tags.setdefault(tag, []).append(relative) + assets.append( + {"name": asset_name, "asset": f"res://packs/{pack_id}/{relative}", "tags": asset_tags} + ) + meta = { + "id": pack_id, + "name": name, + "author": author, + "version": "1.0", + "allow_3rd_party_mapping_software_to_read": True, + } + files["pack.json"] = json.dumps(meta).encode() + files["data/default.dungeondraft_tags"] = json.dumps( + {"tags": tags, "sets": {name: list(tags)}} + ).encode() + files = {f"res://packs/{pack_id}/{key}": value for key, value in files.items()} + # Native pack enumeration reads this root manifest; the inner pack.json is + # also emitted by Dungeondraft's own packager and read by our indexer. + files[f"res://packs/{pack_id}.json"] = json.dumps(meta).encode() + names = [key.encode() for key in files] + names = [value + b"\0" * (-len(value) % 4) for value in names] + offset = 88 + sum(4 + len(value) + 32 for value in names) + index = bytearray() + for entry, data in zip(names, files.values(), strict=True): + index.extend(struct.pack(" dict: + """Build a native, reusable .dungeondraft_pack of named, tagged PNG objects. + + Writes only into Dungeondraft's configured asset folder (Settings > Assets), + never to an arbitrary path. filename: bare NEW .dungeondraft_pack name in + that folder; existing files are never overwritten. name: pack title related + to the map/project. Each image needs an absolute PNG path, a library name, + and descriptive tags (e.g. furniture, workshop, oak). PNG alpha is kept. + pack_id: optional eight alphanumeric characters; generated if omitted. + + This creates a complete pack; it does not edit third-party archives. To + extend a collection, rebuild from the full image list under a new filename. + Prefer a new id during a live session; Dungeondraft caches loaded pack ids. + + After writing, rescan packs in the Assets window (or restart Dungeondraft), + then prepare_map_with_packs with the returned id. This tool does not refresh + the editor or change the open map's included packs. search_pack_contents can + already list the new archive from disk. Embedded import_image objects stay + map-local; these pack assets become searchable library entries once included. + """ + entries = [PackImage.model_validate(item).model_dump() for item in images] + return image_import.build_pack(filename, name, entries, pack_id, author) + + @tool() def place_object( asset: str, diff --git a/server/tests/test_image_import.py b/server/tests/test_image_import.py index d6717cd..302012f 100644 --- a/server/tests/test_image_import.py +++ b/server/tests/test_image_import.py @@ -1,10 +1,12 @@ +import os import struct import zlib +from pathlib import Path import pytest from PIL import Image -from battlemap_mcp import image_import, server +from battlemap_mcp import image_import, pack_contents, server from battlemap_mcp.errors import ValidationError @@ -15,6 +17,14 @@ def png(tmp_path): return path +@pytest.fixture +def assets_dir(tmp_path, monkeypatch): + folder = tmp_path / "assets" + folder.mkdir() + monkeypatch.setenv(pack_contents.ASSETS_DIR_ENV, str(folder)) + return folder + + def test_embedded_request(png, monkeypatch): calls = [] monkeypatch.setattr( @@ -68,7 +78,7 @@ def test_oversized_png_is_refused_before_decoding(tmp_path): image_import.read_png(str(big)) -def test_valid_png_chunks_with_corrupt_pixels_are_rejected(png): +def test_valid_png_chunks_with_corrupt_pixels_are_rejected(png, assets_dir): def chunk(kind, data): return ( struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) @@ -81,4 +91,108 @@ def chunk(kind, data): + chunk(b"IEND", b"") ) with pytest.raises(ValidationError, match="invalid"): - image_import.read_png(str(png)) + image_import.build_pack( + "bad.dungeondraft_pack", + "Project", + [{"path": str(png), "name": "Test", "tags": ["Wood"]}], + ) + assert not (assets_dir / "bad.dungeondraft_pack").exists() + + +def test_native_pack_roundtrip(png, assets_dir): + result = server.create_image_pack( + "Project.dungeondraft_pack", + "Project props", + [{"path": str(png), "name": "Test prop", "tags": ["Workshop", "Wood"]}], + pack_id="test1234", + ) + output = assets_dir / "Project.dungeondraft_pack" + assert result["path"] == str(output.resolve()) + pack = pack_contents.read_pack(output) + assert pack.name == "Project props" + [(asset, tags)] = pack.assets["Objects"] + assert tags == ("Workshop", "Wood") + assert asset == result["assets"][0]["asset"] + with output.open("rb") as handle: + handle.seek(84) + count = struct.unpack("