agent-manifesto-kit 1.8.0 → 1.8.2

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 (55) hide show
  1. package/README.md +44 -0
  2. package/collection/skills/art-direction-pass/SKILL.md +245 -0
  3. package/collection/skills/art-direction-pass/agents/openai.yaml +4 -0
  4. package/collection/skills/art-direction-pass/assets/presets.json +9 -0
  5. package/collection/skills/art-direction-pass/assets/visual_capture.gd +77 -0
  6. package/collection/skills/art-direction-pass/scripts/compare.py +86 -0
  7. package/collection/skills/art-direction-pass/scripts/metrics.py +56 -0
  8. package/collection/skills/art-direction-pass/scripts/test_tools.py +83 -0
  9. package/collection/skills/concept-asset-builder/SKILL.md +124 -0
  10. package/collection/skills/concept-asset-builder/agents/openai.yaml +4 -0
  11. package/collection/skills/concept-asset-builder/assets/templates/agent_brief.md +56 -0
  12. package/collection/skills/concept-asset-builder/assets/templates/rubric.json +50 -0
  13. package/collection/skills/concept-asset-builder/assets/templates/rubric_example_vending.json +14 -0
  14. package/collection/skills/concept-asset-builder/assets/templates/scene_style_example.md +30 -0
  15. package/collection/skills/concept-asset-builder/assets/templates/wear_description_example.md +50 -0
  16. package/collection/skills/concept-asset-builder/assets/templates/zones.json +10 -0
  17. package/collection/skills/concept-asset-builder/assets/templates/zones_example_vending.json +69 -0
  18. package/collection/skills/concept-asset-builder/references/examples/postbox_blender.py +1112 -0
  19. package/collection/skills/concept-asset-builder/references/examples/postbox_wear_three.js +742 -0
  20. package/collection/skills/concept-asset-builder/references/examples/vending_materials_blender.py +487 -0
  21. package/collection/skills/concept-asset-builder/references/examples/vending_wear_three.js +798 -0
  22. package/collection/skills/concept-asset-builder/references/field-lessons.md +36 -0
  23. package/collection/skills/concept-asset-builder/references/wear-language.md +36 -0
  24. package/collection/skills/concept-asset-builder/scripts/blender/bake_export.py +174 -0
  25. package/collection/skills/concept-asset-builder/scripts/blender/render_views.py +100 -0
  26. package/collection/skills/concept-asset-builder/scripts/blender/studio.py +73 -0
  27. package/collection/skills/concept-asset-builder/scripts/capture.mjs +44 -0
  28. package/collection/skills/concept-asset-builder/scripts/codex_review.sh +88 -0
  29. package/collection/skills/concept-asset-builder/scripts/compare_to.py +24 -0
  30. package/collection/skills/concept-asset-builder/scripts/composite_godot.py +13 -0
  31. package/collection/skills/concept-asset-builder/scripts/crop.py +9 -0
  32. package/collection/skills/concept-asset-builder/scripts/gen_texture.sh +18 -0
  33. package/collection/skills/concept-asset-builder/scripts/godot/capture.gd +122 -0
  34. package/collection/skills/concept-asset-builder/scripts/godot/project.godot +18 -0
  35. package/collection/skills/concept-asset-builder/scripts/init_workspace.sh +17 -0
  36. package/collection/skills/concept-asset-builder/scripts/measure_silhouette.py +40 -0
  37. package/collection/skills/concept-asset-builder/scripts/metrics.py +144 -0
  38. package/collection/skills/concept-asset-builder/scripts/sheet.py +19 -0
  39. package/collection/skills/concept-asset-builder/scripts/test_tools.py +121 -0
  40. package/collection/skills/concept-asset-builder/scripts/threejs/index.html +23 -0
  41. package/collection/skills/concept-asset-builder/scripts/threejs/model.js +9 -0
  42. package/collection/skills/concept-asset-builder/scripts/threejs/studio.js +178 -0
  43. package/collection/skills/concept-asset-builder/scripts/wear_stats.py +130 -0
  44. package/collection/skills/concept-scene-builder/SKILL.md +326 -0
  45. package/collection/skills/concept-scene-builder/agents/openai.yaml +4 -0
  46. package/collection/skills/concept-scene-builder/references/field-lessons.md +113 -0
  47. package/collection/skills/concept-scene-builder/scripts/blend.py +32 -0
  48. package/collection/skills/concept-scene-builder/scripts/crop.py +56 -0
  49. package/collection/skills/concept-scene-builder/scripts/grid_overlay.py +117 -0
  50. package/collection/skills/concept-scene-builder/scripts/test_tools.py +89 -0
  51. package/collection/skills/machine-builder/SKILL.md +222 -0
  52. package/collection/skills/machine-builder/agents/openai.yaml +4 -0
  53. package/collection/skills/machine-builder/assets/spec.example.yaml +47 -0
  54. package/collection/skills/machine-builder/scripts/validate.py +307 -0
  55. package/package.json +1 -1
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "Concept Scene Builder"
3
+ short_description: "Rebuild a concept's game environment from a data-driven asset kit and layout"
4
+ default_prompt: "Use $concept-scene-builder to rebuild this concept image as a game environment scene from a reusable asset kit and a layout file."
@@ -0,0 +1,113 @@
1
+ # Field lessons (from real runs)
2
+
3
+ Each rule comes from a correction the user had to make or a fix that worked. Read the section for the asset you are
4
+ building before its first iteration. Short rules are repeated in SKILL.md; the recipes live only here.
5
+
6
+ ## Process
7
+
8
+ - **Words before code.** When the user says an asset is "far from the concept", write how the concept looks, how ours
9
+ looks, and a table of the 5 main differences with one fix each; apply after approval (or, unattended, apply the
10
+ table and keep it in the report). Blind parameter tweaking took several rounds; the table landed in one.
11
+ - **"Too X" means measure first.** "Too yellow" was not too much yellow (the concept measured more yellow than ours);
12
+ it was hard transitions: two steep curves, two palettes, ground switching colour under patches. Check transitions
13
+ and contrast before changing amounts.
14
+ - **New feature at low strength, then measure its share** against the concept (share of ochre dust, cracks per metre,
15
+ foam area). Every first pass at full strength overshot: dust covered half the road, plates read as cobbles,
16
+ water went opaque, a ford of 52 stones read as a blockage (15 was right).
17
+ - **Colour numbers are not the look.** The asphalt median matched the concept to 2 RGB units and the user still said
18
+ "far". Add structure metrics (contrast inside the region, share of each feature) and compare 3x crops.
19
+ - **Colours come from the concept, not from the prompt.** The user's words ("mostly green") describe the impression;
20
+ sample the concept (5 hue/luminance quantiles of the region) and set the ramp from them. Fully automatic palette
21
+ fitting diverged; quantiles + gentle correction (strength ~0.6) worked.
22
+ - **User overrides beat the concept.** "Asphalt should cover the whole bridge (the concept is wrong here)": record it as
23
+ a contradiction rule in kit.md so no later pass reverts it.
24
+ - **Tweak panel early.** When the user starts asking for "3-4x fewer cracks", give every look parameter a name and a
25
+ live panel generated from shader uniforms and profiles (save/reset; strip runtime-only uniforms on save;
26
+ a self-test that a value round-trips).
27
+ - **Reviewers.** A blind A/B reviewer sees only the wide view and drifts from measurements (it darkened the grass
28
+ median from 0.45 to 0.37 because "darker looked richer"). Give reviewers close crops plus the defect checklist and
29
+ guard every verdict with metrics. If the user prefers to review renders personally, skip reviewers, never the defect pass.
30
+
31
+ ## Iteration speed and performance
32
+
33
+ - Iterate on the single-asset preview (seconds); render the full scene last (minutes).
34
+ - Never time performance while another render, test or agent uses the GPU.
35
+ - Profile by switching features off one at a time. Draw calls fell 882 -> 198 and frame time only 19.4 -> 18.0 ms;
36
+ the real costs were shadows (~7 ms: atlas 8192 -> 4096, cascades 4 -> 2), grass (~6 ms: fewer, wider blades,
37
+ colour conversion moved to the CPU) and SSAO (1.6 ms).
38
+ - Never auto-decimate assets to a triangle cap: a cap removed whole walls of ruins. Use a budget check that fails.
39
+
40
+ ## Runtime deliverable
41
+
42
+ - The scene is interactive by default: zoom/orbit work right away, the report gives the run command and controls.
43
+ - Animated effects (water flow, foam) run at runtime; captures freeze time so comparisons stay deterministic.
44
+ - Depth of field (tilt-shift) is relative to the focus distance (near ~0.8 d, far ~1.12 d), weak (amount ~0.03),
45
+ with a toggle key, and keeps gameplay objects out of the blur. A fixed band blurred the whole board on zoom.
46
+
47
+ ## Light and shading
48
+
49
+ - Faces turned away from the key light render near-black (bridge walls at value 0.18). Add a shadowless fill from the
50
+ camera side, mirrored azimuth, low elevation (~10 deg), and re-check the global median afterwards.
51
+ - Fade sub-pixel detail (joints, bump) with distance and cap the bump tilt: 5 cm joints made masonry black from afar.
52
+ - Colour constants must be in the right colour space: in Godot `source_color` uniforms are sRGB, literals in code are
53
+ linear. A grey entered as a bare 0.5 rendered almost white ("white dots"). A shared effect (chips, grime) changes
54
+ every asset that uses it: re-check all of them after a change.
55
+ - Give each material role its own material (window frames shared the coping material and went dark with it).
56
+ - Voronoi cells with flat colour and dark outlines read as stained glass. River bed: separate dome-shaded pebbles on
57
+ sand (distance to the feature point), not cells.
58
+
59
+ ## Recipes
60
+
61
+ ### Camera-following GPU grass (Godot or three.js)
62
+
63
+ - Every blade is built in the vertex shader from a hash of its world-grid cell: stable under camera motion and LOD.
64
+ - Two LOD rings of fixed patches around the focus; cull patches on the CPU against the board and the view frustum.
65
+ - Grid sized to the normal density; rejected blades collapse to a degenerate point. ~8 vertices per blade.
66
+ - Back faces: reset the normal (double-sided blades flip it).
67
+ - One include shared by the ground shader and the blade shader, so the ground under blades has the same colour field.
68
+ - Keep-out (roads, rivers, structures) as a baked distance field: interpolates cleanly, edges stay sharp.
69
+ - Result: build 1.5 s -> 0.02 s, 27 MB of per-blade data -> 0.2 MB of tables, cost follows screen coverage, not map
70
+ size (100x100 board: 2.4-6.6 ms).
71
+
72
+ ### Broadleaf tree
73
+
74
+ - Recursive branch skeleton (trunk -> 7-9 limbs -> 3-5 branches -> 2-3 twigs), golden-angle phyllotaxis (137.5 deg),
75
+ gnarl and an up force; low limbs spread 60-70 deg so the crown starts at ~30 % of the height.
76
+ - Foliage clusters on twig tips AND along the outer half of limbs and branches; tips only gave a flat high umbrella.
77
+ - Crown-centre normals and interior darkening for the foam-clump look.
78
+ - Bark without textures: per-vertex (around, along, circumference) coordinates on the tubes + a procedural shader
79
+ (furrows, plates, knots, moss low and on up-facing sides).
80
+
81
+ ### Generators
82
+
83
+ - Check openings in the mesh, not only placements: an arch notch in one n-gon was triangulated across the opening.
84
+ Build walls with openings from strips.
85
+ - Every defect the user finds that a rule could catch becomes a failing build check.
86
+
87
+ ### Camera match
88
+
89
+ - Do not trust a closed-form homography decomposition for the camera; fit pose and FOV by reprojection error with
90
+ free yaw and roll (AI concepts have inconsistent perspective; ~12 px RMS is normal).
91
+
92
+ ## Porting a kit to another engine (Godot -> three.js)
93
+
94
+ - Keep one scale constant (kit unit -> game metres) and compute every pattern in kit units (`p_kit = p_world / S`);
95
+ never rescale shader constants by hand. Scale models at load.
96
+ - Uniform values live in the material files (.tres), not in the shader defaults: read both.
97
+ - Godot light energy E ~ three.js intensity E * pi (physically based lights); ambient colour * energy the same.
98
+ - Port surface shaders into the engine's standard material (three.js: onBeforeCompile) so shadows, fog and AO keep
99
+ working; a custom ShaderMaterial only where the vertex stage is fully custom (GPU grass), and then wire shadows yourself.
100
+ - Assets made for one board layout need adapting to the game's own map: multi-cell footprints, a bridge length that
101
+ matches the crossing, clear cell centres where units stand, heights from the game's grid. Example: the kit bridge
102
+ crossed a shallow stream at grade; the game's river ran 5 m below the meadow, so the bridge needed abutments and an
103
+ arch down to the water, an oblique plan (bank edges at 30 deg to the road) and a wider deck (units stand on it).
104
+ - Vertex colours: check how the source engine reads COLOR_0 before porting. Godot passes the glb values raw and the kit
105
+ shaders converted them from sRGB (`color_srgb`); reading them as linear made walls 2.7x too light.
106
+ - Light: compare against the source engine's render of the SAME surfaces in-scene (grass, forest, walls, cliffs),
107
+ not against isolated kit renders on a different background. Tonemapper and screen-space AO differ between engines
108
+ (three.js AO darkens direct light too; Godot SSAO only ambient): calibrate exposure, shadow lift and AO by
109
+ measurement, one preset, then fix remaining per-material gaps in the materials.
110
+ - Port per zone with parallel executors only after a written contract (scale, mask functions, material names,
111
+ ownership) and a scaffold where every zone starts as a stub on the old code, so each executor sees a complete scene.
112
+ With several executors on one dev server, hot reload restarts their captures: give each its own server without HMR,
113
+ and treat frame times as noisy (measure with/without the feature, not absolute).
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env python3
2
+ """Overlay a render on the concept to check camera and layout alignment.
3
+
4
+ blend.py CONCEPT RENDER -o out.png [--alpha 0.5] (the render is resized to the concept size)
5
+ Requires Pillow.
6
+ """
7
+ import argparse
8
+
9
+ from PIL import Image
10
+
11
+
12
+ def blend(concept, render, out, alpha=0.5):
13
+ c = Image.open(concept).convert("RGB")
14
+ r = Image.open(render).convert("RGB").resize(c.size, Image.LANCZOS)
15
+ Image.blend(c, r, alpha).save(out)
16
+
17
+
18
+ def main(argv=None):
19
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
20
+ ap.add_argument("concept")
21
+ ap.add_argument("render")
22
+ ap.add_argument("-o", required=True)
23
+ ap.add_argument("--alpha", type=float, default=0.5)
24
+ a = ap.parse_args(argv)
25
+ if not 0.0 <= a.alpha <= 1.0:
26
+ ap.error("--alpha must be between 0 and 1")
27
+ blend(a.concept, a.render, a.o, a.alpha)
28
+ return 0
29
+
30
+
31
+ if __name__ == "__main__":
32
+ raise SystemExit(main())
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env python3
2
+ """Cut kit-sheet items into per-asset reference images.
3
+
4
+ crop.py SHEET boxes.json -o docs/art/reference/kit/
5
+ boxes.json: {"tile_grass": [x0, y0, x1, y1], ...} in sheet pixels. Requires Pillow.
6
+ """
7
+ import argparse
8
+ import json
9
+ import pathlib
10
+ import re
11
+
12
+ from PIL import Image
13
+
14
+
15
+ NAME = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.-]*$")
16
+
17
+
18
+ def crop(sheet, boxes, out_dir):
19
+ if not isinstance(boxes, dict):
20
+ raise ValueError('boxes must be an object: {"name": [x0, y0, x1, y1], ...}')
21
+ im = Image.open(sheet).convert("RGB")
22
+ for name, box in boxes.items(): # check everything before writing anything
23
+ if not NAME.match(name):
24
+ raise ValueError(f"box name {name!r} must be a plain file name")
25
+ if not (isinstance(box, list) and len(box) == 4 and all(isinstance(v, int) for v in box)):
26
+ raise ValueError(f"box {name} must be four integers [x0, y0, x1, y1], got {box!r}")
27
+ x0, y0, x1, y1 = box
28
+ if not (0 <= x0 < x1 <= im.width and 0 <= y0 < y1 <= im.height):
29
+ raise ValueError(f"box {name} {box} is outside the {im.width}x{im.height} sheet or empty")
30
+ out = pathlib.Path(out_dir)
31
+ out.mkdir(parents=True, exist_ok=True)
32
+ written = []
33
+ for name, box in boxes.items():
34
+ path = out / f"{name}.png"
35
+ im.crop(tuple(box)).save(path)
36
+ written.append(path)
37
+ return written
38
+
39
+
40
+ def main(argv=None):
41
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
42
+ ap.add_argument("sheet")
43
+ ap.add_argument("boxes")
44
+ ap.add_argument("-o", required=True)
45
+ a = ap.parse_args(argv)
46
+ with open(a.boxes) as f:
47
+ boxes = json.load(f)
48
+ try:
49
+ crop(a.sheet, boxes, a.o)
50
+ except ValueError as e:
51
+ ap.error(str(e))
52
+ return 0
53
+
54
+
55
+ if __name__ == "__main__":
56
+ raise SystemExit(main())
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env python3
2
+ """Project a hex/square grid onto a concept image to read the layout cell by cell.
3
+
4
+ grid_overlay.py CONCEPT --grid hex --orient pointy --cols 12 --rows 9 \
5
+ --corners "x,y x,y x,y x,y" -o overlay.png
6
+ Corners = image pixels of the grid's bounding box: top-left, top-right, bottom-right, bottom-left
7
+ (as the board appears in the image). Labels are axial q,r (hex) or col,row (square).
8
+ The board is treated as a plane: raised tiles (plateaus) will look shifted, that is expected.
9
+
10
+ Free-form concepts (no game grid): use --grid square as a MEASUREMENT grid on the ground plane.
11
+ Pick 4 ground points that form a rectangle in the world, set --cols/--rows to its size in cells
12
+ and --cell-m to the cell size in metres; labels then show the metre coordinates (x,y) of each
13
+ cell's centre instead of indices. Corners that are repeated, collinear or out of order are rejected.
14
+ Requires Pillow and numpy.
15
+ """
16
+ import argparse
17
+ import math
18
+
19
+ import numpy as np
20
+ from PIL import Image, ImageDraw, ImageFont
21
+
22
+
23
+ def homography(src, dst):
24
+ rows = []
25
+ for (x, y), (u, v) in zip(src, dst):
26
+ rows.append([-x, -y, -1, 0, 0, 0, u * x, u * y, u])
27
+ rows.append([0, 0, 0, -x, -y, -1, v * x, v * y, v])
28
+ _, _, vt = np.linalg.svd(np.asarray(rows, float))
29
+ h = vt[-1].reshape(3, 3)
30
+ return h / h[2, 2]
31
+
32
+
33
+ def project(h, pts):
34
+ p = np.c_[pts, np.ones(len(pts))] @ h.T
35
+ return p[:, :2] / p[:, 2:3]
36
+
37
+
38
+ def cells(grid, orient, cols, rows, cell_m=None):
39
+ out = []
40
+ for row in range(rows):
41
+ for col in range(cols):
42
+ if grid == "square":
43
+ poly = [(col, row), (col + 1, row), (col + 1, row + 1), (col, row + 1)]
44
+ label = f"{(col + 0.5) * cell_m:g},{(row + 0.5) * cell_m:g}" if cell_m else f"{col},{row}"
45
+ elif orient == "pointy":
46
+ cx, cy = math.sqrt(3) * (col + 0.5 * (row & 1)), 1.5 * row
47
+ poly = [(cx + math.cos(math.radians(60 * i - 30)), cy + math.sin(math.radians(60 * i - 30))) for i in range(6)]
48
+ label = f"{col - (row - (row & 1)) // 2},{row}"
49
+ else:
50
+ cx, cy = 1.5 * col, math.sqrt(3) * (row + 0.5 * (col & 1))
51
+ poly = [(cx + math.cos(math.radians(60 * i)), cy + math.sin(math.radians(60 * i))) for i in range(6)]
52
+ label = f"{col},{row - (col - (col & 1)) // 2}"
53
+ out.append((np.asarray(poly, float), label))
54
+ return out
55
+
56
+
57
+ def parse_corners(text):
58
+ corners = [tuple(map(float, c.split(","))) for c in text.split()]
59
+ if len(corners) != 4:
60
+ raise ValueError('--corners needs four "x,y" points: TL TR BR BL')
61
+ # A usable quad is strictly convex: all turns in one direction and no repeated or collinear points.
62
+ turns = []
63
+ for i in range(4):
64
+ (ax, ay), (bx, by), (cx, cy) = corners[i], corners[(i + 1) % 4], corners[(i + 2) % 4]
65
+ turns.append((bx - ax) * (cy - by) - (by - ay) * (cx - bx))
66
+ if not (all(t > 0 for t in turns) or all(t < 0 for t in turns)):
67
+ raise ValueError("--corners must form a convex quad in order TL TR BR BL (no repeated or collinear points)")
68
+ return corners
69
+
70
+
71
+ def overlay(concept, out, grid="hex", orient="pointy", cols=1, rows=1, corners=None, cell_m=None):
72
+ polys = cells(grid, orient, cols, rows, cell_m)
73
+ allp = np.vstack([p for p, _ in polys])
74
+ x0, y0 = allp.min(0)
75
+ x1, y1 = allp.max(0)
76
+ src = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
77
+ h = homography(src, corners)
78
+ im = Image.open(concept).convert("RGB")
79
+ draw = ImageDraw.Draw(im)
80
+ try:
81
+ font = ImageFont.load_default(size=max(12, im.width // 110))
82
+ except TypeError: # Pillow < 10.1
83
+ font = ImageFont.load_default()
84
+ for poly, label in polys:
85
+ pp = [tuple(p) for p in project(h, poly)]
86
+ draw.line(pp + [pp[0]], fill=(255, 0, 255), width=2)
87
+ c = project(h, poly.mean(0, keepdims=True))[0]
88
+ draw.text((c[0], c[1]), label, fill=(255, 255, 0), font=font, anchor="mm", stroke_width=2, stroke_fill=(0, 0, 0))
89
+ im.save(out)
90
+ return h
91
+
92
+
93
+ def main(argv=None):
94
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
95
+ ap.add_argument("concept")
96
+ ap.add_argument("--grid", choices=["hex", "square"], default="hex")
97
+ ap.add_argument("--orient", choices=["pointy", "flat"], default="pointy")
98
+ ap.add_argument("--cols", type=int, required=True)
99
+ ap.add_argument("--rows", type=int, required=True)
100
+ ap.add_argument("--corners", required=True, help='"x,y x,y x,y x,y" TL TR BR BL')
101
+ ap.add_argument("--cell-m", type=float, default=None, help="square grid: cell size in metres (labels in metres)")
102
+ ap.add_argument("-o", required=True)
103
+ a = ap.parse_args(argv)
104
+ if a.cols < 1 or a.rows < 1:
105
+ ap.error("--cols and --rows must be positive")
106
+ if a.cell_m is not None and (a.grid != "square" or a.cell_m <= 0):
107
+ ap.error("--cell-m needs --grid square and a positive size")
108
+ try:
109
+ corners = parse_corners(a.corners)
110
+ except ValueError as e:
111
+ ap.error(str(e))
112
+ overlay(a.concept, a.o, a.grid, a.orient, a.cols, a.rows, corners, a.cell_m)
113
+ return 0
114
+
115
+
116
+ if __name__ == "__main__":
117
+ raise SystemExit(main())
@@ -0,0 +1,89 @@
1
+ """Model-free tests for grid_overlay.py, crop.py and blend.py. Skipped when Pillow or numpy is missing."""
2
+ import json
3
+ import pathlib
4
+ import sys
5
+ import tempfile
6
+ import unittest
7
+
8
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
9
+
10
+ try:
11
+ import numpy as np
12
+ from PIL import Image
13
+ HAVE_DEPS = True
14
+ except ImportError:
15
+ HAVE_DEPS = False
16
+
17
+
18
+ @unittest.skipUnless(HAVE_DEPS, "Pillow and numpy are required")
19
+ class ToolsTest(unittest.TestCase):
20
+ def setUp(self):
21
+ self.tmp = tempfile.TemporaryDirectory()
22
+ self.dir = pathlib.Path(self.tmp.name)
23
+ self.concept = self.dir / "concept.png"
24
+ Image.new("RGB", (200, 100), (10, 20, 30)).save(self.concept)
25
+
26
+ def tearDown(self):
27
+ self.tmp.cleanup()
28
+
29
+ def test_homography_maps_the_four_corners(self):
30
+ import grid_overlay
31
+ src = [(0, 0), (4, 0), (4, 3), (0, 3)]
32
+ dst = [(20, 10), (180, 15), (170, 90), (30, 85)]
33
+ h = grid_overlay.homography(src, dst)
34
+ np.testing.assert_allclose(grid_overlay.project(h, np.asarray(src, float)), dst, atol=1e-6)
35
+
36
+ def test_cell_labels(self):
37
+ import grid_overlay
38
+ square = grid_overlay.cells("square", "pointy", 2, 2, cell_m=2.5)
39
+ self.assertEqual([label for _, label in square], ["1.25,1.25", "3.75,1.25", "1.25,3.75", "3.75,3.75"])
40
+ hexes = grid_overlay.cells("hex", "pointy", 2, 3)
41
+ self.assertEqual([label for _, label in hexes], ["0,0", "1,0", "0,1", "1,1", "-1,2", "0,2"])
42
+ self.assertTrue(all(len(p) == 6 for p, _ in hexes))
43
+ flat = grid_overlay.cells("hex", "flat", 3, 2)
44
+ self.assertEqual([label for _, label in flat], ["0,0", "1,0", "2,-1", "0,1", "1,1", "2,0"])
45
+
46
+ def test_overlay_draws_on_the_concept(self):
47
+ import grid_overlay
48
+ out = self.dir / "overlay.png"
49
+ grid_overlay.main([str(self.concept), "--grid", "square", "--cols", "4", "--rows", "2",
50
+ "--corners", "10,10 190,10 190,90 10,90", "-o", str(out)])
51
+ im = Image.open(out)
52
+ self.assertEqual(im.size, (200, 100))
53
+ self.assertIn((255, 0, 255), {px for _, px in im.getcolors(200 * 100)})
54
+ for bad in ("1,1 2,2 3,3", "5,5 5,5 5,5 5,5", "0,0 10,0 20,0 30,0", "10,10 190,10 10,90 190,90"):
55
+ with self.assertRaises(ValueError, msg=bad):
56
+ grid_overlay.parse_corners(bad)
57
+ # mirrored order (counter-clockwise) is still a valid convex quad
58
+ grid_overlay.parse_corners("10,90 190,90 190,10 10,10")
59
+
60
+ def test_crop_writes_each_box_and_rejects_bad_boxes(self):
61
+ import crop
62
+ out = self.dir / "kit"
63
+ written = crop.crop(str(self.concept), {"tile_grass": [0, 0, 50, 40]}, out)
64
+ self.assertEqual([p.name for p in written], ["tile_grass.png"])
65
+ self.assertEqual(Image.open(out / "tile_grass.png").size, (50, 40))
66
+ fresh = self.dir / "fresh"
67
+ for boxes in ({"ok": [0, 0, 5, 5], "bad": [150, 0, 250, 40]}, {"../escape": [0, 0, 5, 5]},
68
+ {"short": [0, 0, 5]}, [[0, 0, 5, 5]]):
69
+ with self.assertRaises(ValueError, msg=str(boxes)):
70
+ crop.crop(str(self.concept), boxes, fresh)
71
+ self.assertFalse(fresh.exists())
72
+ boxes = self.dir / "boxes.json"
73
+ boxes.write_text(json.dumps({"rock": [10, 10, 20, 30]}))
74
+ crop.main([str(self.concept), str(boxes), "-o", str(out)])
75
+ self.assertEqual(Image.open(out / "rock.png").size, (10, 20))
76
+
77
+ def test_blend_resizes_the_render_to_the_concept(self):
78
+ import blend
79
+ render = self.dir / "render.png"
80
+ Image.new("RGB", (50, 25), (210, 220, 230)).save(render)
81
+ out = self.dir / "blend.png"
82
+ blend.main([str(self.concept), str(render), "-o", str(out)])
83
+ im = Image.open(out)
84
+ self.assertEqual(im.size, (200, 100))
85
+ self.assertEqual(im.getpixel((100, 50)), (110, 120, 130))
86
+
87
+
88
+ if __name__ == "__main__":
89
+ unittest.main()
@@ -0,0 +1,222 @@
1
+ ---
2
+ name: machine-builder
3
+ description: Design and build game-ready 3D models of mechs and other hard-surface machines (tanks, wheeled vehicles, hover, helicopters, aircraft/VTOL, turrets) from a brief or concept: engineering spec, rig, Blender procedural kit, validation tests, materials, LODs, export contract. Model only, no animation or damage. Use when a game needs a new mech, vehicle, aircraft or turret model.
4
+ ---
5
+
6
+ # Machine Builder
7
+
8
+ You design and build hard-surface machines — mechs, tanks, wheeled vehicles, hovercraft, helicopters, aircraft/VTOL, turrets and emplacements — as rigid parts on an armature, generated by Blender scripts from a reusable kit and an engineering spec.
9
+
10
+ One job: the MODEL. Animation and damage states belong to downstream tooling; this skill hands it a clean contract (section 9). Environment is out of scope.
11
+
12
+ Core idea: concept art is a picture, not a machine. The source of truth is the spec: skeleton, joints and their ranges, parts with a function, hardpoints. Geometry is generated from the spec and must pass automated tests before it is detailed.
13
+
14
+ Never use image-to-3D output (Tripo and similar) as final geometry. At most as a visual reference.
15
+
16
+ ## Prerequisites
17
+
18
+ - Blender 4.2 or later run headless (tested on 5.2). Find it as `blender` on PATH, the `BLENDER` environment variable or the standard install location (macOS: `/Applications/Blender.app/Contents/MacOS/Blender`); verify with `--version`. PyYAML inside Blender's Python for `.yaml` specs, or pass a `.json` copy.
19
+ - Optional: an image-generation tool for `refine`/`generate` concept modes (see Phase 1 for working without one).
20
+ - Optional: the `art-direction-pass` skill (shared `docs/art/direction/` format).
21
+ - The skill's resources, installed with it under `.claude/skills/machine-builder/` (other tools use their own skills directory): the skill's own `assets/spec.example.yaml` and `scripts/validate.py`. Invoke them by path from the project root.
22
+
23
+ ## Git
24
+
25
+ Follow the project's own Git rules. The workflow commits once per phase and per kept review iteration: if the project's instructions require approval for commits, ask once at the start. Never push, and never commit changes this run did not make.
26
+
27
+ Without permission, or when the working tree already has the user's own changes, use snapshots instead of commits. A snapshot is a tree object written through a temporary index; it creates no commit, ref or tag and leaves the project's index alone. `docs/art/` is excluded so reverts never touch the records:
28
+
29
+ ```sh
30
+ snap() { idx=$(mktemp); GIT_INDEX_FILE=$idx git read-tree HEAD && GIT_INDEX_FILE=$idx git add -A -- . ':!docs/art' && GIT_INDEX_FILE=$idx git write-tree; rm -f "$idx"; }
31
+ ```
32
+
33
+ - Baseline: `snap` before any change; record its id and `git rev-parse HEAD` in `docs/art/units.md`. The user's uncommitted and untracked files are part of it.
34
+ - Kept phase or iteration: `snap` again and record the id with the phase's outputs and files in `units.md`.
35
+ - Revert: `snap` the current state as `<cur>`, run `git diff --binary <cur> <last kept> | git apply --binary` (this also deletes files the step added), then check that a fresh `snap` equals `<last kept>`. Never use tree-wide `checkout`, `reset`, `clean` or `stash`.
36
+
37
+ ---
38
+
39
+ ## 0. Arguments
40
+
41
+ Defaults in brackets. Read them from the invocation text.
42
+
43
+ - `unit` — id, e.g. `striker_03`.
44
+ - `brief` — role, class/weight, faction, style references, intended games/cameras. Can be a few lines.
45
+ - `concept` — image(s), optional.
46
+ - `concept_mode` [auto] — `provided` (use the concept as is, after engineering review), `refine` (clean up the user's concept with image generation), `generate` (create concepts from the brief). Auto: `provided` if a clean concept exists, `generate` if none.
47
+ - `profile` [auto] — `walker` (biped, reverse-joint, quad, hexapod), `tracked`, `wheeled`, `hover`, `rotorcraft`, `fixed_wing` (incl. VTOL), `static` (turrets, emplacements).
48
+ - `quality` [hangar] — `hangar`: LOD0 must survive close-up inspection in a hangar view, plus gameplay LODs. `gameplay`: gameplay LODs only.
49
+ - `max_iterations` [5] for the review loop.
50
+
51
+ ---
52
+
53
+ ## 1. Shared foundations (once per project, extended by every unit)
54
+
55
+ Check and create if missing:
56
+ - `docs/art/direction/50-characters.md` (the `art-direction-pass` category-file format: role, shape language, proportions, detail hierarchy, material presets, palette slice, readability, asset spec, Do/Don't, Uncertain), with a **Machines design language** section: bevel widths per part size, chamfer angles, armour plate thickness, panel size and panel-line rules, joint-type catalogue, colour blocking, decal rules (numbers, stripes, insignia), wear level, emissive rules, scale references (cockpit hatch, ladder rung, human pilot 1.8 m).
57
+ - `tools/blender/units/kit/` — parametric part library: armour plates, joint housings, actuators and pistons, hydraulic lines, weapon pods (missile racks, cannons, lasers, gatlings), sensors and cockpits, vents and heat sinks, feet and toes, hands, wheels, road wheels and track links, rotors, nozzles, landing gear, hatches, ladders, antennas. One script per family, parameters at the top, deterministic with `--seed`.
58
+ - `docs/art/units.md` — registry of all units: id, profile, class, thumbnail, status.
59
+
60
+ If the project has no design language yet, derive it from the first unit's concept, write it down, and keep it for every next unit. Consistency across units matters more than the beauty of one unit: everything must look like it came from the same factories.
61
+
62
+ ## 2. Phase 1 — Concept
63
+
64
+ Concepts serve the design; they are never the final word on mechanics.
65
+
66
+ **Engineering review** (all modes) — annotate the concept with keep / remove / change:
67
+ - every visible part must have a function: armour, actuator, weapon, sensor, cooling, ammo, power, access;
68
+ - every joint must be able to move through the range its motions need and have something that drives it;
69
+ - armour must not block joints at the extremes;
70
+ - contact parts (feet, wheels, tracks, gear) must plausibly carry the mass;
71
+ - remove decorative gears, impossible joints, floating parts, details that change between views.
72
+
73
+ **provided** — run the review, write the result to `assets/units/<id>/concept-review.md`, go to Phase 2.
74
+
75
+ **refine** — run the review, then use image generation (edit mode) to produce a cleaned concept and a turnaround. Keep the user's design intent; change only what the review flagged.
76
+
77
+ **generate** — from the brief:
78
+ 1. 6–9 silhouette thumbnails (solid black on white, same scale, side and three-quarter views).
79
+ 2. Checkpoint: the user picks 1–2 (if unattended, pick by silhouette distinctiveness against existing units in `units.md` and note why).
80
+ 3. Design sheet of the pick in colour.
81
+ 4. Turnaround.
82
+
83
+ Image generation: use whatever is available (the tool's built-in image generation, an image MCP, another tool). If nothing is available, write the prompts to `assets/units/<id>/concept-prompts.md` and ask the user to run them. If unattended, mark the concept as pending in `units.md` and continue from the brief: the spec stays the source of truth, silhouettes are checked against the brief and existing units, and the reviewer gets the brief instead of a concept.
84
+
85
+ Prompt templates (adapt; keep "no text" — generated lettering is noise):
86
+
87
+ ```text
88
+ THUMBNAILS: Sheet of 8 distinct silhouette thumbnails of a {class} {profile} combat machine, {role}.
89
+ Solid black silhouettes on white, same scale, side view and three-quarter view, grounded stance,
90
+ functional engineering: every joint can move, no decorative gears. Style: {design language summary}. No text.
91
+
92
+ DESIGN SHEET: Industrial concept of the {class} {profile} machine from the chosen silhouette, three-quarter view,
93
+ neutral grey studio background, soft light. Painted armour plates with chamfered edges, visible actuators at joints,
94
+ {weapons}. Plausible mechanics only. Matches: {design language summary}. No text, no logos.
95
+
96
+ TURNAROUND: Orthographic turnaround of the same machine: front, side, back, top. Identical scale and design in all
97
+ views, aligned on one ground line, neutral background, flat even light, no perspective, no text.
98
+ ```
99
+
100
+ ## 3. Phase 2 — Spec
101
+
102
+ `assets/units/<id>/spec.yaml` — the single source of truth. Start from the skill's `assets/spec.example.yaml` (a walker; other profiles in section 10). Top-level keys: `unit`, `profile`, `class`, `dimensions_m`, `mass_t`, `design_language`, `skeleton` (bone → parent, `rom` per axis, `joint`), `parts` (id, bone, location, function, kit, params, `drives`, `contact`), `hardpoints`, `fx_sockets`, `paint_schemes`, `budgets`, `test_poses`, `sweeps`, `allowed_contacts`, `min_support_margin_m`, optional `ground_check`. Rotations are Euler XYZ in Blender bone-local space; Y runs along the bone (twist).
103
+
104
+ Location tags (`location`) group parts for the damage skill: walker `hd, ct, lt, rt, la, ra, ll, rl`; vehicles `front, left, right, rear, turret, rotor` — pick a set per profile and keep it consistent across units.
105
+
106
+ Spec review before modelling: every part has a function, every joint has an actuator part, ROM covers the motions in section 10, armour does not obviously block joints, mass is plausible for the contact area.
107
+
108
+ ## 4. Phase 3 — Skeleton and blockout
109
+
110
+ 1. Generate the armature and a blockout (one simple volume per part, true dimensions) from the spec with a script: `tools/blender/units/build_unit.py --spec ... --stage blockout`.
111
+ 2. Run `validate.py` (template below). All tests must pass before detailing.
112
+ 3. Silhouette check: render solid-black silhouettes from the side, front and three-quarter views, and at the gameplay camera distance(s) the brief names. Compare with the concept silhouette (side by side, and a 50% blend, e.g. Pillow's `Image.blend`) and with existing units of other classes — classes must read apart.
113
+ 4. Checkpoint: show the blockout turnaround, silhouettes and validation report. If unattended, continue and note it.
114
+
115
+ ## 5. Phase 4 — Detailing from the kit
116
+
117
+ - Build every part from kit families with parameters from the spec. A missing family → add it to the kit library (parametric, reusable), not a one-off mesh.
118
+ - Detail hierarchy for a hangar close-up: macro (plates, volumes) → medium (panel splits, actuators, vents, hatches, hydraulic lines) → micro (bolts, grilles, small hatches, cable clamps). Micro detail never compensates for a weak silhouette.
119
+ - LODs are generated, not decimated: every kit script takes `--detail 0|1|2`. LOD0 everything; LOD1 without micro; LOD2 macro volumes only. Hard-surface decimation destroys bevels.
120
+ - Bevels and weighted normals on all hard edges; apply booleans; no n-gon artefacts on curved surfaces.
121
+ - Parts stay separate objects parented to their bone. Never merge the machine into one mesh: animation and damage need the parts.
122
+ - Each part is one connected island unless the custom property `max_islands` says otherwise.
123
+ - Re-run `validate.py` after detailing: added details often create new collisions at extreme poses.
124
+
125
+ ## 6. Phase 5 — Materials and paint
126
+
127
+ - Material presets shared by all units: painted armour, bare metal, dark metal/frames, rubber, hydraulics/chrome, glass, emissive sensors. Values from the design language.
128
+ - Masks baked in Blender (Cycles bake, headless): ambient occlusion and an edge/curvature mask, into vertex colours or small per-unit mask textures. The engine material uses them for wear, dirt and edge highlights.
129
+ - Paint schemes are data (`paint_schemes` in the spec): base, secondary, accent, optional camo pattern, unit number, insignia. Applied through material parameters and decals, so new schemes need no new geometry.
130
+ - Decals (numbers, hazard stripes, insignia) as separate decal meshes or engine decals, never painted into geometry.
131
+ - For `hangar` quality, check close-ups under studio light: no stretched UVs, no visible gaps between plates, no empty flat areas larger than the design language allows.
132
+
133
+ ## 7. Phase 6 — Review loop
134
+
135
+ Each iteration (up to `max_iterations`):
136
+ 1. Render a turntable (8 angles), the concept angle, a hangar close-up set (studio 3-point light + neutral HDRI) and gameplay-distance shots.
137
+ 2. Make sheets: concept vs render; this unit next to 2–3 existing units.
138
+ 3. Spawn a FRESH blind reviewer (a subagent, or a separate session when the tool has none) with only the concept/turnaround, the design-language section and the renders (A/B blind when comparing two versions). It scores 1–5: silhouette, proportions, engineering plausibility, detail hierarchy, style consistency with existing units, material read, hangar close-up quality, readability at gameplay distance — and lists the top 3 problems.
139
+ 4. Fix the top problems, re-run `validate.py`, record the iteration (commit when the Git rules allow). Keep or revert by evidence.
140
+
141
+ Never claim a match without renders you looked at.
142
+
143
+ ## 8. Phase 7 — Export
144
+
145
+ - GLB per LOD (or one GLB with LOD nodes, following the engine's convention): metres, Y-up, applied transforms, armature included, parts as separate meshes parented to bones, `export_apply=True`.
146
+ - Naming: bones `<region>[_L|_R]`; parts `<location>__<part>[_L|_R]`; sockets `socket_<hardpoint>`; effects `fx_<kind>_<id>`; cameras `cam_<view>`.
147
+ - Engine check: import the GLB in the project's engine, place it in a test scene next to an environment scale reference, capture hangar and gameplay views.
148
+
149
+ ## 9. Contract for other skills
150
+
151
+ `assets/units/<id>/contract.json`, generated from the spec and the final file:
152
+ - bones: name, parent, rest transform, ROM per axis, joint type;
153
+ - parts: name, bone, location tag, function, contact flag, approximate mass;
154
+ - sockets: hardpoints (type, size), fx sockets, cameras;
155
+ - dimensions, mass, centre of mass at rest, ground contacts;
156
+ - LOD files and triangle counts; paint schemes.
157
+
158
+ Animation tooling reads bones, ROM and contacts. Damage tooling reads location tags, parts and fx sockets. Keep the contract stable: rename only with a migration note.
159
+
160
+ Update `docs/art/units.md` (status, thumbnail, files).
161
+
162
+ ## 10. Profiles
163
+
164
+ Each profile defines the skeleton template, mandatory motions (test poses / sweeps) and typical concept errors.
165
+
166
+ **walker** — sub-types biped, reverse-joint (digitigrade), quad, hexapod.
167
+ - Skeleton: root → pelvis → torso (twist) → arms/weapon mounts, head/cockpit; legs hip (3 DOF) → knee → ankle (2 DOF) → toes optional.
168
+ - Motions: stride both sides, crouch with flat feet, step-up (one leg raised ~0.5 m), full torso twist sweep, arms raised/forward.
169
+ - Ground check on; support margin in every pose.
170
+ - Typical errors: knees that cannot bend past ~20°, thigh armour fused to the pelvis, flat single-plate feet on a heavy machine, decorative gears, arms that collide with the torso when it twists.
171
+
172
+ **tracked** — tanks, tracked artillery, APCs.
173
+ - Skeleton: root → hull → turret (yaw) → mantlet/gun (pitch); road wheels and sprockets as bones (spin, suspension travel).
174
+ - Motions: full turret sweep 360° at max depression and max elevation (two sweeps with a base `pose` holding the gun), suspension compression per side (test poses with `loc` on the wheel bones).
175
+ - Tracks: separate part on the hull, UV-scroll friendly; wheels touch the track run.
176
+ - Typical errors: gun hitting the hull or engine deck when traversing at depression, turret wider than the ring allows, wheels floating above the track.
177
+
178
+ **wheeled** — trucks, buggies, wheeled APCs.
179
+ - Skeleton: root → body → axles/wheel hubs (spin, steer on steering axles, suspension travel) → turret if any.
180
+ - Motions: full steering lock both sides with suspension compressed (test poses combining `rot` and `loc`), turret sweep.
181
+ - Typical errors: wheels clipping fenders at lock, no visible suspension, wheels too small for the mass.
182
+
183
+ **hover** — hovercraft, hover tanks.
184
+ - Skeleton: root → body → fans/nozzles (tilt) → turret.
185
+ - Ground check off (the profile default); test nozzle tilt range with sweeps. Skirt clearance is not checked by `validate.py`: measure it in a side render and record it in the review.
186
+ - Typical errors: no visible lift source, nozzles that cannot tilt.
187
+
188
+ **rotorcraft** — helicopters, gunships.
189
+ - Skeleton: root → fuselage → main rotor hub (spin) → blades; tail rotor; landing gear (optional retract); weapon pylons.
190
+ - Motions: rotor sweep (blade clearance from tail boom and pylons, with flapping angle), gear down.
191
+ - Ground check only in a gear-down pose: `ground_check_poses: [gear_down]`.
192
+ - Typical errors: blades intersecting the tail boom, pylons inside the rotor disc, landing gear that cannot carry the mass.
193
+
194
+ **fixed_wing** — aircraft, VTOL, aerodyne dropships.
195
+ - Skeleton: root → fuselage → control surfaces (ailerons, elevators, rudder), VTOL nacelles (tilt), gear, bay doors.
196
+ - Motions: control surface extremes, nacelle tilt full range, gear down, bay doors open.
197
+ - Typical errors: nacelles colliding with wings when tilted, gear doors larger than their bays.
198
+
199
+ **static** — turrets, emplacements, towers.
200
+ - Skeleton: root → base → yaw ring → pitch cradle → barrels.
201
+ - Motions: full yaw sweep at min and max pitch (two sweeps with a base `pose` on the pitch cradle).
202
+ - Typical errors: barrels hitting the base at depression, no ammo feed or power access.
203
+
204
+ ## 11. Constraints
205
+
206
+ - Model only: no animation clips, no damage states, no environment.
207
+ - Everything regenerable from spec + kit scripts; no manual-only Blender steps.
208
+ - Deterministic builds (`--seed`), one recorded state per phase (see Git).
209
+ - No image-to-3D geometry in the final model.
210
+ - Do not lower test thresholds to make a unit pass: change the design or the spec, and record why.
211
+
212
+ ## 12. Templates
213
+
214
+ ### validate.py
215
+
216
+ Run headless from the project root: `blender -b assets/units/<id>/<id>.blend --python-exit-code 1 --python .claude/skills/machine-builder/scripts/validate.py -- --spec assets/units/<id>/spec.yaml --out assets/units/<id>/validation.json` (or copy it to `tools/blender/units/validate.py`). It exits 1 when any check fails and on any error (bad spec, unknown bone, missing armature); it deletes the old report first and then always writes one, with `"passed": false` on errors.
217
+
218
+ Pose values are `[x, y, z]` rotations in degrees, or `{rot: [x, y, z], loc: [x, y, z]}` for translations such as suspension travel. A sweep may carry a base `pose` applied before the swept bone (a turret sweep at full depression). `ground_check_poses` limits the support check to the named poses.
219
+
220
+ Mark ground-contact parts with the custom property `contact = True`; optional part properties are `density` (default 1.0) and `max_islands` (default 1).
221
+
222
+ Checks: per test pose and sweep step, collisions between parts not on the same or directly connected bones (except `allowed_contacts`), the centre of mass over the support polygon of the contact parts by `min_support_margin_m`, and no non-contact part below the contacts, when the ground check applies; statically, triangles against `budgets.tris_lod0`, extra islands per part, missing `socket_<hardpoint>` objects and meshes not parented to bones.
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "Machine Builder"
3
+ short_description: "Spec-driven, validated game-ready 3D models of mechs and vehicles in Blender"
4
+ default_prompt: "Use $machine-builder to design and build this machine as a validated, rigged Blender model from a spec, with LODs, materials and an export contract."