@threenative/playtest 0.1.0 → 0.3.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.
@@ -1,8 +1,415 @@
1
+ #!/usr/bin/env node
1
2
  import { Vector2, Vector3, Box3, Matrix4, Frustum } from 'three';
2
3
 
4
+ // src/three/renderWorkloadAdvisor.ts
5
+ var DEFAULT_TOP_N = 10;
6
+ var MAX_TOP_N = 32;
7
+ var MAX_OBSERVED_PASSES = 64;
8
+ var GROUP_FLOOR = 16;
9
+ var SPRITE_FLOOR = 32;
10
+ var POINT_OBJECT_FLOOR = 16;
11
+ var VERIFIED_EXAMPLE_PATHS = {
12
+ gpuParticles: "examples/abyss-framework/src/scenes/Abyss.ts",
13
+ hudInstancing: "packages/create-threenative/templates/minimal/src/render/hud.ts",
14
+ materialSharing: "packages/create-threenative/templates/starter/src/render/materials.ts",
15
+ staticMerge: "examples/native-cpu-load-test/src/main.ts"
16
+ };
17
+ function adviseThreeRenderWorkload(input) {
18
+ const examplePaths = validateVerifiedExamplePaths(input.verifiedExamplePaths);
19
+ const topN = clampTopN(input.topN);
20
+ const geometryIds = /* @__PURE__ */ new WeakMap();
21
+ const materialIds = /* @__PURE__ */ new WeakMap();
22
+ let nextGeometryId = 1;
23
+ let nextMaterialId = 1;
24
+ const geometries = /* @__PURE__ */ new Set();
25
+ const materials = /* @__PURE__ */ new Set();
26
+ const groups = /* @__PURE__ */ new Map();
27
+ const materialComparableGroups = /* @__PURE__ */ new Map();
28
+ let logicalObjectCount = 0;
29
+ let renderableCount = 0;
30
+ let instancedRenderableCount = 0;
31
+ let spriteCount = 0;
32
+ let pointsCount = 0;
33
+ const geometryId = (value) => idOf(geometryIds, value, () => nextGeometryId++);
34
+ const materialId = (value) => idOf(materialIds, value, () => nextMaterialId++);
35
+ input.scene.traverse((object) => {
36
+ logicalObjectCount += 1;
37
+ const renderable = object;
38
+ if (!isRenderable(renderable)) return;
39
+ if (!object.visible) return;
40
+ if (renderable.isInstancedMesh === true) instancedRenderableCount += instanceCount(renderable);
41
+ if (renderable.isSprite === true) spriteCount += 1;
42
+ if (renderable.isPoints === true) pointsCount += 1;
43
+ renderableCount += 1;
44
+ const geometry = renderable.geometry;
45
+ const objectMaterials = materialList(renderable.material);
46
+ if (geometry !== void 0) geometries.add(geometry);
47
+ for (const material of objectMaterials) materials.add(material);
48
+ const key = groupKey(renderable, geometry, objectMaterials, geometryId, materialId);
49
+ const group = groups.get(key) ?? createGroup();
50
+ groups.set(key, group);
51
+ const count = renderable.isInstancedMesh === true ? instanceCount(renderable) : 1;
52
+ group.memberCount += count;
53
+ if (geometry !== void 0) group.geometries.add(geometry);
54
+ for (const material of objectMaterials) group.materials.add(material);
55
+ if (objectMaterials.length > 0 && renderable.isMesh === true && geometry !== void 0) {
56
+ const comparableSignatures = objectMaterials.map(comparableMaterialSignature);
57
+ if (comparableSignatures.every((signature) => signature !== void 0)) {
58
+ const comparableKey = `${geometryId(geometry)}:${comparableSignatures.join("+")}`;
59
+ const comparable = materialComparableGroups.get(comparableKey) ?? createGroup();
60
+ materialComparableGroups.set(comparableKey, comparable);
61
+ comparable.memberCount += count;
62
+ comparable.geometries.add(geometry);
63
+ for (const material of objectMaterials) comparable.materials.add(material);
64
+ }
65
+ }
66
+ const reasons = constraintReasons(renderable, input.materialMutationSafety ?? "unknown");
67
+ if (reasons.length === 0) {
68
+ if ((input.transformSafety ?? "unknown") === "caller-declared-static") group.eligibleStaticCount += count;
69
+ else group.eligibleDynamicCount += count;
70
+ } else {
71
+ for (const reason of reasons) increment(group.constraintReasonCounts, reason, count);
72
+ }
73
+ });
74
+ if ((input.materialMutationSafety ?? "unknown") === "unknown") {
75
+ for (const group of materialComparableGroups.values()) {
76
+ if (group.materials.size > 1) increment(group.constraintReasonCounts, "materialMutationSafetyUnknown", group.memberCount);
77
+ }
78
+ }
79
+ const allGroups = [...groups.values()].map(serializeGroup).sort((left, right) => right.memberCount - left.memberCount);
80
+ const materialShareGroups = [...materialComparableGroups.values()].map(serializeGroup).sort((left, right) => right.memberCount - left.memberCount);
81
+ const topGroups = allGroups.slice(0, topN);
82
+ const observedPasses = validatedPasses(input.observed?.passes ?? []);
83
+ const observed = {
84
+ passes: {
85
+ recorded: observedPasses.length,
86
+ truncated: Math.max(0, (input.observed?.passes?.length ?? 0) - observedPasses.length)
87
+ },
88
+ renderer: sanitizeObservedRenderer(input.observed?.renderer)
89
+ };
90
+ const passObservations = observePasses(observedPasses);
91
+ const recommendations = [];
92
+ const compatibleGroups = allGroupsWithMinimum(allGroups, GROUP_FLOOR);
93
+ const compatibleCount = compatibleGroups.reduce((sum, group) => sum + group.memberCount, 0);
94
+ const expectedGroups = compatibleGroups.length;
95
+ const firstCompatible = compatibleGroups[0];
96
+ if (firstCompatible !== void 0 && instancedRenderableCount === 0) {
97
+ recommendations.push({
98
+ caveats: [
99
+ "dynamic-transforms-use-instancing",
100
+ "generated-source-remedy-only",
101
+ "static-merge-requires-caller-declared-static-transforms"
102
+ ],
103
+ code: "TN_RENDER_ADVISE_INSTANCE_COMPATIBLE",
104
+ constraints: firstCompatible.constraintReasonCounts,
105
+ evidence: { metric: "snapshot.compatibleGroups.memberCount", path: "topGroups.memberCount" },
106
+ examplePath: examplePaths.staticMerge,
107
+ expectedReducedCount: expectedGroups,
108
+ observedCount: compatibleCount,
109
+ owner: "generated-src",
110
+ severity: "warning"
111
+ });
112
+ if ((input.transformSafety ?? "unknown") === "caller-declared-static") {
113
+ recommendations.push({
114
+ caveats: ["caller-declared-static-transforms", "preserve-pickability-and-animation-semantics"],
115
+ code: "TN_RENDER_ADVISE_STATIC_MERGE_COMPATIBLE",
116
+ constraints: firstCompatible.constraintReasonCounts,
117
+ evidence: { metric: "snapshot.compatibleGroups.eligibleStaticCount", path: "topGroups.eligibleStaticCount" },
118
+ examplePath: examplePaths.staticMerge,
119
+ expectedReducedCount: expectedGroups,
120
+ observedCount: compatibleCount,
121
+ owner: "generated-src",
122
+ severity: "warning"
123
+ });
124
+ }
125
+ }
126
+ const materialShareGroup = materialShareGroups.find((group) => group.memberCount >= GROUP_FLOOR && group.materialIdentities > 1 && group.constraintReasonCounts.materialMutationSafetyUnknown === void 0);
127
+ if (materialShareGroup !== void 0 && input.materialMutationSafety === "caller-declared-stable") {
128
+ recommendations.push({
129
+ caveats: ["caller-declared-material-mutation-safe", "do-not-stringify-shaders-textures-userData"],
130
+ code: "TN_RENDER_ADVISE_SHARE_MATERIALS",
131
+ constraints: materialShareGroup.constraintReasonCounts,
132
+ evidence: { metric: "snapshot.materialComparableGroup.materialIdentities", path: "topGroups.materialIdentities" },
133
+ examplePath: examplePaths.materialSharing,
134
+ expectedReducedCount: materialShareGroup.geometryIdentities,
135
+ observedCount: materialShareGroup.materialIdentities,
136
+ owner: "generated-src",
137
+ severity: "info"
138
+ });
139
+ }
140
+ if (spriteCount >= SPRITE_FLOOR && input.spriteWorkload === "caller-declared-camera-overlay") {
141
+ recommendations.push({
142
+ caveats: ["camera-parented-hud-only", "negative-controls-stay-ordinary-sprites"],
143
+ code: "TN_RENDER_ADVISE_HUD_INSTANCING",
144
+ constraints: {},
145
+ evidence: { metric: "snapshot.spriteCount", path: "snapshot.spriteCount" },
146
+ examplePath: examplePaths.hudInstancing,
147
+ expectedReducedCount: 1,
148
+ observedCount: spriteCount,
149
+ owner: "generated-src",
150
+ severity: "info"
151
+ });
152
+ }
153
+ if (pointsCount >= POINT_OBJECT_FLOOR && input.particleWorkload === "caller-declared-many-independent-objects") {
154
+ recommendations.push({
155
+ caveats: ["many-independent-point-or-sprite-like-objects-only", "single-Points-is-already-batched"],
156
+ code: "TN_RENDER_ADVISE_GPU_PARTICLES",
157
+ constraints: {},
158
+ evidence: { metric: "snapshot.pointsCount", path: "snapshot.pointsCount" },
159
+ examplePath: examplePaths.gpuParticles,
160
+ expectedReducedCount: 1,
161
+ observedCount: pointsCount,
162
+ owner: "generated-src",
163
+ severity: "info"
164
+ });
165
+ }
166
+ const redundantPass = passObservations.find((entry) => entry.reasonCode === "repeatedEquivalentPass");
167
+ if (redundantPass !== void 0) {
168
+ recommendations.push({
169
+ caveats: ["caller-provided-pass-equivalence-required", "do-not-remove-depth-shadow-post-passes"],
170
+ code: "TN_RENDER_ADVISE_REPEATED_PASS",
171
+ constraints: {},
172
+ evidence: { metric: "observed.passSemantics", path: "passObservations" },
173
+ examplePath: examplePaths.staticMerge,
174
+ expectedReducedCount: 1,
175
+ observedCount: redundantPass.count,
176
+ owner: "generated-src",
177
+ severity: "warning"
178
+ });
179
+ }
180
+ return {
181
+ schemaVersion: 1,
182
+ observed,
183
+ passObservations,
184
+ recommendations,
185
+ snapshot: {
186
+ geometryIdentityCount: geometries.size,
187
+ instancedRenderableCount,
188
+ logicalObjectCount,
189
+ logicalObjectCountIncludesRootScene: true,
190
+ materialIdentityCount: materials.size,
191
+ pointsCount,
192
+ renderableCount,
193
+ spriteCount,
194
+ visibleFlagRenderableCount: renderableCount
195
+ },
196
+ topGroups
197
+ };
198
+ }
199
+ function clampTopN(value) {
200
+ if (value === void 0) return DEFAULT_TOP_N;
201
+ if (!Number.isFinite(value)) return DEFAULT_TOP_N;
202
+ return Math.max(1, Math.min(MAX_TOP_N, Math.floor(value)));
203
+ }
204
+ function validateVerifiedExamplePaths(paths) {
205
+ for (const key of Object.keys(VERIFIED_EXAMPLE_PATHS)) {
206
+ if (paths[key] !== VERIFIED_EXAMPLE_PATHS[key]) {
207
+ throw new Error(`verifiedExamplePaths.${key} must be the exact advisor allowlist path.`);
208
+ }
209
+ }
210
+ return VERIFIED_EXAMPLE_PATHS;
211
+ }
212
+ function sanitizeObservedRenderer(counters) {
213
+ return {
214
+ ...safeObservedCounter(counters?.drawCalls) === void 0 ? {} : { drawCalls: safeObservedCounter(counters?.drawCalls) },
215
+ ...safeObservedCounter(counters?.triangles) === void 0 ? {} : { triangles: safeObservedCounter(counters?.triangles) }
216
+ };
217
+ }
218
+ function safeObservedCounter(value) {
219
+ if (value === void 0) return void 0;
220
+ if (!Number.isFinite(value) || value < 0) return void 0;
221
+ return value;
222
+ }
223
+ function idOf(map, value, next) {
224
+ const existing = map.get(value);
225
+ if (existing !== void 0) return existing;
226
+ const created = next();
227
+ map.set(value, created);
228
+ return created;
229
+ }
230
+ function createGroup() {
231
+ return {
232
+ constraintReasonCounts: /* @__PURE__ */ new Map(),
233
+ eligibleDynamicCount: 0,
234
+ eligibleStaticCount: 0,
235
+ geometries: /* @__PURE__ */ new Set(),
236
+ materials: /* @__PURE__ */ new Set(),
237
+ memberCount: 0
238
+ };
239
+ }
240
+ function serializeGroup(group) {
241
+ return {
242
+ constraintReasonCounts: Object.fromEntries([...group.constraintReasonCounts.entries()].sort(([left], [right]) => left.localeCompare(right))),
243
+ eligibleDynamicCount: group.eligibleDynamicCount,
244
+ eligibleStaticCount: group.eligibleStaticCount,
245
+ geometryIdentities: group.geometries.size,
246
+ materialIdentities: group.materials.size,
247
+ memberCount: group.memberCount
248
+ };
249
+ }
250
+ function isRenderable(object) {
251
+ return object.isMesh === true || object.isInstancedMesh === true || object.isSprite === true || object.isPoints === true;
252
+ }
253
+ function materialList(material) {
254
+ if (Array.isArray(material)) {
255
+ const items = [];
256
+ for (const item of material) {
257
+ if (typeof item !== "object" || item === null) throw new Error("render advisor material array contains a non-object material.");
258
+ items.push(item);
259
+ }
260
+ return items;
261
+ }
262
+ if (material === void 0 || material === null) return [];
263
+ if (typeof material !== "object") throw new Error("render advisor material must be an object.");
264
+ return [material];
265
+ }
266
+ function groupKey(object, geometry, materials, geometryId, materialId) {
267
+ if (object.isSprite === true) return "sprite";
268
+ if (object.isPoints === true) return `points:${geometry === void 0 ? "none" : geometryId(geometry)}`;
269
+ const material = materials.length === 0 ? "none" : materials.map((item) => materialSignature(item, materialId)).join("+");
270
+ return `${geometry === void 0 ? "none" : geometryId(geometry)}:${material}`;
271
+ }
272
+ function materialSignature(material, materialId) {
273
+ const record = material;
274
+ const color = record.color;
275
+ const type = String(record.type ?? "Material");
276
+ if (isCustomShaderMaterial(record)) return `unsafe-custom-shader:${type}`;
277
+ if (isNodeMaterial(record)) return `unsafe-node-material:${type}`;
278
+ if (hasMappedTexture(record)) return `unsafe-mapped-texture:${type}`;
279
+ return [
280
+ `identity-${materialId(material)}`,
281
+ type,
282
+ color?.getHexString?.() ?? "no-color",
283
+ String(record.transparent ?? false),
284
+ String(record.blending ?? ""),
285
+ String(record.depthWrite ?? ""),
286
+ String(record.depthTest ?? ""),
287
+ String(record.side ?? ""),
288
+ String(record.roughness ?? ""),
289
+ String(record.metalness ?? ""),
290
+ String(record.flatShading ?? "")
291
+ ].join("|");
292
+ }
293
+ function comparableMaterialSignature(material) {
294
+ const record = material;
295
+ if (isCustomShaderMaterial(record) || isNodeMaterial(record) || hasMappedTexture(record)) return void 0;
296
+ const color = record.color;
297
+ const type = String(record.type ?? "Material");
298
+ return [
299
+ type,
300
+ color?.getHexString?.() ?? "no-color",
301
+ String(record.transparent ?? false),
302
+ String(record.blending ?? ""),
303
+ String(record.depthWrite ?? ""),
304
+ String(record.depthTest ?? ""),
305
+ String(record.side ?? ""),
306
+ String(record.roughness ?? ""),
307
+ String(record.metalness ?? ""),
308
+ String(record.flatShading ?? "")
309
+ ].join("|");
310
+ }
311
+ function constraintReasons(object, _materialMutationSafety) {
312
+ const reasons = [];
313
+ const materials = materialList(object.material);
314
+ if (object.isSkinnedMesh === true) reasons.push("skinnedMesh");
315
+ if (Array.isArray(object.morphTargetInfluences) && object.morphTargetInfluences.length > 0) reasons.push("morphTargets");
316
+ if (hasOwnFunction(object, "onBeforeRender")) reasons.push("renderHook");
317
+ if (hasOwnFunction(object, "onAfterRender")) reasons.push("renderHook");
318
+ if (object.layers.mask !== 1) reasons.push("customLayerMask");
319
+ if (object.renderOrder !== 0) reasons.push("customRenderOrder");
320
+ for (const material of materials) {
321
+ if (material.transparent === true) reasons.push("transparentMaterial");
322
+ if (isCustomShaderMaterial(material)) reasons.push("customShader", "materialCustomShader");
323
+ if (isNodeMaterial(material)) reasons.push("customNode", "materialCustomNode");
324
+ if (hasMappedTexture(material)) reasons.push("materialTextureMap");
325
+ }
326
+ return uniqueStrings(reasons);
327
+ }
328
+ function hasOwnFunction(object, key) {
329
+ return Object.hasOwn(object, key) && typeof object[key] === "function";
330
+ }
331
+ function isCustomShaderMaterial(material) {
332
+ const type = String(material.type ?? "");
333
+ return type === "ShaderMaterial" || type === "RawShaderMaterial" || Object.hasOwn(material, "onBeforeCompile") && typeof material.onBeforeCompile === "function";
334
+ }
335
+ function isNodeMaterial(material) {
336
+ return String(material.type ?? "").includes("Node");
337
+ }
338
+ function hasMappedTexture(material) {
339
+ const map = material.map;
340
+ return typeof map === "object" && map !== null;
341
+ }
342
+ function uniqueStrings(values) {
343
+ const seen = /* @__PURE__ */ new Set();
344
+ const result = [];
345
+ for (const value of values) {
346
+ if (!seen.has(value)) {
347
+ seen.add(value);
348
+ result.push(value);
349
+ }
350
+ }
351
+ return result;
352
+ }
353
+ function instanceCount(object) {
354
+ const value = object.count;
355
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 1;
356
+ }
357
+ function increment(map, key, amount) {
358
+ map.set(key, (map.get(key) ?? 0) + amount);
359
+ }
360
+ function incompatibleCount(group) {
361
+ let sum = 0;
362
+ for (const [reason, count] of Object.entries(group.constraintReasonCounts)) {
363
+ if (reason !== "materialMutationSafetyUnknown") sum += count;
364
+ }
365
+ return sum;
366
+ }
367
+ function allGroupsWithMinimum(groups, minimum) {
368
+ const result = [];
369
+ for (const group of groups) {
370
+ if (group.memberCount >= minimum && incompatibleCount(group) === 0) result.push(group);
371
+ }
372
+ return result;
373
+ }
374
+ function validatedPasses(passes) {
375
+ const result = [];
376
+ const limit = Math.min(MAX_OBSERVED_PASSES, passes.length);
377
+ for (let index = 0; index < limit; index += 1) {
378
+ const pass = passes[index];
379
+ if (pass === void 0) throw new Error("observed.passes contains an empty entry.");
380
+ for (const key of ["sceneToken", "cameraToken"]) {
381
+ if (typeof pass[key] !== "string" || pass[key].length === 0) throw new Error(`observed.passes.${key} must be a non-empty string.`);
382
+ }
383
+ for (const key of ["depthToken", "equivalenceToken", "targetToken"]) {
384
+ const value = pass[key];
385
+ if (value !== void 0 && (typeof value !== "string" || value.length === 0)) throw new Error(`observed.passes.${key} must be a non-empty string when present.`);
386
+ }
387
+ if (pass.renderCalls !== void 0 && (!Number.isSafeInteger(pass.renderCalls) || pass.renderCalls < 0)) throw new Error("observed.passes.renderCalls must be a non-negative integer.");
388
+ result.push(pass);
389
+ }
390
+ return result;
391
+ }
392
+ function observePasses(passes) {
393
+ if (passes.length <= 1) return passes.length === 0 ? [] : [{ count: passes.length, reasonCode: "singlePassObserved" }];
394
+ const buckets = /* @__PURE__ */ new Map();
395
+ let different = 0;
396
+ for (const pass of passes) {
397
+ const key = [pass.sceneToken, pass.cameraToken, pass.targetToken ?? "screen", pass.depthToken ?? "default", pass.purpose ?? "color", pass.equivalenceToken ?? "unknown"].join("|");
398
+ buckets.set(key, (buckets.get(key) ?? 0) + 1);
399
+ }
400
+ const observations = [];
401
+ for (const count of buckets.values()) {
402
+ if (count > 1) observations.push({ count, reasonCode: "repeatedEquivalentPass" });
403
+ else different += 1;
404
+ }
405
+ if (different > 0) observations.push({ count: different, reasonCode: "differentPassSemantics" });
406
+ return observations;
407
+ }
408
+
3
409
  // src/protocol.ts
4
410
  var PLAYTEST_BRIDGE_GLOBAL = "__THREENATIVE_PLAYTEST_BRIDGE__";
5
411
  var PLAYTEST_PROTOCOL_VERSION = 1;
412
+ var PLAYTEST_FROZEN_MARKER = "__threenativeFrozen";
6
413
  var PLAYTEST_PROTOCOL_LIMITS = {
7
414
  maxEntitiesPerSample: 100,
8
415
  maxEventsPerDrain: 1e3,
@@ -77,6 +484,8 @@ function sampleThreeObservations(input, request) {
77
484
  input.camera.updateMatrixWorld(true);
78
485
  const rendererSize = input.renderer.getDrawingBufferSize(new Vector2());
79
486
  const entities = input.registry.select(request.entities).map(({ id, object }) => observeEntity(id, object, input.camera, rendererSize.x, rendererSize.y));
487
+ const renderPerformance = rendererPerformance(input.renderer);
488
+ const renderChain = input.renderChain?.();
80
489
  return {
81
490
  clock: {
82
491
  mode: input.clockMode,
@@ -85,9 +494,25 @@ function sampleThreeObservations(input, request) {
85
494
  ...input.diagnostics === void 0 ? {} : { diagnostics: input.diagnostics() },
86
495
  entities,
87
496
  ...input.gameplay === void 0 ? {} : { gameplay: input.gameplay() },
497
+ ...renderPerformance === void 0 ? {} : { performance: renderPerformance },
498
+ ...renderChain === void 0 ? {} : { renderChain },
499
+ ...input.runtimeDiagnosticsSeries === void 0 ? {} : { runtimeDiagnosticsSeries: input.runtimeDiagnosticsSeries().map((sample) => ({ ...sample })) },
88
500
  ...input.resources === void 0 ? {} : { resources: input.resources() }
89
501
  };
90
502
  }
503
+ function rendererPerformance(renderer) {
504
+ const render = renderer.info?.render;
505
+ const drawCalls = finiteNumber(render?.drawCalls) ? render.drawCalls : void 0;
506
+ const triangles = finiteNumber(render?.triangles) ? render.triangles : void 0;
507
+ if (drawCalls === void 0 && triangles === void 0) return void 0;
508
+ return {
509
+ ...drawCalls === void 0 ? {} : { drawCalls },
510
+ ...triangles === void 0 ? {} : { triangles }
511
+ };
512
+ }
513
+ function finiteNumber(value) {
514
+ return typeof value === "number" && Number.isFinite(value);
515
+ }
91
516
  function observeEntity(id, object, camera, viewportWidth, viewportHeight) {
92
517
  const position = object.getWorldPosition(new Vector3());
93
518
  const bounds = projectedBounds(object, camera, viewportWidth, viewportHeight);
@@ -131,7 +556,69 @@ function projectedBounds(object, camera, viewportWidth, viewportHeight) {
131
556
  };
132
557
  }
133
558
 
559
+ // src/three/physics.ts
560
+ var PLAYTEST_PHYSICS_BODY_LIMIT = 100;
561
+ var PLAYTEST_PHYSICS_SAMPLE_LIMIT = 100;
562
+ var ThreePlaytestPhysicsRecorder = class {
563
+ #physics;
564
+ #series = [];
565
+ constructor(physics) {
566
+ this.#physics = physics;
567
+ }
568
+ sample(request, tick) {
569
+ if (request.label !== void 0) {
570
+ if (this.#series.some(({ label }) => label === request.label))
571
+ throw new Error(`TN_PLAYTEST_PHYSICS_LABEL_DUPLICATE: '${request.label}' was already sampled.`);
572
+ if (this.#series.length >= PLAYTEST_PHYSICS_SAMPLE_LIMIT)
573
+ throw new Error(`TN_PLAYTEST_PHYSICS_SAMPLE_LIMIT: at most ${PLAYTEST_PHYSICS_SAMPLE_LIMIT} labelled samples are retained.`);
574
+ this.#series.push({ label: request.label, snapshot: physicsSnapshot(this.#physics.bodies()), tick });
575
+ }
576
+ return this.#series.map((sample) => ({ ...sample }));
577
+ }
578
+ };
579
+ function physicsSnapshot(bodies) {
580
+ if (!Array.isArray(bodies))
581
+ throw new Error("TN_PLAYTEST_PHYSICS_BODIES: the physics provider must return an array of bodies.");
582
+ const retained = bodies.slice(0, PLAYTEST_PHYSICS_BODY_LIMIT);
583
+ const seen = /* @__PURE__ */ new Set();
584
+ const primitives = retained.flatMap((body) => {
585
+ if (typeof body?.id !== "string" || body.id.length === 0)
586
+ throw new Error("TN_PLAYTEST_PHYSICS_BODY_ID: every observed physics body needs a non-empty string id.");
587
+ if (seen.has(body.id))
588
+ throw new Error(`TN_PLAYTEST_PHYSICS_BODY_DUPLICATE: body id '${body.id}' was reported twice in one sample.`);
589
+ seen.add(body.id);
590
+ if (typeof body.sleeping !== "boolean")
591
+ throw new Error(`TN_PLAYTEST_PHYSICS_BODY_SLEEPING: body '${body.id}' must report sleeping as a boolean.`);
592
+ if (!isFiniteVec3(body.position))
593
+ throw new Error(`TN_PLAYTEST_PHYSICS_BODY_POSITION: body '${body.id}' must report a finite [x, y, z] position.`);
594
+ const sleep = { category: "sleep", entity: body.id, value: body.sleeping ? 1 : 0 };
595
+ const centerOfMass = { category: "center-of-mass", entity: body.id, position: [...body.position] };
596
+ return [sleep, centerOfMass];
597
+ });
598
+ return { artifact: { overflow: { omittedBodies: bodies.length - retained.length }, primitives } };
599
+ }
600
+ function isFiniteVec3(value) {
601
+ return Array.isArray(value) && value.length === 3 && value.every((component) => typeof component === "number" && Number.isFinite(component));
602
+ }
603
+
604
+ // src/diagnostics.ts
605
+ function playtestDiagnostic(code, message, instruction, details = {}) {
606
+ return {
607
+ ...details.capability === void 0 ? {} : { capability: details.capability },
608
+ code,
609
+ fix: {
610
+ instruction,
611
+ ...details.nextCommand === void 0 ? {} : { nextCommand: details.nextCommand }
612
+ },
613
+ message,
614
+ ...details.path === void 0 ? {} : { path: details.path },
615
+ severity: "error"
616
+ };
617
+ }
618
+
134
619
  // src/three/device.ts
620
+ var MAILBOX_WATCHDOG_BEAT_MS = 250;
621
+ var MAILBOX_POLL_STALL_BEATS = 8;
135
622
  var BRIDGE_METHODS = /* @__PURE__ */ new Set([
136
623
  "advance",
137
624
  "applySetup",
@@ -146,6 +633,7 @@ function connectDevicePlaytestBridge(bridge, endpoint) {
146
633
  if (nativeInstallation !== void 0) return nativeInstallation;
147
634
  let closed = false;
148
635
  let reportedError = false;
636
+ const nativePointers = /* @__PURE__ */ new Map();
149
637
  let scheduled;
150
638
  const schedule = () => {
151
639
  if (closed) return;
@@ -162,7 +650,7 @@ function connectDevicePlaytestBridge(bridge, endpoint) {
162
650
  if (response.status !== 204) {
163
651
  if (!response.ok) throw new Error(`Device bridge poll failed with HTTP ${response.status}.`);
164
652
  const request = parseRequest(await response.json());
165
- await postResponse(endpoint, await dispatch(bridge, request));
653
+ await postResponse(endpoint, await dispatch(bridge, request, nativePointers));
166
654
  }
167
655
  } catch (error) {
168
656
  if (!reportedError) {
@@ -191,6 +679,10 @@ function connectNativeMailbox(bridge) {
191
679
  if (typeof mailbox?.request !== "string" || typeof mailbox.response !== "string" || typeof host?.receive !== "function" || typeof host.respond !== "function") return void 0;
192
680
  let closed = false;
193
681
  let frame;
682
+ const nativePointers = /* @__PURE__ */ new Map();
683
+ let watchdogBeats = 0;
684
+ let polledAtBeat = 0;
685
+ let stallReported = false;
194
686
  const respond = (response) => {
195
687
  if (!host.respond(mailbox.response, JSON.stringify(response))) {
196
688
  console.error("TN_PLAYTEST_DEVICE_TRANSPORT: native mailbox response failed");
@@ -198,11 +690,12 @@ function connectNativeMailbox(bridge) {
198
690
  };
199
691
  const poll = () => {
200
692
  if (closed) return;
693
+ polledAtBeat = watchdogBeats;
201
694
  const raw = host.receive(mailbox.request);
202
695
  if (raw !== void 0) {
203
696
  try {
204
697
  const request = parseRequest(JSON.parse(raw));
205
- void dispatch(bridge, request).then(respond);
698
+ void dispatch(bridge, request, nativePointers).then(respond);
206
699
  } catch (error) {
207
700
  respond({
208
701
  error: { message: error instanceof Error ? error.message : String(error) },
@@ -212,11 +705,28 @@ function connectNativeMailbox(bridge) {
212
705
  }
213
706
  frame = globalThis.requestAnimationFrame(poll);
214
707
  };
708
+ const pollWatchdog = setInterval(() => {
709
+ watchdogBeats += 1;
710
+ if (closed || watchdogBeats - polledAtBeat < MAILBOX_POLL_STALL_BEATS) return;
711
+ if (!stallReported) {
712
+ stallReported = true;
713
+ const stall = playtestDiagnostic(
714
+ "TN_PLAYTEST_MAILBOX_POLL_STALLED",
715
+ `the native mailbox poll has not run for ${MAILBOX_POLL_STALL_BEATS * MAILBOX_WATCHDOG_BEAT_MS}ms while timers still fire; the host's requestAnimationFrame frame pump stopped servicing it`,
716
+ "Inspect the host for a stopped or crashed frame pump; the mailbox will keep polling while frames recover."
717
+ );
718
+ console.error(`${stall.code}: ${stall.message}`);
719
+ }
720
+ if (frame !== void 0) globalThis.cancelAnimationFrame(frame);
721
+ frame = void 0;
722
+ poll();
723
+ }, MAILBOX_WATCHDOG_BEAT_MS);
215
724
  respond({ id: "ready", result: null });
216
725
  frame = globalThis.requestAnimationFrame(poll);
217
726
  return {
218
727
  close: () => {
219
728
  closed = true;
729
+ clearInterval(pollWatchdog);
220
730
  if (frame !== void 0) globalThis.cancelAnimationFrame(frame);
221
731
  }
222
732
  };
@@ -225,10 +735,10 @@ function readPlaytestEndpoint() {
225
735
  const value = globalThis.TN_PLAYTEST_ENDPOINT;
226
736
  return typeof value === "string" && value.length > 0 ? value : void 0;
227
737
  }
228
- async function dispatch(bridge, request) {
738
+ async function dispatch(bridge, request, nativePointers) {
229
739
  try {
230
740
  if (request.method.startsWith("input.")) {
231
- return { id: request.id, result: dispatchInput(request.method, request.argument) };
741
+ return { id: request.id, result: dispatchInput(request.method, request.argument, nativePointers) };
232
742
  }
233
743
  if (!BRIDGE_METHODS.has(request.method)) {
234
744
  throw new Error(`Bridge operation '${request.method}' is unavailable.`);
@@ -242,7 +752,7 @@ async function dispatch(bridge, request) {
242
752
  return { error: { message: error instanceof Error ? error.message : String(error) }, id: request.id };
243
753
  }
244
754
  }
245
- function dispatchInput(method, argument) {
755
+ function dispatchInput(method, argument, nativePointers) {
246
756
  const host = globalThis.__THREENATIVE_NATIVE__?.playtestInput;
247
757
  if (!isRecord(argument)) throw new Error(`Device ${method} requires an object argument.`);
248
758
  if (method === "input.keyDown" || method === "input.keyUp") {
@@ -262,8 +772,75 @@ function dispatchInput(method, argument) {
262
772
  host.pointer(type, argument.x, argument.y, argument.buttons);
263
773
  return null;
264
774
  }
775
+ if (method === "input.pointers") {
776
+ if (typeof host?.pointer !== "function") {
777
+ throw new Error("Native playtest multi-pointer input is unavailable.");
778
+ }
779
+ const next = parseNativePointers(argument.pointers);
780
+ const nextById = new Map(next.map((pointer) => [pointer.id, pointer]));
781
+ const previousPrimary = nativePointers.keys().next().value;
782
+ const nextPrimary = nextById.keys().next().value;
783
+ for (const pointer of nativePointers.values()) {
784
+ if (nextById.has(pointer.id)) continue;
785
+ host.pointer(
786
+ "pointerup",
787
+ pointer.x,
788
+ pointer.y,
789
+ 0,
790
+ pointer.id,
791
+ "touch",
792
+ pointer.id === previousPrimary
793
+ );
794
+ }
795
+ for (const pointer of next) {
796
+ const previous = nativePointers.get(pointer.id);
797
+ if (previous === void 0) {
798
+ host.pointer(
799
+ "pointerdown",
800
+ pointer.x,
801
+ pointer.y,
802
+ pointer.buttons,
803
+ pointer.id,
804
+ "touch",
805
+ pointer.id === nextPrimary
806
+ );
807
+ } else if (previous.x !== pointer.x || previous.y !== pointer.y || previous.buttons !== pointer.buttons) {
808
+ host.pointer(
809
+ "pointermove",
810
+ pointer.x,
811
+ pointer.y,
812
+ pointer.buttons,
813
+ pointer.id,
814
+ "touch",
815
+ pointer.id === nextPrimary
816
+ );
817
+ }
818
+ }
819
+ nativePointers.clear();
820
+ for (const pointer of next) nativePointers.set(pointer.id, pointer);
821
+ return null;
822
+ }
265
823
  throw new Error(`Device input operation '${method}' is unavailable.`);
266
824
  }
825
+ function parseNativePointers(value) {
826
+ if (!Array.isArray(value)) throw new Error("Device input.pointers requires a pointer array.");
827
+ const pointers = value.map((pointer, index) => {
828
+ if (!isRecord(pointer)) throw new Error(`Device input.pointers[${index}] must be an object.`);
829
+ if (!Number.isInteger(pointer.id) || pointer.id < 1 || typeof pointer.x !== "number" || !Number.isFinite(pointer.x) || typeof pointer.y !== "number" || !Number.isFinite(pointer.y) || pointer.buttons !== void 0 && (!Number.isInteger(pointer.buttons) || pointer.buttons < 1)) {
830
+ throw new Error(`Device input.pointers[${index}] contains invalid pointer coordinates or buttons.`);
831
+ }
832
+ return {
833
+ buttons: pointer.buttons === void 0 ? 1 : pointer.buttons,
834
+ id: pointer.id,
835
+ x: pointer.x,
836
+ y: pointer.y
837
+ };
838
+ });
839
+ if (new Set(pointers.map(({ id }) => id)).size !== pointers.length) {
840
+ throw new Error("Device input.pointers requires unique pointer ids.");
841
+ }
842
+ return pointers;
843
+ }
267
844
  function parseRequest(value) {
268
845
  assertBounded(value);
269
846
  if (!isRecord(value) || typeof value.id !== "string" || typeof value.method !== "string") {
@@ -291,11 +868,15 @@ function isRecord(value) {
291
868
 
292
869
  // src/three/bridge.ts
293
870
  function installThreePlaytestBridge(options) {
871
+ if (options.fixedStep === void 0 !== (options.tick === void 0))
872
+ throw new Error("fixedStep and its authoritative tick provider must be installed together.");
873
+ if (options.physics !== void 0 && options.tick === void 0)
874
+ throw new Error("A physics provider requires the authoritative tick provider, and therefore fixedStep.");
875
+ const recorder = options.physics === void 0 ? void 0 : new ThreePlaytestPhysicsRecorder(options.physics);
294
876
  const host = globalThis;
295
877
  const previous = host[PLAYTEST_BRIDGE_GLOBAL];
296
878
  const registry = new ThreePlaytestEntityRegistry();
297
879
  syncEntities(registry, options.entities);
298
- let tick = 0;
299
880
  const capabilities = () => [
300
881
  "camera.observe",
301
882
  "entity.bounds",
@@ -307,20 +888,31 @@ function installThreePlaytestBridge(options) {
307
888
  ...Object.keys(options.components?.() ?? {}).length === 0 ? [] : ["runtime.components"],
308
889
  ...options.events === void 0 ? [] : ["runtime.events"],
309
890
  ...options.gameplay === void 0 ? [] : ["runtime.animation", "runtime.state"],
891
+ ...options.physics === void 0 ? [] : ["runtime.physics"],
892
+ ...options.runtimeDiagnosticsSeries === void 0 ? [] : ["runtime.performance"],
893
+ ...options.renderChain === void 0 ? [] : ["runtime.renderChain"],
894
+ ...options.startup === void 0 ? [] : ["runtime.startup"],
310
895
  ...options.gameplayChannels?.().includes("runtime.contacts") === true ? ["runtime.contacts"] : [],
311
- ...options.gameplayChannels?.().includes("runtime.tags") === true ? ["runtime.tags"] : []
896
+ ...options.gameplayChannels?.().includes("runtime.tags") === true ? ["runtime.tags"] : [],
897
+ ...options.gameplayChannels?.().includes("runtime.world") === true ? ["runtime.world"] : []
312
898
  ];
313
899
  const bridge = {
314
900
  ...options.fixedStep === void 0 ? {} : {
315
901
  advance: async (ticks) => {
316
902
  if (!Number.isInteger(ticks) || ticks <= 0) throw new Error("advance ticks must be a positive integer.");
903
+ const startTick = options.tick();
317
904
  await options.fixedStep(ticks);
318
- const startTick = tick;
319
- tick += ticks;
320
- return { clock: { mode: "fixed-step", tick }, ticks: tick - startTick };
905
+ const tick = options.tick();
906
+ const advanced = tick - startTick;
907
+ if (advanced !== ticks)
908
+ throw new Error(`fixedStep advanced ${advanced} actual ticks; expected ${ticks}.`);
909
+ return { clock: { mode: "fixed-step", tick }, ticks: advanced };
321
910
  }
322
911
  },
323
- applySetup: async (request) => applySetup(registry, options.resources, request),
912
+ applySetup: async (request) => {
913
+ syncEntities(registry, options.entities);
914
+ applySetup(registry, options.resources, request);
915
+ },
324
916
  ...options.events === void 0 ? {} : {
325
917
  drainEvents: async (limit = PLAYTEST_PROTOCOL_LIMITS.maxEventsPerDrain) => {
326
918
  if (!Number.isInteger(limit) || limit < 0) throw new Error("drainEvents limit must be a non-negative integer.");
@@ -335,7 +927,12 @@ function installThreePlaytestBridge(options) {
335
927
  name: "@threenative/playtest/three",
336
928
  protocolVersion: PLAYTEST_PROTOCOL_VERSION
337
929
  }),
338
- ready: () => ({ ready: true }),
930
+ ready: () => {
931
+ const startup = options.startup?.();
932
+ if (startup === void 0) return { ready: true };
933
+ assertJsonSafe(startup);
934
+ return { ready: true, startup };
935
+ },
339
936
  sample: (request) => {
340
937
  syncEntities(registry, options.entities);
341
938
  const snapshot = sampleThreeObservations({
@@ -343,14 +940,17 @@ function installThreePlaytestBridge(options) {
343
940
  clockMode: options.fixedStep === void 0 ? "render-frame" : "fixed-step",
344
941
  diagnostics: options.diagnostics,
345
942
  gameplay: options.gameplay,
943
+ runtimeDiagnosticsSeries: options.runtimeDiagnosticsSeries,
944
+ renderChain: options.renderChain,
346
945
  registry,
347
946
  renderer: options.renderer,
348
947
  resources: options.resources === void 0 ? void 0 : () => options.resources.read(),
349
948
  scene: options.scene,
350
- tick: options.fixedStep === void 0 ? void 0 : tick
949
+ tick: options.tick?.()
351
950
  }, request);
352
951
  const components = options.components?.();
353
- const result = components === void 0 || Object.keys(components).length === 0 ? snapshot : { ...snapshot, components };
952
+ const withComponents = components === void 0 || Object.keys(components).length === 0 ? snapshot : { ...snapshot, components };
953
+ const result = recorder === void 0 || request.include?.includes("physicsDebugSeries") !== true ? withComponents : { ...withComponents, physicsDebugSeries: recorder.sample(request, options.tick()) };
354
954
  assertJsonSafe(result);
355
955
  return result;
356
956
  }
@@ -376,12 +976,13 @@ function syncEntities(registry, entities) {
376
976
  registry.replace(typeof entities === "function" ? entities() : entities);
377
977
  }
378
978
  function applySetup(registry, resources, request) {
379
- request.entities?.forEach(({ entity, transform }) => {
979
+ request.entities?.forEach(({ entity, frozen, transform }) => {
380
980
  const object = registry.get(entity)?.object;
381
981
  if (object === void 0) throw new Error(`Setup entity '${entity}' is not registered.`);
382
982
  if (transform.position !== void 0) object.position.fromArray(transform.position);
383
983
  if (transform.rotation !== void 0) object.quaternion.fromArray(transform.rotation);
384
984
  if (transform.scale !== void 0) object.scale.fromArray(transform.scale);
985
+ if (frozen === true) object.userData[PLAYTEST_FROZEN_MARKER] = true;
385
986
  object.updateMatrix();
386
987
  });
387
988
  request.resources?.forEach(({ id, path, value }) => {
@@ -391,4 +992,4 @@ function applySetup(registry, resources, request) {
391
992
  });
392
993
  }
393
994
 
394
- export { ThreePlaytestEntityRegistry, connectDevicePlaytestBridge, installThreePlaytestBridge, objectPath, readPlaytestEndpoint, sampleThreeObservations };
995
+ export { PLAYTEST_PHYSICS_BODY_LIMIT, PLAYTEST_PHYSICS_SAMPLE_LIMIT, ThreePlaytestPhysicsRecorder, adviseThreeRenderWorkload, connectDevicePlaytestBridge, installThreePlaytestBridge, readPlaytestEndpoint };