virtualmatter 0.7.0 → 0.10.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 +17 -2
- package/dist/admin.js +167 -0
- package/dist/agentfiles.js +1 -1
- package/dist/agents-md.generated.js +1 -1
- package/dist/asset-commands.js +8 -0
- package/dist/assets.js +75 -1
- package/dist/depth.js +119 -0
- package/dist/files.js +45 -19
- package/dist/index.js +35 -9
- package/dist/mcp.js +70 -5
- package/dist/server-lifecycle.js +410 -0
- package/package.json +1 -1
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
|
|
|
@@ -105,6 +106,7 @@ npx virtualmatter screenshot --client 4 -o ui.png # what client 4 sees,
|
|
|
105
106
|
```bash
|
|
106
107
|
npx virtualmatter voxelize tower.glb --vpm 32 --place 0,0,0 # one model into the world
|
|
107
108
|
npx virtualmatter voxelize tiles/ --vpm 2 --place -1000,0,-1000 # a folder of map tiles
|
|
109
|
+
npx virtualmatter voxelize scan.zip --vpm 128 --place 0,0,0 # a zip of slice images (CT, MRI) as one volume
|
|
108
110
|
npx virtualmatter assets # your asset library
|
|
109
111
|
npx virtualmatter place "tower" --at 20,0,5 --yaw 90 # place a library asset again
|
|
110
112
|
npx virtualmatter jobs <job id> --wait # follow a --no-wait job
|
|
@@ -121,6 +123,17 @@ metre (a power of two; 2-4 for buildings and terrain, 32-128 for props),
|
|
|
121
123
|
`--method RayCast` suits open meshes such as terrain, and `--rotate -90,0,0`
|
|
122
124
|
stands a Z-up model upright.
|
|
123
125
|
|
|
126
|
+
A zip that holds only images, or a `stack.json`, is voxelized as an image
|
|
127
|
+
stack: the slices in name order become one solid volume, one pixel per voxel,
|
|
128
|
+
solid where the pixel is brighter than `--threshold` (default 0.5). `stack.json`
|
|
129
|
+
at the zip's root splits it into layers, each a folder of slices with its own
|
|
130
|
+
threshold and either one colour or a folder of colour slices:
|
|
131
|
+
`{"layers": [{"images": "bone", "threshold": 0.5, "color": [244, 235, 221]},
|
|
132
|
+
{"images": "muscle", "colorImages": "muscle_rgb"}], "size": [512, 512, 400]}`.
|
|
133
|
+
`size` resamples the stack (for slices spaced wider than their pixels), and
|
|
134
|
+
`transformation` (three rows) reorients it. Voxelize one zip per part you want
|
|
135
|
+
to show and hide on its own, and place them at the same position.
|
|
136
|
+
|
|
124
137
|
## If you are a coding agent, read this part
|
|
125
138
|
|
|
126
139
|
Build through these commands, always. Do not open virtualmatter.ai or
|
|
@@ -162,7 +175,7 @@ It works before a world is selected: `list_projects`, `create_project`, and
|
|
|
162
175
|
`select_project` (any link or id, optionally mirroring into a folder) pick
|
|
163
176
|
one, then `list_files`, `read_file`, `write_file`, `run_lua`,
|
|
164
177
|
`get_engine_errors`, `capture_screenshot`, `open_native_client`, and
|
|
165
|
-
`world_info` act on it. `voxelize_model`, `get_voxelize_job`, `list_assets`
|
|
178
|
+
`world_info` act on it. `restart_server`, `stop_server`, `start_server` and `server_status` control and read the editor server (same behaviour and exit codes as the commands; `server_status` never starts a stopped server). For platform admins, `admin_list_worlds` and `admin_get` read across every account (read-only). `voxelize_model`, `get_voxelize_job`, `list_assets`
|
|
166
179
|
and `place_asset` bring 3D files from disk into the world as voxel assets. `patch_file` edits a world file by replacing one
|
|
167
180
|
exact snippet, and `push_local_files` / `fetch_files` move files between the
|
|
168
181
|
world and the synced folder the server runs in, so big scripts never travel
|
|
@@ -187,7 +200,9 @@ deploying it.
|
|
|
187
200
|
| `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
201
|
| `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
202
|
| `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. |
|
|
203
|
+
| `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). |
|
|
204
|
+
| `restart\|stop\|start [target]` | The world's editor server, by a synced folder or any world link. `restart` is the web editor's Restart button: a clean engine process, which is what returns memory. It lets the engine save first (`--force` skips that for a stuck engine), then waits until the engine answers Lua and prints the seconds taken and `Server:GetMemoryUsage()` (`--no-wait`, `--timeout <s>`, default 900). `stop` leaves it stopped until someone opens the world or runs `start`. `start --reset-terrain` recovers a world stopped for running out of memory by swapping its terrain for an empty grid. Asks before disconnecting connected clients (`--yes` to skip; refused when not on a terminal). Never touches play servers. Owner only. Exit 0 done, 1 failed, 2 nothing done, 3 sent but outcome unknown. `--json` for a result object. |
|
|
205
|
+
| `admin worlds\|users\|get <path>` | Platform admins only, read-only. `admin worlds [--search] [--owner]` lists every account's worlds with owner and edit/play links; `admin users [--search]` lists accounts; `admin get <path> [--query key=value]` prints any admin API read as JSON (`framings`, `sessions`, `hosts`). All take `--json` where a table is the default. A maker account gets a clear "not an admin" error. |
|
|
191
206
|
| `mcp [dir] [--framing <id>]` | Run the stdio MCP server. |
|
|
192
207
|
| `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
208
|
|
package/dist/admin.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { authorizedFetch, editUrl, playUrl } from "./api.js";
|
|
2
|
+
import { apiBase } from "./config.js";
|
|
3
|
+
const ADMIN_PREFIX = "/api/v1/admin/";
|
|
4
|
+
export class NotAdminError extends Error {
|
|
5
|
+
constructor(status) {
|
|
6
|
+
super(`This account is not a Virtual Matter admin (HTTP ${status}). Check who is signed in: npx virtualmatter whoami`);
|
|
7
|
+
this.name = "NotAdminError";
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The admin API URL for `path`: "framings", "/framings" and
|
|
12
|
+
* "/api/v1/admin/framings" all name the same list. Anything that would leave
|
|
13
|
+
* the admin API (another host, `..`, a different API root) is refused, so the
|
|
14
|
+
* signed-in token is only ever sent to the platform's admin reads.
|
|
15
|
+
*/
|
|
16
|
+
export function adminUrl(path, query = {}) {
|
|
17
|
+
const raw = path.trim();
|
|
18
|
+
if (!raw)
|
|
19
|
+
throw new Error("Give an admin API path, for example: framings");
|
|
20
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(raw) || raw.startsWith("//")) {
|
|
21
|
+
throw new Error("Give a path under the admin API, not a full URL.");
|
|
22
|
+
}
|
|
23
|
+
const q = raw.indexOf("?");
|
|
24
|
+
const pathPart = q < 0 ? raw : raw.slice(0, q);
|
|
25
|
+
const queryPart = q < 0 ? "" : raw.slice(q + 1);
|
|
26
|
+
let rel = pathPart.replace(/^\/+/, "");
|
|
27
|
+
if (rel.startsWith(ADMIN_PREFIX.slice(1)))
|
|
28
|
+
rel = rel.slice(ADMIN_PREFIX.length - 1);
|
|
29
|
+
const segments = rel.split("/").filter((s) => s.length > 0);
|
|
30
|
+
if (segments.length === 0)
|
|
31
|
+
throw new Error("Give an admin API path, for example: framings");
|
|
32
|
+
let decoded;
|
|
33
|
+
try {
|
|
34
|
+
decoded = segments.map((s) => decodeURIComponent(s));
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new Error(`Not a valid admin API path: ${path}`);
|
|
38
|
+
}
|
|
39
|
+
if (decoded.some((s) => s === "." || s === ".." || /[\\/]/.test(s))) {
|
|
40
|
+
throw new Error(`Not a valid admin API path: ${path}`);
|
|
41
|
+
}
|
|
42
|
+
const url = new URL(`${apiBase()}${ADMIN_PREFIX}${decoded.map(encodeURIComponent).join("/")}`);
|
|
43
|
+
for (const [k, v] of new URLSearchParams(queryPart))
|
|
44
|
+
url.searchParams.append(k, v);
|
|
45
|
+
for (const [k, v] of Object.entries(query))
|
|
46
|
+
url.searchParams.set(k, v);
|
|
47
|
+
return url.toString();
|
|
48
|
+
}
|
|
49
|
+
/** GET one admin API path and return its JSON. */
|
|
50
|
+
export async function adminGet(path, query = {}, fetchFn = fetch) {
|
|
51
|
+
const url = adminUrl(path, query);
|
|
52
|
+
const res = await authorizedFetch(url, {}, fetchFn);
|
|
53
|
+
if (res.status === 401 || res.status === 403)
|
|
54
|
+
throw new NotAdminError(res.status);
|
|
55
|
+
if (res.status === 404)
|
|
56
|
+
throw new Error(`No admin API read at ${new URL(url).pathname}.`);
|
|
57
|
+
if (!res.ok)
|
|
58
|
+
throw new Error(`GET ${new URL(url).pathname} failed: HTTP ${res.status}`);
|
|
59
|
+
return res.json();
|
|
60
|
+
}
|
|
61
|
+
export function worldSummary(row) {
|
|
62
|
+
const make = row.framings?.find((f) => f.kind === "make") ?? null;
|
|
63
|
+
const play = row.framings?.find((f) => f.kind === "play") ?? null;
|
|
64
|
+
return {
|
|
65
|
+
name: row.name,
|
|
66
|
+
id: row.id,
|
|
67
|
+
owner_handle: row.owner_handle,
|
|
68
|
+
owner_email: row.owner_email,
|
|
69
|
+
region: row.region,
|
|
70
|
+
tier: row.tier,
|
|
71
|
+
visibility: row.visibility,
|
|
72
|
+
framing_id: make?.id ?? null,
|
|
73
|
+
edit_url: make ? editUrl(make.id, row.url_slug) : null,
|
|
74
|
+
play_framing_id: play?.id ?? null,
|
|
75
|
+
play_url: play ? playUrl(play.id) : null,
|
|
76
|
+
updated_at: row.updated_at,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** Case-insensitive "contains" over the listed fields; no needle keeps every row. */
|
|
80
|
+
export function matchRows(rows, needle, fields) {
|
|
81
|
+
const n = needle?.trim().toLowerCase();
|
|
82
|
+
if (!n)
|
|
83
|
+
return rows;
|
|
84
|
+
return rows.filter((row) => fields(row).some((v) => typeof v === "string" && v.toLowerCase().includes(n)));
|
|
85
|
+
}
|
|
86
|
+
/** Every account's worlds, newest first, with their edit and play links. */
|
|
87
|
+
export async function listAdminWorlds(filter = {}, fetchFn = fetch) {
|
|
88
|
+
let rows = (await adminGet("montages", {}, fetchFn));
|
|
89
|
+
rows = matchRows(rows, filter.search, (r) => [
|
|
90
|
+
r.name,
|
|
91
|
+
r.url_slug,
|
|
92
|
+
r.id,
|
|
93
|
+
r.public_id,
|
|
94
|
+
...(r.framings ?? []).map((f) => f.id),
|
|
95
|
+
]);
|
|
96
|
+
rows = matchRows(rows, filter.owner, (r) => [r.owner_handle, r.owner_email]);
|
|
97
|
+
return rows.map(worldSummary);
|
|
98
|
+
}
|
|
99
|
+
export async function listAdminUsers(search, fetchFn = fetch) {
|
|
100
|
+
const rows = (await adminGet("users", {}, fetchFn));
|
|
101
|
+
return matchRows(rows, search, (u) => [u.handle, u.username, u.email, u.first_name, u.last_name, u.id]);
|
|
102
|
+
}
|
|
103
|
+
function table(header, rows) {
|
|
104
|
+
const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)));
|
|
105
|
+
const line = (cells) => cells.map((c, i) => c.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
|
|
106
|
+
return [line(header), ...rows.map(line)].join("\n");
|
|
107
|
+
}
|
|
108
|
+
export function formatWorlds(worlds) {
|
|
109
|
+
return table(["NAME", "OWNER", "REGION", "EDIT"], worlds.map((w) => [w.name, w.owner_handle, w.region, w.edit_url ?? "-"]));
|
|
110
|
+
}
|
|
111
|
+
export function formatUsers(users) {
|
|
112
|
+
return table(["HANDLE", "EMAIL", "WORLDS", "CREDITS", "LAST SEEN"], users.map((u) => [
|
|
113
|
+
u.handle,
|
|
114
|
+
u.email,
|
|
115
|
+
String(u.project_count),
|
|
116
|
+
String(u.credits_balance),
|
|
117
|
+
String(u.last_seen_at).slice(0, 10),
|
|
118
|
+
]));
|
|
119
|
+
}
|
|
120
|
+
function parseQuery(pairs) {
|
|
121
|
+
const out = {};
|
|
122
|
+
for (const pair of pairs) {
|
|
123
|
+
const eq = pair.indexOf("=");
|
|
124
|
+
if (eq <= 0)
|
|
125
|
+
throw new Error(`--query takes key=value (got ${JSON.stringify(pair)})`);
|
|
126
|
+
out[pair.slice(0, eq)] = pair.slice(eq + 1);
|
|
127
|
+
}
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
export function registerAdminCommands(program, run) {
|
|
131
|
+
const admin = program
|
|
132
|
+
.command("admin")
|
|
133
|
+
.description("Read across every account's worlds (platform admins only; read-only)");
|
|
134
|
+
admin
|
|
135
|
+
.command("worlds")
|
|
136
|
+
.alias("projects")
|
|
137
|
+
.description("Every account's worlds with their owner and edit/play links")
|
|
138
|
+
.option("--search <text>", "only worlds whose name, slug or an id contains this")
|
|
139
|
+
.option("--owner <text>", "only worlds whose owner's handle or email contains this")
|
|
140
|
+
.option("--json", "machine-readable output")
|
|
141
|
+
.action((opts) => run(async () => {
|
|
142
|
+
const worlds = await listAdminWorlds({ search: opts.search, owner: opts.owner });
|
|
143
|
+
if (opts.json)
|
|
144
|
+
console.log(JSON.stringify(worlds, null, 2));
|
|
145
|
+
else
|
|
146
|
+
console.log(worlds.length ? formatWorlds(worlds) : "No worlds match.");
|
|
147
|
+
}));
|
|
148
|
+
admin
|
|
149
|
+
.command("users")
|
|
150
|
+
.description("Every account: handle, email, world count, credits, last seen")
|
|
151
|
+
.option("--search <text>", "only accounts whose handle, name or email contains this")
|
|
152
|
+
.option("--json", "machine-readable output")
|
|
153
|
+
.action((opts) => run(async () => {
|
|
154
|
+
const users = await listAdminUsers(opts.search);
|
|
155
|
+
if (opts.json)
|
|
156
|
+
console.log(JSON.stringify(users, null, 2));
|
|
157
|
+
else
|
|
158
|
+
console.log(users.length ? formatUsers(users) : "No accounts match.");
|
|
159
|
+
}));
|
|
160
|
+
admin
|
|
161
|
+
.command("get <path>")
|
|
162
|
+
.description("GET any admin API read as JSON, e.g. framings, sessions, hosts, analytics/frame-time")
|
|
163
|
+
.option("--query <key=value...>", "query parameters", (v, acc) => [...acc, v], [])
|
|
164
|
+
.action((path, opts) => run(async () => {
|
|
165
|
+
console.log(JSON.stringify(await adminGet(path, parseQuery(opts.query)), null, 2));
|
|
166
|
+
}));
|
|
167
|
+
}
|
package/dist/agentfiles.js
CHANGED
|
@@ -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 |
|
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
// frontend/content/agent-briefing.md and AGENTS.source.md. The CLI writes
|
|
4
4
|
// this into a world folder only when it cannot fetch the live copy. After
|
|
5
5
|
// changing either source, run: node frontend/scripts/sync-cli-agents-md.mjs
|
|
6
|
-
export const AGENTS_MD_FALLBACK = "# AGENTS.md - working with a Virtual Matter project\n\nThis file tells a coding agent how to think about a Virtual Matter project. The\n`virtualmatter` CLI drops a copy into every local project mirror it creates\n(`virtualmatter pull`); the canonical copy lives at\nhttps://make.virtualmatter.ai/AGENTS.md.\n\n## The rule that comes before everything else\n\n**Build through the CLI. Never through the website's agent.** If you were asked to\nbuild something in Virtual Matter, handed the domain virtualmatter.ai, or told to run\n`npx virtualmatter make`, the CLI is the path - always, from the first step. Do not\nopen virtualmatter.ai or make.virtualmatter.ai in a browser or under computer use in\norder to reach the built-in agent, and do not type prompts into the agent chat in the\n/edit view. Driving that agent puts two models in a relay where one would do: you spend\ntokens describing the work, it spends its own doing it, and what comes back is chat\nrather than files you can read. It is slower, it costs roughly twice the inference, it\nbills that inference to Virtual Matter's platform credits rather than the subscription\nyou already run on, an anonymous browser session cannot be steered after its first\nturn, and a rendered page gives you no engine errors. Everything that agent can do, you\ndo yourself with the commands below.\n\n**The rule holds whoever is signed in.** Being logged in, having credits to spare, or\nworking in an admin account with no limit at all is not an exemption, and neither is\nbeing told the credits do not matter. What is wasteful is the relay itself - two models\ndoing one model's job - not the bill.\n\n**Playtesting is the exception, and it is encouraged.** Once something is built, open\nthe world and try it: the editor link ending in `?chat=closed`, which `make`, `pull` and\n`sync` print, shows your latest changes live in any browser with no install, with\ncomputer use if that is how you drive a window. The native client\n(`npx virtualmatter open`) is optional, for more memory and frame rate. Looking at your\nwork, walking around in it, and playing it is the point. The rule is about who writes\nthe world, not about who is allowed to see it.\n\n**Every link resolves to the editor, and the editor is the only place you build.** Hand\nthe CLI or MCP server any link to a world - its editor, a play or share link, the\nproject page, an embed's iframe src, or the maker's own website - and it works on that\nworld's editor (its make framing). Play servers show the last published version and are\noverwritten on every publish, so work never goes there, and their /play and /g links\nshow that published copy rather than your latest edits.\n\n## The mental model\n\n- The world itself runs on Virtual Matter servers, not on the maker's machine. There is\n one authoritative server simulation per world session, and any number of connected\n clients (browser WASM or the native client).\n- The project's content is SDK Lua scripts plus assets (voxel data, prefabs, images,\n sounds) under a `Montage/` tree. Virtual Matter can publish that tree to a GitHub repo\n in the maker's account for versioning and remixing; pushing to that repo does not feed\n back into the running world today - live edits happen in the session.\n- Changes hot-reload. Saving a `.lua` file in the live session's Montage tree re-runs\n the module and its `Start()` on a fresh instance inside the running world - no restart,\n no build step.\n- Prefabs are reusable scene-graph snippets: JSON files with a `.prefab` extension in the\n Montage folder, instantiated at runtime via `Server:InsertPrefab(asset)`.\n- There is no local runtime - the world cannot run on the maker's machine. The\n `virtualmatter` CLI (npm) is how you reach it from a local harness, and it needs no\n setup: the first command that needs an account signs you in with a device code.\n `npx virtualmatter make \"My world\"` makes a world and mirrors its Montage tree\n into `./my-world`; `npx virtualmatter pull <any Virtual Matter link>` mirrors an\n existing one (/edit, /play, /g, /p, /projects links all work, with or without a\n readable slug); `npx virtualmatter list` shows your worlds; `npx virtualmatter sync`\n live-pushes saves into the running session (which hot-reloads them), and\n `npx virtualmatter push <files>` deploys named files once, reporting each one - the\n better fit for an agent that saves in quick succession (each script write resets the\n world's Lua, and push skips files that did not change);\n `npx virtualmatter run-lua` / `errors` / `screenshot` drive the engine;\n `npx virtualmatter open` optionally opens the world in the native desktop client,\n downloaded and signed in on first use; and `npx virtualmatter mcp` serves\n all of it over MCP. A mirrored folder carries `.mcp.json` and `.cursor/mcp.json`\n (so Claude Code and Cursor register the MCP server on their own), this file, and a\n `CLAUDE.md` that imports it. Folders from virtualmatter 0.5.0 on also carry\n `.codex/config.toml`, which Codex loads once you trust the folder; with an older\n CLI, or if Codex does not list the server, register it once with\n `codex mcp add virtualmatter -- npx -y virtualmatter mcp`. In Claude Code outside a\n mirrored folder, use `claude mcp add virtualmatter -- npx -y virtualmatter mcp`. The\n server works before a world\n is selected (`list_projects`, `create_project`, `select_project`), then exposes\n `list_files`, `read_file`, `write_file`, `run_lua`, `get_engine_errors`,\n `capture_screenshot`, `open_native_client`, `world_info`, and the 3D-model tools\n `voxelize_model`, `get_voxelize_job`, `list_assets` and `place_asset`.\n- Work through the CLI, not the website - see the rule above. Prompting the built-in\n agent to do your building is the one thing to avoid; opening the world to play it is\n not.\n- Seeing your work: `virtualmatter screenshot` shoots a default overview of the world\n origin, `--target <object>` frames one object by name or id, and `--at x,y,z --rot\n yaw,pitch,roll` places the camera exactly. Y is up and -Z is forward, and the\n rotation really is yaw first: yaw 0 faces -Z, pitch -90 looks straight down, pitch 0\n is the horizon. The MCP `capture_screenshot`\n tool takes the same arguments. Verify a change with a screenshot plus `errors` rather\n than assuming a write worked.\n- A `run-lua` that fails with HTTP 504 (`run-lua timed out`, exit code 3 from CLI\n 0.6.4 on; the MCP `run_lua` tool returns the same text) reached the engine, which\n may still be running it. Do not send code that changes the world again: check its\n effect first, by reading back what it sets or taking a screenshot. Any other\n failure never reached the engine and is safe to retry.\n- The mirrored folder's AGENTS.md is this guide followed by the engine SDK's own agent guide\n (the AGENTS.md that lives in every Montage tree and inside the desktop client's\n Data/Sdk/Montage/). The engine guide assumes an in-session agent driving the engine\n through `atomo`; the merged file maps each `atomo` step to the CLI or MCP equivalent, and\n the `Skills/*.md` references it points at are in the folder. The SDK's own tooling\n (`atomo`, `vm_auth.py`, the agent-log hooks) is not mirrored: it only works inside a\n session. From CLI 0.6.5 on, macOS and Linux folders get their own `./atomo`, which\n serves the guide's `./atomo run-lua`, `run-lua-client` and `errors` through the CLI.\n Sandboxed agents need network access for every CLI command.\n- After saving a `.lua` file with `sync` running, check it with\n `./atomo errors --after-reload <file>` (CLI 0.6.8 on) instead of sleeping: it waits\n until the world has the save and has reloaded it, then lists the errors. `./atomo`\n exits like the engine's own: 1 when `run-lua` raised or `errors` shows an error no\n earlier check reported, 2 when nothing ran, 3 when the engine may still be running it.\n- 3D models go in through the voxelizer, never through Lua. From CLI 0.7.0 on,\n `npx virtualmatter voxelize <files or folders> --place x,y,z` uploads GLB, OBJ, FBX,\n STL, point clouds (PLY, LAS/LAZ, E57) or zips from disk (resumable, up to 10 GiB),\n voxelizes them on Virtual Matter's voxelizer into the maker's asset library, attaches\n them to the world and places them in the scene; the MCP `voxelize_model` tool does the\n same. `virtualmatter assets` lists the library and `place <asset> --at x,y,z` puts one\n in again. A model keeps its own coordinates in metres and `--place` moves its 0,0,0,\n so map or city tiles voxelized from one dataset line up when placed with the same\n offset (`voxelize tiles/ --vpm 2 --place -1000,0,-1000`). 2-4 voxels per metre suits\n buildings and terrain, 32-128 props. Never paste mesh, footprint or height-grid text\n into a script or rebuild a model out of Lua primitives: that costs credits and engine\n memory and comes out wrong.\n- Worlds with the platform's skill packages carry them in `Skills/atomontage-*`.\n From CLI 0.6.5 on, `pull` and `sync` also copy them into `.claude/skills/`, so Claude\n Code loads them as skills; other harnesses follow the routing table in AGENTS.md.\n Start from `atomontage-game-starters` for any of the 15 homepage starter games: its\n `starterctl.py build <preset>` builds a playable starter in seconds through\n `./atomo`. Where a skill says to hand a live check to the in-game agent, run it\n yourself: never send prompts to the world's built-in agent.\n\n## Reference\n\nThe same facts as terse lists, for quick lookup.\n\n### Project model\n- A project (\"montage\") is one voxel world hosted with Virtual Matter.\n- A project has framings: \"make\" framings (editing sessions) and \"play\"\n framings (public play sessions). A framing is a running session slot\n on a voxel host.\n- Project content = SDK Lua scripts + assets under a Montage/ tree.\n Edits made in the live session hot-reload into the running world.\n The tree can be published to a maker-owned GitHub repo.\n\n### URL shapes (make.virtualmatter.ai)\n- /new builder for people: create a world from a prompt\n (also at https://virtualmatter.ai/); coding agents\n use npx virtualmatter make instead\n- /edit/<framing-id> maker session: live world + agent chat. The chat is\n for people; a coding agent builds with the CLI and\n never prompts it\n (also /edit/<slug>-<framing-id>; the CLI accepts both)\n- /play/<framing-id> play session for a specific framing\n- /g/<id> share URL resolver: 302s to a live session\n\n### APIs (unauthenticated)\n- GET https://make.virtualmatter.ai/api/v1/public/native-clients\n JSON: { iteration, clients: [{ platform, kind, variant, url, filename,\n file_size, branch, commit, match }] } - per-platform native client\n installers (kind \"download\") or store links (kind \"store\", iOS).\n Windows and Linux list two downloads each: variant \"installer\" /\n \"flatpak\" for people, and \"portable\" / \"tarball\", the file tree the\n CLI installs.\n\n### CLI + MCP (npm package \"virtualmatter\", Node >= 20)\n- npx virtualmatter make \"<name>\" make a world, mirror it into ./<slug>\n- npx virtualmatter pull <link> mirror an existing world (any link shape)\n- npx virtualmatter list your worlds with framing ids + URLs\n- npx virtualmatter sync live-push saves into the running world\n (one per folder; does not pull files too\n large to push back, such as terrain)\n- npx virtualmatter push [files] one-shot deploy, per-file result; exit 1\n on any conflict or failure\n- npx virtualmatter fetch [files] one-shot download; never overwrites\n local edits (conflict -> .remote-conflict)\n- npx virtualmatter logs --restarts why the world restarted (crash + last\n log lines, or the platform's reason)\n- npx virtualmatter publish update the play servers; reports each\n server, says which scene they load\n- npx virtualmatter status engine iteration, play servers vs the\n editor, last update\n- npx virtualmatter voxelize <files|folders> [--vpm 4] [--place x,y,z]\n 3D models (glb obj fbx stl, point\n clouds, zip) into voxel assets: upload,\n voxelize, attach, place; real-world\n metres, tiles line up\n- npx virtualmatter assets your asset library (--project: one\n world's attached assets)\n- npx virtualmatter place <asset> --at x,y,z put a library asset in\n the world at real size\n- npx virtualmatter open optional: open it in the native client\n- npx virtualmatter mcp stdio MCP server (list_projects,\n create_project, select_project, list_files, read_file, write_file,\n patch_file, push_local_files, fetch_files, run_lua, get_engine_errors,\n get_engine_logs, capture_screenshot, play_server_status,\n publish_play_servers, open_native_client, world_info, voxelize_model,\n get_voxelize_job, list_assets, place_asset)\n- Sign-in happens on first use (device code); no separate login step.\n- These commands are the whole build path. Never prompt the built-in\n agent on the site to do the work; a browser or the native client is\n for playtesting what you built.\n- Any link to a world (editor, play or share link, project page, embed,\n or the maker's own website) resolves to its editor, the only place\n the CLI and MCP server work. Play servers show the last published\n version and are overwritten on publish.\n- Watch changes land live at the editor link ending in ?chat=closed,\n in any browser, no install. The native client is optional.\n- A mirrored folder carries .mcp.json, .cursor/mcp.json, AGENTS.md and\n CLAUDE.md, so Claude Code and Cursor register the server on their own.\n- Codex: folders from 0.5.0 on carry .codex/config.toml, loaded once the\n folder is trusted; otherwise register the server once:\n codex mcp add virtualmatter -- npx -y virtualmatter mcp\n\n## SDK Lua cheat sheet\n\nThe scripting language is Lua 5.4, sandboxed: `os`, `io`, `require`, `package`,\n`dofile`, `loadfile`, `loadstring` are nil. `math`, `string`, `table`, `coroutine`\nremain. No `os.time` - use `Time.time` (sim time), `Time.frame`, or\n`AE:GetDebugTime()` (wall clock).\n\n### Script shape\n\nEvery persistent behavior is a `.lua` file in the Montage tree returning a `self` table:\n\n```lua\nlocal self = {}\nfunction self:Start() end\nfunction self:Update(deltaTime) end\nreturn self\n```\n\nAttach to an object with `obj:AddScript(script, sync)`; `sync = true` replicates the\nscript to clients. On iteration073 `script` is a path relative to the Montage root\n(`\"My Folder/Example.lua\"`); from iteration076 it must be the script's Asset (see\n\"Worlds on iteration076\" below). `obj:FindScript(\"Example\")` returns the live instance.\n\n### Server / client split\n\nThe same script runs on the server and (when synced) on every client. Branch with\n`self.onServer` / `self.onClient`:\n\n```lua\nfunction self:Update(dt)\n if self.onClient then return end -- voxel edits are server-only\n -- authoritative logic here\nend\n```\n\nNothing replicates automatically: set `syncToClients = true` on the script or\nVoxelData component, and use `util:makeNetworkedTable(self, { hp = 100 })` for\nproperties that should sync (server writes, clients read, deltas only).\n`obj.pos` / `obj.rot` do not auto-sync - replicate them yourself.\n\n### RPC\n\n```lua\nself:RPC(\"serverDoSomething\", pos, dir) -- on a client: goes to the server\nfunction self:serverDoSomething(pos, dir, clientID) -- clientID auto-appended\n assert(self.onServer)\nend\n```\n\nOn the server, `self:RPC(...)` fans out to all clients. Reliable, FIFO per direction.\nRequires `self.component.syncToClients = true`.\n\n### Scene and objects (server)\n\n```lua\nlocal ob = Scene:CreateObject(\"Name\")\nob.save = true\nob:AddScript(scriptAsset) -- a path string on 073, an Asset from 076\nScene:GetObjectByName(\"Name\")\nScene:CloneObject(ob) -- prefer over rebuilding\nob.active = false -- prefer over destroy; clients don't see it\nob:AddTag(\"Enemy\"); FindObjectsWithTag(\"Enemy\") -- tags are runtime-only state\n```\n\n### Voxel editing (server only, async)\n\n```lua\nVox:Add(Sphere(pos, 2)):Color(1, 0, 0):Run()\nVox:Add(Box(Vec3(0, -1, 0), Vec3(20, 2, 20))):ForceStatic():Run()\n```\n\nShapes: `Box(center, fullSize)`, `Sphere(center, r)`, `Capsule(p1, p2, r)`,\n`Cylinder(p1, p2, r1[, r2])`. `Run()` is async - chain `:OnFinished(fn)` before\n`:Run()` to read post-commit state. Big edits stall the frame for every client;\nkeep in-game edits small and infrequent.\n\n### Input (event-driven, client input reaches the server)\n\n```lua\nself.component.syncToClients = true\nevents.keyDown.addListener(self, function(key, from) self.keys[key] = true end)\nevents.keyUp.addListener(self, function(key, from) self.keys[key] = false end)\n```\n\nPlayer-driven movement must be client-predicted - never gate the player's own\nfeedback on the server round-trip.\n\n### Physics\n\n```lua\nlocal rb = obj:AddComponent(\"RigidBody\")\nrb:AddImpulse(Vec3(0, 50, 0), obj.pos)\nrb.velocity; rb.mass; rb.gravityScale\n```\n\n### Time and diagnostics\n\n```lua\nTime.dt; Time.time; Time.frame; Time.timeScale\nAE:GetLogValue(\"Raycasts\") -- engine counters, e.g. raycasts this frame\nAE:GetAssets() -- list all assets (APIs take Assets, not paths)\n```\n\n### UI (client-side HUD)\n\nBuild screen UI with the MUI builder: `UI:AddPanel|AddButton|AddLabel|AddSlider|...`\nchained with `:Set{...}`; flexbox-like row-wrap layout.\n\n### Engine behaviours that catch people out\n\nEach of these has broken a real game. An error inside a `util:schedule` chain or an\n`Update` stops that loop without anything else visible, so check `errors` after a\nchange even when the world looks fine.\n\n- Object names may hold only letters, digits and single spaces. `Scene:CreateObject`\n rejects `_`, `-`, `.` and leading or trailing spaces with \"Failed to create object.\n Given name was invalid.\"\n- `Cast:Ray` with a zero-length vector throws \"ray is zero length\". Guard every ray\n whose vector can be zero: coincident positions, a target standing on the shooter, a\n projectile at rest.\n- Client rays cannot read surfaces. `ForceStatic()` (on `Cast:Ray(...)` and\n `Collide(...)`), `WithNormal()`, `WithColor()` and `WithMaterial()` throw on a client\n (\"... only supported on server\"), and so does reading `hit.normal`, `hit.color` or\n `hit.material`; `hit.obj` is nil for every client hit. On a client, use a plain ray\n and skip dynamic objects with `Ignore`; read surfaces on the server and send what the\n client needs with the event (for example the impact material as an RPC argument). On\n the server, reading `hit.material` without `WithMaterial()` throws.\n- `Audio:PlaySound(asset, nil, ...)` throws, although the position is typed optional.\n Play a non-positional sound with `Audio:PlaySoundRelative(asset, Vec3(0,0,0), volume,\n false)`.\n- `obj.active = false` does not replicate. Clients keep the object active, frozen where\n it last streamed, with its client scripts running and any client-made meshes visible;\n an object created and deactivated in the same frame shows up at (0,0,0). To pool\n objects, also send a park position (a networked-table write in the same frame does\n arrive), move the object there on the client, and skip parked objects in client code.\n- A transform written in `LateUpdate` renders one frame behind the camera. Pose\n anything held against the camera (viewmodels, held items, camera-attached 3D) in\n `Update`, right after the camera moves.\n- Window z-order follows creation order and cannot be set: among `stayOnBottom`\n windows the earliest created draws on top, and toggling `visible` does not reorder\n them. Create windows in the order you want them stacked.\n- A `zNear` written right after `AddComponent(\"Camera\")` is reset to 0.1; write it\n again a frame later.\n- An RPC round trip (client -> server -> client) takes several times what\n `Client:GetPing()` reports (125-192 ms against 30 ms on a local connection), and\n networked tables reach clients at about 13-15 Hz. Measure the round trip your game\n sees with `AE:GetDebugTime()` before gating prediction on it.\n- The static edit guard's budget is per frame, not per op. About the 4th large op in\n one Lua call throws \"frame voxel budget exhausted\", leaving the earlier ops applied.\n Spread batches over frames and retry a refused op on the next frame, or a reset or\n map build leaves terrain half-edited.\n- Every static `Vox` op (Remove, Add, Paint) costs one 30-50 ms server frame whatever\n its size (55-85 ms in a test on iteration076, where `OpBase:Batch()` saved nothing\n on the server and delayed delivery). Prefer fewer, bigger ops and budget the rate:\n about 1 op/s keeps the p99 frame near 33 ms.\n- Static edits reach connected clients seconds to tens of seconds late, and a freshly\n joined client that is still streaming the map can wait 45 s or more. Gameplay must\n not depend on client terrain: hit checks, cover and validation belong on the server.\n- Client terrain rays are LOD-quantised in 0.125-0.25 m steps a few metres from the\n camera. Give client-side terrain checks a tolerance of 0.3 m or more, and use server\n rays for anything authoritative.\n- Setting `child.parent = obj` keeps the child's world transform. Set `localPos` and\n `localRot` after parenting, not before.\n- `Server:GetStreamingStats()` reports `STALLING` and `finalRatioPct = 0` for healthy\n clients too, so it cannot tell you a client has stopped receiving edits.\n- After a map-scale rebuild, the default `screenshot` (rendered by the server's own\n view) can show stale or missing terrain. Check with server rays or with\n `screenshot --client <id>` from a freshly connected client.\n\n### Worlds on iteration076\n\n`print(AE:GetVersion())` through `run-lua` tells you the engine build (76.x is\niteration076). A world moved from 073 keeps running code that 076 rejects, and the\n`pcall` guards games put around engine calls hide every one of these failures:\n\n- `receiveTransform` is a field of `Object` (`obj.receiveTransform = false`), not of\n `VoxelData`. On 076 `vd.receiveTransform` reads nil and writing it throws.\n- `Audio:PlaySound`, `Audio:PlaySoundRelative` and `Object:AddScript` take an Asset,\n not a path (\"expected a AudioFile Asset, got string\"). Resolve each path once and\n cache it: walk `AE:GetAssets()` and keep the asset for which\n `AE:AssetPathInMontage(asset) == path`. A client lists assets as they sync, so a\n lookup there can return nil for a while; retry instead of caching the nil.\n- There is no `Sky` component: `GetComponentByType(\"Sky\")` returns nil. On a client,\n hide the sky with `Client:SetSkyEnabled(false)`, aim the sun with\n `Client:SetSunDirection(azimuth, altitude)`, and turn off the god rays and lens flare\n (on by default) with `AE:SetLogValue(\"Dev/GodRays\", 0)` and\n `AE:SetLogValue(\"Dev/LensFlare\", 0)`. The SDK's `Sky` script turns the sky back on\n for each joining client; to keep it off, call that script's\n `queueSerializedRender(false)` on the server. A fog density above 0 turns VM Sky\n black.\n- Writing a field an engine object does not have throws, and `Widget:Set{...}` throws\n on an unknown key after applying the keys before it. While migrating, do not swallow\n these: keep the error from `pcall` and print it once\n (`local ok, err = pcall(f); if not ok then print(err) end`). Client `print` output\n does not reach the logs, so exercise client paths with\n `virtualmatter run-lua --target client` and return the error.\n- Edited copies of built-in shaders in `Shaders/` are kept as they are on every engine\n move (the boot log says \"maker edit - kept\"), even when the renderer's inputs have\n changed: the 076 `ssao2.fs` declares its own `FogFrame` block and no longer includes\n `common.glsl`. After a move, diff each kept copy against the new built-in, re-apply\n the edit, and check `Client:GetShaderErrors()` on a real client once it has drawn a\n frame. For a look change, prefer `Client:SetVPuzzleShaderDefines` (`#undef NAME` /\n `#define NAME value` lines, for example `CUSTOM_LIGHTING_MODE` or\n `CUSTOM_LIGHTING_MODE_LIGHTPOSTER`): it changes a client's shading without forking a\n shader, and recompiles every effect (about 100 ms) each time you call it.\n- The post-process chain runs in the live render on 076, whatever the engine's\n shaders skill says: depth of field, god rays, lens flare, tone mapping, outline,\n SSR and the SSAO composite (`ssao2.fs`). Switch them per client with\n `AE:SetLogValue`, for example `AE:SetLogValue(\"Dev/EnableDOF\", 1)` or\n `\"Dev/EnableToneMapping\"`. On 073 the chain is not wired and editing its shaders\n does nothing.\n\n### Generated sounds\n\n`Fal:requestTextToSound` returns takes that play quiet and thin: most of their energy\nsits below 20 Hz, with a DC offset and peaks around -25 dBFS. The engine's output\nalso removes most of what is below about 150 Hz and levels sounds by loudness, not\npeak. Before using a take, fetch the mp3 from `Sounds/Generated/`, clean it locally,\nand push it under a new name:\n\n```sh\nffmpeg -i take.mp3 -af \"highpass=f=40,loudnorm=I=-14:TP=-1\" -ac 1 -ar 44100 \"Clean Take.mp3\"\n```\n\nUse mono for one-shots, and match levels by loudness (LUFS), not by peak. A client\nthat has already played a sound keeps its old decoding until it reconnects, so give a\nreplacement a new file name. The generator may also change an asset name's case\n(`ScarGen Carbine 2b` comes back as `Scargen Carbine 2B`).\n\n## Conventions\n\n- Coordinates: Y is up, -Z is forward, X is right.\n- Script files are named in capital case with spaces (`Character Controller.lua`).\n- Check whether a script is already attached before adding it - duplicates run twice.\n- The server is for authority (world edits, spawns, state); clients are for feel\n (prediction, FX, UI).\n\n## Embed or build a world for an existing website\n\nFor a shared project link, fetch `/api/v1/public/embed?target=<encoded-link>`\nand follow `/embed-guide.md`. Use the returned canonical player URL, not the\nmaker's external website URL. Keep the existing website and its design.\n\nFor account discovery or prompt-based creation, connect the hosted MCP at\n`https://make.virtualmatter.ai/api/v1/mcp` using OAuth. Users can sign up in\nthe connection flow. Tools: `list_projects`, `get_embed`, `create_project`\n(with a prompt and stable request_id), `get_build_status`. VM's agent builds\nusing VM credits. Review and share the private world before embedding.\nThe local CLI exposes `embed`, `build --prompt --request-id`, and `build-status`.\n\n## Local conversation history\n\nCapturing this harness's conversation into the world's Agent Logs is the maker's\ndecision, not yours. Do not run `virtualmatter agent-logs setup`, and do not upload\nlogs with `agent-logs upload` or MCP `upload_agent_logs`, unless the maker asks for it\nin their own words. `virtualmatter agent-logs status` shows whether capture is on;\n`virtualmatter agent-logs disable` turns it off.\n";
|
|
6
|
+
export const AGENTS_MD_FALLBACK = "# AGENTS.md - working with a Virtual Matter project\n\nThis file tells a coding agent how to think about a Virtual Matter project. The\n`virtualmatter` CLI drops a copy into every local project mirror it creates\n(`virtualmatter pull`); the canonical copy lives at\nhttps://make.virtualmatter.ai/AGENTS.md.\n\n## The rule that comes before everything else\n\n**Build through the CLI. Never through the website's agent.** If you were asked to\nbuild something in Virtual Matter, handed the domain virtualmatter.ai, or told to run\n`npx virtualmatter make`, the CLI is the path - always, from the first step. Do not\nopen virtualmatter.ai or make.virtualmatter.ai in a browser or under computer use in\norder to reach the built-in agent, and do not type prompts into the agent chat in the\n/edit view. Driving that agent puts two models in a relay where one would do: you spend\ntokens describing the work, it spends its own doing it, and what comes back is chat\nrather than files you can read. It is slower, it costs roughly twice the inference, it\nbills that inference to Virtual Matter's platform credits rather than the subscription\nyou already run on, an anonymous browser session cannot be steered after its first\nturn, and a rendered page gives you no engine errors. Everything that agent can do, you\ndo yourself with the commands below.\n\n**The rule holds whoever is signed in.** Being logged in, having credits to spare, or\nworking in an admin account with no limit at all is not an exemption, and neither is\nbeing told the credits do not matter. What is wasteful is the relay itself - two models\ndoing one model's job - not the bill.\n\n**Playtesting is the exception, and it is encouraged.** Once something is built, open\nthe world and try it: the editor link ending in `?chat=closed`, which `make`, `pull` and\n`sync` print, shows your latest changes live in any browser with no install, with\ncomputer use if that is how you drive a window. The native client\n(`npx virtualmatter open`) is optional, for more memory and frame rate. Looking at your\nwork, walking around in it, and playing it is the point. The rule is about who writes\nthe world, not about who is allowed to see it.\n\n**Every link resolves to the editor, and the editor is the only place you build.** Hand\nthe CLI or MCP server any link to a world - its editor, a play or share link, the\nproject page, an embed's iframe src, or the maker's own website - and it works on that\nworld's editor (its make framing). Play servers show the last published version and are\noverwritten on every publish, so work never goes there, and their /play and /g links\nshow that published copy rather than your latest edits.\n\n## The mental model\n\n- The world itself runs on Virtual Matter servers, not on the maker's machine. There is\n one authoritative server simulation per world session, and any number of connected\n clients (browser WASM or the native client).\n- The project's content is SDK Lua scripts plus assets (voxel data, prefabs, images,\n sounds) under a `Montage/` tree. Virtual Matter can publish that tree to a GitHub repo\n in the maker's account for versioning and remixing; pushing to that repo does not feed\n back into the running world today - live edits happen in the session.\n- Changes hot-reload. Saving a `.lua` file in the live session's Montage tree re-runs\n the module and its `Start()` on a fresh instance inside the running world - no restart,\n no build step.\n- Prefabs are reusable scene-graph snippets: JSON files with a `.prefab` extension in the\n Montage folder, instantiated at runtime via `Server:InsertPrefab(asset)`.\n- There is no local runtime - the world cannot run on the maker's machine. The\n `virtualmatter` CLI (npm) is how you reach it from a local harness, and it needs no\n setup: the first command that needs an account signs you in with a device code.\n `npx virtualmatter make \"My world\"` makes a world and mirrors its Montage tree\n into `./my-world`; `npx virtualmatter pull <any Virtual Matter link>` mirrors an\n existing one (/edit, /play, /g, /p, /projects links all work, with or without a\n readable slug); `npx virtualmatter list` shows your worlds; `npx virtualmatter sync`\n live-pushes saves into the running session (which hot-reloads them), and\n `npx virtualmatter push <files>` deploys named files once, reporting each one - the\n better fit for an agent that saves in quick succession (each script write resets the\n world's Lua, and push skips files that did not change);\n `npx virtualmatter run-lua` / `errors` / `screenshot` drive the engine;\n `npx virtualmatter open` optionally opens the world in the native desktop client,\n downloaded and signed in on first use; and `npx virtualmatter mcp` serves\n all of it over MCP. A mirrored folder carries `.mcp.json` and `.cursor/mcp.json`\n (so Claude Code and Cursor register the MCP server on their own), this file, and a\n `CLAUDE.md` that imports it. Folders from virtualmatter 0.5.0 on also carry\n `.codex/config.toml`, which Codex loads once you trust the folder; with an older\n CLI, or if Codex does not list the server, register it once with\n `codex mcp add virtualmatter -- npx -y virtualmatter mcp`. In Claude Code outside a\n mirrored folder, use `claude mcp add virtualmatter -- npx -y virtualmatter mcp`. The\n server works before a world\n is selected (`list_projects`, `create_project`, `select_project`), then exposes\n `list_files`, `read_file`, `write_file`, `run_lua`, `get_engine_errors`,\n `capture_screenshot`, `open_native_client`, `world_info`, and the 3D-model tools\n `voxelize_model`, `get_voxelize_job`, `list_assets` and `place_asset`.\n- Work through the CLI, not the website - see the rule above. Prompting the built-in\n agent to do your building is the one thing to avoid; opening the world to play it is\n not.\n- Seeing your work: `virtualmatter screenshot` shoots a default overview of the world\n origin, `--target <object>` frames one object by name or id, and `--at x,y,z --rot\n yaw,pitch,roll` places the camera exactly. Y is up and -Z is forward, and the\n rotation really is yaw first: yaw 0 faces -Z, pitch -90 looks straight down, pitch 0\n is the horizon. The MCP `capture_screenshot`\n tool takes the same arguments. Verify a change with a screenshot plus `errors` rather\n than assuming a write worked.\n- A `run-lua` that fails with HTTP 504 (`run-lua timed out`, exit code 3 from CLI\n 0.6.4 on; the MCP `run_lua` tool returns the same text) reached the engine, which\n may still be running it. Do not send code that changes the world again: check its\n effect first, by reading back what it sets or taking a screenshot. Any other\n failure never reached the engine and is safe to retry.\n- The mirrored folder's AGENTS.md is this guide followed by the engine SDK's own agent guide\n (the AGENTS.md that lives in every Montage tree and inside the desktop client's\n Data/Sdk/Montage/). The engine guide assumes an in-session agent driving the engine\n through `atomo`; the merged file maps each `atomo` step to the CLI or MCP equivalent, and\n the `Skills/*.md` references it points at are in the folder. The SDK's own tooling\n (`atomo`, `vm_auth.py`, the agent-log hooks) is not mirrored: it only works inside a\n session. From CLI 0.6.5 on, macOS and Linux folders get their own `./atomo`, which\n serves the guide's `./atomo run-lua`, `run-lua-client` and `errors` through the CLI.\n Sandboxed agents need network access for every CLI command.\n- After saving a `.lua` file with `sync` running, check it with\n `./atomo errors --after-reload <file>` (CLI 0.6.8 on) instead of sleeping: it waits\n until the world has the save and has reloaded it, then lists the errors. `./atomo`\n exits like the engine's own: 1 when `run-lua` raised or `errors` shows an error no\n earlier check reported, 2 when nothing ran, 3 when the engine may still be running it.\n- 3D models go in through the voxelizer, never through Lua. From CLI 0.7.0 on,\n `npx virtualmatter voxelize <files or folders> --place x,y,z` uploads GLB, OBJ, FBX,\n STL, point clouds (PLY, LAS/LAZ, E57) or zips from disk (resumable, up to 10 GiB),\n voxelizes them on Virtual Matter's voxelizer into the maker's asset library, attaches\n them to the world and places them in the scene; the MCP `voxelize_model` tool does the\n same. `virtualmatter assets` lists the library and `place <asset> --at x,y,z` puts one\n in again. A model keeps its own coordinates in metres and `--place` moves its 0,0,0,\n so map or city tiles voxelized from one dataset line up when placed with the same\n offset (`voxelize tiles/ --vpm 2 --place -1000,0,-1000`). 2-4 voxels per metre suits\n buildings and terrain, 32-128 props. Never paste mesh, footprint or height-grid text\n into a script or rebuild a model out of Lua primitives: that costs credits and engine\n memory and comes out wrong.\n- Worlds with the platform's skill packages carry them in `Skills/atomontage-*`.\n From CLI 0.6.5 on, `pull` and `sync` also copy them into `.claude/skills/`, so Claude\n Code loads them as skills; other harnesses follow the routing table in AGENTS.md.\n Start from `atomontage-game-starters` for any of the 15 homepage starter games: its\n `starterctl.py build <preset>` builds a playable starter in seconds through\n `./atomo`. Where a skill says to hand a live check to the in-game agent, run it\n yourself: never send prompts to the world's built-in agent.\n\n## Reference\n\nThe same facts as terse lists, for quick lookup.\n\n### Project model\n- A project (\"montage\") is one voxel world hosted with Virtual Matter.\n- A project has framings: \"make\" framings (editing sessions) and \"play\"\n framings (public play sessions). A framing is a running session slot\n on a voxel host.\n- Project content = SDK Lua scripts + assets under a Montage/ tree.\n Edits made in the live session hot-reload into the running world.\n The tree can be published to a maker-owned GitHub repo.\n\n### URL shapes (make.virtualmatter.ai)\n- /new builder for people: create a world from a prompt\n (also at https://virtualmatter.ai/); coding agents\n use npx virtualmatter make instead\n- /edit/<framing-id> maker session: live world + agent chat. The chat is\n for people; a coding agent builds with the CLI and\n never prompts it\n (also /edit/<slug>-<framing-id>; the CLI accepts both)\n- /play/<framing-id> play session for a specific framing\n- /g/<id> share URL resolver: 302s to a live session\n\n### APIs (unauthenticated)\n- GET https://make.virtualmatter.ai/api/v1/public/native-clients\n JSON: { iteration, clients: [{ platform, kind, variant, url, filename,\n file_size, branch, commit, match }] } - per-platform native client\n installers (kind \"download\") or store links (kind \"store\", iOS).\n Windows and Linux list two downloads each: variant \"installer\" /\n \"flatpak\" for people, and \"portable\" / \"tarball\", the file tree the\n CLI installs.\n\n### CLI + MCP (npm package \"virtualmatter\", Node >= 20)\n- npx virtualmatter make \"<name>\" make a world, mirror it into ./<slug>\n- npx virtualmatter pull <link> mirror an existing world (any link shape)\n- npx virtualmatter list your worlds with framing ids + URLs\n- npx virtualmatter sync live-push saves into the running world\n (one per folder; does not pull files too\n large to push back, such as terrain)\n- npx virtualmatter push [files] one-shot deploy, per-file result; exit 1\n on any conflict or failure\n- npx virtualmatter fetch [files] one-shot download; never overwrites\n local edits (conflict -> .remote-conflict)\n- npx virtualmatter logs --restarts why the world restarted (crash + last\n log lines, or the platform's reason)\n- npx virtualmatter restart restart the editor server: a clean engine\n process (the only thing that returns\n memory; Server:ReloadScene() does not).\n Saves first, waits until Lua answers,\n prints the time and Server:GetMemoryUsage().\n --force for a stuck engine, --yes when\n clients are connected. Never a play server\n- npx virtualmatter stop | start stop the editor server and leave it\n stopped / start a stopped one. Exit 3 =\n sent, outcome unknown: check status first\n- npx virtualmatter publish update the play servers; reports each\n server, says which scene they load\n- npx virtualmatter status editor server running or stopped, engine\n iteration, play servers vs the editor,\n last update\n- npx virtualmatter voxelize <files|folders> [--vpm 4] [--place x,y,z]\n 3D models (glb obj fbx stl, point\n clouds, zip) into voxel assets: upload,\n voxelize, attach, place; real-world\n metres, tiles line up\n- npx virtualmatter assets your asset library (--project: one\n world's attached assets)\n- npx virtualmatter place <asset> --at x,y,z put a library asset in\n the world at real size\n- npx virtualmatter open optional: open it in the native client\n- npx virtualmatter mcp stdio MCP server (list_projects,\n create_project, select_project, list_files, read_file, write_file,\n patch_file, push_local_files, fetch_files, run_lua, get_engine_errors,\n get_engine_logs, capture_screenshot, play_server_status,\n publish_play_servers, open_native_client, world_info, voxelize_model,\n get_voxelize_job, list_assets, place_asset)\n- Sign-in happens on first use (device code); no separate login step.\n- These commands are the whole build path. Never prompt the built-in\n agent on the site to do the work; a browser or the native client is\n for playtesting what you built.\n- Any link to a world (editor, play or share link, project page, embed,\n or the maker's own website) resolves to its editor, the only place\n the CLI and MCP server work. Play servers show the last published\n version and are overwritten on publish.\n- Watch changes land live at the editor link ending in ?chat=closed,\n in any browser, no install. The native client is optional.\n- A mirrored folder carries .mcp.json, .cursor/mcp.json, AGENTS.md and\n CLAUDE.md, so Claude Code and Cursor register the server on their own.\n- Codex: folders from 0.5.0 on carry .codex/config.toml, loaded once the\n folder is trusted; otherwise register the server once:\n codex mcp add virtualmatter -- npx -y virtualmatter mcp\n\n## SDK Lua cheat sheet\n\nThe scripting language is Lua 5.4, sandboxed: `os`, `io`, `require`, `package`,\n`dofile`, `loadfile`, `loadstring` are nil. `math`, `string`, `table`, `coroutine`\nremain. No `os.time` - use `Time.time` (sim time), `Time.frame`, or\n`AE:GetDebugTime()` (wall clock).\n\n### Script shape\n\nEvery persistent behavior is a `.lua` file in the Montage tree returning a `self` table:\n\n```lua\nlocal self = {}\nfunction self:Start() end\nfunction self:Update(deltaTime) end\nreturn self\n```\n\nAttach to an object with `obj:AddScript(script, sync)`; `sync = true` replicates the\nscript to clients. On iteration073 `script` is a path relative to the Montage root\n(`\"My Folder/Example.lua\"`); from iteration076 it must be the script's Asset (see\n\"Worlds on iteration076\" below). `obj:FindScript(\"Example\")` returns the live instance.\n\n### Server / client split\n\nThe same script runs on the server and (when synced) on every client. Branch with\n`self.onServer` / `self.onClient`:\n\n```lua\nfunction self:Update(dt)\n if self.onClient then return end -- voxel edits are server-only\n -- authoritative logic here\nend\n```\n\nNothing replicates automatically: set `syncToClients = true` on the script or\nVoxelData component, and use `util:makeNetworkedTable(self, { hp = 100 })` for\nproperties that should sync (server writes, clients read, deltas only).\n`obj.pos` / `obj.rot` do not auto-sync - replicate them yourself.\n\n### RPC\n\n```lua\nself:RPC(\"serverDoSomething\", pos, dir) -- on a client: goes to the server\nfunction self:serverDoSomething(pos, dir, clientID) -- clientID auto-appended\n assert(self.onServer)\nend\n```\n\nOn the server, `self:RPC(...)` fans out to all clients. Reliable, FIFO per direction.\nRequires `self.component.syncToClients = true`.\n\n### Scene and objects (server)\n\n```lua\nlocal ob = Scene:CreateObject(\"Name\")\nob.save = true\nob:AddScript(scriptAsset) -- a path string on 073, an Asset from 076\nScene:GetObjectByName(\"Name\")\nScene:CloneObject(ob) -- prefer over rebuilding\nob.active = false -- prefer over destroy; clients don't see it\nob:AddTag(\"Enemy\"); FindObjectsWithTag(\"Enemy\") -- tags are runtime-only state\n```\n\n### Voxel editing (server only, async)\n\n```lua\nVox:Add(Sphere(pos, 2)):Color(1, 0, 0):Run()\nVox:Add(Box(Vec3(0, -1, 0), Vec3(20, 2, 20))):ForceStatic():Run()\n```\n\nShapes: `Box(center, fullSize)`, `Sphere(center, r)`, `Capsule(p1, p2, r)`,\n`Cylinder(p1, p2, r1[, r2])`. `Run()` is async - chain `:OnFinished(fn)` before\n`:Run()` to read post-commit state. Big edits stall the frame for every client;\nkeep in-game edits small and infrequent.\n\n### Input (event-driven, client input reaches the server)\n\n```lua\nself.component.syncToClients = true\nevents.keyDown.addListener(self, function(key, from) self.keys[key] = true end)\nevents.keyUp.addListener(self, function(key, from) self.keys[key] = false end)\n```\n\nPlayer-driven movement must be client-predicted - never gate the player's own\nfeedback on the server round-trip.\n\n### Physics\n\n```lua\nlocal rb = obj:AddComponent(\"RigidBody\")\nrb:AddImpulse(Vec3(0, 50, 0), obj.pos)\nrb.velocity; rb.mass; rb.gravityScale\n```\n\n### Time and diagnostics\n\n```lua\nTime.dt; Time.time; Time.frame; Time.timeScale\nAE:GetLogValue(\"Raycasts\") -- engine counters, e.g. raycasts this frame\nAE:GetAssets() -- list all assets (APIs take Assets, not paths)\n```\n\n### UI (client-side HUD)\n\nBuild screen UI with the MUI builder: `UI:AddPanel|AddButton|AddLabel|AddSlider|...`\nchained with `:Set{...}`; flexbox-like row-wrap layout.\n\n### Engine behaviours that catch people out\n\nEach of these has broken a real game. An error inside a `util:schedule` chain or an\n`Update` stops that loop without anything else visible, so check `errors` after a\nchange even when the world looks fine.\n\n- Object names may hold only letters, digits and single spaces. `Scene:CreateObject`\n rejects `_`, `-`, `.` and leading or trailing spaces with \"Failed to create object.\n Given name was invalid.\"\n- `Cast:Ray` with a zero-length vector throws \"ray is zero length\". Guard every ray\n whose vector can be zero: coincident positions, a target standing on the shooter, a\n projectile at rest.\n- Client rays cannot read surfaces. `ForceStatic()` (on `Cast:Ray(...)` and\n `Collide(...)`), `WithNormal()`, `WithColor()` and `WithMaterial()` throw on a client\n (\"... only supported on server\"), and so does reading `hit.normal`, `hit.color` or\n `hit.material`; `hit.obj` is nil for every client hit. On a client, use a plain ray\n and skip dynamic objects with `Ignore`; read surfaces on the server and send what the\n client needs with the event (for example the impact material as an RPC argument). On\n the server, reading `hit.material` without `WithMaterial()` throws.\n- `Audio:PlaySound(asset, nil, ...)` throws, although the position is typed optional.\n Play a non-positional sound with `Audio:PlaySoundRelative(asset, Vec3(0,0,0), volume,\n false)`.\n- `obj.active = false` does not replicate. Clients keep the object active, frozen where\n it last streamed, with its client scripts running and any client-made meshes visible;\n an object created and deactivated in the same frame shows up at (0,0,0). To pool\n objects, also send a park position (a networked-table write in the same frame does\n arrive), move the object there on the client, and skip parked objects in client code.\n- A transform written in `LateUpdate` renders one frame behind the camera. Pose\n anything held against the camera (viewmodels, held items, camera-attached 3D) in\n `Update`, right after the camera moves.\n- Window z-order follows creation order and cannot be set: among `stayOnBottom`\n windows the earliest created draws on top, and toggling `visible` does not reorder\n them. Create windows in the order you want them stacked.\n- A `zNear` written right after `AddComponent(\"Camera\")` is reset to 0.1; write it\n again a frame later.\n- An RPC round trip (client -> server -> client) takes several times what\n `Client:GetPing()` reports (125-192 ms against 30 ms on a local connection), and\n networked tables reach clients at about 13-15 Hz. Measure the round trip your game\n sees with `AE:GetDebugTime()` before gating prediction on it.\n- The static edit guard's budget is per frame, not per op. About the 4th large op in\n one Lua call throws \"frame voxel budget exhausted\", leaving the earlier ops applied.\n Spread batches over frames and retry a refused op on the next frame, or a reset or\n map build leaves terrain half-edited.\n- Every static `Vox` op (Remove, Add, Paint) costs one 30-50 ms server frame whatever\n its size (55-85 ms in a test on iteration076, where `OpBase:Batch()` saved nothing\n on the server and delayed delivery). Prefer fewer, bigger ops and budget the rate:\n about 1 op/s keeps the p99 frame near 33 ms.\n- Static edits reach connected clients seconds to tens of seconds late, and a freshly\n joined client that is still streaming the map can wait 45 s or more. Gameplay must\n not depend on client terrain: hit checks, cover and validation belong on the server.\n- Client terrain rays are LOD-quantised in 0.125-0.25 m steps a few metres from the\n camera. Give client-side terrain checks a tolerance of 0.3 m or more, and use server\n rays for anything authoritative.\n- Setting `child.parent = obj` keeps the child's world transform. Set `localPos` and\n `localRot` after parenting, not before.\n- `Server:GetStreamingStats()` reports `STALLING` and `finalRatioPct = 0` for healthy\n clients too, so it cannot tell you a client has stopped receiving edits.\n- After a map-scale rebuild, the default `screenshot` (rendered by the server's own\n view) can show stale or missing terrain. Check with server rays or with\n `screenshot --client <id>` from a freshly connected client.\n\n### Worlds on iteration076\n\n`print(AE:GetVersion())` through `run-lua` tells you the engine build (76.x is\niteration076). A world moved from 073 keeps running code that 076 rejects, and the\n`pcall` guards games put around engine calls hide every one of these failures:\n\n- `receiveTransform` is a field of `Object` (`obj.receiveTransform = false`), not of\n `VoxelData`. On 076 `vd.receiveTransform` reads nil and writing it throws.\n- `Audio:PlaySound`, `Audio:PlaySoundRelative` and `Object:AddScript` take an Asset,\n not a path (\"expected a AudioFile Asset, got string\"). Resolve each path once and\n cache it: walk `AE:GetAssets()` and keep the asset for which\n `AE:AssetPathInMontage(asset) == path`. A client lists assets as they sync, so a\n lookup there can return nil for a while; retry instead of caching the nil.\n- There is no `Sky` component: `GetComponentByType(\"Sky\")` returns nil. On a client,\n hide the sky with `Client:SetSkyEnabled(false)`, aim the sun with\n `Client:SetSunDirection(azimuth, altitude)`, and turn off the god rays and lens flare\n (on by default) with `AE:SetLogValue(\"Dev/GodRays\", 0)` and\n `AE:SetLogValue(\"Dev/LensFlare\", 0)`. The SDK's `Sky` script turns the sky back on\n for each joining client; to keep it off, call that script's\n `queueSerializedRender(false)` on the server. A fog density above 0 turns VM Sky\n black.\n- Writing a field an engine object does not have throws, and `Widget:Set{...}` throws\n on an unknown key after applying the keys before it. While migrating, do not swallow\n these: keep the error from `pcall` and print it once\n (`local ok, err = pcall(f); if not ok then print(err) end`). Client `print` output\n does not reach the logs, so exercise client paths with\n `virtualmatter run-lua --target client` and return the error.\n- Edited copies of built-in shaders in `Shaders/` are kept as they are on every engine\n move (the boot log says \"maker edit - kept\"), even when the renderer's inputs have\n changed: the 076 `ssao2.fs` declares its own `FogFrame` block and no longer includes\n `common.glsl`. After a move, diff each kept copy against the new built-in, re-apply\n the edit, and check `Client:GetShaderErrors()` on a real client once it has drawn a\n frame. For a look change, prefer `Client:SetVPuzzleShaderDefines` (`#undef NAME` /\n `#define NAME value` lines, for example `CUSTOM_LIGHTING_MODE` or\n `CUSTOM_LIGHTING_MODE_LIGHTPOSTER`): it changes a client's shading without forking a\n shader, and recompiles every effect (about 100 ms) each time you call it.\n- The post-process chain runs in the live render on 076, whatever the engine's\n shaders skill says: depth of field, god rays, lens flare, tone mapping, outline,\n SSR and the SSAO composite (`ssao2.fs`). Switch them per client with\n `AE:SetLogValue`, for example `AE:SetLogValue(\"Dev/EnableDOF\", 1)` or\n `\"Dev/EnableToneMapping\"`. On 073 the chain is not wired and editing its shaders\n does nothing.\n\n### Generated sounds\n\n`Fal:requestTextToSound` returns takes that play quiet and thin: most of their energy\nsits below 20 Hz, with a DC offset and peaks around -25 dBFS. The engine's output\nalso removes most of what is below about 150 Hz and levels sounds by loudness, not\npeak. Before using a take, fetch the mp3 from `Sounds/Generated/`, clean it locally,\nand push it under a new name:\n\n```sh\nffmpeg -i take.mp3 -af \"highpass=f=40,loudnorm=I=-14:TP=-1\" -ac 1 -ar 44100 \"Clean Take.mp3\"\n```\n\nUse mono for one-shots, and match levels by loudness (LUFS), not by peak. A client\nthat has already played a sound keeps its old decoding until it reconnects, so give a\nreplacement a new file name. The generator may also change an asset name's case\n(`ScarGen Carbine 2b` comes back as `Scargen Carbine 2B`).\n\n## Conventions\n\n- Coordinates: Y is up, -Z is forward, X is right.\n- Script files are named in capital case with spaces (`Character Controller.lua`).\n- Check whether a script is already attached before adding it - duplicates run twice.\n- The server is for authority (world edits, spawns, state); clients are for feel\n (prediction, FX, UI).\n\n## Embed or build a world for an existing website\n\nFor a shared project link, fetch `/api/v1/public/embed?target=<encoded-link>`\nand follow `/embed-guide.md`. Use the returned canonical player URL, not the\nmaker's external website URL. Keep the existing website and its design.\n\nFor account discovery or prompt-based creation, connect the hosted MCP at\n`https://make.virtualmatter.ai/api/v1/mcp` using OAuth. Users can sign up in\nthe connection flow. Tools: `list_projects`, `get_embed`, `create_project`\n(with a prompt and stable request_id), `get_build_status`. VM's agent builds\nusing VM credits. Review and share the private world before embedding.\nThe local CLI exposes `embed`, `build --prompt --request-id`, and `build-status`.\n\n## Local conversation history\n\nCapturing this harness's conversation into the world's Agent Logs is the maker's\ndecision, not yours. Do not run `virtualmatter agent-logs setup`, and do not upload\nlogs with `agent-logs upload` or MCP `upload_agent_logs`, unless the maker asks for it\nin their own words. `virtualmatter agent-logs status` shows whether capture is on;\n`virtualmatter agent-logs disable` turns it off.\n";
|
package/dist/asset-commands.js
CHANGED
|
@@ -58,6 +58,14 @@ export function voxelizeOptions(opts) {
|
|
|
58
58
|
out.rotation = parseTriple(opts.rotate, "--rotate");
|
|
59
59
|
if (opts.shading === false)
|
|
60
60
|
out.applyShading = false;
|
|
61
|
+
if (opts.imageStack)
|
|
62
|
+
out.imageStack = true;
|
|
63
|
+
if (opts.threshold !== undefined) {
|
|
64
|
+
const threshold = Number(opts.threshold);
|
|
65
|
+
if (!(threshold > 0 && threshold < 1))
|
|
66
|
+
throw new Error(`--threshold takes a number between 0 and 1 (got "${opts.threshold}")`);
|
|
67
|
+
out.threshold = threshold;
|
|
68
|
+
}
|
|
61
69
|
return out;
|
|
62
70
|
}
|
|
63
71
|
/** `voxelize <sources...>`. Returns the exit code. */
|
package/dist/assets.js
CHANGED
|
@@ -157,6 +157,13 @@ export function voxelizeParameters(kind, opts) {
|
|
|
157
157
|
return shared;
|
|
158
158
|
if (kind === "voxel")
|
|
159
159
|
return {};
|
|
160
|
+
if (kind === "bundle" && opts.imageStack) {
|
|
161
|
+
// Slices carry no outside light worth baking: shading is on only when asked for.
|
|
162
|
+
const image_stack = { voxel_size_m, apply_shading: opts.applyShading === true };
|
|
163
|
+
if (opts.threshold !== undefined)
|
|
164
|
+
image_stack.threshold = opts.threshold;
|
|
165
|
+
return { inner_kind: "image_stack", image_stack };
|
|
166
|
+
}
|
|
160
167
|
if (kind === "bundle")
|
|
161
168
|
return { inner_kind: "mesh", mesh };
|
|
162
169
|
throw new Error(`Uploads of kind ${kind} cannot be voxelized.`);
|
|
@@ -338,13 +345,80 @@ export async function voxelizeSource(source, opts = {}) {
|
|
|
338
345
|
const upload = UUID_RE.test(source) && !fs.existsSync(source)
|
|
339
346
|
? await getUpload(source, opts.fetchFn)
|
|
340
347
|
: await uploadFile(source, { onProgress: opts.onUploadProgress, fetchFn: opts.fetchFn });
|
|
341
|
-
|
|
348
|
+
const isLocalZip = fs.existsSync(source) && source.toLowerCase().endsWith(".zip");
|
|
349
|
+
const imageStack = opts.imageStack ?? (isLocalZip && zipIsImageStack(source));
|
|
350
|
+
let job = await startVoxelize(upload, { ...opts, imageStack }, opts.fetchFn);
|
|
342
351
|
if (opts.wait === false)
|
|
343
352
|
return { upload, job, asset: null };
|
|
344
353
|
job = await waitForJob(job.id, { fetchFn: opts.fetchFn, onUpdate: opts.onJobUpdate, timeoutMs: opts.waitTimeoutMs });
|
|
345
354
|
const asset = job.status === "succeeded" ? await assetForJob(job.id, opts.fetchFn) : null;
|
|
346
355
|
return { upload, job, asset };
|
|
347
356
|
}
|
|
357
|
+
const STACK_IMAGE_EXTENSIONS = new Set(["png", "jpg", "jpeg", "tif", "tiff", "bmp", "tga"]);
|
|
358
|
+
/** The file names in a zip, read from its central directory; null when it cannot be read. */
|
|
359
|
+
export function zipEntryNames(filePath) {
|
|
360
|
+
const fd = fs.openSync(filePath, "r");
|
|
361
|
+
try {
|
|
362
|
+
const size = fs.fstatSync(fd).size;
|
|
363
|
+
const read = (offset, length) => {
|
|
364
|
+
const buf = Buffer.alloc(length);
|
|
365
|
+
fs.readSync(fd, buf, 0, length, offset);
|
|
366
|
+
return buf;
|
|
367
|
+
};
|
|
368
|
+
// The end record sits in the last 22 bytes plus an optional comment of up to 64 KiB.
|
|
369
|
+
const tailLength = Math.min(size, 22 + 0xffff);
|
|
370
|
+
const tailStart = size - tailLength;
|
|
371
|
+
const tail = read(tailStart, tailLength);
|
|
372
|
+
let end = -1;
|
|
373
|
+
for (let i = tail.length - 22; i >= 0; i--) {
|
|
374
|
+
if (tail.readUInt32LE(i) === 0x06054b50) {
|
|
375
|
+
end = i;
|
|
376
|
+
break;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (end < 0)
|
|
380
|
+
return null;
|
|
381
|
+
let dirSize = tail.readUInt32LE(end + 12);
|
|
382
|
+
let dirOffset = tail.readUInt32LE(end + 16);
|
|
383
|
+
// Zip64 (over 4 GiB or 65,535 entries): the real numbers are in the record its locator points at.
|
|
384
|
+
if (end >= 20 && tail.readUInt32LE(end - 20) === 0x07064b50) {
|
|
385
|
+
const record = read(Number(tail.readBigUInt64LE(end - 20 + 8)), 56);
|
|
386
|
+
if (record.readUInt32LE(0) !== 0x06064b50)
|
|
387
|
+
return null;
|
|
388
|
+
dirSize = Number(record.readBigUInt64LE(40));
|
|
389
|
+
dirOffset = Number(record.readBigUInt64LE(48));
|
|
390
|
+
}
|
|
391
|
+
if (dirOffset + dirSize > size)
|
|
392
|
+
return null;
|
|
393
|
+
const dir = read(dirOffset, dirSize);
|
|
394
|
+
const names = [];
|
|
395
|
+
for (let at = 0; at + 46 <= dir.length && dir.readUInt32LE(at) === 0x02014b50;) {
|
|
396
|
+
const nameLength = dir.readUInt16LE(at + 28);
|
|
397
|
+
names.push(dir.toString("utf8", at + 46, at + 46 + nameLength));
|
|
398
|
+
at += 46 + nameLength + dir.readUInt16LE(at + 30) + dir.readUInt16LE(at + 32);
|
|
399
|
+
}
|
|
400
|
+
return names;
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
finally {
|
|
406
|
+
fs.closeSync(fd);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Whether a zip is a stack of slice images rather than a set of 3D models: it
|
|
411
|
+
* has a stack.json, or every file in it is an image. A textured model's zip
|
|
412
|
+
* always has a model file too, so it stays a mesh bundle.
|
|
413
|
+
*/
|
|
414
|
+
export function zipIsImageStack(filePath) {
|
|
415
|
+
const names = zipEntryNames(filePath)?.filter((n) => !n.endsWith("/") && !n.startsWith("__MACOSX/") && !path.posix.basename(n).startsWith("."));
|
|
416
|
+
if (!names || names.length === 0)
|
|
417
|
+
return false;
|
|
418
|
+
if (names.some((n) => path.posix.basename(n) === "stack.json" && n.split("/").length <= 2))
|
|
419
|
+
return true;
|
|
420
|
+
return names.every((n) => STACK_IMAGE_EXTENSIONS.has(n.split(".").pop().toLowerCase()));
|
|
421
|
+
}
|
|
348
422
|
/** File extensions the platform accepts as uploads (backend services/uploads.py). */
|
|
349
423
|
export const UPLOAD_EXTENSIONS = new Set([
|
|
350
424
|
"glb", "gltf", "fbx", "obj", "stl",
|
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
|
+
}
|