Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
36 changes: 36 additions & 0 deletions docs/image-pack.md
Original file line number Diff line number Diff line change
@@ -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/.
1 change: 1 addition & 0 deletions server/battlemap_mcp/bridge_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
{
"arrange_objects",
"clear_captures",
"create_image_pack",
"crop_map",
"export_dd2vtt",
"get_export",
Expand Down
147 changes: 146 additions & 1 deletion server/battlemap_mcp/image_import.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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("<I", len(entry)) + entry)
index.extend(struct.pack("<QQ", offset, len(data)) + hashlib.md5(data).digest())
offset += len(data)
created = False
try:
with _open_new_pack(destination) as handle:
created = True
handle.write(struct.pack("<5I", pack_contents.PCK_MAGIC, 1, 3, 4, 2) + b"\0" * 64)
handle.write(struct.pack("<I", len(files)) + index)
for data in files.values():
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
except Exception:
# Only remove a file this call created; never a competing writer's.
if created:
try:
os.unlink(destination)
except OSError:
pass
raise
return {
"path": str(destination),
"pack": meta,
"assets": assets,
"installed": False,
"included_in_map": False,
"note": "Wrote into Dungeondraft's configured asset folder. "
"Rescan packs in the Assets window (or restart Dungeondraft), then include "
"this pack with prepare_map_with_packs. This tool does not call Assets.UpdateTree. "
"search_pack_contents can already see the new archive on disk. "
"Use a new pack id for additions during a session: already-loaded pack ids "
"are cached until Dungeondraft restarts. Keep old packs for existing maps. "
"Never move or remove a mounted pack while Dungeondraft is running.",
}
41 changes: 41 additions & 0 deletions server/battlemap_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -2108,6 +2108,7 @@ def import_image(
checkpoints. The image does not join the asset library, so list_assets
will not find it. Reimporting changed bytes makes a new texture.
PNG only: at most 32 MiB, 8192 px per side and 16 million pixels.
For a reusable tagged library entry, use create_image_pack instead.
"""
source = Path(path).expanduser()
if not source.is_absolute() or not source.is_file():
Expand Down Expand Up @@ -2142,6 +2143,46 @@ def import_image(
return _with_snap(bridge.request("import_image", **params), snap_info)


class PackImage(BaseModel):
"""A PNG and its searchable library name and tags."""

model_config = ConfigDict(extra="forbid")
path: str
name: str
tags: list[str]


@tool()
def create_image_pack(
filename: str,
name: str,
images: list[PackImage],
pack_id: str = "",
author: str = "",
) -> 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,
Expand Down
Loading
Loading