@bluemoonfoundry/daz-ts 0.0.0-stage → 0.1.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.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +377 -2
  3. package/dist/animation.d.ts +129 -0
  4. package/dist/animation.js +276 -0
  5. package/dist/batch.d.ts +118 -0
  6. package/dist/batch.js +186 -0
  7. package/dist/bone.d.ts +50 -0
  8. package/dist/bone.js +66 -0
  9. package/dist/camera.d.ts +61 -0
  10. package/dist/camera.js +120 -0
  11. package/dist/cinematics.d.ts +188 -0
  12. package/dist/cinematics.js +165 -0
  13. package/dist/client.d.ts +399 -0
  14. package/dist/client.js +769 -0
  15. package/dist/dforce.d.ts +15 -0
  16. package/dist/dforce.js +36 -0
  17. package/dist/element.d.ts +51 -0
  18. package/dist/element.js +141 -0
  19. package/dist/exceptions.d.ts +124 -0
  20. package/dist/exceptions.js +173 -0
  21. package/dist/geometry.d.ts +81 -0
  22. package/dist/geometry.js +433 -0
  23. package/dist/index.d.ts +50 -0
  24. package/dist/index.js +36 -0
  25. package/dist/light.d.ts +24 -0
  26. package/dist/light.js +40 -0
  27. package/dist/lighting.d.ts +120 -0
  28. package/dist/lighting.js +107 -0
  29. package/dist/material.d.ts +27 -0
  30. package/dist/material.js +63 -0
  31. package/dist/materials.d.ts +107 -0
  32. package/dist/materials.js +165 -0
  33. package/dist/math3.d.ts +204 -0
  34. package/dist/math3.js +502 -0
  35. package/dist/modifier.d.ts +14 -0
  36. package/dist/modifier.js +24 -0
  37. package/dist/morph.d.ts +11 -0
  38. package/dist/morph.js +24 -0
  39. package/dist/node.d.ts +196 -0
  40. package/dist/node.js +447 -0
  41. package/dist/polling.d.ts +24 -0
  42. package/dist/polling.js +50 -0
  43. package/dist/pose.d.ts +82 -0
  44. package/dist/pose.js +295 -0
  45. package/dist/poses.d.ts +54 -0
  46. package/dist/poses.js +40 -0
  47. package/dist/property.d.ts +64 -0
  48. package/dist/property.js +125 -0
  49. package/dist/render.d.ts +242 -0
  50. package/dist/render.js +811 -0
  51. package/dist/renderApi.d.ts +124 -0
  52. package/dist/renderApi.js +235 -0
  53. package/dist/result.d.ts +15 -0
  54. package/dist/result.js +1 -0
  55. package/dist/scene.d.ts +154 -0
  56. package/dist/scene.js +584 -0
  57. package/dist/sceneEvents.d.ts +63 -0
  58. package/dist/sceneEvents.js +102 -0
  59. package/dist/sceneState.d.ts +167 -0
  60. package/dist/sceneState.js +430 -0
  61. package/dist/scriptBuilder.d.ts +41 -0
  62. package/dist/scriptBuilder.js +72 -0
  63. package/dist/shotGeometry.d.ts +49 -0
  64. package/dist/shotGeometry.js +76 -0
  65. package/dist/skeleton.d.ts +120 -0
  66. package/dist/skeleton.js +561 -0
  67. package/dist/timeline.d.ts +24 -0
  68. package/dist/timeline.js +39 -0
  69. package/dist/undo.d.ts +24 -0
  70. package/dist/undo.js +45 -0
  71. package/dist/version.d.ts +31 -0
  72. package/dist/version.js +36 -0
  73. package/dist/viewport.d.ts +58 -0
  74. package/dist/viewport.js +239 -0
  75. package/package.json +52 -4
package/dist/scene.js ADDED
@@ -0,0 +1,584 @@
1
+ import { DazCamera } from "./camera.js";
2
+ import { DazClient } from "./client.js";
3
+ import { NodeNotFoundError, ScriptRuntimeError } from "./exceptions.js";
4
+ import { DazLight } from "./light.js";
5
+ import { DazNode } from "./node.js";
6
+ import { executeLong } from "./polling.js";
7
+ import { ScriptBuilder } from "./scriptBuilder.js";
8
+ import { DazSkeleton } from "./skeleton.js";
9
+ import { withUndo } from "./undo.js";
10
+ const LIGHT_TYPE_CLASSES = {
11
+ spot: "DzSpotLight",
12
+ point: "DzPointLight",
13
+ distant: "DzDistantLight",
14
+ };
15
+ function sleep(seconds) {
16
+ return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
17
+ }
18
+ /**
19
+ * High-level proxy for the active DAZ Studio scene (`Scene` global) — the
20
+ * primary entry point for inspecting and manipulating the scene.
21
+ *
22
+ * This file covers node/camera/light/skeleton factories and selection
23
+ * (Phase 2 Task 12); later tasks (13-14) add bulk scene snapshots and
24
+ * I/O/playback/undo/dForce methods to this same class.
25
+ *
26
+ * @remarks
27
+ * `applyInteractionRecipe()` (dazpy's multi-figure IK recipe application) is
28
+ * Phase 5 scope (`daz-script-server-sf7y`), not implemented here.
29
+ */
30
+ export class DazScene {
31
+ client;
32
+ constructor(client) {
33
+ this.client = client ?? new DazClient();
34
+ }
35
+ /**
36
+ * The underlying {@link DazClient}, for domain-helper modules
37
+ * (`sceneState.ts`, `lighting.ts`, `cinematics.ts`, ...) that need to
38
+ * issue their own custom scripts. Mirrors dazpy's soft-private `_client`
39
+ * attribute, which sibling modules access directly.
40
+ */
41
+ getClient() {
42
+ return this.client;
43
+ }
44
+ // ---------------------------------------------------------------------
45
+ // Node factories
46
+ // ---------------------------------------------------------------------
47
+ /** All top-level and child nodes in the scene, typed via `inherits()` (DazSkeleton/DazCamera/DazLight/DazNode), scene-panel order. */
48
+ async nodes() {
49
+ const script = ScriptBuilder.iife(`
50
+ var result = [];
51
+ for (var i = 0; i < Scene.getNumNodes(); i++) {
52
+ var n = Scene.getNode(i);
53
+ var nodeType = "DzNode";
54
+ if (n.inherits("DzSkeleton")) { nodeType = "DzSkeleton"; }
55
+ else if (n.inherits("DzCamera")) { nodeType = "DzCamera"; }
56
+ else if (n.inherits("DzLight")) { nodeType = "DzLight"; }
57
+ result.push({name: n.getName(), className: nodeType});
58
+ }
59
+ return result;
60
+ `);
61
+ const items = (await this.client.execute(script)).value ?? [];
62
+ return items.map((item) => {
63
+ const identifier = { value: item.name, kind: "name" };
64
+ if (item.className === "DzSkeleton")
65
+ return new DazSkeleton(this.client, identifier);
66
+ if (item.className === "DzCamera")
67
+ return new DazCamera(this.client, identifier);
68
+ if (item.className === "DzLight")
69
+ return new DazLight(this.client, identifier);
70
+ return new DazNode(this.client, identifier);
71
+ });
72
+ }
73
+ /** Find a scene node by internal name. */
74
+ async findNode(name) {
75
+ const exists = ScriptBuilder.iife(`return !!Scene.findNode(${ScriptBuilder.escapeString(name)});`);
76
+ if (!(await this.client.execute(exists)).value) {
77
+ throw new NodeNotFoundError(`Node not found: ${JSON.stringify(name)}`);
78
+ }
79
+ return new DazNode(this.client, { value: name, kind: "name" });
80
+ }
81
+ /** Find a scene node by its user-visible label. Anchored to the internal *name*, so it stays stable if the label later changes. */
82
+ async findNodeByLabel(label) {
83
+ const exists = ScriptBuilder.iife(`return !!Scene.findNodeByLabel(${ScriptBuilder.escapeString(label)});`);
84
+ if (!(await this.client.execute(exists)).value) {
85
+ throw new NodeNotFoundError(`Node with label not found: ${JSON.stringify(label)}`);
86
+ }
87
+ return new DazNode(this.client, { value: label, kind: "label" });
88
+ }
89
+ async numNodes() {
90
+ return (await this.client.execute(ScriptBuilder.iife("return Scene.getNumNodes();"))).value ?? 0;
91
+ }
92
+ // ---------------------------------------------------------------------
93
+ // Camera factories
94
+ // ---------------------------------------------------------------------
95
+ async cameras() {
96
+ const script = ScriptBuilder.iife("var names = []; for (var i = 0; i < Scene.getNumCameras(); i++) { names.push(Scene.getCamera(i).getName()); } return names;");
97
+ const names = (await this.client.execute(script)).value ?? [];
98
+ return names.map((n) => new DazCamera(this.client, { value: n, kind: "name" }));
99
+ }
100
+ /** Find a camera by its user-visible label (same value accepted by `render()`'s `camera` parameter in Phase 3). */
101
+ async findCameraByLabel(label) {
102
+ const exists = ScriptBuilder.iife(`return !!Scene.findCameraByLabel(${ScriptBuilder.escapeString(label)});`);
103
+ if (!(await this.client.execute(exists)).value) {
104
+ throw new NodeNotFoundError(`Camera with label not found: ${JSON.stringify(label)}`);
105
+ }
106
+ return new DazCamera(this.client, { value: label, kind: "label" });
107
+ }
108
+ /** Create a new basic camera node and add it to the scene. `name` omitted → DAZ Studio assigns its default (de-duplicated) name. */
109
+ async createCamera(name) {
110
+ const nameExpr = name !== undefined ? ScriptBuilder.escapeString(name) : "null";
111
+ const script = ScriptBuilder.iife(`
112
+ var cam = new DzBasicCamera();
113
+ if (${nameExpr} !== null) cam.setName(${nameExpr});
114
+ Scene.addNode(cam);
115
+ return cam.getName();
116
+ `);
117
+ const createdName = (await this.client.execute(script)).value;
118
+ return new DazCamera(this.client, { value: createdName, kind: "name" });
119
+ }
120
+ // ---------------------------------------------------------------------
121
+ // Light factories
122
+ // ---------------------------------------------------------------------
123
+ async lights() {
124
+ const script = ScriptBuilder.iife("var names = []; for (var i = 0; i < Scene.getNumLights(); i++) { names.push(Scene.getLight(i).getName()); } return names;");
125
+ const names = (await this.client.execute(script)).value ?? [];
126
+ return names.map((n) => new DazLight(this.client, { value: n, kind: "name" }));
127
+ }
128
+ /** Create a new light node (`"spot"`/`"point"`/`"distant"`) and add it to the scene. */
129
+ async createLight(lightType, name) {
130
+ const className = LIGHT_TYPE_CLASSES[lightType];
131
+ if (className === undefined) {
132
+ throw new Error(`Unknown light_type ${JSON.stringify(lightType)}; expected one of ${JSON.stringify(Object.keys(LIGHT_TYPE_CLASSES).sort())}`);
133
+ }
134
+ const nameExpr = name !== undefined ? ScriptBuilder.escapeString(name) : "null";
135
+ const script = ScriptBuilder.iife(`
136
+ var light = new ${className}();
137
+ if (${nameExpr} !== null) light.setName(${nameExpr});
138
+ Scene.addNode(light);
139
+ return light.getName();
140
+ `);
141
+ const createdName = (await this.client.execute(script)).value;
142
+ return new DazLight(this.client, { value: createdName, kind: "name" });
143
+ }
144
+ async findLightByLabel(label) {
145
+ const exists = ScriptBuilder.iife(`return !!Scene.findLightByLabel(${ScriptBuilder.escapeString(label)});`);
146
+ if (!(await this.client.execute(exists)).value) {
147
+ throw new NodeNotFoundError(`Light with label not found: ${JSON.stringify(label)}`);
148
+ }
149
+ return new DazLight(this.client, { value: label, kind: "label" });
150
+ }
151
+ // ---------------------------------------------------------------------
152
+ // Skeleton factories
153
+ // ---------------------------------------------------------------------
154
+ async skeletons() {
155
+ const script = ScriptBuilder.iife("var names = []; var skels = Scene.getSkeletonList(); for (var i = 0; i < skels.length; i++) { names.push(skels[i].getName()); } return names;");
156
+ const names = (await this.client.execute(script)).value ?? [];
157
+ return names.map((n) => new DazSkeleton(this.client, { value: n, kind: "name" }));
158
+ }
159
+ /**
160
+ * Find a skeleton by internal name, retrying `Scene.getSkeletonList()` up
161
+ * to `retryAttempts` times (default 3, `retryDelay * attemptNumber`
162
+ * seconds apart, default base 0.15s) — `getSkeletonList()` has been
163
+ * observed to transiently omit a present skeleton under main-thread load
164
+ * (daz-script-server-xtkd); a momentary miss is retried rather than
165
+ * immediately raised. Pass `retryAttempts: 1` to disable retrying.
166
+ */
167
+ async findSkeleton(name, opts = {}) {
168
+ const { retryAttempts = 3, retryDelay = 0.15 } = opts;
169
+ const lookup = ScriptBuilder.iife(`
170
+ var skels = Scene.getSkeletonList();
171
+ for (var i = 0; i < skels.length; i++) {
172
+ if (skels[i].getName() === ${ScriptBuilder.escapeString(name)}) return true;
173
+ }
174
+ return false;
175
+ `);
176
+ let found = false;
177
+ for (let attempt = 0; attempt < retryAttempts; attempt++) {
178
+ if ((await this.client.execute(lookup)).value) {
179
+ found = true;
180
+ break;
181
+ }
182
+ if (attempt < retryAttempts - 1) {
183
+ await sleep(retryDelay * (attempt + 1));
184
+ }
185
+ }
186
+ if (!found) {
187
+ const hint = ScriptBuilder.iife(`
188
+ var info = [];
189
+ var skels = Scene.getSkeletonList();
190
+ for (var i = 0; i < skels.length; i++) {
191
+ info.push(skels[i].getName() + "|" + skels[i].getLabel());
192
+ }
193
+ return info;
194
+ `);
195
+ const pairs = (await this.client.execute(hint)).value ?? [];
196
+ if (pairs.length > 0) {
197
+ const available = pairs
198
+ .map((entry) => {
199
+ const [n, l] = entry.split("|");
200
+ return `${JSON.stringify(n)} (label: ${JSON.stringify(l)})`;
201
+ })
202
+ .join(", ");
203
+ throw new NodeNotFoundError(`Skeleton not found: ${JSON.stringify(name)}. Available skeletons: ${available}. ` +
204
+ `Tip: use findSkeletonByLabel() to search by the Scene-panel label.`);
205
+ }
206
+ throw new NodeNotFoundError(`Skeleton not found: ${JSON.stringify(name)} (no skeletons in scene).`);
207
+ }
208
+ return new DazSkeleton(this.client, { value: name, kind: "name" });
209
+ }
210
+ /** Find a skeleton by its user-visible label. Kept as `kind: "label"` — same-asset figures share an internal name, so name-based lookup would collapse distinct figures into one. */
211
+ async findSkeletonByLabel(label) {
212
+ const exists = ScriptBuilder.iife(`return !!Scene.findSkeletonByLabel(${ScriptBuilder.escapeString(label)});`);
213
+ if (!(await this.client.execute(exists)).value) {
214
+ throw new NodeNotFoundError(`Skeleton with label not found: ${JSON.stringify(label)}`);
215
+ }
216
+ return new DazSkeleton(this.client, { value: label, kind: "label" });
217
+ }
218
+ async numSkeletons() {
219
+ return (await this.client.execute(ScriptBuilder.iife("return Scene.getNumSkeletons();"))).value ?? 0;
220
+ }
221
+ // ---------------------------------------------------------------------
222
+ // Selection
223
+ // ---------------------------------------------------------------------
224
+ async selectedNodes() {
225
+ const script = ScriptBuilder.iife(`
226
+ var nodes = Scene.getSelectedNodeList();
227
+ var names = [];
228
+ for (var i = 0; i < nodes.length; i++) {
229
+ names.push(nodes[i].getName());
230
+ }
231
+ return names;
232
+ `);
233
+ const names = (await this.client.execute(script)).value ?? [];
234
+ return names.map((n) => new DazNode(this.client, { value: n, kind: "name" }));
235
+ }
236
+ async primarySelection() {
237
+ const name = (await this.client.execute(ScriptBuilder.iife("var n = Scene.getPrimarySelection(); return n ? n.getName() : null;")))
238
+ .value;
239
+ if (name === null)
240
+ return null;
241
+ return new DazNode(this.client, { value: name, kind: "name" });
242
+ }
243
+ async setPrimarySelection(node) {
244
+ const findExpr = ScriptBuilder.findNodeExpr(node.identifier);
245
+ await this.client.execute(ScriptBuilder.iife(`Scene.setPrimarySelection(${findExpr});`));
246
+ }
247
+ async selectAll(on = true) {
248
+ await this.client.execute(ScriptBuilder.iife(`Scene.selectAllNodes(${ScriptBuilder.serializeArg(on)});`));
249
+ }
250
+ // ---------------------------------------------------------------------
251
+ // Bulk scene snapshots
252
+ // ---------------------------------------------------------------------
253
+ /**
254
+ * Full skeleton and bone metadata for the scene in one HTTP call.
255
+ * @param skeletonLabels Optional subset of skeleton names/labels to include; omit to return every skeleton.
256
+ */
257
+ async sceneSnapshot(skeletonLabels) {
258
+ const filterJs = skeletonLabels !== undefined ? ScriptBuilder.serializeArg(skeletonLabels) : "null";
259
+ const script = ScriptBuilder.iife(`
260
+ var _filter = ${filterJs};
261
+ var _skels = Scene.getSkeletonList();
262
+ var _result = [];
263
+ for (var _s = 0; _s < _skels.length; _s++) {
264
+ var _skel = _skels[_s];
265
+ if (_filter !== null) {
266
+ var _found = false;
267
+ for (var _f = 0; _f < _filter.length; _f++) {
268
+ if (_filter[_f] === _skel.getName() || _filter[_f] === _skel.getLabel()) {
269
+ _found = true; break;
270
+ }
271
+ }
272
+ if (!_found) continue;
273
+ }
274
+ var _bones = _skel.getAllBones();
275
+ var _boneList = [];
276
+ for (var _i = 0; _i < _bones.length; _i++) {
277
+ var _b = _bones[_i];
278
+ var _parent = _b.getNodeParent();
279
+ var _parentName = null;
280
+ if (_parent && _parent.className && _parent.className() === "DzBone") {
281
+ _parentName = _parent.getName();
282
+ }
283
+ var _lpos = _b.getLocalPos();
284
+ var _wpos = _b.getWSPos();
285
+ _boneList.push({
286
+ name: _b.getName(),
287
+ label: _b.getLabel(),
288
+ parent_name: _parentName,
289
+ rotation_order: _b.getRotationOrder(),
290
+ local_position: {x: _lpos.x, y: _lpos.y, z: _lpos.z},
291
+ world_position: {x: _wpos.x, y: _wpos.y, z: _wpos.z},
292
+ local_euler: {
293
+ x: _b.getXRotControl().getValue(),
294
+ y: _b.getYRotControl().getValue(),
295
+ z: _b.getZRotControl().getValue()
296
+ }
297
+ });
298
+ }
299
+ _result.push({
300
+ name: _skel.getName(),
301
+ label: _skel.getLabel(),
302
+ bones: _boneList
303
+ });
304
+ }
305
+ return _result;
306
+ `);
307
+ return (await this.client.execute(script)).value ?? [];
308
+ }
309
+ /** World-space transforms (`name`/`label`/`position`/`rotation`/`visible`) for every node, in one HTTP call. */
310
+ async allNodeTransforms() {
311
+ const script = ScriptBuilder.iife(`
312
+ var result = [];
313
+ for (var i = 0; i < Scene.getNumNodes(); i++) {
314
+ var n = Scene.getNode(i);
315
+ var pos = n.getWSPos();
316
+ var rot = n.getWSRot();
317
+ result.push({
318
+ name: n.getName(),
319
+ label: n.getLabel(),
320
+ position: [pos.x, pos.y, pos.z],
321
+ rotation: [rot.x, rot.y, rot.z],
322
+ visible: n.isVisible()
323
+ });
324
+ }
325
+ return result;
326
+ `);
327
+ return (await this.client.execute(script)).value ?? [];
328
+ }
329
+ /** Full scene hierarchy as nested `{name, label, children}` dicts, one entry per root-level node. */
330
+ async nodeTree() {
331
+ const script = ScriptBuilder.iife(`
332
+ function nodeToDict(n) {
333
+ var children = [];
334
+ for (var i = 0; i < n.getNumNodeChildren(); i++) {
335
+ children.push(nodeToDict(n.getNodeChild(i)));
336
+ }
337
+ return {name: n.getName(), label: n.getLabel(), children: children};
338
+ }
339
+ var roots = [];
340
+ for (var i = 0; i < Scene.getNumNodes(); i++) {
341
+ var n = Scene.getNode(i);
342
+ if (!n.getNodeParent()) roots.push(nodeToDict(n));
343
+ }
344
+ return roots;
345
+ `);
346
+ return (await this.client.execute(script)).value ?? [];
347
+ }
348
+ /**
349
+ * Descendant tree rooted at a single node (searched by label first, then internal name), with an optional recursion-depth limit.
350
+ * @throws NodeNotFoundError if `root` cannot be found.
351
+ */
352
+ async nodeHierarchy(opts = {}) {
353
+ const rootJson = opts.root !== undefined ? ScriptBuilder.escapeString(opts.root) : "null";
354
+ const depthJs = opts.maxDepth ? ScriptBuilder.serializeArg(Math.trunc(opts.maxDepth)) : "0";
355
+ const script = ScriptBuilder.iife(`
356
+ var _rootLabel = ${rootJson};
357
+ var _node = Scene.findNodeByLabel(_rootLabel);
358
+ if (!_node) _node = Scene.findNode(_rootLabel);
359
+ if (!_node) return null;
360
+
361
+ var _maxDepth = ${depthJs};
362
+ var _totalDescendants = 0;
363
+
364
+ function _build(n, depth) {
365
+ if (_maxDepth > 0 && depth >= _maxDepth) return null;
366
+ var info = {label: n.getLabel(), name: n.getName(), type: n.className()};
367
+ var children = [];
368
+ for (var i = 0; i < n.getNumNodeChildren(); i++) {
369
+ _totalDescendants++;
370
+ var childInfo = _build(n.getNodeChild(i), depth + 1);
371
+ if (childInfo) children.push(childInfo);
372
+ }
373
+ if (children.length > 0) info.children = children;
374
+ return info;
375
+ }
376
+
377
+ var hierarchy = _build(_node, 0);
378
+ return {node: _node.getLabel(), hierarchy: hierarchy, total_descendants: _totalDescendants};
379
+ `);
380
+ const result = (await this.client.execute(script)).value;
381
+ if (result === null) {
382
+ throw new NodeNotFoundError(`Node not found: ${JSON.stringify(opts.root)}`);
383
+ }
384
+ return { node: result.node, hierarchy: result.hierarchy, totalDescendants: result.total_descendants };
385
+ }
386
+ /** Lightweight top-level snapshot: root-level figures, cameras, lights, scene file, and primary selection. Follower figures (parented under another figure) are excluded from `figures`. */
387
+ async overview() {
388
+ const script = ScriptBuilder.iife(`
389
+ var figures = [];
390
+ for (var i = 0; i < Scene.getNumSkeletons(); i++) {
391
+ var s = Scene.getSkeleton(i);
392
+ var parent = s.getNodeParent();
393
+ if (parent && parent.inherits("DzFigure")) continue;
394
+ figures.push({name: s.getName(), label: s.getLabel(), type: s.className()});
395
+ }
396
+ var cameras = [];
397
+ for (var i = 0; i < Scene.getNumCameras(); i++) {
398
+ var c = Scene.getCamera(i);
399
+ cameras.push({name: c.getName(), label: c.getLabel()});
400
+ }
401
+ var lights = [];
402
+ for (var i = 0; i < Scene.getNumLights(); i++) {
403
+ var l = Scene.getLight(i);
404
+ lights.push({name: l.getName(), label: l.getLabel(), type: l.className()});
405
+ }
406
+ var sel = Scene.getPrimarySelection();
407
+ return {
408
+ scene_file: Scene.getFilename(),
409
+ selected_node: sel ? sel.getLabel() : null,
410
+ figures: figures,
411
+ cameras: cameras,
412
+ lights: lights,
413
+ total_nodes: Scene.getNumNodes()
414
+ };
415
+ `);
416
+ return (await this.client.execute(script)).value ?? { scene_file: "", selected_node: null, figures: [], cameras: [], lights: [], total_nodes: 0 };
417
+ }
418
+ // ---------------------------------------------------------------------
419
+ // I/O, playback, undo, dForce
420
+ // ---------------------------------------------------------------------
421
+ async exportViaNativeExporter(exporterClass, path, overrides) {
422
+ const settingsCalls = [];
423
+ for (const [key, value] of Object.entries(overrides)) {
424
+ const jsKey = ScriptBuilder.escapeString(key);
425
+ if (typeof value === "boolean") {
426
+ settingsCalls.push(`settings.setBoolValue(${jsKey}, ${ScriptBuilder.serializeArg(value)});`);
427
+ }
428
+ else if (Number.isInteger(value)) {
429
+ settingsCalls.push(`settings.setIntValue(${jsKey}, ${ScriptBuilder.serializeArg(value)});`);
430
+ }
431
+ else if (typeof value === "number") {
432
+ settingsCalls.push(`settings.setFloatValue(${jsKey}, ${ScriptBuilder.serializeArg(value)});`);
433
+ }
434
+ else {
435
+ settingsCalls.push(`settings.setStringValue(${jsKey}, ${ScriptBuilder.escapeString(String(value))});`);
436
+ }
437
+ }
438
+ const script = ScriptBuilder.iife(`
439
+ var mgr = App.getExportMgr();
440
+ var exp = mgr.findExporterByClassName(${ScriptBuilder.escapeString(exporterClass)});
441
+ if (!exp) return;
442
+ var settings = new DzFileIOSettings();
443
+ exp.getDefaultOptions(settings);
444
+ ${settingsCalls.join(" ")}
445
+ exp.writeFile(${ScriptBuilder.escapeString(path)}, settings);
446
+ `);
447
+ await this.client.execute(script);
448
+ }
449
+ /** Load a scene file (merge mode — does not clear the existing scene). `path` is an absolute path on the server host. */
450
+ async load(path) {
451
+ await this.client.execute(ScriptBuilder.iife(`Scene.loadScene(${ScriptBuilder.escapeString(path)}, 0);`));
452
+ }
453
+ /** Save the scene to `path` (absolute path on the server host). */
454
+ async save(path) {
455
+ await this.client.execute(ScriptBuilder.iife(`Scene.saveScene(${ScriptBuilder.escapeString(path)});`));
456
+ }
457
+ /** Save a copy of the scene without changing its current file or dirty state. See `DazClient.sceneSaveCopy` for the copy-vs-serialize tradeoff. */
458
+ async saveCopy(path) {
459
+ return this.client.sceneSaveCopy(path);
460
+ }
461
+ /** Export the scene to FBX via DAZ Studio's built-in `DzFbxExporter` (synchronous — no async job to poll). */
462
+ async exportFbx(path, opts = {}) {
463
+ const overrides = {
464
+ IncludeSelectedOnly: opts.selectedOnly ?? false,
465
+ IncludeFigures: opts.includeFigures ?? true,
466
+ IncludeProps: opts.includeProps ?? false,
467
+ IncludeLights: opts.includeLights ?? false,
468
+ IncludeCameras: opts.includeCameras ?? false,
469
+ IncludeAnimations: opts.includeAnimations ?? false,
470
+ EmbedTextures: opts.embedTextures ?? true,
471
+ ...opts.options,
472
+ RunSilent: 1,
473
+ };
474
+ await this.exportViaNativeExporter("DzFbxExporter", path, overrides);
475
+ }
476
+ /** Export the scene to OBJ via DAZ Studio's built-in `DzObjExporter` (synchronous, see {@link exportFbx}). */
477
+ async exportObj(path, opts = {}) {
478
+ const overrides = {
479
+ SelectedOnly: opts.selectedOnly ?? false,
480
+ IgnoreInvisible: opts.ignoreInvisible ?? true,
481
+ WriteVN: opts.includeNormals ?? false,
482
+ CollectMaps: opts.collectMaps ?? false,
483
+ ...opts.options,
484
+ RunSilent: 1,
485
+ };
486
+ await this.exportViaNativeExporter("DzObjExporter", path, overrides);
487
+ }
488
+ async filename() {
489
+ return (await this.client.execute(ScriptBuilder.iife("return Scene.getFilename();"))).value ?? "";
490
+ }
491
+ async needsSave() {
492
+ return Boolean((await this.client.execute(ScriptBuilder.iife("return Scene.needsSave();"))).value);
493
+ }
494
+ /** Playback range as `{start, end}` in frames. */
495
+ async playRange() {
496
+ const script = ScriptBuilder.iife("var r = Scene.getPlayRange(); var step = Scene.getTimeStep(); return {start: Math.round(r.start / step), end: Math.round(r.end / step)};");
497
+ return (await this.client.execute(script)).value ?? { start: 0, end: 0 };
498
+ }
499
+ async setPlayRange(start, end) {
500
+ const script = ScriptBuilder.iife(`var step = Scene.getTimeStep();Scene.setPlayRange(new DzTimeRange(${ScriptBuilder.serializeArg(Math.trunc(start))} * step, ${ScriptBuilder.serializeArg(Math.trunc(end))} * step));`);
501
+ await this.client.execute(script);
502
+ }
503
+ /** Animation range as `{start, end}` in frames. */
504
+ async animRange() {
505
+ const script = ScriptBuilder.iife("var r = Scene.getAnimRange(); var step = Scene.getTimeStep(); return {start: Math.round(r.start / step), end: Math.round(r.end / step)};");
506
+ return (await this.client.execute(script)).value ?? { start: 0, end: 0 };
507
+ }
508
+ async setAnimRange(start, end) {
509
+ const script = ScriptBuilder.iife(`var step = Scene.getTimeStep();Scene.setAnimRange(new DzTimeRange(${ScriptBuilder.serializeArg(Math.trunc(start))} * step, ${ScriptBuilder.serializeArg(Math.trunc(end))} * step));`);
510
+ await this.client.execute(script);
511
+ }
512
+ async isPlaying() {
513
+ return Boolean((await this.client.execute(ScriptBuilder.iife("return Scene.isPlaying();"))).value);
514
+ }
515
+ async loopPlayback(on) {
516
+ await this.client.execute(ScriptBuilder.iife(`Scene.loopPlayback(${ScriptBuilder.serializeArg(on)});`));
517
+ }
518
+ /** Step back one level in DAZ Studio's undo stack (the *global* stack — use {@link undo} to group a series of changes instead). */
519
+ async undoLast() {
520
+ await this.client.execute(ScriptBuilder.iife("App.getUndoStack().undo();"));
521
+ }
522
+ async redoLast() {
523
+ await this.client.execute(ScriptBuilder.iife("App.getUndoStack().redo();"));
524
+ }
525
+ async isSimulating() {
526
+ return Boolean((await this.client.execute(ScriptBuilder.iife("return App.getSimulationMgr().isSimulating();"))).value);
527
+ }
528
+ async clearDforceSimulation() {
529
+ await this.client.execute(ScriptBuilder.iife("App.getSimulationMgr().clearSimulation();"));
530
+ }
531
+ /**
532
+ * Run a dForce simulation. `nodes` omitted simulates the whole scene via
533
+ * `DzSimulationMgr.simulate()` (follows the configured Simulation
534
+ * Settings frame range); `nodes` provided runs `customSimulate()` on
535
+ * that subset via the active engine.
536
+ * @param wait When `true` (default), block (via the async execute-and-poll endpoint, since dForce runs can take minutes) until finished, returning `null`. When `false`, submit and return the `requestId` immediately.
537
+ * @throws ScriptRuntimeError if the simulation engine reports an error (only when `wait` is `true`).
538
+ */
539
+ async runDforceSimulation(nodes, opts = {}) {
540
+ const { wait = true, timeout = 300.0 } = opts;
541
+ let body;
542
+ if (nodes && nodes.length > 0) {
543
+ const nodeExprs = nodes.map((n) => ScriptBuilder.findNodeExpr(n.identifier)).join(",");
544
+ body = `
545
+ var mgr = App.getSimulationMgr();
546
+ var engine = mgr.getActiveSimulationEngine();
547
+ if (!engine) return {"error": "no_active_engine"};
548
+ var err = engine.customSimulate([${nodeExprs}]);
549
+ return {"error": err ? String(err) : null};
550
+ `;
551
+ }
552
+ else {
553
+ body = `
554
+ var mgr = App.getSimulationMgr();
555
+ var err = mgr.simulate();
556
+ return {"error": err ? String(err) : null};
557
+ `;
558
+ }
559
+ const script = ScriptBuilder.iife(body);
560
+ if (!wait) {
561
+ return this.client.executeAsyncSubmit(script);
562
+ }
563
+ const result = await executeLong(this.client, script, undefined, { timeoutMs: timeout * 1000 });
564
+ const data = result.value ?? { error: null };
565
+ if (data.error) {
566
+ throw new ScriptRuntimeError(`dForce simulation failed: ${data.error}`);
567
+ }
568
+ return null;
569
+ }
570
+ async frame() {
571
+ return (await this.client.execute(ScriptBuilder.iife("return Scene.getFrame();"))).value ?? 0;
572
+ }
573
+ async setFrame(frame) {
574
+ await this.client.execute(ScriptBuilder.iife(`Scene.setFrame(${ScriptBuilder.serializeArg(Math.trunc(frame))});`));
575
+ }
576
+ /**
577
+ * Run `fn` with all its changes grouped into a single undo step labeled
578
+ * `label` (see {@link withUndo}). TS equivalent of dazpy's
579
+ * `with scene.undo(label): ...` context manager.
580
+ */
581
+ async undo(label, fn) {
582
+ return withUndo(this.client, label, fn);
583
+ }
584
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * General scene-change event stream -- SSE-based watcher for `GET /scene/events`.
3
+ * Mirrors dazpy's `_scene_events.py`.
4
+ *
5
+ * Mirrors the shape of the render-progress stream (`renderApi.ts`'s
6
+ * `waitRenderSse`/`parseSseStream`) but for the broader set of scene-change
7
+ * notifications DAZ Studio emits: nodes/skeletons/lights/cameras added or
8
+ * removed, selection changes, time scrubs, scene load/save, and render
9
+ * start/end.
10
+ */
11
+ import { DazClient } from "./client.js";
12
+ /** A single scene-change event received from the SSE stream. */
13
+ export interface SceneEvent {
14
+ type: string;
15
+ ts: number;
16
+ data: Record<string, unknown>;
17
+ }
18
+ /**
19
+ * Yield {@link SceneEvent} objects as DAZ Studio reports scene changes.
20
+ *
21
+ * Opens an SSE connection to `GET /scene/events` and yields events as they
22
+ * arrive, filtered server-side by `categories` and optionally client-side
23
+ * by exact `eventTypes` (e.g. `["node.added", "node.removed"]`).
24
+ *
25
+ * The connection stays open until the caller stops iterating (e.g. via
26
+ * `break`) or the server closes the stream.
27
+ *
28
+ * @param categories Optional subset of event categories to subscribe to
29
+ * server-side. Omit to subscribe to all categories.
30
+ * @param eventTypes Optional set of exact event types to keep; all others
31
+ * are dropped client-side. Omit to yield every event received.
32
+ * @param streamTimeoutMs Maximum lifetime of the stream in milliseconds;
33
+ * when it elapses iteration throws `DazTimeoutError`. Omit to wait
34
+ * indefinitely -- the server sends a keepalive comment every 15 seconds, so
35
+ * the connection never idles out.
36
+ *
37
+ * @throws ConnectionError If the SSE endpoint could not be reached.
38
+ * @throws AuthenticationError If the server rejects the token.
39
+ * @throws DazTimeoutError If `streamTimeoutMs` elapses.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const client = new DazClient();
44
+ * for await (const event of watchSceneEvents(client, ["node", "selection"])) {
45
+ * console.log(event.type, event.data);
46
+ * if (event.type === "node.added") break;
47
+ * }
48
+ * ```
49
+ */
50
+ export declare function watchSceneEvents(client: DazClient, categories?: string[], eventTypes?: string[], streamTimeoutMs?: number): AsyncGenerator<SceneEvent>;
51
+ /**
52
+ * Block until a scene event of `eventType` arrives, then return it.
53
+ *
54
+ * @param eventType Exact event type to wait for, e.g. `"node.added"` or
55
+ * `"render.finished"`. The category prefix (text before the first `.`) is
56
+ * used to narrow the server-side subscription.
57
+ * @param timeoutMs Maximum milliseconds to wait. Default `300000` (5 minutes).
58
+ *
59
+ * @throws DazTimeoutError If `timeoutMs` elapses before a matching event arrives.
60
+ * @throws ConnectionError If the SSE endpoint could not be reached.
61
+ * @throws AuthenticationError If the server rejects the token.
62
+ */
63
+ export declare function waitForSceneEvent(client: DazClient, eventType: string, timeoutMs?: number): Promise<SceneEvent>;