scenesonar-mcp 0.1.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.
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: scenesonar-mcp
3
+ Version: 0.1.0
4
+ Summary: SceneSonar MCP - geometry telemetry for AI agents in Unity
5
+ Author: PaveltPhP
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/PaveltPhP/scene-sonar
8
+ Project-URL: Repository, https://github.com/PaveltPhP/scene-sonar
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ Requires-Dist: mcp>=2.0
12
+ Requires-Dist: numpy>=1.23
13
+ Requires-Dist: pillow>=9.0
14
+
15
+ # scenesonar-mcp
16
+
17
+ MCP server for **SceneSonar** — geometry telemetry for AI agents working in a Unity scene.
18
+
19
+ It measures, per frame, where one mesh is relative to another (penetration depth, gaps,
20
+ contacts) and returns counts, an event stream and point-cloud images. This is touch, not
21
+ sight: it answers *where* and *when*, not *how it looks*.
22
+
23
+ ## Install
24
+
25
+ ```
26
+ pip install scenesonar-mcp
27
+ ```
28
+
29
+ Requires the Unity package `com.scenesonar` (see the repository README).
30
+
31
+ ## Configure
32
+
33
+ `~/.scenesonar/config.json`:
34
+
35
+ ```json
36
+ {
37
+ "projectPath": "D:/MyGame",
38
+ "unityPath": "C:/Program Files/Unity/Hub/Editor/6000.0.0f1/Editor/Unity.exe",
39
+ "outRoot": "D:/SceneSonarRuns"
40
+ }
41
+ ```
42
+
43
+ Environment overrides: `SCENESONAR_PROJECT`, `SCENESONAR_UNITY`, `SCENESONAR_OUTROOT`.
44
+
45
+ ## Add to an agent
46
+
47
+ ```json
48
+ {
49
+ "mcpServers": {
50
+ "scenesonar": {
51
+ "command": "scenesonar-mcp"
52
+ }
53
+ }
54
+ }
55
+ ```
56
+
57
+ ## Tools
58
+
59
+ - `sonar_start` — launch a run (Unity in batch mode; the editor must be closed);
60
+ - `sonar_status` — running / done / failed, sample count, log tail;
61
+ - `sonar_report` — max penetration, event counts, detector self-test, worst points, timeline;
62
+ - `sonar_events` — when a vertex entered or left another mesh;
63
+ - `sonar_view` / `sonar_slice` — point-cloud images and cross-sections;
64
+ - `sonar_clip` — GIF, render-vs-sonar pair, or worst frames;
65
+ - `sonar_list` / `sonar_config`.
66
+
67
+ ## License
68
+
69
+ MIT.
@@ -0,0 +1,55 @@
1
+ # scenesonar-mcp
2
+
3
+ MCP server for **SceneSonar** — geometry telemetry for AI agents working in a Unity scene.
4
+
5
+ It measures, per frame, where one mesh is relative to another (penetration depth, gaps,
6
+ contacts) and returns counts, an event stream and point-cloud images. This is touch, not
7
+ sight: it answers *where* and *when*, not *how it looks*.
8
+
9
+ ## Install
10
+
11
+ ```
12
+ pip install scenesonar-mcp
13
+ ```
14
+
15
+ Requires the Unity package `com.scenesonar` (see the repository README).
16
+
17
+ ## Configure
18
+
19
+ `~/.scenesonar/config.json`:
20
+
21
+ ```json
22
+ {
23
+ "projectPath": "D:/MyGame",
24
+ "unityPath": "C:/Program Files/Unity/Hub/Editor/6000.0.0f1/Editor/Unity.exe",
25
+ "outRoot": "D:/SceneSonarRuns"
26
+ }
27
+ ```
28
+
29
+ Environment overrides: `SCENESONAR_PROJECT`, `SCENESONAR_UNITY`, `SCENESONAR_OUTROOT`.
30
+
31
+ ## Add to an agent
32
+
33
+ ```json
34
+ {
35
+ "mcpServers": {
36
+ "scenesonar": {
37
+ "command": "scenesonar-mcp"
38
+ }
39
+ }
40
+ }
41
+ ```
42
+
43
+ ## Tools
44
+
45
+ - `sonar_start` — launch a run (Unity in batch mode; the editor must be closed);
46
+ - `sonar_status` — running / done / failed, sample count, log tail;
47
+ - `sonar_report` — max penetration, event counts, detector self-test, worst points, timeline;
48
+ - `sonar_events` — when a vertex entered or left another mesh;
49
+ - `sonar_view` / `sonar_slice` — point-cloud images and cross-sections;
50
+ - `sonar_clip` — GIF, render-vs-sonar pair, or worst frames;
51
+ - `sonar_list` / `sonar_config`.
52
+
53
+ ## License
54
+
55
+ MIT.
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "scenesonar-mcp"
7
+ version = "0.1.0"
8
+ description = "SceneSonar MCP - geometry telemetry for AI agents in Unity"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ authors = [{ name = "PaveltPhP" }]
12
+ dependencies = ["mcp>=2.0", "numpy>=1.23", "pillow>=9.0"]
13
+ license = { text = "MIT" }
14
+
15
+ [project.urls]
16
+ Homepage = "https://github.com/PaveltPhP/scene-sonar"
17
+ Repository = "https://github.com/PaveltPhP/scene-sonar"
18
+
19
+ [project.scripts]
20
+ scenesonar-mcp = "scenesonar_server:main"
21
+
22
+ [tool.setuptools]
23
+ py-modules = ["scenesonar_server", "scenesonar_core", "scenesonar_miasight",
24
+ "scenesonar_view", "scenesonar_clip", "scenesonar_labeltext"]
@@ -0,0 +1,129 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """clip.py — clips from captured frames and render-vs-sonar pairs.
4
+
5
+ python clip.py gif --dir <run> [--fps 10] [--width 360]
6
+ python clip.py pair --dir <run> --sample 120 [--angle 20]
7
+ python clip.py worst --dir <run> [--top 3]
8
+
9
+ pair: the real rendered frame (cap/cNNNN.png) on the left, the same figure
10
+ reconstructed from the sensors on the right.
11
+ """
12
+ import argparse
13
+ import csv
14
+ import glob
15
+ import os
16
+
17
+ import numpy as np
18
+ from PIL import Image, ImageDraw
19
+
20
+ import scenesonar_labeltext as labeltext
21
+ import scenesonar_miasight as M
22
+ import scenesonar_view as V
23
+
24
+ BG = (16, 18, 23)
25
+
26
+
27
+ def label(dr, xy, text, size=16):
28
+ labeltext.label(dr, xy, text, size=size, fill=(235, 238, 245))
29
+
30
+
31
+ def load_env(d):
32
+ p = os.path.join(d, "env.bin")
33
+ return M.load(p) if os.path.exists(p) else None
34
+
35
+
36
+ def cap_for(d, sample):
37
+ files = sorted(glob.glob(os.path.join(d, "cap", "c*.png")))
38
+ if not files:
39
+ return None
40
+ return min(files, key=lambda f: abs(int(os.path.basename(f)[1:5]) - sample))
41
+
42
+
43
+ def pair(d, sample, angle=20, out=None):
44
+ p = M.load(os.path.join(d, "p%04d.bin" % sample))
45
+ env = load_env(d)
46
+ cloud = p if env is None else np.concatenate([env, p])
47
+ cloud = cloud[cloud["c"] != 2] # no furniture
48
+ canvas = V.render(cloud, angle, px_per_m=560, title="")
49
+
50
+ cap_path = cap_for(d, sample)
51
+ if cap_path is not None:
52
+ img = Image.open(cap_path).convert("RGB")
53
+ h = canvas.height
54
+ w = int(img.width * h / img.height)
55
+ img = img.resize((w, h), Image.LANCZOS)
56
+ else:
57
+ img = Image.new("RGB", (canvas.width, canvas.height), BG)
58
+ label(ImageDraw.Draw(img), (10, 8), "no render captured")
59
+
60
+ W = img.width + canvas.width + 12
61
+ sheet = Image.new("RGB", (W, canvas.height + 34), BG)
62
+ sheet.paste(img, (0, 34))
63
+ sheet.paste(canvas, (img.width + 12, 34))
64
+ dr = ImageDraw.Draw(sheet)
65
+ label(dr, (10, 8), "RENDER sample %d" % sample)
66
+ label(dr, (img.width + 22, 8), "SONAR sample %d" % sample)
67
+
68
+ out = out or os.path.join(d, "shots", "pair_%04d.png" % sample)
69
+ os.makedirs(os.path.dirname(out), exist_ok=True)
70
+ sheet.save(out)
71
+ return out
72
+
73
+
74
+ def gif(d, fps=10, width=360, out=None):
75
+ files = sorted(glob.glob(os.path.join(d, "cap", "c*.png")))
76
+ if not files:
77
+ raise SystemExit("no frames in " + os.path.join(d, "cap"))
78
+ frames = []
79
+ for f in files:
80
+ im = Image.open(f).convert("RGB")
81
+ h = int(im.height * width / im.width)
82
+ frames.append(im.resize((width, h), Image.LANCZOS))
83
+ out = out or os.path.join(d, "shots", "clip.gif")
84
+ os.makedirs(os.path.dirname(out), exist_ok=True)
85
+ frames[0].save(out, save_all=True, append_images=frames[1:],
86
+ duration=max(20, int(1000 / fps)), loop=0, optimize=True)
87
+ return out
88
+
89
+
90
+ def worst(d, top=3):
91
+ """Samples with the deepest penetration (from frames.csv)."""
92
+ rows = list(csv.DictReader(open(os.path.join(d, "frames.csv"), encoding="utf-8")))
93
+ rows = [r for r in rows if r.get("maxDepthMM")]
94
+ rows.sort(key=lambda r: float(r["maxDepthMM"]), reverse=True)
95
+ seen, res = set(), []
96
+ for r in rows:
97
+ s = int(r["sample"])
98
+ if any(abs(s - x) < 8 for x in seen):
99
+ continue
100
+ seen.add(s)
101
+ res.append((s, float(r["maxDepthMM"]), int(r["over3"])))
102
+ if len(res) >= top:
103
+ break
104
+ return res
105
+
106
+
107
+ def main():
108
+ ap = argparse.ArgumentParser()
109
+ ap.add_argument("cmd", choices=["gif", "pair", "worst"])
110
+ ap.add_argument("--dir", required=True)
111
+ ap.add_argument("--fps", type=int, default=10)
112
+ ap.add_argument("--width", type=int, default=360)
113
+ ap.add_argument("--sample", type=int, default=1)
114
+ ap.add_argument("--angle", type=float, default=20)
115
+ ap.add_argument("--top", type=int, default=3)
116
+ ap.add_argument("--out", default=None)
117
+ a = ap.parse_args()
118
+
119
+ if a.cmd == "gif":
120
+ print(gif(a.dir, a.fps, a.width, a.out))
121
+ elif a.cmd == "pair":
122
+ print(pair(a.dir, a.sample, a.angle, a.out))
123
+ else:
124
+ for s, mx, o3 in worst(a.dir, a.top):
125
+ print(s, "max %.1f mm, >3mm %d" % (mx, o3))
126
+
127
+
128
+ if __name__ == "__main__":
129
+ main()
@@ -0,0 +1,293 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """SceneSonar MCP — geometry telemetry for AI agents in Unity.
4
+
5
+ Transport: stdio, JSON-RPC 2.0 (official `mcp` SDK, MCPServer).
6
+
7
+ Config (first found wins):
8
+ ~/.scenesonar/config.json
9
+ ./config.json next to this file
10
+ env: SCENESONAR_PROJECT, SCENESONAR_UNITY, SCENESONAR_OUTROOT
11
+
12
+ {
13
+ "projectPath": "D:/MyGame",
14
+ "unityPath": "C:/Program Files/Unity/Hub/Editor/6000.0.0f1/Editor/Unity.exe",
15
+ "outRoot": "D:/SceneSonarRuns"
16
+ }
17
+ """
18
+ import json
19
+ import os
20
+ import subprocess
21
+ import sys
22
+ import time
23
+
24
+ HERE = os.path.dirname(os.path.abspath(__file__))
25
+ PY = sys.executable
26
+ EXECUTE = "SceneSonar.Editor.SonarRun.Run"
27
+
28
+
29
+ def _load_cfg():
30
+ cfg = {}
31
+ for p in (os.path.expanduser("~/.scenesonar/config.json"), os.path.join(HERE, "config.json")):
32
+ if os.path.exists(p):
33
+ try:
34
+ cfg.update(json.load(open(p, encoding="utf-8")))
35
+ break
36
+ except Exception:
37
+ pass
38
+ return cfg
39
+
40
+
41
+ CFG = _load_cfg()
42
+ PROJECT = os.environ.get("SCENESONAR_PROJECT") or CFG.get("projectPath", "")
43
+ UNITY = os.environ.get("SCENESONAR_UNITY") or CFG.get("unityPath", "")
44
+ OUTROOT = os.environ.get("SCENESONAR_OUTROOT") or CFG.get("outRoot", os.path.expanduser("~/SceneSonarRuns"))
45
+
46
+
47
+ # ---------------------------------------------------------------- utils
48
+
49
+ def _pid_alive(pid):
50
+ try:
51
+ out = subprocess.run(["tasklist", "/FI", "PID eq %d" % int(pid)],
52
+ capture_output=True, text=True, timeout=20,
53
+ creationflags=0x08000000).stdout
54
+ return str(pid) in out
55
+ except Exception:
56
+ return False
57
+
58
+
59
+ def _unity_busy():
60
+ try:
61
+ out = subprocess.run(["tasklist", "/FI", "IMAGENAME eq Unity.exe"],
62
+ capture_output=True, text=True, timeout=20,
63
+ creationflags=0x08000000).stdout
64
+ return "Unity.exe" in out
65
+ except Exception:
66
+ return False
67
+
68
+
69
+ def _dir(name):
70
+ return os.path.join(OUTROOT, name)
71
+
72
+
73
+ def _json(path, default=None):
74
+ try:
75
+ return json.load(open(path, encoding="utf-8"))
76
+ except Exception:
77
+ return default
78
+
79
+
80
+ def _state(d):
81
+ if os.path.exists(os.path.join(d, "summary.json")):
82
+ return "done"
83
+ info = _json(os.path.join(d, "run.json"), {}) or {}
84
+ pid = info.get("pid")
85
+ if pid and _pid_alive(pid):
86
+ return "running"
87
+ return "failed" if pid else "unknown"
88
+
89
+
90
+ def _samples(d):
91
+ try:
92
+ return len([f for f in os.listdir(d) if f.startswith("p") and f.endswith(".bin")])
93
+ except Exception:
94
+ return 0
95
+
96
+
97
+ def _timeline(d, rows=28):
98
+ p = os.path.join(d, "frames.csv")
99
+ if not os.path.exists(p):
100
+ return []
101
+ data = [l.strip().split(",") for l in open(p, encoding="utf-8").read().splitlines()[1:] if l.strip()]
102
+ if not data:
103
+ return []
104
+ step = max(1, len(data) // rows)
105
+ out = []
106
+ for r in data[::step]:
107
+ try:
108
+ out.append({"t": float(r[2]), "over3": int(r[5]), "max_mm": float(r[7])})
109
+ except Exception:
110
+ continue
111
+ return out
112
+
113
+
114
+ def _log_tail(d, n=12):
115
+ p = os.path.join(d, "batch.log")
116
+ if not os.path.exists(p):
117
+ return []
118
+ raw = open(p, "rb").read().decode("utf-8", "replace").splitlines()
119
+ keep = [l for l in raw if "[SceneSonar]" in l or "error CS" in l]
120
+ return keep[-n:]
121
+
122
+
123
+ def _tool(script, args, timeout=900):
124
+ r = subprocess.run([PY, "-X", "utf8", os.path.join(HERE, script)] + args,
125
+ capture_output=True, text=True, timeout=timeout,
126
+ creationflags=0x08000000)
127
+ if r.returncode != 0:
128
+ return None, (r.stderr or r.stdout)[-800:]
129
+ return [l.strip() for l in r.stdout.splitlines() if l.strip()], None
130
+
131
+
132
+ # ---------------------------------------------------------------- tools
133
+
134
+ def t_start(args):
135
+ if not PROJECT or not os.path.isdir(PROJECT):
136
+ return {"ok": False, "error": "projectPath is not set. Create ~/.scenesonar/config.json"}
137
+ if not UNITY or not os.path.exists(UNITY):
138
+ return {"ok": False, "error": "unityPath is not set or does not exist"}
139
+ tag = args.get("tag") or time.strftime("run_%Y%m%d_%H%M%S")
140
+ d = _dir(tag)
141
+ if os.path.exists(d) and os.listdir(d):
142
+ return {"ok": False, "error": "run already exists: " + tag}
143
+ if _unity_busy():
144
+ return {"ok": False, "error": "Unity is already running: batch mode needs the editor closed"}
145
+
146
+ os.makedirs(d, exist_ok=True)
147
+ env = os.environ.copy()
148
+ env.update({
149
+ "SCENESONAR_OUT": d,
150
+ "SCENESONAR_SECONDS": str(args.get("seconds", 8)),
151
+ "SCENESONAR_EVERY": str(args.get("every", 1)),
152
+ "SCENESONAR_BODY": args.get("body", ""),
153
+ "SCENESONAR_PARTS": args.get("parts", ""),
154
+ "SCENESONAR_SKIP": args.get("skip", ""),
155
+ "SCENESONAR_CAPTURE": "1" if args.get("capture") else "0",
156
+ "SCENESONAR_CAPEVERY": str(args.get("cap_every", 3)),
157
+ })
158
+ if args.get("scene"):
159
+ env["SCENESONAR_SCENE"] = args["scene"]
160
+ if args.get("motion"):
161
+ env["SCENESONAR_MOTION"] = args["motion"]
162
+
163
+ p = subprocess.Popen([UNITY, "-batchmode", "-projectPath", PROJECT,
164
+ "-executeMethod", EXECUTE, "-logFile", os.path.join(d, "batch.log")],
165
+ env=env, cwd=PROJECT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
166
+ creationflags=0x00000008 | 0x00000200)
167
+ json.dump({"tag": tag, "dir": d, "pid": p.pid, "scene": args.get("scene", ""),
168
+ "seconds": args.get("seconds", 8), "started": time.time(),
169
+ "motion": args.get("motion", "")},
170
+ open(os.path.join(d, "run.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
171
+ return {"ok": True, "run": tag, "dir": d, "pid": p.pid, "note": "2-4 minutes; poll sonar_status"}
172
+
173
+
174
+ def t_status(args):
175
+ d = _dir(args.get("run", ""))
176
+ if not os.path.isdir(d):
177
+ return {"ok": False, "error": "no such run"}
178
+ st = _state(d)
179
+ return {"ok": True, "run": args["run"], "state": st, "samples": _samples(d),
180
+ "log": _log_tail(d) if st != "done" else []}
181
+
182
+
183
+ def t_report(args):
184
+ d = _dir(args.get("run", ""))
185
+ s = _json(os.path.join(d, "summary.json"))
186
+ if not s:
187
+ return {"ok": False, "error": "not finished", "state": _state(d), "samples": _samples(d)}
188
+ return {"ok": True, "run": args["run"], "samples": s.get("samples"),
189
+ "seconds": s.get("seconds"), "verts": s.get("clothVerts"),
190
+ "max_depth_mm": s.get("maxDepthMM"), "events": s.get("events"),
191
+ "detector": s.get("needle"), "ground_y": s.get("groundY"),
192
+ "worst": (s.get("worst") or [])[:10], "timeline": _timeline(d)}
193
+
194
+
195
+ def t_events(args):
196
+ d = _dir(args.get("run", ""))
197
+ p = os.path.join(d, "sonar.jsonl")
198
+ if not os.path.exists(p):
199
+ return {"ok": False, "error": "no sonar.jsonl"}
200
+ limit = int(args.get("limit", 40))
201
+ part, ev = args.get("part", ""), args.get("ev", "")
202
+ out = []
203
+ for line in open(p, encoding="utf-8", errors="replace"):
204
+ if len(out) >= limit:
205
+ break
206
+ try:
207
+ o = json.loads(line)
208
+ except Exception:
209
+ continue
210
+ if part and part not in o.get("part", ""):
211
+ continue
212
+ if ev and o.get("ev") != ev:
213
+ continue
214
+ out.append({k: o.get(k) for k in ("ev", "t", "part", "idx", "depth_mm", "x", "y", "z")})
215
+ return {"ok": True, "count": len(out), "events": out}
216
+
217
+
218
+ def t_view(args):
219
+ d = _dir(args.get("run", ""))
220
+ if not os.path.isdir(d):
221
+ return {"ok": False, "error": "no such run"}
222
+ if args.get("strip"):
223
+ a = ["--dir", d, "--strip", str(args["strip"]), "--angle", str(args.get("angle", 20))]
224
+ if args.get("legs"):
225
+ a.append("--legs")
226
+ else:
227
+ a = ["--dir", d, "--frame", str(args.get("frame", 1)), "--angle", str(args.get("angle", 20))]
228
+ if args.get("legs"):
229
+ a.append("--legs")
230
+ out, err = _tool("scenesonar_view.py", a)
231
+ return {"ok": bool(out), "png": (out or [""])[-1], "error": err}
232
+
233
+
234
+ def t_slice(args):
235
+ d = _dir(args.get("run", ""))
236
+ if not os.path.isdir(d):
237
+ return {"ok": False, "error": "no such run"}
238
+ a = ["--dir", d, "--frame", str(args.get("frame", 1))]
239
+ if args.get("auto"):
240
+ a.append("--auto")
241
+ else:
242
+ a += ["--view", args.get("view", "xz")]
243
+ if args.get("slice"):
244
+ a += ["--slice", args["slice"]]
245
+ if args.get("thick"):
246
+ a += ["--thick", str(args["thick"])]
247
+ if args.get("scale"):
248
+ a += ["--scale", str(args["scale"])]
249
+ out, err = _tool("scenesonar_miasight.py", a)
250
+ return {"ok": bool(out), "png": [x for x in (out or []) if x.lower().endswith(".png")], "error": err}
251
+
252
+
253
+ def t_clip(args):
254
+ d = _dir(args.get("run", ""))
255
+ if not os.path.isdir(d):
256
+ return {"ok": False, "error": "no such run"}
257
+ mode = args.get("mode", "gif")
258
+ a = [mode, "--dir", d]
259
+ if mode == "gif":
260
+ a += ["--fps", str(args.get("fps", 10))]
261
+ elif mode == "pair":
262
+ a += ["--sample", str(args.get("sample", 1)), "--angle", str(args.get("angle", 20))]
263
+ else:
264
+ a += ["--top", str(args.get("top", 3))]
265
+ out, err = _tool("scenesonar_clip.py", a)
266
+ return {"ok": bool(out), "mode": mode,
267
+ "files": [x for x in (out or []) if x.lower().endswith((".png", ".gif", ".mp4"))],
268
+ "lines": out, "error": err}
269
+
270
+
271
+ def t_list(args):
272
+ items = []
273
+ if os.path.isdir(OUTROOT):
274
+ for name in sorted(os.listdir(OUTROOT)):
275
+ d = os.path.join(OUTROOT, name)
276
+ if not os.path.isdir(d):
277
+ continue
278
+ s = _json(os.path.join(d, "summary.json"), {}) or {}
279
+ items.append({"run": name, "state": _state(d), "samples": _samples(d),
280
+ "max_depth_mm": s.get("maxDepthMM")})
281
+ return {"ok": True, "runs": items}
282
+
283
+
284
+ def t_config(args):
285
+ return {"ok": True, "projectPath": PROJECT, "unityPath": UNITY, "outRoot": OUTROOT,
286
+ "config_file": os.path.expanduser("~/.scenesonar/config.json")}
287
+
288
+
289
+ TOOLS = {
290
+ "sonar_start": t_start, "sonar_status": t_status, "sonar_report": t_report,
291
+ "sonar_events": t_events, "sonar_view": t_view, "sonar_slice": t_slice,
292
+ "sonar_clip": t_clip, "sonar_list": t_list, "sonar_config": t_config,
293
+ }
@@ -0,0 +1,45 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Font-aware text labels for the generated PNGs.
3
+
4
+ Pillow's built-in bitmap font is ASCII-only, so non-Latin text turns into boxes.
5
+ This helper picks a system TTF that has Latin + Cyrillic glyphs and silently
6
+ falls back to the default font when none is found.
7
+ """
8
+ import os
9
+
10
+ from PIL import ImageFont
11
+
12
+ _CANDIDATES = [
13
+ r"C:\Windows\Fonts\segoeui.ttf",
14
+ r"C:\Windows\Fonts\arial.ttf",
15
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
16
+ "/usr/share/fonts/dejavu/DejaVuSans.ttf",
17
+ "/Library/Fonts/Arial.ttf",
18
+ "/System/Library/Fonts/Supplemental/Arial.ttf",
19
+ ]
20
+
21
+ _cache = {}
22
+
23
+
24
+ def _font(size):
25
+ key = int(size)
26
+ if key in _cache:
27
+ return _cache[key]
28
+ font = None
29
+ for path in _CANDIDATES:
30
+ if os.path.exists(path):
31
+ try:
32
+ font = ImageFont.truetype(path, key)
33
+ break
34
+ except Exception:
35
+ pass
36
+ _cache[key] = font
37
+ return font
38
+
39
+
40
+ def label(draw, xy, text, size=15, fill=(235, 238, 245)):
41
+ font = _font(size)
42
+ if font is None:
43
+ draw.text(xy, text, fill=fill)
44
+ else:
45
+ draw.text(xy, text, font=font, fill=fill)
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: scenesonar-mcp
3
+ Version: 0.1.0
4
+ Summary: SceneSonar MCP - geometry telemetry for AI agents in Unity
5
+ Author: PaveltPhP
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/PaveltPhP/scene-sonar
8
+ Project-URL: Repository, https://github.com/PaveltPhP/scene-sonar
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ Requires-Dist: mcp>=2.0
12
+ Requires-Dist: numpy>=1.23
13
+ Requires-Dist: pillow>=9.0
14
+
15
+ # scenesonar-mcp
16
+
17
+ MCP server for **SceneSonar** — geometry telemetry for AI agents working in a Unity scene.
18
+
19
+ It measures, per frame, where one mesh is relative to another (penetration depth, gaps,
20
+ contacts) and returns counts, an event stream and point-cloud images. This is touch, not
21
+ sight: it answers *where* and *when*, not *how it looks*.
22
+
23
+ ## Install
24
+
25
+ ```
26
+ pip install scenesonar-mcp
27
+ ```
28
+
29
+ Requires the Unity package `com.scenesonar` (see the repository README).
30
+
31
+ ## Configure
32
+
33
+ `~/.scenesonar/config.json`:
34
+
35
+ ```json
36
+ {
37
+ "projectPath": "D:/MyGame",
38
+ "unityPath": "C:/Program Files/Unity/Hub/Editor/6000.0.0f1/Editor/Unity.exe",
39
+ "outRoot": "D:/SceneSonarRuns"
40
+ }
41
+ ```
42
+
43
+ Environment overrides: `SCENESONAR_PROJECT`, `SCENESONAR_UNITY`, `SCENESONAR_OUTROOT`.
44
+
45
+ ## Add to an agent
46
+
47
+ ```json
48
+ {
49
+ "mcpServers": {
50
+ "scenesonar": {
51
+ "command": "scenesonar-mcp"
52
+ }
53
+ }
54
+ }
55
+ ```
56
+
57
+ ## Tools
58
+
59
+ - `sonar_start` — launch a run (Unity in batch mode; the editor must be closed);
60
+ - `sonar_status` — running / done / failed, sample count, log tail;
61
+ - `sonar_report` — max penetration, event counts, detector self-test, worst points, timeline;
62
+ - `sonar_events` — when a vertex entered or left another mesh;
63
+ - `sonar_view` / `sonar_slice` — point-cloud images and cross-sections;
64
+ - `sonar_clip` — GIF, render-vs-sonar pair, or worst frames;
65
+ - `sonar_list` / `sonar_config`.
66
+
67
+ ## License
68
+
69
+ MIT.
@@ -0,0 +1,14 @@
1
+ README.md
2
+ pyproject.toml
3
+ scenesonar_clip.py
4
+ scenesonar_core.py
5
+ scenesonar_labeltext.py
6
+ scenesonar_miasight.py
7
+ scenesonar_server.py
8
+ scenesonar_view.py
9
+ scenesonar_mcp.egg-info/PKG-INFO
10
+ scenesonar_mcp.egg-info/SOURCES.txt
11
+ scenesonar_mcp.egg-info/dependency_links.txt
12
+ scenesonar_mcp.egg-info/entry_points.txt
13
+ scenesonar_mcp.egg-info/requires.txt
14
+ scenesonar_mcp.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ scenesonar-mcp = scenesonar_server:main
@@ -0,0 +1,3 @@
1
+ mcp>=2.0
2
+ numpy>=1.23
3
+ pillow>=9.0
@@ -0,0 +1,6 @@
1
+ scenesonar_clip
2
+ scenesonar_core
3
+ scenesonar_labeltext
4
+ scenesonar_miasight
5
+ scenesonar_server
6
+ scenesonar_view
@@ -0,0 +1,270 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """miasight — turns a sonar point cloud into an image.
4
+
5
+ Input: a run folder (p0001.bin ... + frames.csv + sonar.jsonl + summary.json).
6
+ Output: a PNG with a cross-section or a projection. This is an "X-ray": the body
7
+ under the clothing is visible and the penetration depth is colour-coded.
8
+
9
+ Examples:
10
+ python miasight.py --dir <run> --list
11
+ python miasight.py --dir <run> --auto
12
+ python miasight.py --dir <run> --frame 40 --slice z=0.62
13
+ python miasight.py --dir <run> --frame 40 --view xz --slice y=0.05
14
+ python miasight.py --dir <run> --sheet 1,20,40,60 --view xz
15
+ """
16
+ import argparse
17
+ import csv
18
+ import math
19
+ import os
20
+ import struct
21
+
22
+ import numpy as np
23
+ from PIL import Image, ImageDraw
24
+
25
+ import scenesonar_labeltext as labeltext
26
+
27
+ DT = np.dtype([("x", "<f4"), ("y", "<f4"), ("z", "<f4"), ("d", "<f4"), ("c", "<i4")])
28
+ PX = 0.002 # 2 mm per pixel
29
+ BG = (14, 16, 20)
30
+ BODY = (150, 156, 168)
31
+ CLOTH_DIM = (26, 40, 56)
32
+ ENV_DIM = (46, 40, 34)
33
+ FLOOR_DIM = (34, 54, 46)
34
+ GRID = (38, 42, 50)
35
+ TXT = (235, 238, 245)
36
+
37
+
38
+ def load(path):
39
+ with open(path, "rb") as f:
40
+ magic = f.read(4)
41
+ if magic != b"MIAS":
42
+ raise SystemExit("not a MIAS cloud: " + path)
43
+ ver, n = struct.unpack("<ii", f.read(8))
44
+ a = np.fromfile(f, dtype=DT, count=n)
45
+ return a
46
+
47
+
48
+ def depth_color(d):
49
+ """0 mm — cold, 3 mm — yellow, 8 mm and deeper — red."""
50
+ t = min(1.0, max(0.0, d / 0.015))
51
+ if t < 0.4:
52
+ k = t / 0.4
53
+ return (int(40 + 215 * k), int(210 - 40 * k), int(190 - 120 * k))
54
+ k = (t - 0.4) / 0.6
55
+ return (255, int(170 - 120 * k), int(70 - 50 * k))
56
+
57
+
58
+ class Canvas:
59
+ def __init__(self, lo, hi, pad=0.03):
60
+ self.lo = np.array(lo, float) - pad
61
+ self.hi = np.array(hi, float) + pad
62
+ self.w = max(64, int(math.ceil((self.hi[0] - self.lo[0]) / PX)))
63
+ self.h = max(64, int(math.ceil((self.hi[1] - self.lo[1]) / PX)))
64
+ self.img = Image.new("RGB", (self.w, self.h), BG)
65
+ self.dr = ImageDraw.Draw(self.img)
66
+
67
+ def px(self, a, b, flip_v=True):
68
+ x = (a - self.lo[0]) / PX
69
+ y = (b - self.lo[1]) / PX
70
+ if flip_v:
71
+ y = self.h - 1 - y
72
+ return x, y
73
+
74
+ def grid(self, step_m=0.1):
75
+ step = step_m / PX
76
+ x = 0.0
77
+ while x < self.w:
78
+ self.dr.line([(x, 0), (x, self.h)], fill=GRID)
79
+ x += step
80
+ y = 0.0
81
+ while y < self.h:
82
+ self.dr.line([(0, y), (self.w, y)], fill=GRID)
83
+ y += step
84
+
85
+ def label(self, text, xy=(10, 8), size=17):
86
+ labeltext.label(self.dr, xy, text, size=size, fill=TXT)
87
+
88
+ def save(self, path):
89
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
90
+ self.img.save(path)
91
+ return path
92
+
93
+
94
+ def pick_axes(view):
95
+ # (horizontal, vertical, depth)
96
+ return {"xy": (0, 1, 2), "xz": (0, 2, 1), "yz": (1, 2, 0)}[view]
97
+
98
+
99
+ def render(points, view="xz", slice_axis=None, slice_val=None, thick=0.012,
100
+ title="", draw_body=True):
101
+ ha, va, da = pick_axes(view)
102
+ a, b, d = points["x"], points["y"], points["z"]
103
+ if slice_axis is not None:
104
+ coord = {"x": a, "y": b, "z": d}[slice_axis]
105
+ m = np.abs(coord - slice_val) <= thick / 2.0
106
+ a, b, d, c, dep = a[m], b[m], d[m], points["c"][m], points["d"][m]
107
+ else:
108
+ c, dep = points["c"], points["d"]
109
+
110
+ if len(a) == 0:
111
+ raise SystemExit("no points in the selected layer")
112
+
113
+ lo = (float(a.min()), float(b.min()))
114
+ hi = (float(a.max()), float(b.max()))
115
+ cv = Canvas(lo, hi)
116
+ cv.grid()
117
+
118
+ order = np.argsort(d) # far first
119
+ is_body = c == 0
120
+ is_hit = (c == 1) & (dep > 0.0005)
121
+ is_room = c == 2
122
+ is_floor = c == 3
123
+
124
+ # 0) environment — dim, so the floor reads
125
+ for i in order:
126
+ if is_room[i]:
127
+ x, y = cv.px(float(a[i]), float(b[i]))
128
+ cv.dr.point([x, y], fill=ENV_DIM)
129
+ elif is_floor[i]:
130
+ x, y = cv.px(float(a[i]), float(b[i]))
131
+ cv.dr.point([x, y], fill=FLOOR_DIM)
132
+
133
+ # 1) clean cloth — dim, so it does not hide the body
134
+ for i in order:
135
+ if is_body[i] or is_hit[i] or is_room[i] or is_floor[i]:
136
+ continue
137
+ x, y = cv.px(float(a[i]), float(b[i]))
138
+ cv.dr.point([x, y], fill=CLOTH_DIM)
139
+
140
+ # 2) body — light, on top of clean cloth (X-ray)
141
+ if draw_body:
142
+ for i in order:
143
+ if not is_body[i]:
144
+ continue
145
+ x, y = cv.px(float(a[i]), float(b[i]))
146
+ cv.dr.point([x, y], fill=BODY)
147
+
148
+ # 3) penetration — bright and thicker
149
+ for i in order:
150
+ if not is_hit[i]:
151
+ continue
152
+ x, y = cv.px(float(a[i]), float(b[i]))
153
+ cv.dr.rectangle([x - 1, y - 1, x + 1, y + 1], fill=depth_color(float(dep[i])))
154
+
155
+ if slice_axis:
156
+ cv.label(f"{title} slice {slice_axis}={slice_val*1000:.0f} mm (+/-{thick*1000:.0f})")
157
+ else:
158
+ cv.label(f"{title} {view} projection")
159
+ cv.label("body grey; cloth by depth: cold=0, yellow=3, red=8+ mm", (10, 30), 15)
160
+ cv.label("grid 10 cm", (10, 50), 14)
161
+ return cv
162
+
163
+
164
+ def auto_slice_point(points):
165
+ """The deepest penetration point (or centre if clean)."""
166
+ cloth = points[points["c"] == 1]
167
+ if len(cloth) == 0:
168
+ return None
169
+ i = int(np.argmax(cloth["d"]))
170
+ return (float(cloth["x"][i]), float(cloth["y"][i]),
171
+ float(cloth["z"][i]), float(cloth["d"][i]))
172
+
173
+
174
+ def main():
175
+ ap = argparse.ArgumentParser()
176
+ ap.add_argument("--dir", default=".", help="run folder with pNNNN.bin")
177
+ ap.add_argument("--list", action="store_true")
178
+ ap.add_argument("--timeline", action="store_true")
179
+ ap.add_argument("--frame", type=int)
180
+ ap.add_argument("--auto", action="store_true")
181
+ ap.add_argument("--view", default="xz", choices=["xy", "xz", "yz"])
182
+ ap.add_argument("--slice", default=None, help="z=0.62 / x=0 / y=0.1")
183
+ ap.add_argument("--thick", type=float, default=0.012)
184
+ ap.add_argument("--sheet", default=None, help="1,20,40 — contact sheet")
185
+ ap.add_argument("--scale", type=float, default=1.0,
186
+ help="image zoom (4 = 0.5 mm/px)")
187
+ ap.add_argument("--out", default=None)
188
+ args = ap.parse_args()
189
+
190
+ global PX
191
+ if args.scale and args.scale != 1.0:
192
+ PX = PX / args.scale
193
+
194
+ frames = sorted(f for f in os.listdir(args.dir) if f.startswith("p") and f.endswith(".bin"))
195
+ if not frames:
196
+ raise SystemExit("no pNNNN.bin in " + args.dir)
197
+
198
+ if args.list:
199
+ print("samples:", len(frames))
200
+ p = os.path.join(args.dir, "frames.csv")
201
+ if os.path.exists(p):
202
+ print(open(p, encoding="utf-8").read().strip())
203
+ return
204
+
205
+ if args.timeline:
206
+ rows = list(csv.DictReader(open(os.path.join(args.dir, "frames.csv"), encoding="utf-8")))
207
+ rows = [r for r in rows if r.get("over3")]
208
+ step = max(1, len(rows) // 32)
209
+ print(" t over3 max,mm bar")
210
+ for r in rows[::step]:
211
+ o = int(r["over3"])
212
+ mx = float(r["maxDepthMM"])
213
+ t = float(r["time"])
214
+ bar = "#" * min(50, int(o / 20))
215
+ print("%5.2f %6d %7.1f %s" % (t, o, mx, bar))
216
+ return
217
+
218
+ def fr(n):
219
+ return os.path.join(args.dir, "p%04d.bin" % n)
220
+
221
+ if args.sheet:
222
+ nums = [int(x) for x in args.sheet.split(",")]
223
+ imgs = []
224
+ for n in nums:
225
+ p = load(fr(n))
226
+ imgs.append(render(p, args.view, None, None, args.thick, "sample %d" % n).img)
227
+ w = max(i.width for i in imgs)
228
+ h = max(i.height for i in imgs)
229
+ cols = 2
230
+ rows = int(math.ceil(len(imgs) / cols))
231
+ sheet = Image.new("RGB", (w * cols, h * rows), BG)
232
+ for k, im in enumerate(imgs):
233
+ sheet.paste(im, ((k % cols) * w, (k // cols) * h))
234
+ out = args.out or os.path.join(args.dir, "shots", "sheet_%s.png" % "_".join(map(str, nums)))
235
+ os.makedirs(os.path.dirname(out), exist_ok=True)
236
+ sheet.save(out)
237
+ print(out)
238
+ return
239
+
240
+ n = args.frame if args.frame is not None else 1
241
+ if not os.path.exists(fr(n)):
242
+ raise SystemExit("no such frame " + fr(n))
243
+ pts = load(fr(n))
244
+
245
+ axis = val = None
246
+ if args.auto:
247
+ hit = auto_slice_point(pts)
248
+ if hit is None:
249
+ print("no cloth points in this frame")
250
+ return
251
+ print("worst point: %.1f mm at (%.3f, %.3f, %.3f)" % (hit[3] * 1000, hit[0], hit[1], hit[2]))
252
+ # three orthogonal sections through the worst point
253
+ for ax, v in zip(("x", "y", "z"), hit[:3]):
254
+ cv = render(pts, "yz" if ax == "x" else ("xz" if ax == "y" else "xy"),
255
+ ax, v, args.thick, "sample %d" % n)
256
+ out = os.path.join(args.dir, "shots", "f%04d_%s.png" % (n, ax))
257
+ print(cv.save(out))
258
+ return
259
+
260
+ if args.slice:
261
+ axis, val = args.slice.split("=")
262
+ val = float(val)
263
+ cv = render(pts, args.view, axis, val, args.thick, "sample %d" % n)
264
+ out = args.out or os.path.join(
265
+ args.dir, "shots", "f%04d_%s%s.png" % (n, args.view, ("_%s%.2f" % (axis, val)) if axis else ""))
266
+ print(cv.save(out))
267
+
268
+
269
+ if __name__ == "__main__":
270
+ main()
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """SceneSonar MCP server (stdio).
4
+
5
+ Install: pip install mcp
6
+ Run: python -X utf8 server.py
7
+ Config: ~/.scenesonar/config.json (projectPath, unityPath, outRoot)
8
+ """
9
+ import sys
10
+
11
+ import scenesonar_core as core
12
+ from mcp.server.mcpserver import MCPServer
13
+
14
+ srv = MCPServer(
15
+ "scenesonar",
16
+ version="0.1.0",
17
+ instructions=(
18
+ "Geometry telemetry for a Unity scene: per-frame penetration, gaps and contacts "
19
+ "between a body and everything around it. Returns numbers, an event stream and "
20
+ "point-cloud images. This is touch, not sight: it answers WHERE and WHEN, not how "
21
+ "it looks. Start with sonar_start, poll sonar_status, then sonar_report."
22
+ ),
23
+ )
24
+
25
+
26
+ @srv.tool(description="Start a SceneSonar run (Unity in -batchmode, Play Mode). Takes 2-4 minutes. "
27
+ "The editor must be closed.")
28
+ def sonar_start(tag: str = "", scene: str = "", seconds: float = 8.0, motion: str = "",
29
+ body: str = "", parts: str = "", skip: str = "", every: int = 1,
30
+ capture: bool = False, cap_every: int = 3) -> dict:
31
+ return core.t_start({"tag": tag, "scene": scene, "seconds": seconds, "motion": motion,
32
+ "body": body, "parts": parts, "skip": skip, "every": every,
33
+ "capture": capture, "cap_every": cap_every})
34
+
35
+
36
+ @srv.tool(description="Run state: running / done / failed, sample count, log tail.")
37
+ def sonar_status(run: str) -> dict:
38
+ return core.t_status({"run": run})
39
+
40
+
41
+ @srv.tool(description="Result: max penetration, event counts, detector self-test, "
42
+ "10 worst points, timeline over time.")
43
+ def sonar_report(run: str) -> dict:
44
+ return core.t_report({"run": run})
45
+
46
+
47
+ @srv.tool(description="Event stream: when a vertex entered or left another mesh.")
48
+ def sonar_events(run: str, part: str = "", ev: str = "", limit: int = 40) -> dict:
49
+ return core.t_events({"run": run, "part": part, "ev": ev, "limit": limit})
50
+
51
+
52
+ @srv.tool(description="PNG of the point cloud. strip=\"1,60,120\" makes a frame strip; "
53
+ "legs=True crops to legs and floor.")
54
+ def sonar_view(run: str, frame: int = 1, strip: str = "", angle: float = 20.0,
55
+ legs: bool = False) -> dict:
56
+ return core.t_view({"run": run, "frame": frame, "strip": strip, "angle": angle, "legs": legs})
57
+
58
+
59
+ @srv.tool(description="PNG cross-section (slice=\"z=0.62\", scale=3) or auto = three sections "
60
+ "through the worst point.")
61
+ def sonar_slice(run: str, frame: int = 1, auto: bool = False, view: str = "xz",
62
+ slice: str = "", thick: float = 0.0, scale: float = 1.0) -> dict:
63
+ return core.t_slice({"run": run, "frame": frame, "auto": auto, "view": view,
64
+ "slice": slice, "thick": thick or None, "scale": scale})
65
+
66
+
67
+ @srv.tool(description="Clip from captured frames (gif), render-vs-pointcloud pair (pair), "
68
+ "or worst frames (worst).")
69
+ def sonar_clip(run: str, mode: str = "gif", fps: int = 10, sample: int = 1,
70
+ angle: float = 20.0, top: int = 3) -> dict:
71
+ return core.t_clip({"run": run, "mode": mode, "fps": fps, "sample": sample,
72
+ "angle": angle, "top": top})
73
+
74
+
75
+ @srv.tool(description="List runs with state and max penetration.")
76
+ def sonar_list() -> dict:
77
+ return core.t_list({})
78
+
79
+
80
+ @srv.tool(description="Show the resolved configuration (project, Unity path, output root).")
81
+ def sonar_config() -> dict:
82
+ return core.t_config({})
83
+
84
+
85
+ def main():
86
+ srv.run("stdio")
87
+
88
+
89
+ if __name__ == "__main__":
90
+ main()
@@ -0,0 +1,202 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """view.py — draws a "figure" from the sonar point cloud (pseudo-3D).
4
+
5
+ Points are sorted by depth and shaded by distance, so volume reads.
6
+ Body is light grey, clean cloth is blue-teal, penetration is red.
7
+
8
+ python view.py --dir ... --frame 1 --sheet
9
+ python view.py --dir ... --frame 1 --angle 35 --zoom
10
+ """
11
+ import argparse
12
+ import math
13
+ import os
14
+
15
+ import numpy as np
16
+ from PIL import Image, ImageDraw
17
+
18
+ import scenesonar_labeltext as labeltext
19
+ import scenesonar_miasight as M
20
+
21
+ BODY = np.array([205, 205, 212], float)
22
+ CLOTH = np.array([86, 150, 178], float)
23
+ HIT = np.array([255, 84, 58], float)
24
+ ROOM = np.array([104, 92, 74], float)
25
+ FLOOR = np.array([74, 146, 116], float)
26
+
27
+
28
+ def shade(col, k):
29
+ return tuple(int(min(255, c * k)) for c in col)
30
+
31
+
32
+ def project(pts, angle_deg):
33
+ a = math.radians(angle_deg)
34
+ ca, sa = math.cos(a), math.sin(a)
35
+ x = pts["x"] * ca - pts["z"] * sa
36
+ z = pts["x"] * sa + pts["z"] * ca
37
+ return x, pts["y"], z # screen X, screen Y, depth (towards camera +)
38
+
39
+
40
+ def render(pts, angle=0.0, px_per_m=560, pad=0.03, bg=(16, 18, 23), mark=None,
41
+ crop=None, title="", bounds=None, crop_y=None):
42
+ x, y, d = project(pts, angle)
43
+ if crop_y is not None:
44
+ m = (y >= crop_y[0]) & (y <= crop_y[1])
45
+ x, y, d = x[m], y[m], d[m]
46
+ pts = pts[m]
47
+ if crop is not None:
48
+ cx, cy, half = crop
49
+ m = (np.abs(x - cx) <= half) & (np.abs(y - cy) <= half)
50
+ x, y, d = x[m], y[m], d[m]
51
+ cls = pts["c"][m]
52
+ dep = pts["d"][m]
53
+ px_per_m = 420.0 / (2.0 * half) # hotspot ~420 px wide
54
+ else:
55
+ cls = pts["c"]
56
+ dep = pts["d"]
57
+
58
+ if len(x) == 0:
59
+ raise SystemExit("no points")
60
+
61
+ if bounds is not None:
62
+ x0, x1, y0, y1 = bounds
63
+ else:
64
+ x0, x1 = float(x.min()), float(x.max())
65
+ y0, y1 = float(y.min()), float(y.max())
66
+ W = max(32, int((x1 - x0 + 2 * pad) * px_per_m))
67
+ H = max(32, int((y1 - y0 + 2 * pad) * px_per_m))
68
+ img = Image.new("RGB", (W, H), bg)
69
+ dr = ImageDraw.Draw(img)
70
+
71
+ def px(a, b):
72
+ return ((a - x0 + pad) * px_per_m, (y1 - b + pad) * px_per_m)
73
+
74
+ dmin, dmax = float(d.min()), float(d.max())
75
+ span = max(1e-6, dmax - dmin)
76
+ order = np.argsort(d) # far first
77
+
78
+ for i in order:
79
+ k = 0.42 + 0.58 * ((d[i] - dmin) / span)
80
+ if cls[i] == 0:
81
+ col = shade(BODY, k)
82
+ r = 0
83
+ elif cls[i] == 2:
84
+ col = shade(ROOM, k)
85
+ r = 0
86
+ elif cls[i] == 3:
87
+ col = shade(FLOOR, 0.7 + 0.3 * k)
88
+ r = 1
89
+ elif dep[i] > 0.0005:
90
+ col = shade(HIT, 0.75 + 0.25 * k)
91
+ r = 1
92
+ else:
93
+ col = shade(CLOTH, k)
94
+ r = 0
95
+ X, Y = px(float(x[i]), float(y[i]))
96
+ if r:
97
+ dr.rectangle([X - r, Y - r, X + r, Y + r], fill=col)
98
+ else:
99
+ dr.point([X, Y], fill=col)
100
+
101
+ # floor line — so the height reads, not just points
102
+ fl = np.nonzero(cls == 3)[0]
103
+ if len(fl):
104
+ fy = float(np.median(y[fl]))
105
+ Y = px(0.0, fy)[1]
106
+ dr.line([(0, Y), (W, Y)], fill=(80, 160, 122))
107
+ dr.line([(0, Y + 1), (W, Y + 1)], fill=(54, 104, 82))
108
+
109
+ if mark is not None:
110
+ X, Y = px(mark[0], mark[1])
111
+ rr = 14
112
+ dr.ellipse([X - rr, Y - rr, X + rr, Y + rr], outline=(255, 255, 255))
113
+
114
+ if title:
115
+ labeltext.label(dr, (8, 6), title, size=15, fill=(230, 233, 240))
116
+ return img
117
+
118
+
119
+ def main():
120
+ ap = argparse.ArgumentParser()
121
+ ap.add_argument("--dir", required=True)
122
+ ap.add_argument("--frame", type=int, default=1)
123
+ ap.add_argument("--angle", type=float, default=0.0)
124
+ ap.add_argument("--sheet", action="store_true")
125
+ ap.add_argument("--strip", default=None, help="1,60,120 — frame strip")
126
+ ap.add_argument("--legs", action="store_true", help="legs + floor only, zoomed")
127
+ ap.add_argument("--zoom", action="store_true", help="close-up on the worst point")
128
+ ap.add_argument("--out", default=None)
129
+ a = ap.parse_args()
130
+
131
+ pts = M.load(os.path.join(a.dir, "p%04d.bin" % a.frame))
132
+ env_path = os.path.join(a.dir, "env.bin")
133
+ env = M.load(env_path) if os.path.exists(env_path) else None
134
+ if env is not None:
135
+ pts = np.concatenate([env, pts])
136
+
137
+ if a.strip:
138
+ nums = [int(x) for x in a.strip.split(",")]
139
+ cy = (0.0, 0.85) if a.legs else None
140
+ ppm = 900 if a.legs else 560
141
+ imgs = []
142
+ allp = []
143
+ for n in nums:
144
+ p = M.load(os.path.join(a.dir, "p%04d.bin" % n))
145
+ p = p if env is None else np.concatenate([env, p])
146
+ if a.legs:
147
+ p = p[p["c"] != 2] # no furniture: frame around the legs
148
+ if cy is not None:
149
+ p = p[(p["y"] >= cy[0]) & (p["y"] <= cy[1])]
150
+ allp.append(p)
151
+ xs, ys, _ = project(np.concatenate(allp), a.angle)
152
+ bounds = (float(xs.min()), float(xs.max()), float(ys.min()), float(ys.max()))
153
+ for n, p in zip(nums, allp):
154
+ imgs.append(render(p, a.angle, px_per_m=ppm, bounds=bounds, title="sample %d" % n))
155
+ gap = 8
156
+ W = sum(i.width for i in imgs) + gap * (len(imgs) - 1)
157
+ H = max(i.height for i in imgs)
158
+ sheet = Image.new("RGB", (W, H), (16, 18, 23))
159
+ X = 0
160
+ for im in imgs:
161
+ sheet.paste(im, (X, 0))
162
+ X += im.width + gap
163
+ out = a.out or os.path.join(a.dir, "shots", "strip_%s.png" % "_".join(map(str, nums)))
164
+ os.makedirs(os.path.dirname(out), exist_ok=True)
165
+ sheet.save(out)
166
+ print(out)
167
+ return
168
+
169
+ cloth = pts[pts["c"] == 1]
170
+ i = int(np.argmax(cloth["d"]))
171
+ hit = (float(cloth["x"][i]), float(cloth["y"][i]), float(cloth["z"][i]), float(cloth["d"][i]))
172
+ print("worst point: %.1f mm at (%.3f, %.3f, %.3f)" % (hit[3] * 1000, hit[0], hit[1], hit[2]))
173
+
174
+ if a.sheet:
175
+ front = render(pts, 0, title="sample %d: front" % a.frame)
176
+ q = render(pts, 35, title="three-quarter")
177
+ side = render(pts, 90, title="side")
178
+ crop = (hit[0], hit[1], 0.10) if not a.zoom else (hit[0], hit[1], 0.075)
179
+ zoom = render(pts, 0, crop=crop, mark=None, title="hotspot %.1f mm" % (hit[3] * 1000))
180
+ gap = 10
181
+ H = max(front.height, q.height, side.height, zoom.height)
182
+ W = front.width + q.width + side.width + zoom.width + gap * 3
183
+ sheet = Image.new("RGB", (W, H), (16, 18, 23))
184
+ X = 0
185
+ for im in (front, q, side, zoom):
186
+ sheet.paste(im, (X, 0))
187
+ X += im.width + gap
188
+ out = a.out or os.path.join(a.dir, "shots", "figure_f%04d.png" % a.frame)
189
+ os.makedirs(os.path.dirname(out), exist_ok=True)
190
+ sheet.save(out)
191
+ print(out)
192
+ return
193
+
194
+ im = render(pts, a.angle, title="sample %d" % a.frame)
195
+ out = a.out or os.path.join(a.dir, "shots", "v_f%04d_%03d.png" % (a.frame, int(a.angle)))
196
+ os.makedirs(os.path.dirname(out), exist_ok=True)
197
+ im.save(out)
198
+ print(out)
199
+
200
+
201
+ if __name__ == "__main__":
202
+ main()
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+