virtualmatter 0.7.0 → 0.8.0

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.
package/README.md CHANGED
@@ -97,6 +97,7 @@ npx virtualmatter screenshot -o shot.png # default overview
97
97
  npx virtualmatter screenshot --target "Player" -o p.png # frame one object
98
98
  npx virtualmatter screenshot --at 0,30,40 --rot 0,-35,0 # exact camera
99
99
  npx virtualmatter screenshot --client 4 -o ui.png # what client 4 sees, UI included
100
+ npx virtualmatter screenshot --depth -o st.png # + st.depth.npy (metres), .depth.png, .depth.json
100
101
  # --rot is yaw,pitch,roll
101
102
  ```
102
103
 
@@ -187,7 +188,7 @@ deploying it.
187
188
  | `run-lua [dir] --code "<lua>" [--target server\|client] [--client <id>]` | Execute Lua in the running engine. A client run uses the only connected client unless `--client` names one (list them with `--code "return Server:GetClients()"`). Exit code 3 means the engine did not answer in time and may still be running the code: check its effect before sending code that changes the world again. It is never retried for you. |
188
189
  | `errors [dir]` | Recent engine errors. Retried twice when the engine is busy or briefly unreachable, since it only reads. Notes on stderr when the engine restarted in the last hour, since a restart clears the error buffer. |
189
190
  | `atomo [--dir <dir>] -- <command> ...` | The engine SDK's `atomo` commands (`run-lua`, `run-lua-client [id]`, `errors [--after-reload <file>...] [--timeout <s>]`) in atomo's own output format and exit status, for agents following the engine guide and tools written against atomo such as the starter builder. The folder's `./atomo` calls this. Exit 1: the Lua snippet raised, or `errors` printed an error that no earlier check reported; 2: nothing ran; 3: a bridge timeout, the engine may still be running it. `errors --after-reload` waits (default 10 s) until the world has the saved files, which `sync` pushes, and has reloaded them, then reads the errors: run it right after a save instead of sleeping. |
190
- | `screenshot [dir] [-o out.png] [--client <id>]` | Capture the engine's view; `--client` captures through a connected client, UI included. |
191
+ | `screenshot [dir] [-o out.png] [--client <id>] [--depth]` | Capture the engine's view; `--client` captures through a connected client, UI included. `--depth` also reads the frame's depth buffer: `<out>.depth.npy` (float32 metres along the view axis, height x width, 0 = sky), a `.depth.png` preview and a `.depth.json` with the camera. Needs an engine with depth capture (MR !2671 / !2672). |
191
192
  | `mcp [dir] [--framing <id>]` | Run the stdio MCP server. |
192
193
  | `login` / `logout` / `whoami` | Device-code sign-in; every other command signs you in automatically when needed. Tokens live in `~/.config/virtualmatter/credentials.json` (mode 0600) and refresh automatically. |
193
194
 
@@ -115,7 +115,7 @@ call them (the starters' \`starterctl.py\`). Everything else maps to the
115
115
  | \`atomo run-lua '<code>'\` | \`./atomo run-lua '<code>'\`, or \`npx virtualmatter run-lua --code '<code>'\` (MCP: \`run_lua\`) |
116
116
  | \`atomo run-lua-client ...\` | \`./atomo run-lua-client <id> '<code>'\`, or \`npx virtualmatter run-lua --target client --code '<code>'\` |
117
117
  | \`atomo errors\` | \`./atomo errors\` (exits 1 when any error is new since the last check), or \`npx virtualmatter errors\` (MCP: \`get_engine_errors\`) |
118
- | \`atomo screenshot\` / \`screenshot-at\` / \`screenshot-obj\` | \`npx virtualmatter screenshot -o shot.png\` (MCP: \`capture_screenshot\`); aim the camera with run-lua first if needed |
118
+ | \`atomo screenshot\` / \`screenshot-at\` / \`screenshot-obj\` | \`npx virtualmatter screenshot -o shot.png\` (MCP: \`capture_screenshot\`); aim the camera with run-lua first if needed. Add \`--depth\` (MCP: \`depth: true\`) for the frame's depth in metres instead of casting rays |
119
119
  | \`atomo prints\` / \`atomo status\` | not available locally; use \`return\` values from run-lua |
120
120
  | edit a .lua file, then check \`atomo errors\` | save the file with \`npx virtualmatter sync\` running (or MCP \`write_file\`), then run \`./atomo errors --after-reload <file>\` straight away: it waits until the world has the save and has reloaded it, so never sleep first |
121
121
  | \`Skills/git-commit.md\` (git add/commit) | skip it - there is no git here; sync IS the persistence |
package/dist/depth.js ADDED
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Depth captures: `screenshot --depth` and the MCP tool's `depth`.
3
+ *
4
+ * The engine reads the captured frame's depth buffer back and answers
5
+ * metres along the view axis ("planar"), one float32 per pixel of the
6
+ * picture, top row first, 0 where nothing was drawn (sky, or beyond the
7
+ * far plane). Pixel (x, y) of the depth is pixel (x, y) of the image.
8
+ */
9
+ import zlib from "node:zlib";
10
+ /** The depth object as the engine (and the session's /engine/screenshot) sends it. */
11
+ export function decodeDepth(raw) {
12
+ if (!raw || typeof raw !== "object")
13
+ throw new Error("The depth answer is not an object.");
14
+ const { data, ...info } = raw;
15
+ const width = Number(info.width);
16
+ const height = Number(info.height);
17
+ if (typeof data !== "string" || !(width > 0) || !(height > 0)) {
18
+ throw new Error("The depth answer has no data or no size.");
19
+ }
20
+ if (info.encoding !== "float32le")
21
+ throw new Error(`Unknown depth encoding ${String(info.encoding)}.`);
22
+ const bytes = Buffer.from(data, "base64");
23
+ if (bytes.length !== width * height * 4) {
24
+ throw new Error(`Depth data is ${bytes.length} bytes, expected ${width * height * 4} for ${width}x${height}.`);
25
+ }
26
+ const metres = new Float32Array(width * height);
27
+ for (let i = 0; i < metres.length; i++)
28
+ metres[i] = bytes.readFloatLE(i * 4);
29
+ return { info: info, metres };
30
+ }
31
+ /** A NumPy .npy file: float32, shape (height, width). `numpy.load` reads it. */
32
+ export function depthToNpy(map) {
33
+ const { width, height } = map.info;
34
+ let header = `{'descr': '<f4', 'fortran_order': False, 'shape': (${height}, ${width}), }`;
35
+ // magic (6) + version (2) + header length (2) + header, padded with spaces to 64 bytes, ending in \n
36
+ const total = Math.ceil((10 + header.length + 1) / 64) * 64;
37
+ header = header.padEnd(total - 10 - 1, " ") + "\n";
38
+ const head = Buffer.alloc(10);
39
+ head.write("\x93NUMPY", 0, "latin1");
40
+ head[6] = 1;
41
+ head[7] = 0;
42
+ head.writeUInt16LE(header.length, 8);
43
+ const body = Buffer.alloc(width * height * 4);
44
+ for (let i = 0; i < map.metres.length; i++)
45
+ body.writeFloatLE(map.metres[i] ?? 0, i * 4);
46
+ return Buffer.concat([head, Buffer.from(header, "latin1"), body]);
47
+ }
48
+ /**
49
+ * An 8-bit grayscale PNG to look at: nearest is white, farthest dark grey,
50
+ * no hit black. The scale is inverse depth between the frame's min and max,
51
+ * so near detail keeps its contrast; read the numbers from the .npy.
52
+ */
53
+ export function depthToPreviewPng(map) {
54
+ const { width, height } = map.info;
55
+ let lo = Infinity;
56
+ let hi = 0;
57
+ for (const z of map.metres) {
58
+ if (z > 0) {
59
+ lo = Math.min(lo, z);
60
+ hi = Math.max(hi, z);
61
+ }
62
+ }
63
+ const span = lo < hi ? 1 / lo - 1 / hi : 0;
64
+ const raw = Buffer.alloc((width + 1) * height);
65
+ for (let y = 0; y < height; y++) {
66
+ raw[y * (width + 1)] = 0; // filter: none
67
+ for (let x = 0; x < width; x++) {
68
+ const z = map.metres[y * width + x] ?? 0;
69
+ const t = !(z > 0) ? -1 : span > 0 ? (1 / z - 1 / hi) / span : 1;
70
+ raw[y * (width + 1) + 1 + x] = t < 0 ? 0 : Math.round(40 + 215 * t);
71
+ }
72
+ }
73
+ const ihdr = Buffer.alloc(13);
74
+ ihdr.writeUInt32BE(width, 0);
75
+ ihdr.writeUInt32BE(height, 4);
76
+ ihdr[8] = 8; // bit depth
77
+ ihdr[9] = 0; // grayscale
78
+ return Buffer.concat([
79
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
80
+ pngChunk("IHDR", ihdr),
81
+ pngChunk("IDAT", zlib.deflateSync(raw)),
82
+ pngChunk("IEND", Buffer.alloc(0)),
83
+ ]);
84
+ }
85
+ const CRC_TABLE = (() => {
86
+ const t = new Uint32Array(256);
87
+ for (let n = 0; n < 256; n++) {
88
+ let c = n;
89
+ for (let k = 0; k < 8; k++)
90
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
91
+ t[n] = c >>> 0;
92
+ }
93
+ return t;
94
+ })();
95
+ function crc32(buf) {
96
+ let c = 0xffffffff;
97
+ for (const b of buf)
98
+ c = (CRC_TABLE[(c ^ b) & 0xff] ?? 0) ^ (c >>> 8);
99
+ return (c ^ 0xffffffff) >>> 0;
100
+ }
101
+ function pngChunk(type, data) {
102
+ const len = Buffer.alloc(4);
103
+ len.writeUInt32BE(data.length, 0);
104
+ const typed = Buffer.concat([Buffer.from(type, "latin1"), data]);
105
+ const crc = Buffer.alloc(4);
106
+ crc.writeUInt32BE(crc32(typed), 0);
107
+ return Buffer.concat([len, typed, crc]);
108
+ }
109
+ /** Paths beside an image file: shot.png -> shot.depth.npy / .depth.png / .depth.json. */
110
+ export function depthPaths(imagePath) {
111
+ const stem = imagePath.replace(/\.(png|jpe?g)$/i, "");
112
+ return { npy: `${stem}.depth.npy`, png: `${stem}.depth.png`, json: `${stem}.depth.json` };
113
+ }
114
+ /** One line for a terminal or an agent: range, coverage and where the camera was. */
115
+ export function describeDepth(info) {
116
+ const cover = Math.round((100 * info.hits) / (info.width * info.height));
117
+ const at = info.camera.pos.map((v) => v.toFixed(1)).join(",");
118
+ return `depth ${info.width}x${info.height}, ${info.min.toFixed(2)}-${info.max.toFixed(2)} m (planar), ${cover}% of pixels hit, camera at ${at}`;
119
+ }
package/dist/files.js CHANGED
@@ -10,6 +10,7 @@ import { pipeline } from "node:stream/promises";
10
10
  import { authorizedFetch, resolveSession, sessionBaseUrl } from "./api.js";
11
11
  import { DOWNLOAD_TEMP_MARKER } from "./ignore.js";
12
12
  import { getEngineRestarts } from "./world-status.js";
13
+ import { decodeDepth } from "./depth.js";
13
14
  /**
14
15
  * The session API's per-write cap (session-agent server/api/files.py
15
16
  * MAX_WRITE_BYTES). A bigger PUT is answered 413, so sync skips such files
@@ -499,26 +500,28 @@ export class FilesClient {
499
500
  }
500
501
  }
501
502
  async screenshot(opts = {}) {
502
- const body = {};
503
- if (opts.target) {
504
- body.target_object_id = opts.target;
505
- if (opts.distance !== undefined)
506
- body.distance = opts.distance;
503
+ const res = await this.requestScreenshot(screenshotBody(opts));
504
+ return Buffer.from(await res.arrayBuffer());
505
+ }
506
+ async screenshotDepth(opts = {}) {
507
+ if (opts.clientId !== undefined) {
508
+ throw new Error("Depth is read from the server's own view; it does not combine with a client capture.");
507
509
  }
508
- else if (opts.at || opts.rot) {
509
- const [px, py, pz] = opts.at ?? [0, 20, 20];
510
- const [rx, ry, rz] = opts.rot ?? [0, -45, 0];
511
- Object.assign(body, {
512
- camera_pos_x: px,
513
- camera_pos_y: py,
514
- camera_pos_z: pz,
515
- camera_rot_x: rx,
516
- camera_rot_y: ry,
517
- camera_rot_z: rz,
518
- });
510
+ const res = await this.requestScreenshot({ ...screenshotBody(opts), depth: true });
511
+ if (!(res.headers.get("Content-Type") ?? "").includes("json")) {
512
+ // A session agent older than depth support ignores the flag and answers a bare image.
513
+ throw new Error("This world's session predates depth capture and answered a plain picture. Restart the world from its editor page so it gets a current session, then try again.");
519
514
  }
520
- if (opts.clientId !== undefined)
521
- body.client_id = opts.clientId;
515
+ const body = (await res.json());
516
+ if (!body.image?.data)
517
+ throw new Error("The screenshot answer has no image.");
518
+ return {
519
+ image: Buffer.from(body.image.data, "base64"),
520
+ mediaType: body.image.media_type ?? "image/png",
521
+ depth: decodeDepth(body.depth),
522
+ };
523
+ }
524
+ async requestScreenshot(body) {
522
525
  const res = await this.send("/engine/screenshot", {
523
526
  method: "POST",
524
527
  headers: { "Content-Type": "application/json" },
@@ -526,8 +529,31 @@ export class FilesClient {
526
529
  }, "safe");
527
530
  if (!res.ok)
528
531
  throw new Error(await engineErrorMessage(res, "Screenshot"));
529
- return Buffer.from(await res.arrayBuffer());
532
+ return res;
533
+ }
534
+ }
535
+ function screenshotBody(opts) {
536
+ const body = {};
537
+ if (opts.target) {
538
+ body.target_object_id = opts.target;
539
+ if (opts.distance !== undefined)
540
+ body.distance = opts.distance;
541
+ }
542
+ else if (opts.at || opts.rot) {
543
+ const [px, py, pz] = opts.at ?? [0, 20, 20];
544
+ const [rx, ry, rz] = opts.rot ?? [0, -45, 0];
545
+ Object.assign(body, {
546
+ camera_pos_x: px,
547
+ camera_pos_y: py,
548
+ camera_pos_z: pz,
549
+ camera_rot_x: rx,
550
+ camera_rot_y: ry,
551
+ camera_rot_z: rz,
552
+ });
530
553
  }
554
+ if (opts.clientId !== undefined)
555
+ body.client_id = opts.clientId;
556
+ return body;
531
557
  }
532
558
  /**
533
559
  * A client for the editor session of `framingId` that follows the session
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ import { openInBrowser } from "./browser.js";
10
10
  import { detectPlatform, ensureClientInstalled, launchClient, seedNativeAuth } from "./client.js";
11
11
  import { apiBase, packageVersion } from "./config.js";
12
12
  import { ENGINE_TIMEOUT_EXIT_CODE, EngineTimeoutError, editSessionClient } from "./files.js";
13
+ import { depthPaths, depthToNpy, depthToPreviewPng, describeDepth } from "./depth.js";
13
14
  import { acquireFolderLock } from "./lock.js";
14
15
  import { runMcpServer } from "./mcp.js";
15
16
  import { defaultErrorsStateFile, runAtomo } from "./atomo.js";
@@ -620,7 +621,7 @@ function triple(value, flag) {
620
621
  }
621
622
  program
622
623
  .command("screenshot")
623
- .description("Capture a PNG of the world - a default overview, or aimed with --at/--rot or --target")
624
+ .description("Capture a PNG of the world - a default overview, or aimed with --at/--rot or --target. --depth also saves the frame's depth in metres")
624
625
  .argument("[dir]", "a synced folder", ".")
625
626
  .option("-o, --out <file>", "output file", "screenshot.png")
626
627
  .option("--at <x,y,z>", "camera position (default: 0,20,20)")
@@ -628,17 +629,32 @@ program
628
629
  .option("--target <id-or-name>", "frame this object instead of using a camera pose")
629
630
  .option("--distance <meters>", "framing distance for --target (default: from the object's bounds)")
630
631
  .option("--client <id>", "capture through this connected client, UI included; with no --at/--rot/--target it is exactly what that client sees")
632
+ .option("--depth", "also read the frame's depth buffer: <out>.depth.npy (float32 metres along the view axis, height x width, 0 = sky), <out>.depth.png (preview, near is white) and <out>.depth.json (camera and range). Not with --client")
631
633
  .action((dir, opts) => run(async () => {
632
634
  const { client } = await clientForDir(path.resolve(dir));
633
- const png = await client.screenshot({
635
+ const aim = {
634
636
  at: opts.at ? triple(opts.at, "--at") : undefined,
635
637
  rot: opts.rot ? triple(opts.rot, "--rot") : undefined,
636
638
  target: opts.target,
637
639
  distance: opts.distance === undefined ? undefined : Number(opts.distance),
638
640
  clientId: opts.client === undefined ? undefined : clientIdFlag(opts.client),
639
- });
640
- fs.writeFileSync(opts.out, png);
641
- console.log(`Wrote ${opts.out} (${png.length} bytes).`);
641
+ };
642
+ if (!opts.depth) {
643
+ const png = await client.screenshot(aim);
644
+ fs.writeFileSync(opts.out, png);
645
+ console.log(`Wrote ${opts.out} (${png.length} bytes).`);
646
+ return;
647
+ }
648
+ if (aim.clientId !== undefined)
649
+ fail("--depth reads the server's own view; drop --client.");
650
+ const shot = await client.screenshotDepth(aim);
651
+ const files = depthPaths(opts.out);
652
+ fs.writeFileSync(opts.out, shot.image);
653
+ fs.writeFileSync(files.npy, depthToNpy(shot.depth));
654
+ fs.writeFileSync(files.png, depthToPreviewPng(shot.depth));
655
+ fs.writeFileSync(files.json, JSON.stringify(shot.depth.info, null, 2) + "\n");
656
+ console.log(`Wrote ${opts.out} (${shot.image.length} bytes), ${files.npy}, ${files.png} and ${files.json}.`);
657
+ console.log(describeDepth(shot.depth.info));
642
658
  }));
643
659
  /** Install the native client if needed, sign it in, and launch it into a world. */
644
660
  async function openNative(framingId, url, force = false) {
package/dist/mcp.js CHANGED
@@ -11,6 +11,9 @@ import { eventSchema } from "./log-events.js";
11
11
  * and `select_project` work in that state, and every world-bound tool says
12
12
  * how to pick one.
13
13
  */
14
+ import fs from "node:fs";
15
+ import os from "node:os";
16
+ import path from "node:path";
14
17
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
15
18
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
16
19
  import { z } from "zod";
@@ -18,6 +21,7 @@ import { createProject, createWebsiteBuild, getWebsiteBuild, getEmbed, defaultRe
18
21
  import { attachAsset, findAsset, getJob, assetForJob, listAssets, listProjectAssets, placeInWorld, voxelizeSource, } from "./assets.js";
19
22
  import { ensureClientInstalled, launchClient, seedNativeAuth } from "./client.js";
20
23
  import { packageVersion } from "./config.js";
24
+ import { depthToNpy, depthToPreviewPng, describeDepth } from "./depth.js";
21
25
  import { ConflictError, editSessionClient } from "./files.js";
22
26
  import { acquireFolderLock } from "./lock.js";
23
27
  import { pullCommand } from "./pull.js";
@@ -499,18 +503,36 @@ export async function runMcpServer(dir, framingFlag) {
499
503
  .positive()
500
504
  .optional()
501
505
  .describe("Capture through this connected client, UI (HUD, menus) included - a server capture never shows UI. With no target/at/rot it is exactly what that client sees."),
506
+ depth: z
507
+ .boolean()
508
+ .optional()
509
+ .describe("Also read the frame's depth buffer (server view only, not with client_id). Returns a depth preview image (near is white, sky black) and its range, and saves the metres as a float32 .npy (height x width, distance along the view axis, 0 = sky) whose path is in the answer. One capture, no raycasts."),
502
510
  },
503
- }, async ({ target, at, rot, client_id }) => {
511
+ }, async ({ target, at, rot, client_id, depth }) => {
504
512
  const client = await ctx.getClient();
505
- const png = await client.screenshot({
513
+ const aim = {
506
514
  target,
507
515
  at: at,
508
516
  rot: rot,
509
517
  clientId: client_id,
510
- });
518
+ };
519
+ if (!depth) {
520
+ const png = await client.screenshot(aim);
521
+ return {
522
+ content: [{ type: "image", data: png.toString("base64"), mimeType: "image/png" }],
523
+ };
524
+ }
525
+ const shot = await client.screenshotDepth(aim);
526
+ const npy = path.join(os.tmpdir(), `virtualmatter-depth-${Date.now()}.npy`);
527
+ fs.writeFileSync(npy, depthToNpy(shot.depth));
511
528
  return {
512
529
  content: [
513
- { type: "image", data: png.toString("base64"), mimeType: "image/png" },
530
+ { type: "image", data: shot.image.toString("base64"), mimeType: shot.mediaType },
531
+ { type: "image", data: depthToPreviewPng(shot.depth).toString("base64"), mimeType: "image/png" },
532
+ {
533
+ type: "text",
534
+ text: JSON.stringify({ summary: describeDepth(shot.depth.info), npy, ...shot.depth.info }),
535
+ },
514
536
  ],
515
537
  };
516
538
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "virtualmatter",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "CLI + MCP server for building with Virtual Matter - list and create worlds, sync their files, run Lua, capture screenshots, open the native client, and wire coding agents into a live session.",
5
5
  "license": "MIT",
6
6
  "type": "module",