battlemap-mcp 1.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. battlemap_mcp-1.5.0/LICENSE +22 -0
  2. battlemap_mcp-1.5.0/NOTICE.md +25 -0
  3. battlemap_mcp-1.5.0/PKG-INFO +147 -0
  4. battlemap_mcp-1.5.0/README.md +108 -0
  5. battlemap_mcp-1.5.0/battlemap_mcp/__init__.py +3 -0
  6. battlemap_mcp-1.5.0/battlemap_mcp/__main__.py +6 -0
  7. battlemap_mcp-1.5.0/battlemap_mcp/arrangement.py +107 -0
  8. battlemap_mcp-1.5.0/battlemap_mcp/asset_packs.py +254 -0
  9. battlemap_mcp-1.5.0/battlemap_mcp/asset_search.py +195 -0
  10. battlemap_mcp-1.5.0/battlemap_mcp/bridge_client.py +584 -0
  11. battlemap_mcp-1.5.0/battlemap_mcp/bridge_payload/battlemap-mcp-bridge/LICENSE +22 -0
  12. battlemap_mcp-1.5.0/battlemap_mcp/bridge_payload/battlemap-mcp-bridge/icons/mcp_bridge.png +0 -0
  13. battlemap_mcp-1.5.0/battlemap_mcp/bridge_payload/battlemap-mcp-bridge/mcp_bridge.ddmod +9 -0
  14. battlemap_mcp-1.5.0/battlemap_mcp/bridge_payload/battlemap-mcp-bridge/scripts/tools/mcp_bridge.gd +9405 -0
  15. battlemap_mcp-1.5.0/battlemap_mcp/cli.py +606 -0
  16. battlemap_mcp-1.5.0/battlemap_mcp/client_config.py +367 -0
  17. battlemap_mcp-1.5.0/battlemap_mcp/colors.py +78 -0
  18. battlemap_mcp-1.5.0/battlemap_mcp/companion_update.py +511 -0
  19. battlemap_mcp-1.5.0/battlemap_mcp/cropping.py +138 -0
  20. battlemap_mcp-1.5.0/battlemap_mcp/errors.py +103 -0
  21. battlemap_mcp-1.5.0/battlemap_mcp/floorplan.py +382 -0
  22. battlemap_mcp-1.5.0/battlemap_mcp/geometry.py +72 -0
  23. battlemap_mcp-1.5.0/battlemap_mcp/handshake.py +149 -0
  24. battlemap_mcp-1.5.0/battlemap_mcp/image_import.py +225 -0
  25. battlemap_mcp-1.5.0/battlemap_mcp/installer.py +1075 -0
  26. battlemap_mcp-1.5.0/battlemap_mcp/layout.py +612 -0
  27. battlemap_mcp-1.5.0/battlemap_mcp/lifecycle.py +264 -0
  28. battlemap_mcp-1.5.0/battlemap_mcp/mapfile.py +479 -0
  29. battlemap_mcp-1.5.0/battlemap_mcp/pack_contents.py +367 -0
  30. battlemap_mcp-1.5.0/battlemap_mcp/placement.py +708 -0
  31. battlemap_mcp-1.5.0/battlemap_mcp/preflight.py +64 -0
  32. battlemap_mcp-1.5.0/battlemap_mcp/safe_fetch.py +535 -0
  33. battlemap_mcp-1.5.0/battlemap_mcp/scene.py +284 -0
  34. battlemap_mcp-1.5.0/battlemap_mcp/server.py +7017 -0
  35. battlemap_mcp-1.5.0/battlemap_mcp/shared_walls.py +98 -0
  36. battlemap_mcp-1.5.0/battlemap_mcp/signed_manifest.py +518 -0
  37. battlemap_mcp-1.5.0/battlemap_mcp/skill_updates.py +570 -0
  38. battlemap_mcp-1.5.0/battlemap_mcp/skills.py +147 -0
  39. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/_shared/build-loop.md +522 -0
  40. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/_shared/review-rubric.md +21 -0
  41. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/_shared/style-bible.md +23 -0
  42. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/battlemap-art-direction/SKILL.md +71 -0
  43. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/battlemap-composition-audit/SKILL.md +91 -0
  44. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/battlemap-environments/SKILL.md +294 -0
  45. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/battlemap-interiors/SKILL.md +284 -0
  46. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/battlemap-lighting-hierarchy/SKILL.md +145 -0
  47. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/battlemap-material-language/SKILL.md +236 -0
  48. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/battlemap-visual-review/SKILL.md +37 -0
  49. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/battlemap-vtt-rebuild/SKILL.md +212 -0
  50. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/skill-index.json +68 -0
  51. battlemap_mcp-1.5.0/battlemap_mcp/skills_payload/skills-sequence.json +1 -0
  52. battlemap_mcp-1.5.0/battlemap_mcp/snapping.py +265 -0
  53. battlemap_mcp-1.5.0/battlemap_mcp/state_paths.py +49 -0
  54. battlemap_mcp-1.5.0/battlemap_mcp/timing.py +85 -0
  55. battlemap_mcp-1.5.0/battlemap_mcp/update_staging.py +1003 -0
  56. battlemap_mcp-1.5.0/battlemap_mcp/updates.py +304 -0
  57. battlemap_mcp-1.5.0/battlemap_mcp/user_settings.py +105 -0
  58. battlemap_mcp-1.5.0/battlemap_mcp/uvtt.py +665 -0
  59. battlemap_mcp-1.5.0/battlemap_mcp/validation.py +288 -0
  60. battlemap_mcp-1.5.0/hatch_build.py +36 -0
  61. battlemap_mcp-1.5.0/pyproject.toml +91 -0
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brandon Florian
4
+ Copyright (c) 2026 thekannen (modifications)
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,25 @@
1
+ # Third-party notices
2
+
3
+ This project's own license is in [LICENSE](LICENSE). It also includes work
4
+ derived from the project below, distributed under that project's license.
5
+ The notices of the Python packages bundled into a release live in each
6
+ package's `THIRD_PARTY_NOTICES` folder.
7
+
8
+ ## Custom Snap Mod, by Lievven
9
+
10
+ `server/battlemap_mcp/snapping.py` ports the snapping math of Lievven's
11
+ Custom Snap Mod (`snappy_mod.gd`), so that coordinates the assistant sends
12
+ land where the user's own cursor would snap them.
13
+ Source: https://github.com/Lievven/Snappy-Mod
14
+
15
+ ```
16
+ The MIT License (MIT)
17
+
18
+ Copyright (c) 2024 Lievven
19
+
20
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
21
+
22
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25
+ ```
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: battlemap-mcp
3
+ Version: 1.5.0
4
+ Summary: MCP server bridging an LLM to a running Dungeondraft instance via its modding API
5
+ Project-URL: Homepage, https://github.com/thekannen/battlemap-mcp
6
+ Project-URL: Documentation, https://knownframe.com/battlemap-mcp/docs/
7
+ Project-URL: Repository, https://github.com/thekannen/battlemap-mcp
8
+ Project-URL: Issues, https://github.com/thekannen/battlemap-mcp/issues
9
+ Project-URL: Releases, https://github.com/thekannen/battlemap-mcp/releases
10
+ Author: thekannen
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ License-File: NOTICE.md
14
+ Keywords: Dungeondraft,battle-map,mcp,model-context-protocol,ttrpg
15
+ Classifier: Development Status :: 5 - Production/Stable
16
+ Classifier: Environment :: Console
17
+ Classifier: Intended Audience :: End Users/Desktop
18
+ Classifier: Operating System :: MacOS
19
+ Classifier: Operating System :: Microsoft :: Windows
20
+ Classifier: Operating System :: POSIX :: Linux
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Games/Entertainment :: Role-Playing
25
+ Requires-Python: >=3.11
26
+ Requires-Dist: cryptography<49,>=48; sys_platform == 'darwin' and platform_machine == 'x86_64'
27
+ Requires-Dist: cryptography>=50; sys_platform != 'darwin' or platform_machine != 'x86_64'
28
+ Requires-Dist: mcp<2.3,>=2.2
29
+ Requires-Dist: pillow<14,>=13.0
30
+ Requires-Dist: pydantic>=2
31
+ Provides-Extra: dev
32
+ Requires-Dist: build>=1.2; extra == 'dev'
33
+ Requires-Dist: mypy>=1.11; extra == 'dev'
34
+ Requires-Dist: pip-audit>=2.7; extra == 'dev'
35
+ Requires-Dist: pytest>=8.0; extra == 'dev'
36
+ Requires-Dist: ruff>=0.6; extra == 'dev'
37
+ Requires-Dist: vulture>=2.11; extra == 'dev'
38
+ Description-Content-Type: text/markdown
39
+
40
+ # battlemap-mcp
41
+
42
+ <!-- mcp-name: io.github.thekannen/battlemap-mcp -->
43
+
44
+ An AI collaborator for your Dungeondraft maps: a local bridge that lets your AI
45
+ assistant (Claude, Codex, OpenCode or any other MCP client) build, inspect and
46
+ refine the map you have open, using assets you already own.
47
+
48
+ This package is the **server** your AI app runs. Dungeondraft also needs the
49
+ **mod** it talks to. The package carries the mod, and its `install` command or
50
+ your assistant copies it into Dungeondraft's mods folder.
51
+
52
+ You need **Dungeondraft 1.2.0.1** and an AI app that can run local MCP servers,
53
+ on the same computer.
54
+
55
+ ## Install
56
+
57
+ Pick one way. The first two use [uv](https://docs.astral.sh/uv/).
58
+
59
+ ### uv tool install (recommended)
60
+
61
+ ```text
62
+ uv tool install battlemap-mcp
63
+ uv tool update-shell
64
+ ```
65
+
66
+ Open a new terminal, then install the mod and connect your AI app. With
67
+ Dungeondraft closed:
68
+
69
+ ```text
70
+ battlemap-mcp install
71
+ battlemap-mcp setup --client claude-code
72
+ ```
73
+
74
+ `setup` also takes `codex` and `opencode`. It installs the map-making skills
75
+ and registers the server. Upgrade with `uv tool upgrade battlemap-mcp`.
76
+
77
+ ### uvx, with nothing installed
78
+
79
+ Give your AI app the command `uvx` with the argument `battlemap-mcp`:
80
+
81
+ ```text
82
+ claude mcp add --scope user battlemap -- uvx battlemap-mcp
83
+ codex mcp add battlemap -- uvx battlemap-mcp
84
+ ```
85
+
86
+ For an app set up through a JSON file:
87
+
88
+ ```json
89
+ {"mcpServers": {"battlemap": {"command": "uvx", "args": ["battlemap-mcp"]}}}
90
+ ```
91
+
92
+ `uvx` goes on running the version it first downloaded. Write
93
+ `battlemap-mcp@latest` instead to take each new release as your app starts
94
+ the server, which then needs the network. If your app cannot find `uvx`, give
95
+ it the full path.
96
+
97
+ Install the mod with `uvx battlemap-mcp install`, or ask your assistant to
98
+ install the bridge. `setup` does not work through `uvx`, because it would
99
+ register a temporary file that uv may delete. The map-making skills still work:
100
+ the server hands them to your assistant.
101
+
102
+ ### pip or pipx
103
+
104
+ ```text
105
+ pipx install battlemap-mcp
106
+ ```
107
+
108
+ or `python -m pip install battlemap-mcp` into a virtual environment you keep.
109
+ Then run `battlemap-mcp install` and `battlemap-mcp setup --client ...` as
110
+ above. Upgrade with `pipx upgrade battlemap-mcp` or
111
+ `python -m pip install --upgrade battlemap-mcp`.
112
+
113
+ ## Finish and check
114
+
115
+ In Dungeondraft, under **Mods**, choose the mods folder the installer used, tick
116
+ **Battlemap MCP Bridge**, accept, quit and reopen Dungeondraft, then open a map. Then:
117
+
118
+ ```text
119
+ battlemap-mcp doctor --live --brief
120
+ ```
121
+
122
+ (With `uvx`, put `uvx` in front.) Quit and reopen your AI app after connecting
123
+ it.
124
+
125
+ **After every upgrade**, update the mod too: run `battlemap-mcp install
126
+ --force`, or ask your assistant to install the bridge, then restart
127
+ Dungeondraft. If you used `setup`, run it again with `--force` to update the
128
+ skills. Upgrade with your AI app closed; on Windows a running server cannot be
129
+ replaced.
130
+
131
+ Install it only one way. A second connection to the same AI app shows every tool
132
+ twice.
133
+
134
+ ## No Python
135
+
136
+ The [GitHub releases](https://github.com/thekannen/battlemap-mcp/releases)
137
+ have a self-contained download that needs no Python or uv.
138
+
139
+ ## More
140
+
141
+ - [Documentation](https://knownframe.com/battlemap-mcp/docs/)
142
+ - [Source, changelog and issues](https://github.com/thekannen/battlemap-mcp)
143
+ - [Privacy](https://knownframe.com/privacy/battlemap-mcp/)
144
+
145
+ MIT licensed. This is an independent, unofficial project, not sponsored,
146
+ operated or endorsed by Megasploot or Tailwind Games, LLC. It includes no
147
+ Dungeondraft software, maps or art.
@@ -0,0 +1,108 @@
1
+ # battlemap-mcp
2
+
3
+ <!-- mcp-name: io.github.thekannen/battlemap-mcp -->
4
+
5
+ An AI collaborator for your Dungeondraft maps: a local bridge that lets your AI
6
+ assistant (Claude, Codex, OpenCode or any other MCP client) build, inspect and
7
+ refine the map you have open, using assets you already own.
8
+
9
+ This package is the **server** your AI app runs. Dungeondraft also needs the
10
+ **mod** it talks to. The package carries the mod, and its `install` command or
11
+ your assistant copies it into Dungeondraft's mods folder.
12
+
13
+ You need **Dungeondraft 1.2.0.1** and an AI app that can run local MCP servers,
14
+ on the same computer.
15
+
16
+ ## Install
17
+
18
+ Pick one way. The first two use [uv](https://docs.astral.sh/uv/).
19
+
20
+ ### uv tool install (recommended)
21
+
22
+ ```text
23
+ uv tool install battlemap-mcp
24
+ uv tool update-shell
25
+ ```
26
+
27
+ Open a new terminal, then install the mod and connect your AI app. With
28
+ Dungeondraft closed:
29
+
30
+ ```text
31
+ battlemap-mcp install
32
+ battlemap-mcp setup --client claude-code
33
+ ```
34
+
35
+ `setup` also takes `codex` and `opencode`. It installs the map-making skills
36
+ and registers the server. Upgrade with `uv tool upgrade battlemap-mcp`.
37
+
38
+ ### uvx, with nothing installed
39
+
40
+ Give your AI app the command `uvx` with the argument `battlemap-mcp`:
41
+
42
+ ```text
43
+ claude mcp add --scope user battlemap -- uvx battlemap-mcp
44
+ codex mcp add battlemap -- uvx battlemap-mcp
45
+ ```
46
+
47
+ For an app set up through a JSON file:
48
+
49
+ ```json
50
+ {"mcpServers": {"battlemap": {"command": "uvx", "args": ["battlemap-mcp"]}}}
51
+ ```
52
+
53
+ `uvx` goes on running the version it first downloaded. Write
54
+ `battlemap-mcp@latest` instead to take each new release as your app starts
55
+ the server, which then needs the network. If your app cannot find `uvx`, give
56
+ it the full path.
57
+
58
+ Install the mod with `uvx battlemap-mcp install`, or ask your assistant to
59
+ install the bridge. `setup` does not work through `uvx`, because it would
60
+ register a temporary file that uv may delete. The map-making skills still work:
61
+ the server hands them to your assistant.
62
+
63
+ ### pip or pipx
64
+
65
+ ```text
66
+ pipx install battlemap-mcp
67
+ ```
68
+
69
+ or `python -m pip install battlemap-mcp` into a virtual environment you keep.
70
+ Then run `battlemap-mcp install` and `battlemap-mcp setup --client ...` as
71
+ above. Upgrade with `pipx upgrade battlemap-mcp` or
72
+ `python -m pip install --upgrade battlemap-mcp`.
73
+
74
+ ## Finish and check
75
+
76
+ In Dungeondraft, under **Mods**, choose the mods folder the installer used, tick
77
+ **Battlemap MCP Bridge**, accept, quit and reopen Dungeondraft, then open a map. Then:
78
+
79
+ ```text
80
+ battlemap-mcp doctor --live --brief
81
+ ```
82
+
83
+ (With `uvx`, put `uvx` in front.) Quit and reopen your AI app after connecting
84
+ it.
85
+
86
+ **After every upgrade**, update the mod too: run `battlemap-mcp install
87
+ --force`, or ask your assistant to install the bridge, then restart
88
+ Dungeondraft. If you used `setup`, run it again with `--force` to update the
89
+ skills. Upgrade with your AI app closed; on Windows a running server cannot be
90
+ replaced.
91
+
92
+ Install it only one way. A second connection to the same AI app shows every tool
93
+ twice.
94
+
95
+ ## No Python
96
+
97
+ The [GitHub releases](https://github.com/thekannen/battlemap-mcp/releases)
98
+ have a self-contained download that needs no Python or uv.
99
+
100
+ ## More
101
+
102
+ - [Documentation](https://knownframe.com/battlemap-mcp/docs/)
103
+ - [Source, changelog and issues](https://github.com/thekannen/battlemap-mcp)
104
+ - [Privacy](https://knownframe.com/privacy/battlemap-mcp/)
105
+
106
+ MIT licensed. This is an independent, unofficial project, not sponsored,
107
+ operated or endorsed by Megasploot or Tailwind Games, LLC. It includes no
108
+ Dungeondraft software, maps or art.
@@ -0,0 +1,3 @@
1
+ """Dungeondraft MCP server package."""
2
+
3
+ __version__ = "1.5.0"
@@ -0,0 +1,6 @@
1
+ """Module entry point for portable MCP client registration."""
2
+
3
+ from battlemap_mcp.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1,107 @@
1
+ """Two layout habits that a render shows and no element count does.
2
+
3
+ Rigid placement: objects all at their default size and squared to the grid.
4
+ A room arranged that way reads as a showroom rather than a place in use, and
5
+ every placement call reports success, so nothing says so until someone looks.
6
+
7
+ A small footprint: a building in the middle of a mostly untouched map. At play
8
+ scale the eye lands on the empty ground first.
9
+
10
+ Both are advice, never failures. A shelf squared to its wall is correct, and a
11
+ lone ruin on an open plain can be the point. So neither changes an `ok`, and
12
+ each note says what to do rather than what went wrong.
13
+
14
+ Pure functions over what the bridge already returns; nothing here touches the map.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from .geometry import WOXELS_PER_TILE
20
+
21
+ SCALE_TOLERANCE = 0.01
22
+ ANGLE_TOLERANCE = 1.0
23
+
24
+ BATCH_MINIMUM = 6
25
+ BATCH_RIGID_SHARE = 0.9
26
+ SCENE_MINIMUM = 10
27
+ SCENE_RIGID_SHARE = 0.75
28
+ FOOTPRINT_SHARE = 0.4
29
+
30
+
31
+ def is_rigid(scale: float | None, rotation: float | None) -> bool:
32
+ """Default size and a quarter-turn rotation, within rounding."""
33
+ scale = 1.0 if scale is None else float(scale)
34
+ rotation = 0.0 if rotation is None else float(rotation)
35
+ off_quarter = abs(((rotation + 45.0) % 90.0) - 45.0)
36
+ return abs(scale - 1.0) <= SCALE_TOLERANCE and off_quarter <= ANGLE_TOLERANCE
37
+
38
+
39
+ def rigid_share(entries: list[dict]) -> float:
40
+ if not entries:
41
+ return 0.0
42
+ rigid = sum(is_rigid(e.get("scale"), e.get("rotation")) for e in entries)
43
+ return rigid / len(entries)
44
+
45
+
46
+ def batch_note(entries: list[dict]) -> str | None:
47
+ """A note for a place_objects result, or None when the batch varies enough."""
48
+ if len(entries) < BATCH_MINIMUM or rigid_share(entries) < BATCH_RIGID_SHARE:
49
+ return None
50
+ return (
51
+ f"All {len(entries)} objects in this batch sit at scale 1.0 and on quarter "
52
+ "turns, which reads as a showroom rather than a place in use. Keep "
53
+ "wall-hugging fixtures square, and give the rest a slightly different "
54
+ "scale (about 0.85-1.15) and a few degrees of turn; modify_object "
55
+ "adjusts placed objects."
56
+ )
57
+
58
+
59
+ def _extent(objects: list[dict], walls: list[dict], lights: list[dict]) -> tuple | None:
60
+ points: list[tuple[float, float]] = []
61
+ for element in [*objects, *lights]:
62
+ position = element.get("position")
63
+ if position:
64
+ points.append((float(position[0]), float(position[1])))
65
+ for wall in walls:
66
+ points += [(float(p[0]), float(p[1])) for p in wall.get("points") or []]
67
+ if not points:
68
+ return None
69
+ xs, ys = [p[0] for p in points], [p[1] for p in points]
70
+ return min(xs), min(ys), max(xs), max(ys)
71
+
72
+
73
+ def review(
74
+ map_size: tuple[float, float],
75
+ objects: list[dict],
76
+ walls: list[dict],
77
+ lights: list[dict],
78
+ ) -> dict:
79
+ """validate_scene's arrangement section: two measures and any advice."""
80
+ notes: list[str] = []
81
+ share = rigid_share(objects)
82
+ if len(objects) >= SCENE_MINIMUM and share >= SCENE_RIGID_SHARE:
83
+ notes.append(
84
+ f"{round(share * 100)}% of objects sit at scale 1.0 on quarter turns. "
85
+ "Beyond fixtures that belong squared to a wall, vary scale slightly "
86
+ "and turn pieces a few degrees so the space reads as used."
87
+ )
88
+ extent = _extent(objects, walls, lights)
89
+ map_area = float(map_size[0]) * float(map_size[1])
90
+ coverage = None
91
+ if extent and map_area > 0:
92
+ width = max(extent[2] - extent[0], WOXELS_PER_TILE)
93
+ height = max(extent[3] - extent[1], WOXELS_PER_TILE)
94
+ coverage = min(1.0, width * height / map_area)
95
+ if coverage < FOOTPRINT_SHARE:
96
+ notes.append(
97
+ f"What is built covers about {round(coverage * 100)}% of the map. "
98
+ "Extend the scene's surroundings toward the edges, or plan the "
99
+ "map size before laying out: set_map_size keeps the top-left "
100
+ "origin and does not move what is already placed."
101
+ )
102
+ return {
103
+ "rigid_share": round(share, 3),
104
+ "objects": len(objects),
105
+ "footprint_share": None if coverage is None else round(coverage, 3),
106
+ "notes": notes,
107
+ }
@@ -0,0 +1,254 @@
1
+ """Give a map the asset packs it is allowed to use.
2
+
3
+ The manifest is written into the map FILE rather than onto the live map:
4
+ Dungeondraft's own documentation calls `Header` safe to read and dangerous to
5
+ modify, so nothing here touches a running editor. The map is prepared on disk
6
+ and then opened, which is the same path Dungeondraft takes when it loads any
7
+ map someone else made.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import contextlib
13
+ import json
14
+ import os
15
+ import re
16
+ import shutil
17
+ import stat
18
+ import sys
19
+ import tempfile
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from . import mapfile
24
+
25
+ # Fields a manifest entry carries. Read off maps Dungeondraft itself wrote:
26
+ # every entry has the first four, and packs that ship colour overrides add the
27
+ # fifth. Anything else in pack.json is not part of a map's manifest.
28
+ ENTRY_FIELDS = ("name", "id", "version", "author")
29
+ OPTIONAL_FIELDS = ("keywords", "allow_3rd_party_mapping_software_to_read", "custom_color_overrides")
30
+
31
+
32
+ def manifest_entry(pack: dict[str, Any]) -> dict[str, Any]:
33
+ """One asset_manifest entry from a pack's own pack.json metadata."""
34
+ entry: dict[str, Any] = {field: pack.get(field, "") for field in ENTRY_FIELDS}
35
+ for field in OPTIONAL_FIELDS:
36
+ if field in pack:
37
+ entry[field] = pack[field]
38
+ return entry
39
+
40
+
41
+ def build_manifest(packs: list[dict[str, Any]], wanted: list[str] | None = None) -> list[dict]:
42
+ """Manifest entries for `wanted` pack ids, or for every pack when None.
43
+
44
+ Order follows the installed list so a prepared map is reproducible, and an
45
+ id is never included twice — a duplicate entry is how a map ends up with the
46
+ same pack listed under two versions.
47
+ """
48
+ chosen = []
49
+ seen: set[str] = set()
50
+ for pack in packs:
51
+ pack_id = str(pack.get("id", ""))
52
+ if not pack_id or pack_id in seen:
53
+ continue
54
+ if wanted is not None and pack_id not in wanted:
55
+ continue
56
+ seen.add(pack_id)
57
+ chosen.append(manifest_entry(pack))
58
+ return chosen
59
+
60
+
61
+ def unknown_ids(packs: list[dict[str, Any]], wanted: list[str]) -> list[str]:
62
+ """Requested ids that are not installed — asking for one is a caller error."""
63
+ installed = {str(pack.get("id", "")) for pack in packs}
64
+ return [pack_id for pack_id in wanted if pack_id not in installed]
65
+
66
+
67
+ def merge_manifest(existing: list[dict], adding: list[dict]) -> list[dict]:
68
+ """The packs a prepared map should include: what it already had, plus new ones."""
69
+ merged = [dict(entry) for entry in existing if isinstance(entry, dict)]
70
+ have = {str(entry.get("id", "")) for entry in merged}
71
+ for entry in adding:
72
+ if str(entry.get("id", "")) not in have:
73
+ have.add(str(entry.get("id", "")))
74
+ merged.append(dict(entry))
75
+ return merged
76
+
77
+
78
+ def publish_new_file(temporary: Path, destination: Path) -> None:
79
+ """Give a finished temporary file the new name `destination`.
80
+
81
+ Raises FileExistsError, and changes nothing, if that name is taken, even
82
+ by a file that appeared a moment ago: `os.rename` (Windows) and a hard
83
+ link (POSIX) both fail on an existing name, where `os.replace` would not.
84
+ Where the filesystem has no hard links (exFAT, some network shares) the
85
+ link raises some other OSError (EPERM, ENOTSUP, EXDEV); then the
86
+ destination is created O_CREAT | O_EXCL (refusing an existing name or a
87
+ planted symlink, as the link would), copied into, and given the
88
+ temporary's permission bits. A copy that fails is removed, so a failure
89
+ leaves no partial file under the final name.
90
+
91
+ The caller still removes `temporary`: only a rename consumes it.
92
+ """
93
+ if sys.platform == "win32":
94
+ os.rename(temporary, destination)
95
+ return
96
+ try:
97
+ os.link(temporary, destination, follow_symlinks=False)
98
+ return
99
+ except FileExistsError:
100
+ raise
101
+ except OSError:
102
+ pass
103
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
104
+ fd = os.open(destination, flags, 0o600)
105
+ try:
106
+ with os.fdopen(fd, "wb") as handle, temporary.open("rb") as data:
107
+ # A filesystem without permission bits may refuse this.
108
+ with contextlib.suppress(OSError):
109
+ os.fchmod(handle.fileno(), stat.S_IMODE(temporary.stat().st_mode))
110
+ shutil.copyfileobj(data, handle)
111
+ handle.flush()
112
+ os.fsync(handle.fileno())
113
+ except BaseException:
114
+ destination.unlink(missing_ok=True)
115
+ raise
116
+
117
+
118
+ def _publish_new_file(destination: Path, payload: bytes, *, like: Path) -> None:
119
+ """Create `destination` holding `payload`, never replacing a file.
120
+
121
+ Save directories can be shared, so anyone who can write there can plant
122
+ names in advance. A predictable temporary ("<name>.preparing") written with
123
+ `write_text` follows a symlink planted at that name and truncates whatever
124
+ it points at, before any rename happens. So the temporary is created with
125
+ `mkstemp` — an unpredictable name opened O_CREAT|O_EXCL, which refuses an
126
+ existing entry, symlinks included — and written through that descriptor,
127
+ never reopened by path.
128
+
129
+ `publish_new_file` then gives it the final name without clobbering. The
130
+ copy takes the source map's permission bits, so a map shared with other
131
+ users stays readable by them.
132
+ """
133
+ fd, temporary = tempfile.mkstemp(
134
+ dir=destination.parent, prefix=f".{destination.name}.", suffix=".preparing"
135
+ )
136
+ try:
137
+ with os.fdopen(fd, "wb") as handle:
138
+ if hasattr(os, "fchmod"):
139
+ os.fchmod(handle.fileno(), stat.S_IMODE(like.stat().st_mode))
140
+ handle.write(payload)
141
+ handle.flush()
142
+ os.fsync(handle.fileno())
143
+ try:
144
+ publish_new_file(Path(temporary), destination)
145
+ except FileExistsError as exc:
146
+ raise ValueError(f"{destination.name} already exists; refusing to replace it") from exc
147
+ finally:
148
+ # Only the file mkstemp created. After a successful hard link this
149
+ # removes the extra name; after a successful rename it is already gone.
150
+ if os.path.lexists(temporary):
151
+ os.unlink(temporary)
152
+
153
+
154
+ _DECODER = json.JSONDecoder()
155
+ # A string or a bracket: enough to find where an object or array ends
156
+ # without decoding it, which would build the whole `world` a second time.
157
+ _TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|[{}\[\]]')
158
+
159
+
160
+ def _skip(text: str, at: int) -> int:
161
+ """The first index at or after `at` that is not JSON whitespace."""
162
+ while at < len(text) and text[at] in " \t\n\r":
163
+ at += 1
164
+ return at
165
+
166
+
167
+ def _value_end(text: str, at: int) -> int:
168
+ """Where the JSON value starting at `at` ends."""
169
+ if text[at] not in "{[":
170
+ return _DECODER.raw_decode(text, at)[1]
171
+ depth = 0
172
+ for token in _TOKEN.finditer(text, at):
173
+ mark = token.group()
174
+ if mark in "{[":
175
+ depth += 1
176
+ elif mark in "}]":
177
+ depth -= 1
178
+ if depth == 0:
179
+ return token.end()
180
+ raise ValueError("unterminated JSON value")
181
+
182
+
183
+ def _members(text: str, start: int) -> list[tuple[str, int, int]]:
184
+ """(key, value start, value end) of each member of the object at `start`.
185
+
186
+ Only called on text json.loads has already accepted, so the layout is
187
+ known to be valid JSON.
188
+ """
189
+ members: list[tuple[str, int, int]] = []
190
+ at = _skip(text, start + 1)
191
+ while text[at] != "}":
192
+ key, at = _DECODER.raw_decode(text, at)
193
+ at = _skip(text, at) + 1 # past ':'
194
+ at = _skip(text, at)
195
+ end = _value_end(text, at)
196
+ members.append((key, at, end))
197
+ at = _skip(text, end)
198
+ if text[at] == ",":
199
+ at = _skip(text, at + 1)
200
+ return members
201
+
202
+
203
+ def _with_manifest(text: str, manifest: list[dict]) -> str:
204
+ """`text` with only the header's asset_manifest value replaced.
205
+
206
+ Re-serialising the whole map changed bytes the caller never asked to
207
+ change: line endings, number spellings, and every non-ASCII character,
208
+ an emoji becoming a surrogate-pair escape Godot 3.4 does not recombine.
209
+ The last of duplicate keys is edited, as json.loads reads the last.
210
+ """
211
+ top = _skip(text, 0)
212
+ header = [m for m in _members(text, top) if m[0] == "header"][-1]
213
+ found = [m for m in _members(text, header[1]) if m[0] == "asset_manifest"]
214
+ value = json.dumps(manifest, ensure_ascii=False)
215
+ if found:
216
+ _key, start, end = found[-1]
217
+ return text[:start] + value + text[end:]
218
+ opening = header[1] + 1
219
+ separator = "" if text[_skip(text, opening)] == "}" else ", "
220
+ return text[:opening] + f'"asset_manifest": {value}{separator}' + text[opening:]
221
+
222
+
223
+ def prepare_map_file(source: Path, destination: Path, manifest: list[dict]) -> dict[str, Any]:
224
+ """Write a copy of `source` whose header includes `manifest`.
225
+
226
+ Only the header's asset_manifest changes; every other byte of the map is
227
+ carried across untouched, so the geometry, terrain and objects of the map
228
+ being copied are preserved exactly."""
229
+ if source.resolve() == destination.resolve():
230
+ raise ValueError(
231
+ f"refusing to write the prepared map onto its own source ({source.name}); "
232
+ "this prepares a COPY — choose a different filename"
233
+ )
234
+ # Bytes, not read_text: universal newlines would turn CRLF into LF.
235
+ text = source.read_bytes().decode("utf-8")
236
+ data = mapfile.loads(text)
237
+ header = data.get("header") if isinstance(data, dict) else None
238
+ if not isinstance(header, dict):
239
+ raise ValueError(f"{source.name} has no header object; is it a Dungeondraft map?")
240
+ existing = [e for e in (header.get("asset_manifest") or []) if isinstance(e, dict)]
241
+ final = merge_manifest(existing, manifest)
242
+
243
+ _publish_new_file(destination, _with_manifest(text, final).encode("utf-8"), like=source)
244
+
245
+ kept = [str(e.get("id", "")) for e in existing]
246
+ return {
247
+ "source": str(source),
248
+ "path": str(destination),
249
+ "packs_before": len(existing),
250
+ "packs_after": len(final),
251
+ "pack_ids": [entry["id"] for entry in final],
252
+ "kept_from_source": kept,
253
+ "added": [str(e["id"]) for e in final if str(e.get("id", "")) not in set(kept)],
254
+ }