virtualmatter 0.6.8 → 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 +38 -7
- package/dist/agentfiles.js +1 -1
- package/dist/agents-md.generated.js +1 -1
- package/dist/asset-commands.js +154 -0
- package/dist/assets.js +395 -0
- package/dist/client.js +97 -14
- package/dist/depth.js +119 -0
- package/dist/files.js +151 -44
- package/dist/index.js +195 -12
- package/dist/mcp.js +154 -9
- package/dist/sync.js +83 -6
- package/dist/world-status.js +81 -0
- package/package.json +1 -1
package/dist/assets.js
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Meshes into a world without the website: upload a 3D file, voxelize it on
|
|
3
|
+
* Virtual Matter's voxelizer, keep the result in the maker's asset library,
|
|
4
|
+
* attach it to a project and place it in the scene.
|
|
5
|
+
*
|
|
6
|
+
* Why it exists: on 2026-10-13 a maker importing a Dutch city (OBJ tiles from
|
|
7
|
+
* 3D BAG) had an agent that could not reach any of this. It pasted OBJ text
|
|
8
|
+
* into chat and rebuilt the buildings out of Lua boxes, which burned his
|
|
9
|
+
* credits and the engine's memory. Every step here is one platform endpoint
|
|
10
|
+
* the website already uses; the CLI just signs the calls with its own token.
|
|
11
|
+
*
|
|
12
|
+
* Files up to MULTIPART_MAX_BYTES go up in one request. Larger ones (up to
|
|
13
|
+
* 10 GiB) go through the platform's tus server in resumable chunks.
|
|
14
|
+
*/
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { authorizedFetch } from "./api.js";
|
|
18
|
+
import { apiBase } from "./config.js";
|
|
19
|
+
/** The platform's single-request cap is 200 MiB; leave room for the multipart envelope. */
|
|
20
|
+
export const MULTIPART_MAX_BYTES = 190 * 1024 * 1024;
|
|
21
|
+
/** tusd writes S3 parts of 16 MiB; one PATCH per part. */
|
|
22
|
+
const TUS_CHUNK_BYTES = 16 * 1024 * 1024;
|
|
23
|
+
export const TERMINAL_JOB_STATUSES = new Set(["succeeded", "failed", "cancelled"]);
|
|
24
|
+
async function errorFrom(res, what) {
|
|
25
|
+
let detail = "";
|
|
26
|
+
try {
|
|
27
|
+
const body = (await res.json());
|
|
28
|
+
detail = typeof body.detail === "string" ? body.detail : body.detail ? JSON.stringify(body.detail) : "";
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
/* non-JSON */
|
|
32
|
+
}
|
|
33
|
+
return new Error(`${what} failed: HTTP ${res.status}${detail ? ` - ${detail}` : ""}`);
|
|
34
|
+
}
|
|
35
|
+
/** Upload a 3D file to the maker's library of uploads. Returns the upload row. */
|
|
36
|
+
export async function uploadFile(filePath, opts = {}) {
|
|
37
|
+
const stat = fs.statSync(filePath);
|
|
38
|
+
if (!stat.isFile())
|
|
39
|
+
throw new Error(`${filePath} is not a file.`);
|
|
40
|
+
if (stat.size === 0)
|
|
41
|
+
throw new Error(`${filePath} is empty.`);
|
|
42
|
+
return stat.size <= MULTIPART_MAX_BYTES
|
|
43
|
+
? uploadMultipart(filePath, stat.size, opts)
|
|
44
|
+
: uploadTus(filePath, stat.size, opts);
|
|
45
|
+
}
|
|
46
|
+
async function uploadMultipart(filePath, size, opts) {
|
|
47
|
+
const form = new FormData();
|
|
48
|
+
form.append("file", await fs.openAsBlob(filePath), path.basename(filePath));
|
|
49
|
+
opts.onProgress?.(0, size);
|
|
50
|
+
const res = await authorizedFetch(`${apiBase()}/api/v1/uploads`, { method: "POST", body: form }, opts.fetchFn);
|
|
51
|
+
if (!res.ok)
|
|
52
|
+
throw await errorFrom(res, "Uploading");
|
|
53
|
+
opts.onProgress?.(size, size);
|
|
54
|
+
return (await res.json());
|
|
55
|
+
}
|
|
56
|
+
/** The upload id the platform gave a tus upload, read from its Location. */
|
|
57
|
+
export function uploadIdFromTusLocation(location) {
|
|
58
|
+
let decoded = location;
|
|
59
|
+
try {
|
|
60
|
+
decoded = decodeURIComponent(location);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
/* keep it raw */
|
|
64
|
+
}
|
|
65
|
+
const m = /\/uploads\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\//i.exec(decoded);
|
|
66
|
+
return m?.[1] ?? null;
|
|
67
|
+
}
|
|
68
|
+
function tusMetadata(filename) {
|
|
69
|
+
const b64 = (s) => Buffer.from(s, "utf8").toString("base64");
|
|
70
|
+
return `filename ${b64(filename)},filetype ${b64("application/octet-stream")}`;
|
|
71
|
+
}
|
|
72
|
+
export async function uploadTus(filePath, size, opts) {
|
|
73
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
74
|
+
const base = { "Tus-Resumable": "1.0.0" };
|
|
75
|
+
const created = await authorizedFetch(`${apiBase()}/tus/`, {
|
|
76
|
+
method: "POST",
|
|
77
|
+
headers: { ...base, "Upload-Length": String(size), "Upload-Metadata": tusMetadata(path.basename(filePath)) },
|
|
78
|
+
}, opts.fetchFn);
|
|
79
|
+
if (created.status !== 201)
|
|
80
|
+
throw await errorFrom(created, "Starting the upload");
|
|
81
|
+
const location = created.headers.get("location");
|
|
82
|
+
if (!location)
|
|
83
|
+
throw new Error("The upload server returned no Location.");
|
|
84
|
+
const url = new URL(location, `${apiBase()}/tus/`).toString();
|
|
85
|
+
const uploadId = uploadIdFromTusLocation(url);
|
|
86
|
+
if (!uploadId)
|
|
87
|
+
throw new Error(`Could not read the upload id from ${url}.`);
|
|
88
|
+
const fd = fs.openSync(filePath, "r");
|
|
89
|
+
try {
|
|
90
|
+
let offset = 0;
|
|
91
|
+
let failures = 0;
|
|
92
|
+
while (offset < size) {
|
|
93
|
+
const length = Math.min(TUS_CHUNK_BYTES, size - offset);
|
|
94
|
+
const chunk = Buffer.alloc(length);
|
|
95
|
+
fs.readSync(fd, chunk, 0, length, offset);
|
|
96
|
+
let res = null;
|
|
97
|
+
try {
|
|
98
|
+
res = await authorizedFetch(url, {
|
|
99
|
+
method: "PATCH",
|
|
100
|
+
headers: { ...base, "Upload-Offset": String(offset), "Content-Type": "application/offset+octet-stream" },
|
|
101
|
+
body: chunk,
|
|
102
|
+
}, opts.fetchFn);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
res = null;
|
|
106
|
+
}
|
|
107
|
+
if (res && res.status === 204) {
|
|
108
|
+
offset = Number(res.headers.get("upload-offset") ?? offset + length);
|
|
109
|
+
failures = 0;
|
|
110
|
+
opts.onProgress?.(offset, size);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
// Resume: ask the server how much it has, then carry on from there.
|
|
114
|
+
if (++failures > 5)
|
|
115
|
+
throw res ? await errorFrom(res, "Uploading") : new Error("Uploading failed: network error");
|
|
116
|
+
await sleep(1000 * failures);
|
|
117
|
+
const head = await authorizedFetch(url, { method: "HEAD", headers: base }, opts.fetchFn).catch(() => null);
|
|
118
|
+
const serverOffset = head?.headers.get("upload-offset");
|
|
119
|
+
if (serverOffset !== null && serverOffset !== undefined)
|
|
120
|
+
offset = Number(serverOffset);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
fs.closeSync(fd);
|
|
125
|
+
}
|
|
126
|
+
// The platform writes the upload row from tusd's post-finish hook, just after the last chunk.
|
|
127
|
+
for (let i = 0; i < 60; i++) {
|
|
128
|
+
const res = await authorizedFetch(`${apiBase()}/api/v1/uploads/${uploadId}`, {}, opts.fetchFn);
|
|
129
|
+
if (res.ok)
|
|
130
|
+
return (await res.json());
|
|
131
|
+
if (res.status !== 404)
|
|
132
|
+
throw await errorFrom(res, "Reading the upload");
|
|
133
|
+
await sleep(1000);
|
|
134
|
+
}
|
|
135
|
+
throw new Error(`The upload finished but upload ${uploadId} never appeared on the platform.`);
|
|
136
|
+
}
|
|
137
|
+
export function voxelSizeForVpm(vpm) {
|
|
138
|
+
if (!(vpm > 0))
|
|
139
|
+
throw new Error("voxels per metre must be positive.");
|
|
140
|
+
const pow = Math.max(0, Math.min(13, Math.round(Math.log2(vpm))));
|
|
141
|
+
return 1 / 2 ** pow;
|
|
142
|
+
}
|
|
143
|
+
/** The `parameters` body the platform validates for an upload of this kind. */
|
|
144
|
+
export function voxelizeParameters(kind, opts) {
|
|
145
|
+
const voxel_size_m = voxelSizeForVpm(opts.voxelsPerMeter ?? 4);
|
|
146
|
+
const shared = {
|
|
147
|
+
voxel_size_m,
|
|
148
|
+
method: opts.method ?? "FloodFill",
|
|
149
|
+
apply_shading: opts.applyShading ?? true,
|
|
150
|
+
colorspace: opts.colorspace ?? "srgb",
|
|
151
|
+
};
|
|
152
|
+
const [rx, ry, rz] = opts.rotation ?? [0, 0, 0];
|
|
153
|
+
const mesh = { ...shared, scale: opts.scale ?? 1, rotation_x_deg: rx, rotation_y_deg: ry, rotation_z_deg: rz };
|
|
154
|
+
if (kind === "mesh")
|
|
155
|
+
return mesh;
|
|
156
|
+
if (kind === "pointcloud")
|
|
157
|
+
return shared;
|
|
158
|
+
if (kind === "voxel")
|
|
159
|
+
return {};
|
|
160
|
+
if (kind === "bundle")
|
|
161
|
+
return { inner_kind: "mesh", mesh };
|
|
162
|
+
throw new Error(`Uploads of kind ${kind} cannot be voxelized.`);
|
|
163
|
+
}
|
|
164
|
+
export async function getUpload(uploadId, fetchFn) {
|
|
165
|
+
const res = await authorizedFetch(`${apiBase()}/api/v1/uploads/${encodeURIComponent(uploadId)}`, {}, fetchFn);
|
|
166
|
+
if (res.status === 404)
|
|
167
|
+
throw new Error(`Upload ${uploadId} was not found (or is not yours).`);
|
|
168
|
+
if (!res.ok)
|
|
169
|
+
throw await errorFrom(res, "Reading the upload");
|
|
170
|
+
return (await res.json());
|
|
171
|
+
}
|
|
172
|
+
export async function startVoxelize(upload, opts = {}, fetchFn) {
|
|
173
|
+
const res = await authorizedFetch(`${apiBase()}/api/v1/uploads/${encodeURIComponent(upload.id)}/voxelize`, {
|
|
174
|
+
method: "POST",
|
|
175
|
+
headers: { "Content-Type": "application/json" },
|
|
176
|
+
body: JSON.stringify({
|
|
177
|
+
asset_name: opts.assetName ?? null,
|
|
178
|
+
parameters: voxelizeParameters(upload.kind, opts),
|
|
179
|
+
}),
|
|
180
|
+
}, fetchFn);
|
|
181
|
+
if (!res.ok)
|
|
182
|
+
throw await errorFrom(res, "Starting the voxelizer");
|
|
183
|
+
return (await res.json());
|
|
184
|
+
}
|
|
185
|
+
export async function getJob(jobId, fetchFn) {
|
|
186
|
+
const res = await authorizedFetch(`${apiBase()}/api/v1/jobs/${encodeURIComponent(jobId)}`, {}, fetchFn);
|
|
187
|
+
if (res.status === 404)
|
|
188
|
+
throw new Error(`Voxelize job ${jobId} was not found (or is not yours).`);
|
|
189
|
+
if (!res.ok)
|
|
190
|
+
throw await errorFrom(res, "Reading the voxelize job");
|
|
191
|
+
return (await res.json());
|
|
192
|
+
}
|
|
193
|
+
/** Poll a job until it finishes or the wait times out; returns its last state either way. */
|
|
194
|
+
export async function waitForJob(jobId, opts = {}) {
|
|
195
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
196
|
+
const now = opts.now ?? Date.now;
|
|
197
|
+
const deadline = now() + (opts.timeoutMs ?? 60 * 60_000);
|
|
198
|
+
let last = "";
|
|
199
|
+
for (;;) {
|
|
200
|
+
const job = await getJob(jobId, opts.fetchFn);
|
|
201
|
+
const line = `${job.status}|${job.progress_message ?? ""}`;
|
|
202
|
+
if (line !== last) {
|
|
203
|
+
last = line;
|
|
204
|
+
opts.onUpdate?.(job);
|
|
205
|
+
}
|
|
206
|
+
if (TERMINAL_JOB_STATUSES.has(job.status) || now() >= deadline)
|
|
207
|
+
return job;
|
|
208
|
+
await sleep(opts.intervalMs ?? 5000);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
// ---------------------------------------------------------------- library
|
|
212
|
+
export async function listAssets(fetchFn) {
|
|
213
|
+
const res = await authorizedFetch(`${apiBase()}/api/v1/assets`, {}, fetchFn);
|
|
214
|
+
if (!res.ok)
|
|
215
|
+
throw await errorFrom(res, "Listing assets");
|
|
216
|
+
return (await res.json());
|
|
217
|
+
}
|
|
218
|
+
/** The library asset a finished job produced, or null (failed job, or not finalized yet). */
|
|
219
|
+
export async function assetForJob(jobId, fetchFn) {
|
|
220
|
+
return (await listAssets(fetchFn)).find((a) => a.job_id === jobId) ?? null;
|
|
221
|
+
}
|
|
222
|
+
/** Find one asset by id, am_uuid or exact name (newest wins on a name clash). */
|
|
223
|
+
export async function findAsset(ref, fetchFn) {
|
|
224
|
+
const assets = (await listAssets(fetchFn)).filter((a) => a.status !== "deleted");
|
|
225
|
+
const hit = assets.find((a) => a.id === ref || a.am_uuid === ref) ??
|
|
226
|
+
assets
|
|
227
|
+
.filter((a) => a.name === ref)
|
|
228
|
+
.sort((a, b) => b.created_at.localeCompare(a.created_at))[0];
|
|
229
|
+
if (!hit)
|
|
230
|
+
throw new Error(`No asset in your library matches ${ref}. List them with \`virtualmatter assets\`.`);
|
|
231
|
+
return hit;
|
|
232
|
+
}
|
|
233
|
+
export async function listProjectAssets(montageId, fetchFn) {
|
|
234
|
+
const res = await authorizedFetch(`${apiBase()}/api/v1/montages/${encodeURIComponent(montageId)}/assets`, {}, fetchFn);
|
|
235
|
+
if (!res.ok)
|
|
236
|
+
throw await errorFrom(res, "Listing the project's assets");
|
|
237
|
+
return (await res.json());
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Attach a library asset to a project. The platform copies the file into the
|
|
241
|
+
* world's `Assets/` folder on every live framing (and on every later spawn).
|
|
242
|
+
* Idempotent: attaching twice is fine.
|
|
243
|
+
*/
|
|
244
|
+
export async function attachAsset(montageId, assetId, fetchFn) {
|
|
245
|
+
const res = await authorizedFetch(`${apiBase()}/api/v1/montages/${encodeURIComponent(montageId)}/assets`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ asset_id: assetId }) }, fetchFn);
|
|
246
|
+
if (!res.ok)
|
|
247
|
+
throw await errorFrom(res, "Attaching the asset");
|
|
248
|
+
return (await res.json());
|
|
249
|
+
}
|
|
250
|
+
const luaString = (s) => JSON.stringify(s);
|
|
251
|
+
/**
|
|
252
|
+
* The engine draws an asset's voxels at its native 1/128 m whatever voxel
|
|
253
|
+
* size the asset was made at, so a 25 cm voxelize renders 32x too small
|
|
254
|
+
* unless the object is scaled up by voxel_size_m * 128.
|
|
255
|
+
*/
|
|
256
|
+
export const ENGINE_NATIVE_VPM = 128;
|
|
257
|
+
export function realSizeScale(asset, scale = 1) {
|
|
258
|
+
return scale * (asset.voxel_size_m ? asset.voxel_size_m * ENGINE_NATIVE_VPM : 1);
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* What every copy of an asset's file is named with: the platform stores it as
|
|
262
|
+
* `<name>-<first 8 of am_uuid>.am` (or .aevv), in the library and in a
|
|
263
|
+
* world's Assets/ folder alike.
|
|
264
|
+
*/
|
|
265
|
+
export function assetFileTag(amUuid) {
|
|
266
|
+
return `-${amUuid.slice(0, 8)}.`;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Server Lua that creates a saved scene object showing an attached asset.
|
|
270
|
+
* The engine lists the attached file (`Assets/<name>-<uuid8>.am`) once the
|
|
271
|
+
* attach copy has landed. Returns `vm-place:ok:<object>:<file>`, or
|
|
272
|
+
* `vm-place:missing` until then.
|
|
273
|
+
*/
|
|
274
|
+
export function placeAssetLua(asset, opts = {}) {
|
|
275
|
+
const [x, y, z] = opts.at ?? [0, 0, 0];
|
|
276
|
+
return [
|
|
277
|
+
`local tag = ${luaString(assetFileTag(asset.am_uuid))}`,
|
|
278
|
+
"local found",
|
|
279
|
+
"for _, a in ipairs(AE:GetAssets()) do",
|
|
280
|
+
" local p = tostring(a.relpath or a.filepath or '')",
|
|
281
|
+
" if p:find(tag, 1, true) and not p:find('.zma', 1, true) then found = a break end",
|
|
282
|
+
"end",
|
|
283
|
+
"if not found then return 'vm-place:missing' end",
|
|
284
|
+
"local ob = Scene:CreateObject()",
|
|
285
|
+
`ob.name = Scene:MakeNameValid(${luaString(opts.name ?? asset.name)})`,
|
|
286
|
+
"ob.save = true",
|
|
287
|
+
`ob.pos = Vec3(${x}, ${y}, ${z})`,
|
|
288
|
+
`ob.rot = Quat.Euler(0, ${opts.yawDeg ?? 0}, 0)`,
|
|
289
|
+
`ob.scale = ${realSizeScale(asset, opts.scale)}`,
|
|
290
|
+
"local vd = ob:AddComponent('VoxelData')",
|
|
291
|
+
"vd.asset = found",
|
|
292
|
+
"vd.syncToClients = true",
|
|
293
|
+
"return 'vm-place:ok:' .. ob.name .. ':' .. tostring(found.relpath or found.filepath)",
|
|
294
|
+
].join("\n");
|
|
295
|
+
}
|
|
296
|
+
/** Read placeAssetLua's answer out of run-lua's output text. */
|
|
297
|
+
export function parsePlaceOutput(output) {
|
|
298
|
+
const text = typeof output === "string" ? output : JSON.stringify(output);
|
|
299
|
+
const ok = /vm-place:ok:([^:"\\]*):([^"\\]*)/.exec(text);
|
|
300
|
+
if (ok)
|
|
301
|
+
return { placed: true, object: ok[1], file: ok[2] };
|
|
302
|
+
if (text.includes("vm-place:missing"))
|
|
303
|
+
return { placed: false };
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Place an attached asset in the running world, waiting up to `waitMs` for
|
|
308
|
+
* the attach copy to show up in the engine's asset list. Places exactly once.
|
|
309
|
+
*/
|
|
310
|
+
export async function placeInWorld(client, asset, opts = {}) {
|
|
311
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
312
|
+
const deadline = Date.now() + (opts.waitMs ?? 60_000);
|
|
313
|
+
for (;;) {
|
|
314
|
+
const output = await client.runLua(placeAssetLua(asset, opts), "server");
|
|
315
|
+
const result = parsePlaceOutput(output);
|
|
316
|
+
if (!result) {
|
|
317
|
+
return { placed: false, reason: `The engine did not place it: ${typeof output === "string" ? output : JSON.stringify(output)}` };
|
|
318
|
+
}
|
|
319
|
+
if (result.placed)
|
|
320
|
+
return result;
|
|
321
|
+
if (Date.now() >= deadline) {
|
|
322
|
+
return {
|
|
323
|
+
placed: false,
|
|
324
|
+
reason: `No Assets/*${assetFileTag(asset.am_uuid)}am in this world. Attach the asset to this project first.`,
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
await sleep(3000);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
// ---------------------------------------------------------------- the whole trip
|
|
331
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
332
|
+
/**
|
|
333
|
+
* Voxelize a local file (uploading it first) or an existing upload id, and by
|
|
334
|
+
* default wait for the library asset. With `wait: false` it returns as soon as
|
|
335
|
+
* the job is queued; poll it with getJob / waitForJob.
|
|
336
|
+
*/
|
|
337
|
+
export async function voxelizeSource(source, opts = {}) {
|
|
338
|
+
const upload = UUID_RE.test(source) && !fs.existsSync(source)
|
|
339
|
+
? await getUpload(source, opts.fetchFn)
|
|
340
|
+
: await uploadFile(source, { onProgress: opts.onUploadProgress, fetchFn: opts.fetchFn });
|
|
341
|
+
let job = await startVoxelize(upload, opts, opts.fetchFn);
|
|
342
|
+
if (opts.wait === false)
|
|
343
|
+
return { upload, job, asset: null };
|
|
344
|
+
job = await waitForJob(job.id, { fetchFn: opts.fetchFn, onUpdate: opts.onJobUpdate, timeoutMs: opts.waitTimeoutMs });
|
|
345
|
+
const asset = job.status === "succeeded" ? await assetForJob(job.id, opts.fetchFn) : null;
|
|
346
|
+
return { upload, job, asset };
|
|
347
|
+
}
|
|
348
|
+
/** File extensions the platform accepts as uploads (backend services/uploads.py). */
|
|
349
|
+
export const UPLOAD_EXTENSIONS = new Set([
|
|
350
|
+
"glb", "gltf", "fbx", "obj", "stl",
|
|
351
|
+
"ply", "pts", "xyz", "e57", "las", "laz",
|
|
352
|
+
"vox", "zip", "7z", "unitypackage",
|
|
353
|
+
]);
|
|
354
|
+
/** Sources as given, with each directory replaced by the uploadable files directly in it, sorted. */
|
|
355
|
+
export function expandSources(sources) {
|
|
356
|
+
const out = [];
|
|
357
|
+
for (const source of sources) {
|
|
358
|
+
if (fs.existsSync(source) && fs.statSync(source).isDirectory()) {
|
|
359
|
+
const files = fs
|
|
360
|
+
.readdirSync(source)
|
|
361
|
+
.filter((n) => UPLOAD_EXTENSIONS.has(n.split(".").pop().toLowerCase()))
|
|
362
|
+
.sort()
|
|
363
|
+
.map((n) => path.join(source, n));
|
|
364
|
+
if (files.length === 0)
|
|
365
|
+
throw new Error(`${source} has no 3D files (${[...UPLOAD_EXTENSIONS].join(", ")}).`);
|
|
366
|
+
out.push(...files);
|
|
367
|
+
}
|
|
368
|
+
else {
|
|
369
|
+
out.push(source);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return out;
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Voxelize many sources (e.g. a city's tiles) with at most `concurrency`
|
|
376
|
+
* uploads and jobs in flight; the platform queue paces the voxelizer itself.
|
|
377
|
+
* One source failing does not stop the others.
|
|
378
|
+
*/
|
|
379
|
+
export async function voxelizeMany(sources, each, concurrency = 4) {
|
|
380
|
+
const results = sources.map((source) => ({ source }));
|
|
381
|
+
let next = 0;
|
|
382
|
+
const worker = async () => {
|
|
383
|
+
while (next < sources.length) {
|
|
384
|
+
const i = next++;
|
|
385
|
+
try {
|
|
386
|
+
results[i].result = await each(sources[i]);
|
|
387
|
+
}
|
|
388
|
+
catch (err) {
|
|
389
|
+
results[i].error = err instanceof Error ? err.message : String(err);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, sources.length) }, worker));
|
|
394
|
+
return results;
|
|
395
|
+
}
|
package/dist/client.js
CHANGED
|
@@ -5,8 +5,11 @@
|
|
|
5
5
|
*
|
|
6
6
|
* Builds are unpacked under <configDir>/client/<dir_uid>/ so re-running
|
|
7
7
|
* `open` is instant, and a newer build lands next to the old one instead
|
|
8
|
-
* of over it. Archives are removed after extraction
|
|
9
|
-
*
|
|
8
|
+
* of over it. Archives are removed after extraction. Once a new build is in
|
|
9
|
+
* place, older builds of the SAME engine iteration are removed unless a client
|
|
10
|
+
* is running from them; other iterations' builds stay, because a client only
|
|
11
|
+
* joins worlds of its own iteration (before 0.6.9, opening a 076 world deleted
|
|
12
|
+
* the 073 client every 073 world needs).
|
|
10
13
|
*/
|
|
11
14
|
import { spawn, spawnSync } from "node:child_process";
|
|
12
15
|
import fs from "node:fs";
|
|
@@ -234,6 +237,18 @@ export function extractArchive(archive, dest, platform) {
|
|
|
234
237
|
const ARCHIVE_RE = /\.(zip|tgz|tar\.gz|tar\.xz|tar\.bz2|tar|dmg)(\.part)?$/i;
|
|
235
238
|
/** A partial download younger than this may belong to another `open` still running. */
|
|
236
239
|
const PART_GRACE_MS = 60 * 60 * 1000;
|
|
240
|
+
/** Builds of another iteration unused for this long are removed anyway. */
|
|
241
|
+
const OTHER_ITERATION_KEEP_MS = 30 * 24 * 3600 * 1000;
|
|
242
|
+
/** The engine branch an installed build came from (its marker), or null. */
|
|
243
|
+
function installedBranch(dir) {
|
|
244
|
+
try {
|
|
245
|
+
const raw = JSON.parse(fs.readFileSync(path.join(dir, MARKER), "utf8"));
|
|
246
|
+
return raw.build?.branch ?? null;
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
237
252
|
/** Whether a running process was started from inside `dir`. */
|
|
238
253
|
function runningFrom(dir) {
|
|
239
254
|
if (process.platform === "win32")
|
|
@@ -244,14 +259,16 @@ function runningFrom(dir) {
|
|
|
244
259
|
return res.stdout.split("\n").some((line) => line.includes(dir + path.sep));
|
|
245
260
|
}
|
|
246
261
|
/**
|
|
247
|
-
* Remove what earlier installs left in the install root:
|
|
248
|
-
*
|
|
249
|
-
*
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
*
|
|
262
|
+
* Remove what earlier installs left in the install root: older builds of the
|
|
263
|
+
* kept build's engine branch, builds of other branches unused for a month,
|
|
264
|
+
* empty folders and archives from a download or unpack that never finished.
|
|
265
|
+
* Only touches what this module creates - a folder carrying the install
|
|
266
|
+
* marker, an empty folder, an archive - so a shared VIRTUALMATTER_CLIENT_DIR
|
|
267
|
+
* keeps anything else. A build a client is still running from is kept.
|
|
268
|
+
* Returns the paths removed.
|
|
253
269
|
*/
|
|
254
|
-
export function pruneOtherBuilds(keepDir, root = path.dirname(keepDir)) {
|
|
270
|
+
export function pruneOtherBuilds(keepDir, root = path.dirname(keepDir), now = Date.now()) {
|
|
271
|
+
const keepBranch = installedBranch(keepDir);
|
|
255
272
|
let entries;
|
|
256
273
|
try {
|
|
257
274
|
entries = fs.readdirSync(root, { withFileTypes: true });
|
|
@@ -266,9 +283,18 @@ export function pruneOtherBuilds(keepDir, root = path.dirname(keepDir)) {
|
|
|
266
283
|
continue;
|
|
267
284
|
try {
|
|
268
285
|
if (e.isDirectory()) {
|
|
269
|
-
const
|
|
286
|
+
const marker = path.join(full, MARKER);
|
|
287
|
+
const installed = fs.existsSync(marker);
|
|
288
|
+
const ours = installed || fs.readdirSync(full).length === 0;
|
|
270
289
|
if (!ours || runningFrom(full))
|
|
271
290
|
continue;
|
|
291
|
+
if (installed) {
|
|
292
|
+
const branch = installedBranch(full);
|
|
293
|
+
const sameIteration = keepBranch === null || branch === null || branch === keepBranch;
|
|
294
|
+
const stale = now - fs.statSync(marker).mtimeMs > OTHER_ITERATION_KEEP_MS;
|
|
295
|
+
if (!sameIteration && !stale)
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
272
298
|
}
|
|
273
299
|
else if (e.isFile()) {
|
|
274
300
|
if (!ARCHIVE_RE.test(e.name))
|
|
@@ -304,8 +330,18 @@ export async function ensureClientInstalled(opts = {}) {
|
|
|
304
330
|
}
|
|
305
331
|
const dir = path.join(clientInstallRoot(), buildKey(build));
|
|
306
332
|
const existing = opts.force ? null : loadInstalled(dir);
|
|
307
|
-
if (existing)
|
|
308
|
-
|
|
333
|
+
if (existing) {
|
|
334
|
+
// Last used now: builds of other iterations are kept while they are in use.
|
|
335
|
+
try {
|
|
336
|
+
const marker = path.join(dir, MARKER);
|
|
337
|
+
const t = new Date();
|
|
338
|
+
fs.utimesSync(marker, t, t);
|
|
339
|
+
}
|
|
340
|
+
catch {
|
|
341
|
+
/* tidiness only */
|
|
342
|
+
}
|
|
343
|
+
return giveBundleItsOwnName(existing);
|
|
344
|
+
}
|
|
309
345
|
const url = build.url.startsWith("http") ? build.url : `${apiBaseFor(build)}${build.url}`;
|
|
310
346
|
const archive = path.join(clientInstallRoot(), build.filename ?? path.basename(build.url));
|
|
311
347
|
log(`Downloading the Virtual Matter client for ${platform}${build.file_size ? ` (${formatMb(build.file_size)})` : ""} ...`);
|
|
@@ -348,15 +384,62 @@ export async function ensureClientInstalled(opts = {}) {
|
|
|
348
384
|
}
|
|
349
385
|
}
|
|
350
386
|
}
|
|
351
|
-
const installed = { platform, dir, entrypoint, build };
|
|
387
|
+
const installed = giveBundleItsOwnName({ platform, dir, entrypoint, build }, false);
|
|
352
388
|
// Keep the cache out of the OS's app database (see dropFromLaunchServices).
|
|
353
|
-
dropFromLaunchServices(entrypoint, platform);
|
|
389
|
+
dropFromLaunchServices(installed.entrypoint, platform);
|
|
354
390
|
fs.writeFileSync(path.join(dir, MARKER), JSON.stringify(installed, null, 2) + "\n");
|
|
355
391
|
const pruned = pruneOtherBuilds(dir);
|
|
356
392
|
if (pruned.length)
|
|
357
393
|
log(`Removed ${pruned.length === 1 ? "an older build" : `${pruned.length} older builds and leftovers`}: ${pruned.map((p) => path.basename(p)).join(", ")}`);
|
|
358
394
|
return installed;
|
|
359
395
|
}
|
|
396
|
+
/** "release/iteration073" -> "iteration073"; another branch -> its last path part. */
|
|
397
|
+
export function iterationSuffix(branch) {
|
|
398
|
+
if (!branch)
|
|
399
|
+
return null;
|
|
400
|
+
const tail = branch.split("/").pop() ?? branch;
|
|
401
|
+
return tail.replace(/[^A-Za-z0-9._-]/g, "_") || null;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* On macOS, rename the cached bundle to "<name> <iteration>.app".
|
|
405
|
+
*
|
|
406
|
+
* The engine hands a world link from a copy outside /Applications to
|
|
407
|
+
* "/Applications/<same bundle name>" when that one is a newer build
|
|
408
|
+
* (ForwardLinkToInstalledCopy, engine Core/Platform/Apple/ApplePlatform.mm).
|
|
409
|
+
* With the 076 app installed, the 073 client this CLI fetched for a 073 world
|
|
410
|
+
* passed the link on to the 076 app, which cannot join a 073 server. The
|
|
411
|
+
* engine looks the installed copy up by bundle NAME, so a cached copy with its
|
|
412
|
+
* own name has no installed counterpart and keeps the link. The bundle's
|
|
413
|
+
* signature does not cover its folder name. Also renames a build unpacked by
|
|
414
|
+
* an older CLI (`persist`: rewrite its marker).
|
|
415
|
+
*/
|
|
416
|
+
export function giveBundleItsOwnName(installed, persist = true) {
|
|
417
|
+
if (installed.platform !== "macos" || !installed.entrypoint.endsWith(".app"))
|
|
418
|
+
return installed;
|
|
419
|
+
const suffix = iterationSuffix(installed.build.branch);
|
|
420
|
+
if (!suffix)
|
|
421
|
+
return installed;
|
|
422
|
+
const base = path.basename(installed.entrypoint, ".app");
|
|
423
|
+
if (base.endsWith(` ${suffix}`))
|
|
424
|
+
return installed;
|
|
425
|
+
const renamed = path.join(path.dirname(installed.entrypoint), `${base} ${suffix}.app`);
|
|
426
|
+
try {
|
|
427
|
+
fs.renameSync(installed.entrypoint, renamed);
|
|
428
|
+
}
|
|
429
|
+
catch {
|
|
430
|
+
return installed; // running from it, or read-only: launch it as it is
|
|
431
|
+
}
|
|
432
|
+
const next = { ...installed, entrypoint: renamed };
|
|
433
|
+
if (persist) {
|
|
434
|
+
try {
|
|
435
|
+
fs.writeFileSync(path.join(installed.dir, MARKER), JSON.stringify(next, null, 2) + "\n");
|
|
436
|
+
}
|
|
437
|
+
catch {
|
|
438
|
+
/* the marker keeps the old path, so the next run downloads this build again */
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return next;
|
|
442
|
+
}
|
|
360
443
|
function apiBaseFor(_build) {
|
|
361
444
|
// Download paths are relative to the platform origin the catalog came from.
|
|
362
445
|
return (process.env.VIRTUALMATTER_API_BASE ?? "https://make.virtualmatter.ai").replace(/\/+$/, "");
|
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
|
+
}
|