@threenative/playtest 0.1.0 → 0.2.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,5 +1,447 @@
1
1
  import { Vector2, Vector3, Box3, Matrix4, Frustum } from 'three';
2
2
 
3
+ // src/three/renderWorkloadAdvisor.ts
4
+ var DEFAULT_TOP_N = 10;
5
+ var MAX_TOP_N = 32;
6
+ var MAX_OBSERVED_PASSES = 64;
7
+ var GROUP_FLOOR = 16;
8
+ var SPRITE_FLOOR = 32;
9
+ var POINT_OBJECT_FLOOR = 16;
10
+ var SAFE_SCENE_COLLAPSE_REASONS = /* @__PURE__ */ new Set([
11
+ "applied",
12
+ "belowMeshFloorStillWatching",
13
+ "belowMeshFloorAfterCameraExclusion",
14
+ "missingMaterial",
15
+ "missingGeometry",
16
+ "mergeGroupMissingPosition",
17
+ "mergeRefused",
18
+ "mergeLostNormals",
19
+ "movingGroupLostOwnerId"
20
+ ]);
21
+ var SAFE_SCENE_COLLAPSE_STATUS = /* @__PURE__ */ new Set(["applied", "deferred", "rejected"]);
22
+ var VERIFIED_EXAMPLE_PATHS = {
23
+ gpuParticles: "examples/abyss-framework/src/scenes/Abyss.ts",
24
+ hudInstancing: "packages/create-threenative/templates/minimal/src/render/hud.ts",
25
+ materialSharing: "packages/create-threenative/templates/starter/src/render/materials.ts",
26
+ staticMerge: "examples/native-cpu-load-test/src/main.ts"
27
+ };
28
+ function adviseThreeRenderWorkload(input) {
29
+ const examplePaths = validateVerifiedExamplePaths(input.verifiedExamplePaths);
30
+ const topN = clampTopN(input.topN);
31
+ const geometryIds = /* @__PURE__ */ new WeakMap();
32
+ const materialIds = /* @__PURE__ */ new WeakMap();
33
+ let nextGeometryId = 1;
34
+ let nextMaterialId = 1;
35
+ const geometries = /* @__PURE__ */ new Set();
36
+ const materials = /* @__PURE__ */ new Set();
37
+ const groups = /* @__PURE__ */ new Map();
38
+ const materialComparableGroups = /* @__PURE__ */ new Map();
39
+ let logicalObjectCount = 0;
40
+ let renderableCount = 0;
41
+ let instancedRenderableCount = 0;
42
+ let spriteCount = 0;
43
+ let pointsCount = 0;
44
+ const geometryId = (value) => idOf(geometryIds, value, () => nextGeometryId++);
45
+ const materialId = (value) => idOf(materialIds, value, () => nextMaterialId++);
46
+ input.scene.traverse((object) => {
47
+ logicalObjectCount += 1;
48
+ const renderable = object;
49
+ if (!isRenderable(renderable)) return;
50
+ if (!object.visible) return;
51
+ if (renderable.isInstancedMesh === true) instancedRenderableCount += instanceCount(renderable);
52
+ if (renderable.isSprite === true) spriteCount += 1;
53
+ if (renderable.isPoints === true) pointsCount += 1;
54
+ renderableCount += 1;
55
+ const geometry = renderable.geometry;
56
+ const objectMaterials = materialList(renderable.material);
57
+ if (geometry !== void 0) geometries.add(geometry);
58
+ for (const material of objectMaterials) materials.add(material);
59
+ const key = groupKey(renderable, geometry, objectMaterials, geometryId, materialId);
60
+ const group = groups.get(key) ?? createGroup();
61
+ groups.set(key, group);
62
+ const count = renderable.isInstancedMesh === true ? instanceCount(renderable) : 1;
63
+ group.memberCount += count;
64
+ if (geometry !== void 0) group.geometries.add(geometry);
65
+ for (const material of objectMaterials) group.materials.add(material);
66
+ if (objectMaterials.length > 0 && renderable.isMesh === true && geometry !== void 0) {
67
+ const comparableSignatures = objectMaterials.map(comparableMaterialSignature);
68
+ if (comparableSignatures.every((signature) => signature !== void 0)) {
69
+ const comparableKey = `${geometryId(geometry)}:${comparableSignatures.join("+")}`;
70
+ const comparable = materialComparableGroups.get(comparableKey) ?? createGroup();
71
+ materialComparableGroups.set(comparableKey, comparable);
72
+ comparable.memberCount += count;
73
+ comparable.geometries.add(geometry);
74
+ for (const material of objectMaterials) comparable.materials.add(material);
75
+ }
76
+ }
77
+ const reasons = constraintReasons(renderable, input.materialMutationSafety ?? "unknown");
78
+ if (reasons.length === 0) {
79
+ if ((input.transformSafety ?? "unknown") === "caller-declared-static") group.eligibleStaticCount += count;
80
+ else group.eligibleDynamicCount += count;
81
+ } else {
82
+ for (const reason of reasons) increment(group.constraintReasonCounts, reason, count);
83
+ }
84
+ });
85
+ if ((input.materialMutationSafety ?? "unknown") === "unknown") {
86
+ for (const group of materialComparableGroups.values()) {
87
+ if (group.materials.size > 1) increment(group.constraintReasonCounts, "materialMutationSafetyUnknown", group.memberCount);
88
+ }
89
+ }
90
+ const allGroups = [...groups.values()].map(serializeGroup).sort((left, right) => right.memberCount - left.memberCount);
91
+ const materialShareGroups = [...materialComparableGroups.values()].map(serializeGroup).sort((left, right) => right.memberCount - left.memberCount);
92
+ const topGroups = allGroups.slice(0, topN);
93
+ const observedPasses = validatedPasses(input.observed?.passes ?? []);
94
+ const observed = {
95
+ passes: {
96
+ recorded: observedPasses.length,
97
+ truncated: Math.max(0, (input.observed?.passes?.length ?? 0) - observedPasses.length)
98
+ },
99
+ renderer: sanitizeObservedRenderer(input.observed?.renderer)
100
+ };
101
+ const passObservations = observePasses(observedPasses);
102
+ const recommendations = [];
103
+ const sanitizedSceneCollapse = input.sceneCollapse === void 0 ? void 0 : sanitizeSceneCollapse(input.sceneCollapse);
104
+ const collapseDescribesCurrentGraph = sanitizedSceneCollapse?.status === "applied" && renderableCount <= sanitizedSceneCollapse.mergedMeshes;
105
+ if (!collapseDescribesCurrentGraph) {
106
+ const compatibleGroups = allGroupsWithMinimum(allGroups, GROUP_FLOOR);
107
+ const compatibleCount = compatibleGroups.reduce((sum, group) => sum + group.memberCount, 0);
108
+ const expectedGroups = compatibleGroups.length;
109
+ const firstCompatible = compatibleGroups[0];
110
+ if (firstCompatible !== void 0 && instancedRenderableCount === 0) {
111
+ const staleCollapseCaveat = sanitizedSceneCollapse?.status === "applied" ? ["scene-collapse-report-must-describe-current-graph"] : [];
112
+ recommendations.push({
113
+ caveats: [
114
+ "dynamic-transforms-use-instancing",
115
+ "generated-source-remedy-only",
116
+ "static-merge-requires-caller-declared-static-transforms",
117
+ ...staleCollapseCaveat
118
+ ],
119
+ code: "TN_RENDER_ADVISE_INSTANCE_COMPATIBLE",
120
+ constraints: firstCompatible.constraintReasonCounts,
121
+ evidence: { metric: "snapshot.compatibleGroups.memberCount", path: "topGroups.memberCount" },
122
+ examplePath: examplePaths.staticMerge,
123
+ expectedReducedCount: expectedGroups,
124
+ observedCount: compatibleCount,
125
+ owner: "generated-src",
126
+ severity: "warning"
127
+ });
128
+ if ((input.transformSafety ?? "unknown") === "caller-declared-static") {
129
+ recommendations.push({
130
+ caveats: ["caller-declared-static-transforms", "preserve-pickability-and-animation-semantics"],
131
+ code: "TN_RENDER_ADVISE_STATIC_MERGE_COMPATIBLE",
132
+ constraints: firstCompatible.constraintReasonCounts,
133
+ evidence: { metric: "snapshot.compatibleGroups.eligibleStaticCount", path: "topGroups.eligibleStaticCount" },
134
+ examplePath: examplePaths.staticMerge,
135
+ expectedReducedCount: expectedGroups,
136
+ observedCount: compatibleCount,
137
+ owner: "generated-src",
138
+ severity: "warning"
139
+ });
140
+ }
141
+ }
142
+ }
143
+ const materialShareGroup = materialShareGroups.find((group) => group.memberCount >= GROUP_FLOOR && group.materialIdentities > 1 && group.constraintReasonCounts.materialMutationSafetyUnknown === void 0);
144
+ if (materialShareGroup !== void 0 && input.materialMutationSafety === "caller-declared-stable") {
145
+ recommendations.push({
146
+ caveats: ["caller-declared-material-mutation-safe", "do-not-stringify-shaders-textures-userData"],
147
+ code: "TN_RENDER_ADVISE_SHARE_MATERIALS",
148
+ constraints: materialShareGroup.constraintReasonCounts,
149
+ evidence: { metric: "snapshot.materialComparableGroup.materialIdentities", path: "topGroups.materialIdentities" },
150
+ examplePath: examplePaths.materialSharing,
151
+ expectedReducedCount: materialShareGroup.geometryIdentities,
152
+ observedCount: materialShareGroup.materialIdentities,
153
+ owner: "generated-src",
154
+ severity: "info"
155
+ });
156
+ }
157
+ if (spriteCount >= SPRITE_FLOOR && input.spriteWorkload === "caller-declared-camera-overlay") {
158
+ recommendations.push({
159
+ caveats: ["camera-parented-hud-only", "negative-controls-stay-ordinary-sprites"],
160
+ code: "TN_RENDER_ADVISE_HUD_INSTANCING",
161
+ constraints: {},
162
+ evidence: { metric: "snapshot.spriteCount", path: "snapshot.spriteCount" },
163
+ examplePath: examplePaths.hudInstancing,
164
+ expectedReducedCount: 1,
165
+ observedCount: spriteCount,
166
+ owner: "generated-src",
167
+ severity: "info"
168
+ });
169
+ }
170
+ if (pointsCount >= POINT_OBJECT_FLOOR && input.particleWorkload === "caller-declared-many-independent-objects") {
171
+ recommendations.push({
172
+ caveats: ["many-independent-point-or-sprite-like-objects-only", "single-Points-is-already-batched"],
173
+ code: "TN_RENDER_ADVISE_GPU_PARTICLES",
174
+ constraints: {},
175
+ evidence: { metric: "snapshot.pointsCount", path: "snapshot.pointsCount" },
176
+ examplePath: examplePaths.gpuParticles,
177
+ expectedReducedCount: 1,
178
+ observedCount: pointsCount,
179
+ owner: "generated-src",
180
+ severity: "info"
181
+ });
182
+ }
183
+ const redundantPass = passObservations.find((entry) => entry.reasonCode === "repeatedEquivalentPass");
184
+ if (redundantPass !== void 0) {
185
+ recommendations.push({
186
+ caveats: ["caller-provided-pass-equivalence-required", "do-not-remove-depth-shadow-post-passes"],
187
+ code: "TN_RENDER_ADVISE_REPEATED_PASS",
188
+ constraints: {},
189
+ evidence: { metric: "observed.passSemantics", path: "passObservations" },
190
+ examplePath: examplePaths.staticMerge,
191
+ expectedReducedCount: 1,
192
+ observedCount: redundantPass.count,
193
+ owner: "generated-src",
194
+ severity: "warning"
195
+ });
196
+ }
197
+ return {
198
+ schemaVersion: 1,
199
+ observed,
200
+ passObservations,
201
+ recommendations,
202
+ ...sanitizedSceneCollapse === void 0 ? {} : { sceneCollapse: sanitizedSceneCollapse },
203
+ snapshot: {
204
+ geometryIdentityCount: geometries.size,
205
+ instancedRenderableCount,
206
+ logicalObjectCount,
207
+ logicalObjectCountIncludesRootScene: true,
208
+ materialIdentityCount: materials.size,
209
+ pointsCount,
210
+ renderableCount,
211
+ spriteCount,
212
+ visibleFlagRenderableCount: renderableCount
213
+ },
214
+ topGroups
215
+ };
216
+ }
217
+ function clampTopN(value) {
218
+ if (value === void 0) return DEFAULT_TOP_N;
219
+ if (!Number.isFinite(value)) return DEFAULT_TOP_N;
220
+ return Math.max(1, Math.min(MAX_TOP_N, Math.floor(value)));
221
+ }
222
+ function validateVerifiedExamplePaths(paths) {
223
+ for (const key of Object.keys(VERIFIED_EXAMPLE_PATHS)) {
224
+ if (paths[key] !== VERIFIED_EXAMPLE_PATHS[key]) {
225
+ throw new Error(`verifiedExamplePaths.${key} must be the exact advisor allowlist path.`);
226
+ }
227
+ }
228
+ return VERIFIED_EXAMPLE_PATHS;
229
+ }
230
+ function sanitizeObservedRenderer(counters) {
231
+ return {
232
+ ...safeObservedCounter(counters?.drawCalls) === void 0 ? {} : { drawCalls: safeObservedCounter(counters?.drawCalls) },
233
+ ...safeObservedCounter(counters?.triangles) === void 0 ? {} : { triangles: safeObservedCounter(counters?.triangles) }
234
+ };
235
+ }
236
+ function safeObservedCounter(value) {
237
+ if (value === void 0) return void 0;
238
+ if (!Number.isFinite(value) || value < 0) return void 0;
239
+ return value;
240
+ }
241
+ function idOf(map, value, next) {
242
+ const existing = map.get(value);
243
+ if (existing !== void 0) return existing;
244
+ const created = next();
245
+ map.set(value, created);
246
+ return created;
247
+ }
248
+ function createGroup() {
249
+ return {
250
+ constraintReasonCounts: /* @__PURE__ */ new Map(),
251
+ eligibleDynamicCount: 0,
252
+ eligibleStaticCount: 0,
253
+ geometries: /* @__PURE__ */ new Set(),
254
+ materials: /* @__PURE__ */ new Set(),
255
+ memberCount: 0
256
+ };
257
+ }
258
+ function serializeGroup(group) {
259
+ return {
260
+ constraintReasonCounts: Object.fromEntries([...group.constraintReasonCounts.entries()].sort(([left], [right]) => left.localeCompare(right))),
261
+ eligibleDynamicCount: group.eligibleDynamicCount,
262
+ eligibleStaticCount: group.eligibleStaticCount,
263
+ geometryIdentities: group.geometries.size,
264
+ materialIdentities: group.materials.size,
265
+ memberCount: group.memberCount
266
+ };
267
+ }
268
+ function isRenderable(object) {
269
+ return object.isMesh === true || object.isInstancedMesh === true || object.isSprite === true || object.isPoints === true;
270
+ }
271
+ function materialList(material) {
272
+ if (Array.isArray(material)) {
273
+ const items = [];
274
+ for (const item of material) {
275
+ if (typeof item !== "object" || item === null) throw new Error("render advisor material array contains a non-object material.");
276
+ items.push(item);
277
+ }
278
+ return items;
279
+ }
280
+ if (material === void 0 || material === null) return [];
281
+ if (typeof material !== "object") throw new Error("render advisor material must be an object.");
282
+ return [material];
283
+ }
284
+ function groupKey(object, geometry, materials, geometryId, materialId) {
285
+ if (object.isSprite === true) return "sprite";
286
+ if (object.isPoints === true) return `points:${geometry === void 0 ? "none" : geometryId(geometry)}`;
287
+ const material = materials.length === 0 ? "none" : materials.map((item) => materialSignature(item, materialId)).join("+");
288
+ return `${geometry === void 0 ? "none" : geometryId(geometry)}:${material}`;
289
+ }
290
+ function materialSignature(material, materialId) {
291
+ const record = material;
292
+ const color = record.color;
293
+ const type = String(record.type ?? "Material");
294
+ if (isCustomShaderMaterial(record)) return `unsafe-custom-shader:${type}`;
295
+ if (isNodeMaterial(record)) return `unsafe-node-material:${type}`;
296
+ if (hasMappedTexture(record)) return `unsafe-mapped-texture:${type}`;
297
+ return [
298
+ `identity-${materialId(material)}`,
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 comparableMaterialSignature(material) {
312
+ const record = material;
313
+ if (isCustomShaderMaterial(record) || isNodeMaterial(record) || hasMappedTexture(record)) return void 0;
314
+ const color = record.color;
315
+ const type = String(record.type ?? "Material");
316
+ return [
317
+ type,
318
+ color?.getHexString?.() ?? "no-color",
319
+ String(record.transparent ?? false),
320
+ String(record.blending ?? ""),
321
+ String(record.depthWrite ?? ""),
322
+ String(record.depthTest ?? ""),
323
+ String(record.side ?? ""),
324
+ String(record.roughness ?? ""),
325
+ String(record.metalness ?? ""),
326
+ String(record.flatShading ?? "")
327
+ ].join("|");
328
+ }
329
+ function constraintReasons(object, _materialMutationSafety) {
330
+ const reasons = [];
331
+ const materials = materialList(object.material);
332
+ if (object.isSkinnedMesh === true) reasons.push("skinnedMesh");
333
+ if (Array.isArray(object.morphTargetInfluences) && object.morphTargetInfluences.length > 0) reasons.push("morphTargets");
334
+ if (hasOwnFunction(object, "onBeforeRender")) reasons.push("renderHook");
335
+ if (hasOwnFunction(object, "onAfterRender")) reasons.push("renderHook");
336
+ if (object.layers.mask !== 1) reasons.push("customLayerMask");
337
+ if (object.renderOrder !== 0) reasons.push("customRenderOrder");
338
+ for (const material of materials) {
339
+ if (material.transparent === true) reasons.push("transparentMaterial");
340
+ if (isCustomShaderMaterial(material)) reasons.push("customShader", "materialCustomShader");
341
+ if (isNodeMaterial(material)) reasons.push("customNode", "materialCustomNode");
342
+ if (hasMappedTexture(material)) reasons.push("materialTextureMap");
343
+ }
344
+ return uniqueStrings(reasons);
345
+ }
346
+ function hasOwnFunction(object, key) {
347
+ return Object.hasOwn(object, key) && typeof object[key] === "function";
348
+ }
349
+ function isCustomShaderMaterial(material) {
350
+ const type = String(material.type ?? "");
351
+ return type === "ShaderMaterial" || type === "RawShaderMaterial" || Object.hasOwn(material, "onBeforeCompile") && typeof material.onBeforeCompile === "function";
352
+ }
353
+ function isNodeMaterial(material) {
354
+ return String(material.type ?? "").includes("Node");
355
+ }
356
+ function hasMappedTexture(material) {
357
+ const map = material.map;
358
+ return typeof map === "object" && map !== null;
359
+ }
360
+ function uniqueStrings(values) {
361
+ const seen = /* @__PURE__ */ new Set();
362
+ const result = [];
363
+ for (const value of values) {
364
+ if (!seen.has(value)) {
365
+ seen.add(value);
366
+ result.push(value);
367
+ }
368
+ }
369
+ return result;
370
+ }
371
+ function instanceCount(object) {
372
+ const value = object.count;
373
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 1;
374
+ }
375
+ function increment(map, key, amount) {
376
+ map.set(key, (map.get(key) ?? 0) + amount);
377
+ }
378
+ function incompatibleCount(group) {
379
+ let sum = 0;
380
+ for (const [reason, count] of Object.entries(group.constraintReasonCounts)) {
381
+ if (reason !== "materialMutationSafetyUnknown") sum += count;
382
+ }
383
+ return sum;
384
+ }
385
+ function allGroupsWithMinimum(groups, minimum) {
386
+ const result = [];
387
+ for (const group of groups) {
388
+ if (group.memberCount >= minimum && incompatibleCount(group) === 0) result.push(group);
389
+ }
390
+ return result;
391
+ }
392
+ function validatedPasses(passes) {
393
+ const result = [];
394
+ const limit = Math.min(MAX_OBSERVED_PASSES, passes.length);
395
+ for (let index = 0; index < limit; index += 1) {
396
+ const pass = passes[index];
397
+ if (pass === void 0) throw new Error("observed.passes contains an empty entry.");
398
+ for (const key of ["sceneToken", "cameraToken"]) {
399
+ if (typeof pass[key] !== "string" || pass[key].length === 0) throw new Error(`observed.passes.${key} must be a non-empty string.`);
400
+ }
401
+ for (const key of ["depthToken", "equivalenceToken", "targetToken"]) {
402
+ const value = pass[key];
403
+ if (value !== void 0 && (typeof value !== "string" || value.length === 0)) throw new Error(`observed.passes.${key} must be a non-empty string when present.`);
404
+ }
405
+ if (pass.renderCalls !== void 0 && (!Number.isSafeInteger(pass.renderCalls) || pass.renderCalls < 0)) throw new Error("observed.passes.renderCalls must be a non-negative integer.");
406
+ result.push(pass);
407
+ }
408
+ return result;
409
+ }
410
+ function observePasses(passes) {
411
+ if (passes.length <= 1) return passes.length === 0 ? [] : [{ count: passes.length, reasonCode: "singlePassObserved" }];
412
+ const buckets = /* @__PURE__ */ new Map();
413
+ let different = 0;
414
+ for (const pass of passes) {
415
+ const key = [pass.sceneToken, pass.cameraToken, pass.targetToken ?? "screen", pass.depthToken ?? "default", pass.purpose ?? "color", pass.equivalenceToken ?? "unknown"].join("|");
416
+ buckets.set(key, (buckets.get(key) ?? 0) + 1);
417
+ }
418
+ const observations = [];
419
+ for (const count of buckets.values()) {
420
+ if (count > 1) observations.push({ count, reasonCode: "repeatedEquivalentPass" });
421
+ else different += 1;
422
+ }
423
+ if (different > 0) observations.push({ count: different, reasonCode: "differentPassSemantics" });
424
+ return observations;
425
+ }
426
+ function sanitizeSceneCollapse(report) {
427
+ const reasonCode = SAFE_SCENE_COLLAPSE_REASONS.has(report.reasonCode) ? report.reasonCode : "unknown";
428
+ const status = SAFE_SCENE_COLLAPSE_STATUS.has(report.status) ? report.status : "rejected";
429
+ return {
430
+ ...safeCount(report.mergedMaterialIdentities) === void 0 ? {} : { mergedMaterialIdentities: safeCount(report.mergedMaterialIdentities) },
431
+ mergedMeshes: safeCount(report.mergedMeshes) ?? 0,
432
+ reasonCode,
433
+ schemaVersion: 1,
434
+ ...safeCount(report.sourceMaterialIdentities) === void 0 ? {} : { sourceMaterialIdentities: safeCount(report.sourceMaterialIdentities) },
435
+ sourceMeshes: safeCount(report.sourceMeshes) ?? 0,
436
+ status
437
+ };
438
+ }
439
+ function safeCount(value) {
440
+ if (value === void 0) return void 0;
441
+ if (!Number.isSafeInteger(value) || value < 0) return 0;
442
+ return value;
443
+ }
444
+
3
445
  // src/protocol.ts
4
446
  var PLAYTEST_BRIDGE_GLOBAL = "__THREENATIVE_PLAYTEST_BRIDGE__";
5
447
  var PLAYTEST_PROTOCOL_VERSION = 1;
@@ -77,6 +519,7 @@ function sampleThreeObservations(input, request) {
77
519
  input.camera.updateMatrixWorld(true);
78
520
  const rendererSize = input.renderer.getDrawingBufferSize(new Vector2());
79
521
  const entities = input.registry.select(request.entities).map(({ id, object }) => observeEntity(id, object, input.camera, rendererSize.x, rendererSize.y));
522
+ const renderPerformance = rendererPerformance(input.renderer);
80
523
  return {
81
524
  clock: {
82
525
  mode: input.clockMode,
@@ -85,9 +528,24 @@ function sampleThreeObservations(input, request) {
85
528
  ...input.diagnostics === void 0 ? {} : { diagnostics: input.diagnostics() },
86
529
  entities,
87
530
  ...input.gameplay === void 0 ? {} : { gameplay: input.gameplay() },
531
+ ...renderPerformance === void 0 ? {} : { performance: renderPerformance },
532
+ ...input.runtimeDiagnosticsSeries === void 0 ? {} : { runtimeDiagnosticsSeries: input.runtimeDiagnosticsSeries().map((sample) => ({ ...sample })) },
88
533
  ...input.resources === void 0 ? {} : { resources: input.resources() }
89
534
  };
90
535
  }
536
+ function rendererPerformance(renderer) {
537
+ const render = renderer.info?.render;
538
+ const drawCalls = finiteNumber(render?.drawCalls) ? render.drawCalls : void 0;
539
+ const triangles = finiteNumber(render?.triangles) ? render.triangles : void 0;
540
+ if (drawCalls === void 0 && triangles === void 0) return void 0;
541
+ return {
542
+ ...drawCalls === void 0 ? {} : { drawCalls },
543
+ ...triangles === void 0 ? {} : { triangles }
544
+ };
545
+ }
546
+ function finiteNumber(value) {
547
+ return typeof value === "number" && Number.isFinite(value);
548
+ }
91
549
  function observeEntity(id, object, camera, viewportWidth, viewportHeight) {
92
550
  const position = object.getWorldPosition(new Vector3());
93
551
  const bounds = projectedBounds(object, camera, viewportWidth, viewportHeight);
@@ -131,6 +589,51 @@ function projectedBounds(object, camera, viewportWidth, viewportHeight) {
131
589
  };
132
590
  }
133
591
 
592
+ // src/three/physics.ts
593
+ var PLAYTEST_PHYSICS_BODY_LIMIT = 100;
594
+ var PLAYTEST_PHYSICS_SAMPLE_LIMIT = 100;
595
+ var ThreePlaytestPhysicsRecorder = class {
596
+ #physics;
597
+ #series = [];
598
+ constructor(physics) {
599
+ this.#physics = physics;
600
+ }
601
+ sample(request, tick) {
602
+ if (request.label !== void 0) {
603
+ if (this.#series.some(({ label }) => label === request.label))
604
+ throw new Error(`TN_PLAYTEST_PHYSICS_LABEL_DUPLICATE: '${request.label}' was already sampled.`);
605
+ if (this.#series.length >= PLAYTEST_PHYSICS_SAMPLE_LIMIT)
606
+ throw new Error(`TN_PLAYTEST_PHYSICS_SAMPLE_LIMIT: at most ${PLAYTEST_PHYSICS_SAMPLE_LIMIT} labelled samples are retained.`);
607
+ this.#series.push({ label: request.label, snapshot: physicsSnapshot(this.#physics.bodies()), tick });
608
+ }
609
+ return this.#series.map((sample) => ({ ...sample }));
610
+ }
611
+ };
612
+ function physicsSnapshot(bodies) {
613
+ if (!Array.isArray(bodies))
614
+ throw new Error("TN_PLAYTEST_PHYSICS_BODIES: the physics provider must return an array of bodies.");
615
+ const retained = bodies.slice(0, PLAYTEST_PHYSICS_BODY_LIMIT);
616
+ const seen = /* @__PURE__ */ new Set();
617
+ const primitives = retained.flatMap((body) => {
618
+ if (typeof body?.id !== "string" || body.id.length === 0)
619
+ throw new Error("TN_PLAYTEST_PHYSICS_BODY_ID: every observed physics body needs a non-empty string id.");
620
+ if (seen.has(body.id))
621
+ throw new Error(`TN_PLAYTEST_PHYSICS_BODY_DUPLICATE: body id '${body.id}' was reported twice in one sample.`);
622
+ seen.add(body.id);
623
+ if (typeof body.sleeping !== "boolean")
624
+ throw new Error(`TN_PLAYTEST_PHYSICS_BODY_SLEEPING: body '${body.id}' must report sleeping as a boolean.`);
625
+ if (!isFiniteVec3(body.position))
626
+ throw new Error(`TN_PLAYTEST_PHYSICS_BODY_POSITION: body '${body.id}' must report a finite [x, y, z] position.`);
627
+ const sleep = { category: "sleep", entity: body.id, value: body.sleeping ? 1 : 0 };
628
+ const centerOfMass = { category: "center-of-mass", entity: body.id, position: [...body.position] };
629
+ return [sleep, centerOfMass];
630
+ });
631
+ return { artifact: { overflow: { omittedBodies: bodies.length - retained.length }, primitives } };
632
+ }
633
+ function isFiniteVec3(value) {
634
+ return Array.isArray(value) && value.length === 3 && value.every((component) => typeof component === "number" && Number.isFinite(component));
635
+ }
636
+
134
637
  // src/three/device.ts
135
638
  var BRIDGE_METHODS = /* @__PURE__ */ new Set([
136
639
  "advance",
@@ -291,11 +794,15 @@ function isRecord(value) {
291
794
 
292
795
  // src/three/bridge.ts
293
796
  function installThreePlaytestBridge(options) {
797
+ if (options.fixedStep === void 0 !== (options.tick === void 0))
798
+ throw new Error("fixedStep and its authoritative tick provider must be installed together.");
799
+ if (options.physics !== void 0 && options.tick === void 0)
800
+ throw new Error("A physics provider requires the authoritative tick provider, and therefore fixedStep.");
801
+ const recorder = options.physics === void 0 ? void 0 : new ThreePlaytestPhysicsRecorder(options.physics);
294
802
  const host = globalThis;
295
803
  const previous = host[PLAYTEST_BRIDGE_GLOBAL];
296
804
  const registry = new ThreePlaytestEntityRegistry();
297
805
  syncEntities(registry, options.entities);
298
- let tick = 0;
299
806
  const capabilities = () => [
300
807
  "camera.observe",
301
808
  "entity.bounds",
@@ -307,17 +814,23 @@ function installThreePlaytestBridge(options) {
307
814
  ...Object.keys(options.components?.() ?? {}).length === 0 ? [] : ["runtime.components"],
308
815
  ...options.events === void 0 ? [] : ["runtime.events"],
309
816
  ...options.gameplay === void 0 ? [] : ["runtime.animation", "runtime.state"],
817
+ ...options.physics === void 0 ? [] : ["runtime.physics"],
818
+ ...options.runtimeDiagnosticsSeries === void 0 ? [] : ["runtime.performance"],
310
819
  ...options.gameplayChannels?.().includes("runtime.contacts") === true ? ["runtime.contacts"] : [],
311
- ...options.gameplayChannels?.().includes("runtime.tags") === true ? ["runtime.tags"] : []
820
+ ...options.gameplayChannels?.().includes("runtime.tags") === true ? ["runtime.tags"] : [],
821
+ ...options.gameplayChannels?.().includes("runtime.world") === true ? ["runtime.world"] : []
312
822
  ];
313
823
  const bridge = {
314
824
  ...options.fixedStep === void 0 ? {} : {
315
825
  advance: async (ticks) => {
316
826
  if (!Number.isInteger(ticks) || ticks <= 0) throw new Error("advance ticks must be a positive integer.");
827
+ const startTick = options.tick();
317
828
  await options.fixedStep(ticks);
318
- const startTick = tick;
319
- tick += ticks;
320
- return { clock: { mode: "fixed-step", tick }, ticks: tick - startTick };
829
+ const tick = options.tick();
830
+ const advanced = tick - startTick;
831
+ if (advanced !== ticks)
832
+ throw new Error(`fixedStep advanced ${advanced} actual ticks; expected ${ticks}.`);
833
+ return { clock: { mode: "fixed-step", tick }, ticks: advanced };
321
834
  }
322
835
  },
323
836
  applySetup: async (request) => applySetup(registry, options.resources, request),
@@ -343,14 +856,16 @@ function installThreePlaytestBridge(options) {
343
856
  clockMode: options.fixedStep === void 0 ? "render-frame" : "fixed-step",
344
857
  diagnostics: options.diagnostics,
345
858
  gameplay: options.gameplay,
859
+ runtimeDiagnosticsSeries: options.runtimeDiagnosticsSeries,
346
860
  registry,
347
861
  renderer: options.renderer,
348
862
  resources: options.resources === void 0 ? void 0 : () => options.resources.read(),
349
863
  scene: options.scene,
350
- tick: options.fixedStep === void 0 ? void 0 : tick
864
+ tick: options.tick?.()
351
865
  }, request);
352
866
  const components = options.components?.();
353
- const result = components === void 0 || Object.keys(components).length === 0 ? snapshot : { ...snapshot, components };
867
+ const withComponents = components === void 0 || Object.keys(components).length === 0 ? snapshot : { ...snapshot, components };
868
+ const result = recorder === void 0 || request.include?.includes("physicsDebugSeries") !== true ? withComponents : { ...withComponents, physicsDebugSeries: recorder.sample(request, options.tick()) };
354
869
  assertJsonSafe(result);
355
870
  return result;
356
871
  }
@@ -391,4 +906,4 @@ function applySetup(registry, resources, request) {
391
906
  });
392
907
  }
393
908
 
394
- export { ThreePlaytestEntityRegistry, connectDevicePlaytestBridge, installThreePlaytestBridge, objectPath, readPlaytestEndpoint, sampleThreeObservations };
909
+ export { PLAYTEST_PHYSICS_BODY_LIMIT, PLAYTEST_PHYSICS_SAMPLE_LIMIT, ThreePlaytestPhysicsRecorder, adviseThreeRenderWorkload, connectDevicePlaytestBridge, installThreePlaytestBridge, readPlaytestEndpoint };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/playtest",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Scenario-driven playtest harness for Three.js games. Runs on plain Three.js with zero ThreeNative dependencies.",
5
5
  "type": "module",
6
6
  "files": [