topotopo 0.5.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +2 -1
- package/dist/core/tangents.d.ts +9 -1
- package/dist/core/tangents.js +61 -11
- package/dist/graph/engine.d.ts +7 -0
- package/dist/graph/engine.js +54 -6
- package/dist/nodes/bake.js +2 -2
- package/dist/render/raster.js +4 -0
- package/dist/session.d.ts +5 -1
- package/dist/session.js +93 -40
- package/dist/viewer/app/api.js +5 -2
- package/dist/viewer/app/cooking.js +9 -3
- package/dist/viewer/app/main.js +18 -4
- package/dist/viewer/server.js +20 -3
- package/integrations/godot/addons/topotopo/plugin.cfg +1 -1
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -92,7 +92,8 @@ const graphName = (file) => path.basename(file).replace(/\.json$/i, '').replace(
|
|
|
92
92
|
const prog = import.meta.url.endsWith('.ts') ? 'node src/cli.ts' : 'topotopo';
|
|
93
93
|
// the hints of every command name it so
|
|
94
94
|
setProgram(prog);
|
|
95
|
-
|
|
95
|
+
// the global version flag is the first argument (or the only one); later ones belong to the command (use <package> --version 1.0)
|
|
96
|
+
if (['-v', '-V', '--version'].includes(argv[0] ?? '')) {
|
|
96
97
|
console.log(`topotopo ${TOPOTOPO_VERSION}`);
|
|
97
98
|
process.exit(0);
|
|
98
99
|
}
|
package/dist/core/tangents.d.ts
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import type { Geometry } from './geometry.ts';
|
|
2
|
-
/**
|
|
2
|
+
/** loadMikkTSpace() starts a fresh MikkTSpace instance when the heap of the current one is larger than this. */
|
|
3
|
+
export declare const MIKK_RESET_BYTES: number;
|
|
4
|
+
/**
|
|
5
|
+
* Load and initialise the MikkTSpace WebAssembly module; when the loaded instance's heap has grown past
|
|
6
|
+
* MIKK_RESET_BYTES (or it aborted), replace it with a fresh one. Callers await this before each synchronous run of
|
|
7
|
+
* tangent work (an export, a render, a bake). While a replacement loads, mikkTSpaceReady() is false.
|
|
8
|
+
*/
|
|
3
9
|
export declare function loadMikkTSpace(): Promise<void>;
|
|
10
|
+
/** Bytes of WebAssembly memory the loaded MikkTSpace instance holds (0 when none is loaded). */
|
|
11
|
+
export declare const mikkTSpaceHeapBytes: () => number;
|
|
4
12
|
/** True once loadMikkTSpace() has finished. */
|
|
5
13
|
export declare const mikkTSpaceReady: () => boolean;
|
|
6
14
|
export interface TangentDiagnostics {
|
package/dist/core/tangents.js
CHANGED
|
@@ -6,25 +6,75 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
6
6
|
}
|
|
7
7
|
return path;
|
|
8
8
|
};
|
|
9
|
+
/** loadMikkTSpace() starts a fresh MikkTSpace instance when the heap of the current one is larger than this. */
|
|
10
|
+
export const MIKK_RESET_BYTES = 256 * 2 ** 20;
|
|
9
11
|
let mod = null;
|
|
10
12
|
let loading = null;
|
|
11
|
-
|
|
13
|
+
let spent = false; // the instance aborted (out of memory): replace it on the next load
|
|
14
|
+
/**
|
|
15
|
+
* Load and initialise the MikkTSpace WebAssembly module; when the loaded instance's heap has grown past
|
|
16
|
+
* MIKK_RESET_BYTES (or it aborted), replace it with a fresh one. Callers await this before each synchronous run of
|
|
17
|
+
* tangent work (an export, a render, a bake). While a replacement loads, mikkTSpaceReady() is false.
|
|
18
|
+
*/
|
|
12
19
|
export async function loadMikkTSpace() {
|
|
13
|
-
if (mod)
|
|
20
|
+
if (mod && !spent && mikkTSpaceHeapBytes() <= MIKK_RESET_BYTES)
|
|
14
21
|
return;
|
|
15
22
|
if (!loading) {
|
|
23
|
+
const old = mod;
|
|
24
|
+
mod = null;
|
|
16
25
|
loading = (async () => {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
26
|
+
try {
|
|
27
|
+
let m;
|
|
28
|
+
if (old) {
|
|
29
|
+
m = old;
|
|
30
|
+
m.dispose();
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
const spec = 'three/examples/jsm/libs/mikktspace.module.js';
|
|
34
|
+
m = await import(__rewriteRelativeImportExtension(spec));
|
|
35
|
+
}
|
|
36
|
+
await m.ready;
|
|
37
|
+
spent = false;
|
|
38
|
+
mod = m;
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
loading = null;
|
|
42
|
+
}
|
|
21
43
|
})();
|
|
22
|
-
loading.catch(() => { loading = null; });
|
|
23
44
|
}
|
|
24
|
-
|
|
45
|
+
await loading;
|
|
46
|
+
}
|
|
47
|
+
/** Bytes of WebAssembly memory the loaded MikkTSpace instance holds (0 when none is loaded). */
|
|
48
|
+
export const mikkTSpaceHeapBytes = () => mod?.wasm?.memory.buffer.byteLength ?? 0;
|
|
49
|
+
/** One generateTangents call on the raw exports: 4 floats (xyz, w) per corner. */
|
|
50
|
+
function generate(w, P, N, T) {
|
|
51
|
+
const pass = (a) => {
|
|
52
|
+
const p = w.__wbindgen_malloc(a.length * 4) >>> 0;
|
|
53
|
+
new Float32Array(w.memory.buffer, p, a.length).set(a);
|
|
54
|
+
return p;
|
|
55
|
+
};
|
|
56
|
+
const ret = w.__wbindgen_add_to_stack_pointer(-16) >>> 0;
|
|
57
|
+
try {
|
|
58
|
+
try {
|
|
59
|
+
w.generateTangents(ret, pass(P), P.length, pass(N), N.length, pass(T), T.length);
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
if (!(e instanceof globalThis.WebAssembly.RuntimeError))
|
|
63
|
+
throw e; // a trap: in practice memory.grow failed at 4 GiB
|
|
64
|
+
spent = true;
|
|
65
|
+
throw new Error(`MikkTSpace ran out of WebAssembly memory (${w.memory.buffer.byteLength / 2 ** 20 | 0} MiB) on ${P.length / 9} triangles`);
|
|
66
|
+
}
|
|
67
|
+
const [ptr, len] = new Uint32Array(w.memory.buffer, ret, 2);
|
|
68
|
+
const out = new Float32Array(w.memory.buffer, ptr, len).slice();
|
|
69
|
+
w.__wbindgen_free(ptr, len * 4);
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
w.__wbindgen_add_to_stack_pointer(16);
|
|
74
|
+
}
|
|
25
75
|
}
|
|
26
76
|
/** True once loadMikkTSpace() has finished. */
|
|
27
|
-
export const mikkTSpaceReady = () => mod
|
|
77
|
+
export const mikkTSpaceReady = () => mod?.wasm != null;
|
|
28
78
|
/** uv triangles whose doubled area is below this fraction of their squared edge lengths are collapsed. */
|
|
29
79
|
const UV_DEGENERATE = 1e-9;
|
|
30
80
|
/**
|
|
@@ -33,7 +83,7 @@ const UV_DEGENERATE = 1e-9;
|
|
|
33
83
|
* loaded.
|
|
34
84
|
*/
|
|
35
85
|
export function mikkTangents(pos, nrm, uv) {
|
|
36
|
-
if (!mod)
|
|
86
|
+
if (!mod?.wasm)
|
|
37
87
|
throw new Error('MikkTSpace is not loaded: await loadMikkTSpace() first (exportGLB, renderPBR and bake_normal do)');
|
|
38
88
|
const nt = Math.floor(pos.length / 9);
|
|
39
89
|
const diag = { triangles: nt, uvNonFinite: 0, uvDegenerate: 0, fallbackCorners: 0, firstBad: -1 };
|
|
@@ -75,7 +125,7 @@ export function mikkTangents(pos, nrm, uv) {
|
|
|
75
125
|
N[i + 2] = 1;
|
|
76
126
|
}
|
|
77
127
|
}
|
|
78
|
-
const out = nt ? mod.
|
|
128
|
+
const out = nt ? generate(mod.wasm, P, N, T) : new Float32Array(0);
|
|
79
129
|
for (let t = 0; t < nt; t++)
|
|
80
130
|
for (let k = 0; k < 3; k++) {
|
|
81
131
|
const c = t * 3 + k, o = c * 4, n = c * 3;
|
package/dist/graph/engine.d.ts
CHANGED
|
@@ -111,8 +111,15 @@ export interface FrameRange {
|
|
|
111
111
|
end: number;
|
|
112
112
|
step?: number;
|
|
113
113
|
}
|
|
114
|
+
/**
|
|
115
|
+
* Approximate memory of a geometry for the cache budget: topology, attributes, groups and volume buffers. With `seen`,
|
|
116
|
+
* a buffer already in the set is not counted again (shared between geometries); the buffers counted are added to it.
|
|
117
|
+
*/
|
|
118
|
+
export declare function geoBytes(g: Geometry, seen?: Set<ArrayBuffer>): number;
|
|
114
119
|
declare class GeoCache {
|
|
115
120
|
private map;
|
|
121
|
+
/** volume buffer → entries holding it: a shared buffer is charged once */
|
|
122
|
+
private owners;
|
|
116
123
|
private bytes;
|
|
117
124
|
maxBytes: number;
|
|
118
125
|
constructor(maxBytes?: number);
|
package/dist/graph/engine.js
CHANGED
|
@@ -49,7 +49,19 @@ import { VAR_NAME_HINT, varNameError } from './vars.js';
|
|
|
49
49
|
import { codeVarNames, pickVars } from '../core/usercode.js';
|
|
50
50
|
export { STOPPED };
|
|
51
51
|
// ---------------------------------------------------------------- cache
|
|
52
|
-
|
|
52
|
+
/** The large typed-array buffers the volumes of a geometry hold (image and heightfield layers, SDF grid samples), each once. */
|
|
53
|
+
function volumeBuffers(g) {
|
|
54
|
+
const out = new Set();
|
|
55
|
+
for (const v of g.volumes) {
|
|
56
|
+
if (v.kind === 'grid')
|
|
57
|
+
out.add(v.values.buffer);
|
|
58
|
+
else if (v.kind === 'image' || v.kind === 'heightfield')
|
|
59
|
+
for (const l of v.layers.values())
|
|
60
|
+
out.add(l.buffer);
|
|
61
|
+
}
|
|
62
|
+
return [...out];
|
|
63
|
+
}
|
|
64
|
+
function baseBytes(g) {
|
|
53
65
|
let b = g.primStart.byteLength + g.vertexPoint.byteLength + g.primClosed.byteLength + 256;
|
|
54
66
|
// packed: the per-prim arrays (sources are shared with the nodes that made them)
|
|
55
67
|
if (g.primKind)
|
|
@@ -63,8 +75,26 @@ function geoBytes(g) {
|
|
|
63
75
|
b += m.byteLength;
|
|
64
76
|
return b;
|
|
65
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Approximate memory of a geometry for the cache budget: topology, attributes, groups and volume buffers. With `seen`,
|
|
80
|
+
* a buffer already in the set is not counted again (shared between geometries); the buffers counted are added to it.
|
|
81
|
+
*/
|
|
82
|
+
export function geoBytes(g, seen) {
|
|
83
|
+
let b = baseBytes(g);
|
|
84
|
+
for (const buf of volumeBuffers(g)) {
|
|
85
|
+
if (seen) {
|
|
86
|
+
if (seen.has(buf))
|
|
87
|
+
continue;
|
|
88
|
+
seen.add(buf);
|
|
89
|
+
}
|
|
90
|
+
b += buf.byteLength;
|
|
91
|
+
}
|
|
92
|
+
return b;
|
|
93
|
+
}
|
|
66
94
|
class GeoCache {
|
|
67
95
|
map = new Map();
|
|
96
|
+
/** volume buffer → entries holding it: a shared buffer is charged once */
|
|
97
|
+
owners = new Map();
|
|
68
98
|
bytes = 0;
|
|
69
99
|
maxBytes;
|
|
70
100
|
constructor(maxBytes = 1.5e9) { this.maxBytes = maxBytes; }
|
|
@@ -79,19 +109,37 @@ class GeoCache {
|
|
|
79
109
|
set(k, geo) {
|
|
80
110
|
if (this.map.has(k))
|
|
81
111
|
return;
|
|
82
|
-
const
|
|
83
|
-
|
|
112
|
+
const own = baseBytes(geo), bufs = volumeBuffers(geo);
|
|
113
|
+
let add = own;
|
|
114
|
+
for (const buf of bufs)
|
|
115
|
+
if (!this.owners.has(buf))
|
|
116
|
+
add += buf.byteLength;
|
|
117
|
+
if (add > this.maxBytes / 2)
|
|
84
118
|
return;
|
|
85
|
-
|
|
86
|
-
|
|
119
|
+
for (const buf of bufs) {
|
|
120
|
+
if (!this.owners.has(buf))
|
|
121
|
+
this.bytes += buf.byteLength;
|
|
122
|
+
this.owners.set(buf, (this.owners.get(buf) ?? 0) + 1);
|
|
123
|
+
}
|
|
124
|
+
this.map.set(k, { geo, bytes: own });
|
|
125
|
+
this.bytes += own;
|
|
87
126
|
for (const [key, e] of this.map) {
|
|
88
127
|
if (this.bytes <= this.maxBytes)
|
|
89
128
|
break;
|
|
90
129
|
this.map.delete(key);
|
|
91
130
|
this.bytes -= e.bytes;
|
|
131
|
+
for (const buf of volumeBuffers(e.geo)) {
|
|
132
|
+
const n = (this.owners.get(buf) ?? 1) - 1;
|
|
133
|
+
if (n > 0)
|
|
134
|
+
this.owners.set(buf, n);
|
|
135
|
+
else {
|
|
136
|
+
this.owners.delete(buf);
|
|
137
|
+
this.bytes -= buf.byteLength;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
92
140
|
}
|
|
93
141
|
}
|
|
94
|
-
clear() { this.map.clear(); this.bytes = 0; }
|
|
142
|
+
clear() { this.map.clear(); this.owners.clear(); this.bytes = 0; }
|
|
95
143
|
get stats() { return { entries: this.map.size, mb: +(this.bytes / 1e6).toFixed(1) }; }
|
|
96
144
|
}
|
|
97
145
|
// ---------------------------------------------------------------- helpers
|
package/dist/nodes/bake.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Image, MAIN_LAYER } from '../core/image.js';
|
|
2
2
|
import { averagedVertexNormals, bakeSamples, curvatureEdges, dilate, edgeGrid, idColor, interpolate, interpolateCorners, normalize3, resolve, uvIslands, vertexPositions, vertexValues, } from '../core/bake.js';
|
|
3
|
-
import { cornerTangents, loadMikkTSpace, mikkTSpaceReady, shadingFrame } from '../core/tangents.js';
|
|
3
|
+
import { MIKK_RESET_BYTES, cornerTangents, loadMikkTSpace, mikkTSpaceHeapBytes, mikkTSpaceReady, shadingFrame } from '../core/tangents.js';
|
|
4
4
|
import { RayScene, bboxDiagonal } from '../core/analysis.js';
|
|
5
5
|
import { pointNormals, resolveVertexNormals, triangulate } from '../core/topology.js';
|
|
6
6
|
import { defineNode } from '../graph/registry.js';
|
|
@@ -568,7 +568,7 @@ defineBake({
|
|
|
568
568
|
return finish(b, out, 4, [0.5, 0.5, 1, 1]);
|
|
569
569
|
});
|
|
570
570
|
};
|
|
571
|
-
return mikkTSpaceReady() ? bakeWith() : loadMikkTSpace().then(bakeWith);
|
|
571
|
+
return mikkTSpaceReady() && mikkTSpaceHeapBytes() <= MIKK_RESET_BYTES ? bakeWith() : loadMikkTSpace().then(bakeWith);
|
|
572
572
|
},
|
|
573
573
|
});
|
|
574
574
|
defineBake({
|
package/dist/render/raster.js
CHANGED
|
@@ -26,6 +26,7 @@ import { withSdfGridPreview } from '../core/sdfgrid.js';
|
|
|
26
26
|
import { drawTextureView, textureSampler, withMaterialPreview } from './texview.js';
|
|
27
27
|
import { EMPTY_ATTRIB } from '../core/scene.js';
|
|
28
28
|
import { pbrScene, preparePBR } from './pbr.js';
|
|
29
|
+
import { loadMikkTSpace } from '../core/tangents.js';
|
|
29
30
|
import { decodePNG } from '../io/png-decode.js';
|
|
30
31
|
/**
|
|
31
32
|
* Named three-quarter views: persp views at these azimuths (degrees; 0 = the camera on +Z looking at the front, 90 =
|
|
@@ -211,6 +212,9 @@ export async function renderGeometryAsync(g, o = {}, readFile) {
|
|
|
211
212
|
o = { ...o, pbrTextures: await preparePBR(g, readFile) };
|
|
212
213
|
if (o.underlay && !o.underlayImage)
|
|
213
214
|
o = { ...o, underlayImage: await readUnderlay(o.underlay, readFile) };
|
|
215
|
+
// last, so no other task replaces the MikkTSpace instance between this and the synchronous render
|
|
216
|
+
if (o.shading === 'pbr')
|
|
217
|
+
await loadMikkTSpace();
|
|
214
218
|
return renderGeometry(g, o);
|
|
215
219
|
}
|
|
216
220
|
/** A reference image for the underlay option: a PNG read through readFile (errors say what to pass instead). */
|
package/dist/session.d.ts
CHANGED
|
@@ -293,15 +293,19 @@ export declare class Session {
|
|
|
293
293
|
kind?: CookKind;
|
|
294
294
|
signal?: StopSignal;
|
|
295
295
|
}): Promise<CookReport>;
|
|
296
|
+
/** the folder each watcher follows; a folder that is missing has none until it is made again */
|
|
296
297
|
private watchers;
|
|
297
298
|
private watchTimers;
|
|
299
|
+
private watching;
|
|
298
300
|
/**
|
|
299
301
|
* Follow what other processes write into graphs/ and assets/, and in a package the graph files beside its manifest (a
|
|
300
302
|
* second Session on the same folder: the web app's editor next to an MCP server, or a person editing the JSON). A
|
|
301
303
|
* graph file whose content differs from the stored graph replaces it and notifies the listeners; a removed file
|
|
302
304
|
* removes the graph. Our own writes read back equal, so they change nothing. An asset whose content changed is
|
|
303
305
|
* registered again and every graph is notified (any may use it); a removed asset stays registered until the next
|
|
304
|
-
* load(). Two writers to one graph: the last write wins.
|
|
306
|
+
* load(). Two writers to one graph: the last write wins. graphs/ and assets/ may be removed and made again (a git
|
|
307
|
+
* checkout, stash or branch switch): the package folder is followed too, and a folder made again is followed again
|
|
308
|
+
* and read again whole, as if each of its files had changed.
|
|
305
309
|
*/
|
|
306
310
|
watch(): void;
|
|
307
311
|
/** Stop following the folders (watch()). */
|
package/dist/session.js
CHANGED
|
@@ -710,51 +710,93 @@ export class Session {
|
|
|
710
710
|
this.notifyActivity(name);
|
|
711
711
|
}
|
|
712
712
|
}
|
|
713
|
-
|
|
713
|
+
/** the folder each watcher follows; a folder that is missing has none until it is made again */
|
|
714
|
+
watchers = new Map();
|
|
714
715
|
watchTimers = new Map();
|
|
716
|
+
watching = false;
|
|
715
717
|
/**
|
|
716
718
|
* Follow what other processes write into graphs/ and assets/, and in a package the graph files beside its manifest (a
|
|
717
719
|
* second Session on the same folder: the web app's editor next to an MCP server, or a person editing the JSON). A
|
|
718
720
|
* graph file whose content differs from the stored graph replaces it and notifies the listeners; a removed file
|
|
719
721
|
* removes the graph. Our own writes read back equal, so they change nothing. An asset whose content changed is
|
|
720
722
|
* registered again and every graph is notified (any may use it); a removed asset stays registered until the next
|
|
721
|
-
* load(). Two writers to one graph: the last write wins.
|
|
723
|
+
* load(). Two writers to one graph: the last write wins. graphs/ and assets/ may be removed and made again (a git
|
|
724
|
+
* checkout, stash or branch switch): the package folder is followed too, and a folder made again is followed again
|
|
725
|
+
* and read again whole, as if each of its files had changed.
|
|
722
726
|
*/
|
|
723
727
|
watch() {
|
|
724
|
-
if (this.
|
|
728
|
+
if (this.watching)
|
|
725
729
|
return;
|
|
726
|
-
|
|
730
|
+
this.watching = true;
|
|
731
|
+
const later = (key, ms, fn) => {
|
|
732
|
+
clearTimeout(this.watchTimers.get(key));
|
|
733
|
+
this.watchTimers.set(key, setTimeout(() => { this.watchTimers.delete(key); if (this.watching)
|
|
734
|
+
fn(); }, ms).unref());
|
|
735
|
+
};
|
|
736
|
+
// persist() is not atomic: let the writer finish, and read again if the JSON is still half written
|
|
737
|
+
const settle = (dir, name, apply) => {
|
|
738
|
+
let tries = 0;
|
|
739
|
+
const run = () => {
|
|
740
|
+
try {
|
|
741
|
+
apply(name, path.join(dir, name + '.json'));
|
|
742
|
+
}
|
|
743
|
+
catch (e) {
|
|
744
|
+
if (e instanceof SyntaxError && ++tries < 5)
|
|
745
|
+
later(dir + '|' + name, 100, run);
|
|
746
|
+
}
|
|
747
|
+
};
|
|
748
|
+
later(dir + '|' + name, 150, run);
|
|
749
|
+
};
|
|
750
|
+
const attach = (dir, onFile, onGone, onEntry) => {
|
|
751
|
+
const old = this.watchers.get(dir);
|
|
752
|
+
this.watchers.delete(dir);
|
|
753
|
+
old?.close();
|
|
754
|
+
let w;
|
|
727
755
|
try {
|
|
728
|
-
|
|
756
|
+
w = fs.watch(dir, (ev, f) => {
|
|
729
757
|
const rel = f ? String(f) : '';
|
|
730
|
-
//
|
|
731
|
-
if (path.isAbsolute(rel)) {
|
|
732
|
-
|
|
758
|
+
// the folder itself was removed: Windows names it by its absolute path, Linux by its own name
|
|
759
|
+
if (path.isAbsolute(rel) || (rel === path.basename(dir) && !fs.existsSync(dir))) {
|
|
760
|
+
gone();
|
|
733
761
|
return;
|
|
734
762
|
}
|
|
763
|
+
if (ev === 'rename' && onEntry)
|
|
764
|
+
onEntry(rel);
|
|
735
765
|
if (!rel.endsWith('.json') || rel.includes(path.sep) || rel.startsWith('.'))
|
|
736
766
|
return;
|
|
737
|
-
|
|
738
|
-
clearTimeout(this.watchTimers.get(key));
|
|
739
|
-
// persist() is not atomic: let the writer finish, and read again if the JSON is still half written
|
|
740
|
-
let tries = 0;
|
|
741
|
-
const run = () => {
|
|
742
|
-
this.watchTimers.delete(key);
|
|
743
|
-
try {
|
|
744
|
-
apply(name, path.join(dir, rel));
|
|
745
|
-
}
|
|
746
|
-
catch (e) {
|
|
747
|
-
if (e instanceof SyntaxError && ++tries < 5)
|
|
748
|
-
this.watchTimers.set(key, setTimeout(run, 100).unref());
|
|
749
|
-
}
|
|
750
|
-
};
|
|
751
|
-
this.watchTimers.set(key, setTimeout(run, 150).unref());
|
|
767
|
+
onFile(rel.slice(0, -'.json'.length));
|
|
752
768
|
});
|
|
753
|
-
w.on('error', () => w.close());
|
|
754
|
-
w.unref();
|
|
755
|
-
this.watchers.push(w);
|
|
756
769
|
}
|
|
757
|
-
catch {
|
|
770
|
+
catch {
|
|
771
|
+
return; /* no folder: the package folder's watcher hears when it is made */
|
|
772
|
+
}
|
|
773
|
+
// a removed folder: close at once (Windows keeps a watched folder from going while its handle is open)
|
|
774
|
+
const gone = () => {
|
|
775
|
+
if (this.watchers.get(dir) !== w)
|
|
776
|
+
return;
|
|
777
|
+
this.watchers.delete(dir);
|
|
778
|
+
w.close();
|
|
779
|
+
onGone();
|
|
780
|
+
};
|
|
781
|
+
w.on('error', gone);
|
|
782
|
+
w.on('close', gone);
|
|
783
|
+
w.unref();
|
|
784
|
+
this.watchers.set(dir, w);
|
|
785
|
+
};
|
|
786
|
+
// graphs/ or assets/: follow its files; when it goes or comes back, follow the folder now there and read it again
|
|
787
|
+
const child = (dir, apply, known) => {
|
|
788
|
+
const reopen = () => {
|
|
789
|
+
attach(dir, (name) => settle(dir, name, apply), () => later(dir, 150, reopen));
|
|
790
|
+
let files = [];
|
|
791
|
+
try {
|
|
792
|
+
files = fs.readdirSync(dir).filter((f) => f.endsWith('.json') && !f.startsWith('.')).map((f) => f.slice(0, -'.json'.length));
|
|
793
|
+
}
|
|
794
|
+
catch { /* gone */ }
|
|
795
|
+
for (const name of new Set([...known(), ...files]))
|
|
796
|
+
settle(dir, name, apply);
|
|
797
|
+
};
|
|
798
|
+
attach(dir, (name) => settle(dir, name, apply), () => later(dir, 150, reopen));
|
|
799
|
+
return () => later(dir, 150, reopen);
|
|
758
800
|
};
|
|
759
801
|
const graphChanged = (name, file) => {
|
|
760
802
|
if (!NAME_RE.test(name) || this.graphFile(name) !== file)
|
|
@@ -779,17 +821,8 @@ export class Session {
|
|
|
779
821
|
this.lastReport.delete(name);
|
|
780
822
|
this.bump(name);
|
|
781
823
|
};
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
if (topoFiles(this.dir).length)
|
|
785
|
-
on(this.dir, (name, file) => {
|
|
786
|
-
if (fs.existsSync(path.join(this.graphDir, name + '.json')))
|
|
787
|
-
return;
|
|
788
|
-
if (!this.graphs.has(name) && fs.existsSync(file))
|
|
789
|
-
this.besidePackage.set(name, file);
|
|
790
|
-
graphChanged(name, file);
|
|
791
|
-
});
|
|
792
|
-
on(this.assetDir, (name, file) => {
|
|
824
|
+
const graphsBack = child(this.graphDir, graphChanged, () => [...this.graphs.keys()].filter((n) => this.graphFile(n) === path.join(this.graphDir, n + '.json')));
|
|
825
|
+
const assetsBack = child(this.assetDir, (name, file) => {
|
|
793
826
|
if (!fs.existsSync(file))
|
|
794
827
|
return;
|
|
795
828
|
const spec = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
@@ -801,15 +834,35 @@ export class Session {
|
|
|
801
834
|
this.lastReport.delete(g);
|
|
802
835
|
this.bump(g);
|
|
803
836
|
}
|
|
837
|
+
}, () => []);
|
|
838
|
+
// the package folder: graphs/ and assets/ removed or made again, and a package's graph files beside its manifest,
|
|
839
|
+
// when graphs/ has no graph of that name
|
|
840
|
+
const beside = (name, file) => {
|
|
841
|
+
if (fs.existsSync(path.join(this.graphDir, name + '.json')))
|
|
842
|
+
return;
|
|
843
|
+
if (!this.graphs.has(name) && fs.existsSync(file))
|
|
844
|
+
this.besidePackage.set(name, file);
|
|
845
|
+
graphChanged(name, file);
|
|
846
|
+
};
|
|
847
|
+
const isPackage = topoFiles(this.dir).length > 0;
|
|
848
|
+
const top = path.basename(this.graphDir), assets = path.basename(this.assetDir);
|
|
849
|
+
attach(this.dir, (name) => { if (isPackage)
|
|
850
|
+
settle(this.dir, name, beside); }, () => { }, (rel) => {
|
|
851
|
+
if (rel === top)
|
|
852
|
+
graphsBack();
|
|
853
|
+
else if (rel === assets)
|
|
854
|
+
assetsBack();
|
|
804
855
|
});
|
|
805
856
|
}
|
|
806
857
|
/** Stop following the folders (watch()). */
|
|
807
858
|
unwatch() {
|
|
808
|
-
|
|
859
|
+
this.watching = false;
|
|
860
|
+
const ws = [...this.watchers.values()];
|
|
861
|
+
this.watchers.clear();
|
|
862
|
+
for (const w of ws)
|
|
809
863
|
w.close();
|
|
810
864
|
for (const t of this.watchTimers.values())
|
|
811
865
|
clearTimeout(t);
|
|
812
|
-
this.watchers = [];
|
|
813
866
|
this.watchTimers.clear();
|
|
814
867
|
}
|
|
815
868
|
}
|
package/dist/viewer/app/api.js
CHANGED
|
@@ -11,11 +11,14 @@ async function json(url, init) {
|
|
|
11
11
|
const j = await res.json().catch(() => ({ ok: false, error: `${res.status} ${res.statusText}` }));
|
|
12
12
|
return { status: res.status, j };
|
|
13
13
|
}
|
|
14
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* A GLB route: {ok, buf} or {ok: false, error, stopped?, preview?} (stopped: the node its cook was stopped at; preview:
|
|
16
|
+
* the result cooked but its GLB could not be written).
|
|
17
|
+
*/
|
|
15
18
|
async function glb(url) {
|
|
16
19
|
let res;
|
|
17
20
|
try { res = await fetch(url); } catch { return fail(offline); }
|
|
18
|
-
if (!res.ok) { const j = await res.json().catch(() => ({})); return { ...fail(j.error ?? `${res.status} ${res.statusText}`), ...(j.stopped ? { stopped: j.stopped } : {}) }; }
|
|
21
|
+
if (!res.ok) { const j = await res.json().catch(() => ({})); return { ...fail(j.error ?? `${res.status} ${res.statusText}`), ...(j.stopped ? { stopped: j.stopped } : {}), ...(j.preview ? { preview: true } : {}) }; }
|
|
19
22
|
return { ok: true, buf: await res.arrayBuffer() };
|
|
20
23
|
}
|
|
21
24
|
const post = (body) => ({ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
|
@@ -20,9 +20,11 @@ export const SHOW_AFTER = 150;
|
|
|
20
20
|
/**
|
|
21
21
|
* The line for a graph's cook state: {kind, text, title}. kind: "running", "stopping", "ok", "failed", "stopped" or
|
|
22
22
|
* "none". `state`: {running: {cooks, kinds, elapsed, node, nodeElapsed, inner, stopping} | null, last: {ok, ms,
|
|
23
|
-
* stopped?, error?: {node, message}} | null}; `since`: ms since it arrived, added to the running times.
|
|
23
|
+
* stopped?, error?: {node, message}} | null}; `since`: ms since it arrived, added to the running times. `preview`: why the
|
|
24
|
+
* cooked result could not be shown ("preview failed: …", the GLB route's or the page's), a failure the view keeps the
|
|
25
|
+
* last shown result through.
|
|
24
26
|
*/
|
|
25
|
-
export function cookLine(state, since = 0) {
|
|
27
|
+
export function cookLine(state, since = 0, preview = null) {
|
|
26
28
|
const r = state?.running;
|
|
27
29
|
if (r && (r.elapsed + since >= SHOW_AFTER || r.stopping)) {
|
|
28
30
|
const where = r.node ? `${r.node}${r.inner ? ` › ${r.inner}` : ''}` : '';
|
|
@@ -44,12 +46,16 @@ export function cookLine(state, since = 0) {
|
|
|
44
46
|
return { kind: 'running', text: `${verb}${where ? ` ${where}` : ''} · ${total}`, title: `${node}${r.cooks > 1 ? ` (${r.cooks} cooks of this graph)` : ''}. Stop ends it at the next node; changing a value starts over with the new value.` };
|
|
45
47
|
}
|
|
46
48
|
const l = state?.last;
|
|
47
|
-
|
|
49
|
+
// the cook ended well but its result cannot be shown: said like a failed cook (a failed or stopped one says more)
|
|
50
|
+
const shown = preview && !l?.stopped && l?.ok !== false
|
|
51
|
+
? { kind: 'failed', text: firstLine(preview), title: `${preview} (the cook finished; the view keeps the last result it could show)` } : null;
|
|
52
|
+
if (!l) return shown ?? { kind: 'none', text: '', title: '' };
|
|
48
53
|
if (l.stopped) return { kind: 'stopped', text: `stopped at ${l.stopped} · the view shows the last finished cook`, title: 'change a value (or save the graph file) to cook again' };
|
|
49
54
|
if (!l.ok) {
|
|
50
55
|
const msg = l.error?.message ?? 'failed';
|
|
51
56
|
return { kind: 'failed', text: `failed at ${l.error?.node ?? 'the graph'}: ${firstLine(msg)}`, title: `${l.error?.node ?? ''}: ${msg}` };
|
|
52
57
|
}
|
|
58
|
+
if (shown) return shown;
|
|
53
59
|
return { kind: 'ok', text: `cooked in ${fmtDuration(l.ms)}`, title: `the last cook of the whole graph took ${fmtDuration(l.ms)}` };
|
|
54
60
|
}
|
|
55
61
|
|
package/dist/viewer/app/main.js
CHANGED
|
@@ -72,7 +72,8 @@ ctx.cookState = (graph) => cooks.get(graph)?.state ?? null;
|
|
|
72
72
|
function setCook(graph, state) { cooks.set(graph, { state, at: performance.now() }); renderCook(); }
|
|
73
73
|
function renderCook() {
|
|
74
74
|
const c = cooks.get(ctx.graph?.name), compare = ctx.packages?.running;
|
|
75
|
-
const
|
|
75
|
+
const pe = ctx.output?.previewError, preview = pe && pe.at === `${ctx.graph?.name}/${ctx.graph?.node ?? ''}` ? pe.message : null;
|
|
76
|
+
const line = compare ? compareLine(compare, performance.now() - compare.at) : cookLine(c?.state, c ? performance.now() - c.at : 0, preview);
|
|
76
77
|
for (const el of cookLines) {
|
|
77
78
|
el.className = `cookline ${line.kind}`;
|
|
78
79
|
const t = el.querySelector('.ctext');
|
|
@@ -164,6 +165,8 @@ ctx.setHover = (id) => { if (ctx.hover === id) return; ctx.hover = id; ctx.emit(
|
|
|
164
165
|
// the output: the node being shown, its display mode and visibility remembered
|
|
165
166
|
ctx.output = {
|
|
166
167
|
mesh: null, summary: '', error: null, report: null, loading: false,
|
|
168
|
+
/** {at: "graph/node", message: "preview failed: …"} when that node's result cooked but could not be shown */
|
|
169
|
+
previewError: null,
|
|
167
170
|
visible: local.get('output.visible', true), display: local.get('output.display', 'view'),
|
|
168
171
|
setVisible(v) { this.visible = v; local.set('output.visible', v); outEntry(); ctx.emit('output'); ctx.requestRender(); },
|
|
169
172
|
setDisplay(m) { this.display = m; local.set('output.display', m); outEntry(); ctx.emit('output'); ctx.requestRender(); },
|
|
@@ -259,19 +262,30 @@ const loadGeo = ctx.coalesce(async () => {
|
|
|
259
262
|
const r = await api.geo(graph, node, ctx.sceneLayer.get());
|
|
260
263
|
o.loading = false;
|
|
261
264
|
if (graph !== G.name || node !== (G.node ?? '') || ctx.outputs?.active) { ctx.emit('output'); return; }
|
|
265
|
+
// the result cooked but cannot be shown (its GLB was not written, or does not load here): the cook line says so and
|
|
266
|
+
// the view keeps the last result it showed
|
|
267
|
+
const previewFailed = (e) => {
|
|
268
|
+
const msg = String(e?.message ?? e);
|
|
269
|
+
o.previewError = { at: `${graph}/${node}`, message: msg.startsWith('preview failed') ? msg : `preview failed: ${msg}` };
|
|
270
|
+
if (e?.stack) console.error(e);
|
|
271
|
+
ctx.emit('output'); updateCook(); renderCook();
|
|
272
|
+
};
|
|
262
273
|
if (!r.ok) {
|
|
263
274
|
// the last good geometry stays; a stopped cook is no error (the cook line says where it stopped)
|
|
275
|
+
if (r.preview) return previewFailed(r.error);
|
|
264
276
|
if (!r.stopped) o.error = r.error;
|
|
265
277
|
ctx.emit('output'); updateCook();
|
|
266
278
|
return;
|
|
267
279
|
}
|
|
268
|
-
let src;
|
|
269
|
-
try { src = await parseGLB(r.buf); } catch (e) {
|
|
280
|
+
let src, mesh;
|
|
281
|
+
try { src = await parseGLB(r.buf); } catch (e) { return previewFailed(e); }
|
|
270
282
|
if (graph !== G.name || node !== (G.node ?? '') || ctx.outputs?.active) { new MeshObject('', src).dispose(); return; }
|
|
283
|
+
try { mesh = new MeshObject('out', src); } catch (e) { return previewFailed(e); }
|
|
271
284
|
const prev = o.mesh;
|
|
272
|
-
o.mesh =
|
|
285
|
+
o.mesh = mesh;
|
|
273
286
|
o.mesh.onReady = () => { ctx.requestRender(); ctx.emit('output'); };
|
|
274
287
|
o.error = null;
|
|
288
|
+
if (o.previewError) { o.previewError = null; renderCook(); }
|
|
275
289
|
ctx.outputRoot.add(o.mesh.root);
|
|
276
290
|
if (prev) prev.dispose();
|
|
277
291
|
outEntry();
|
package/dist/viewer/server.js
CHANGED
|
@@ -67,8 +67,25 @@ function outputsLine(v, most = 6) {
|
|
|
67
67
|
const names = Object.entries(v.outputs).filter(([, o]) => !isDefaultOutput(v, o)).map(([k]) => k);
|
|
68
68
|
return `${names.length} output${names.length === 1 ? '' : 's'}${names.length ? `: ${names.slice(0, most).join(', ')}${names.length > most ? ' …' : ''}` : ''}`;
|
|
69
69
|
}
|
|
70
|
+
/** The preview GLB could not be written: the result cooked, the page cannot be shown it (500, {preview: true}). */
|
|
71
|
+
class PreviewError extends HttpError {
|
|
72
|
+
constructor(msg) { super(500, `preview failed: ${msg}`); }
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The GLB a geometry route serves (previewGLB). Writing it fails as the preview's error, not the cook's, and the stack
|
|
76
|
+
* goes to the server's log (stderr) so the step that failed is named.
|
|
77
|
+
*/
|
|
78
|
+
async function previewOf(g, o = {}) {
|
|
79
|
+
try {
|
|
80
|
+
return await previewGLB(g, o);
|
|
81
|
+
}
|
|
82
|
+
catch (e) {
|
|
83
|
+
console.error(`preview failed: ${e?.stack ?? e}`);
|
|
84
|
+
throw new PreviewError(String(e?.message ?? e));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
70
87
|
/** The shape every geometry route serves: the same GLB options as /api/geo; images alone show as textured quads. */
|
|
71
|
-
const toGLB = (g) =>
|
|
88
|
+
const toGLB = (g) => previewOf(g);
|
|
72
89
|
const issueText = (e) => `[${e.node}] ${e.message}`;
|
|
73
90
|
/**
|
|
74
91
|
* A dropped file's name as stored in inputs/: a plain basename with its extension. Path separators and ".." are
|
|
@@ -748,7 +765,7 @@ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ??
|
|
|
748
765
|
if (u.pathname === '/api/info')
|
|
749
766
|
return send(200, JSON.stringify({ target: r.target, summary: summarize(r.geo), ms: r.ms, about: outputKind(r.geo) }), MIME['.json']);
|
|
750
767
|
// heightfields: the layer drawn in red (the page's layer picker; the mask by default)
|
|
751
|
-
return send(200, await
|
|
768
|
+
return send(200, await previewOf(r.geo, { heightfieldLayer: u.searchParams.get('heightfield_layer') || undefined }), MIME['.glb']);
|
|
752
769
|
}
|
|
753
770
|
send(404, 'not found');
|
|
754
771
|
}
|
|
@@ -758,7 +775,7 @@ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ??
|
|
|
758
775
|
const status = e instanceof HttpError ? e.status : 500;
|
|
759
776
|
const msg = String(e?.message ?? e);
|
|
760
777
|
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...(status === 413 ? { connection: 'close' } : {}) });
|
|
761
|
-
res.end(JSON.stringify(route === '/api/vars' ? { ok: false, ms: 0, errors: [msg] } : { ok: false, error: msg }));
|
|
778
|
+
res.end(JSON.stringify(route === '/api/vars' ? { ok: false, ms: 0, errors: [msg] } : { ok: false, error: msg, ...(e instanceof PreviewError ? { preview: true } : {}) }));
|
|
762
779
|
}
|
|
763
780
|
});
|
|
764
781
|
const listen = (p) => new Promise((resolve, reject) => {
|
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
name="TopoTopo"
|
|
4
4
|
description="Imports TopoTopo packages (<id>.topo): their published outputs are cooked into GLBs and PNGs that Godot imports itself, and kept current while the package changes."
|
|
5
5
|
author="TopoTopo"
|
|
6
|
-
version="0.5.
|
|
6
|
+
version="0.5.2"
|
|
7
7
|
script="plugin.gd"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "topotopo",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.2",
|
|
4
4
|
"description": "An open-source procedural geometry engine: node graphs in JSON, cooked headless and deterministic, exported to Unreal, Blender and Houdini. Built for LLM agents through MCP, and for people through the CLI.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"mcp": "node src/mcp/server.ts",
|
|
40
40
|
"preview": "node scripts/preview.ts --examples",
|
|
41
41
|
"cook": "node src/cli.ts",
|
|
42
|
-
"test": "node test/smoke.ts && node test/golden.ts && node test/property.ts && node test/fuzz.ts && node test/docs.ts && node test/portability.ts && node test/examples.ts && node scripts/gen-notice.ts --check && node test/io.ts && node test/import.ts && node test/interop.ts && node test/mcp.ts && node test/engine.ts && node test/scopes.ts && node test/packages.ts && node test/cook.ts && node test/viewer.ts && node test/viewer-logic.ts && node test/topology.ts && node test/deform.ts && node test/cloth.ts && node test/arrays.ts && node test/bugs.ts && node test/uv.ts && node test/polyedit.ts && node test/bevel.ts && node test/meshops.ts && node test/measure.ts && node test/render.ts && node test/packed.ts && node test/heightfield.ts && node test/remesh.ts && node test/pcg.ts && node test/scatterkernel.ts && node test/splines.ts && node test/builtin.ts && node test/textures.ts && node test/texnodes.ts && node test/imageops.ts && node test/pool.ts && node test/kernelsloader.ts && node test/kernels.ts && node test/sdfgrid.ts && node test/remeshquad.ts && node test/erosionkernel.ts && node test/erosionsimd.ts && node test/particles.ts && node test/rbd.ts && node test/limits.ts && node test/viewer-outputs.ts && node test/viewer-packages.ts && node test/library.ts && node test/web.ts && node test/tangents.ts && node test/pbr.ts && node test/materials.ts && node test/sockets.ts && node test/uvreport.ts && node test/solidify.ts",
|
|
42
|
+
"test": "node test/smoke.ts && node test/golden.ts && node test/property.ts && node test/fuzz.ts && node test/docs.ts && node test/portability.ts && node test/examples.ts && node scripts/gen-notice.ts --check && node test/io.ts && node test/import.ts && node test/interop.ts && node test/mcp.ts && node test/engine.ts && node test/scopes.ts && node test/packages.ts && node test/cook.ts && node test/viewer.ts && node test/session-watch.ts && node test/viewer-logic.ts && node test/topology.ts && node test/deform.ts && node test/cloth.ts && node test/arrays.ts && node test/bugs.ts && node test/uv.ts && node test/polyedit.ts && node test/bevel.ts && node test/meshops.ts && node test/measure.ts && node test/render.ts && node test/packed.ts && node test/heightfield.ts && node test/remesh.ts && node test/pcg.ts && node test/scatterkernel.ts && node test/splines.ts && node test/builtin.ts && node test/textures.ts && node test/texnodes.ts && node test/imageops.ts && node test/pool.ts && node test/kernelsloader.ts && node test/kernels.ts && node test/sdfgrid.ts && node test/remeshquad.ts && node test/erosionkernel.ts && node test/erosionsimd.ts && node test/particles.ts && node test/rbd.ts && node test/limits.ts && node test/viewer-outputs.ts && node test/viewer-packages.ts && node test/library.ts && node test/web.ts && node test/tangents.ts && node test/pbr.ts && node test/materials.ts && node test/sockets.ts && node test/uvreport.ts && node test/solidify.ts",
|
|
43
43
|
"test:limits": "node test/limits.ts",
|
|
44
44
|
"kernels:build": "node scripts/kernels-build.ts",
|
|
45
45
|
"test:kernels": "node test/scatterkernel.ts && node test/kernelsloader.ts && node test/kernels.ts && node test/sdfgrid.ts && node test/remeshquad.ts && node test/erosionkernel.ts && node test/erosionsimd.ts",
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
"test:examples": "node test/examples.ts",
|
|
75
75
|
"test:interop": "node test/interop.ts",
|
|
76
76
|
"test:web": "node test/library.ts && node test/web.ts",
|
|
77
|
-
"test:viewer": "node test/viewer.ts && node test/viewer-logic.ts && node test/viewer-outputs.ts && node test/viewer-packages.ts",
|
|
77
|
+
"test:viewer": "node test/viewer.ts && node test/session-watch.ts && node test/viewer-logic.ts && node test/viewer-outputs.ts && node test/viewer-packages.ts",
|
|
78
78
|
"showcase": "node test/showcase.ts",
|
|
79
79
|
"export:demo": "node scripts/export-demo.ts",
|
|
80
80
|
"demo:footage": "node scripts/demo-footage.ts",
|