@threenative/playtest 0.2.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,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  import { Vector2, Vector3, Box3, Matrix4, Frustum } from 'three';
2
3
 
3
4
  // src/three/renderWorkloadAdvisor.ts
@@ -7,18 +8,6 @@ var MAX_OBSERVED_PASSES = 64;
7
8
  var GROUP_FLOOR = 16;
8
9
  var SPRITE_FLOOR = 32;
9
10
  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
11
  var VERIFIED_EXAMPLE_PATHS = {
23
12
  gpuParticles: "examples/abyss-framework/src/scenes/Abyss.ts",
24
13
  hudInstancing: "packages/create-threenative/templates/minimal/src/render/hud.ts",
@@ -100,44 +89,38 @@ function adviseThreeRenderWorkload(input) {
100
89
  };
101
90
  const passObservations = observePasses(observedPasses);
102
91
  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"] : [];
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") {
112
113
  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",
114
+ caveats: ["caller-declared-static-transforms", "preserve-pickability-and-animation-semantics"],
115
+ code: "TN_RENDER_ADVISE_STATIC_MERGE_COMPATIBLE",
120
116
  constraints: firstCompatible.constraintReasonCounts,
121
- evidence: { metric: "snapshot.compatibleGroups.memberCount", path: "topGroups.memberCount" },
117
+ evidence: { metric: "snapshot.compatibleGroups.eligibleStaticCount", path: "topGroups.eligibleStaticCount" },
122
118
  examplePath: examplePaths.staticMerge,
123
119
  expectedReducedCount: expectedGroups,
124
120
  observedCount: compatibleCount,
125
121
  owner: "generated-src",
126
122
  severity: "warning"
127
123
  });
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
124
  }
142
125
  }
143
126
  const materialShareGroup = materialShareGroups.find((group) => group.memberCount >= GROUP_FLOOR && group.materialIdentities > 1 && group.constraintReasonCounts.materialMutationSafetyUnknown === void 0);
@@ -199,7 +182,6 @@ function adviseThreeRenderWorkload(input) {
199
182
  observed,
200
183
  passObservations,
201
184
  recommendations,
202
- ...sanitizedSceneCollapse === void 0 ? {} : { sceneCollapse: sanitizedSceneCollapse },
203
185
  snapshot: {
204
186
  geometryIdentityCount: geometries.size,
205
187
  instancedRenderableCount,
@@ -423,28 +405,11 @@ function observePasses(passes) {
423
405
  if (different > 0) observations.push({ count: different, reasonCode: "differentPassSemantics" });
424
406
  return observations;
425
407
  }
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
408
 
445
409
  // src/protocol.ts
446
410
  var PLAYTEST_BRIDGE_GLOBAL = "__THREENATIVE_PLAYTEST_BRIDGE__";
447
411
  var PLAYTEST_PROTOCOL_VERSION = 1;
412
+ var PLAYTEST_FROZEN_MARKER = "__threenativeFrozen";
448
413
  var PLAYTEST_PROTOCOL_LIMITS = {
449
414
  maxEntitiesPerSample: 100,
450
415
  maxEventsPerDrain: 1e3,
@@ -520,6 +485,7 @@ function sampleThreeObservations(input, request) {
520
485
  const rendererSize = input.renderer.getDrawingBufferSize(new Vector2());
521
486
  const entities = input.registry.select(request.entities).map(({ id, object }) => observeEntity(id, object, input.camera, rendererSize.x, rendererSize.y));
522
487
  const renderPerformance = rendererPerformance(input.renderer);
488
+ const renderChain = input.renderChain?.();
523
489
  return {
524
490
  clock: {
525
491
  mode: input.clockMode,
@@ -529,6 +495,7 @@ function sampleThreeObservations(input, request) {
529
495
  entities,
530
496
  ...input.gameplay === void 0 ? {} : { gameplay: input.gameplay() },
531
497
  ...renderPerformance === void 0 ? {} : { performance: renderPerformance },
498
+ ...renderChain === void 0 ? {} : { renderChain },
532
499
  ...input.runtimeDiagnosticsSeries === void 0 ? {} : { runtimeDiagnosticsSeries: input.runtimeDiagnosticsSeries().map((sample) => ({ ...sample })) },
533
500
  ...input.resources === void 0 ? {} : { resources: input.resources() }
534
501
  };
@@ -634,7 +601,24 @@ function isFiniteVec3(value) {
634
601
  return Array.isArray(value) && value.length === 3 && value.every((component) => typeof component === "number" && Number.isFinite(component));
635
602
  }
636
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
+
637
619
  // src/three/device.ts
620
+ var MAILBOX_WATCHDOG_BEAT_MS = 250;
621
+ var MAILBOX_POLL_STALL_BEATS = 8;
638
622
  var BRIDGE_METHODS = /* @__PURE__ */ new Set([
639
623
  "advance",
640
624
  "applySetup",
@@ -649,6 +633,7 @@ function connectDevicePlaytestBridge(bridge, endpoint) {
649
633
  if (nativeInstallation !== void 0) return nativeInstallation;
650
634
  let closed = false;
651
635
  let reportedError = false;
636
+ const nativePointers = /* @__PURE__ */ new Map();
652
637
  let scheduled;
653
638
  const schedule = () => {
654
639
  if (closed) return;
@@ -665,7 +650,7 @@ function connectDevicePlaytestBridge(bridge, endpoint) {
665
650
  if (response.status !== 204) {
666
651
  if (!response.ok) throw new Error(`Device bridge poll failed with HTTP ${response.status}.`);
667
652
  const request = parseRequest(await response.json());
668
- await postResponse(endpoint, await dispatch(bridge, request));
653
+ await postResponse(endpoint, await dispatch(bridge, request, nativePointers));
669
654
  }
670
655
  } catch (error) {
671
656
  if (!reportedError) {
@@ -694,6 +679,10 @@ function connectNativeMailbox(bridge) {
694
679
  if (typeof mailbox?.request !== "string" || typeof mailbox.response !== "string" || typeof host?.receive !== "function" || typeof host.respond !== "function") return void 0;
695
680
  let closed = false;
696
681
  let frame;
682
+ const nativePointers = /* @__PURE__ */ new Map();
683
+ let watchdogBeats = 0;
684
+ let polledAtBeat = 0;
685
+ let stallReported = false;
697
686
  const respond = (response) => {
698
687
  if (!host.respond(mailbox.response, JSON.stringify(response))) {
699
688
  console.error("TN_PLAYTEST_DEVICE_TRANSPORT: native mailbox response failed");
@@ -701,11 +690,12 @@ function connectNativeMailbox(bridge) {
701
690
  };
702
691
  const poll = () => {
703
692
  if (closed) return;
693
+ polledAtBeat = watchdogBeats;
704
694
  const raw = host.receive(mailbox.request);
705
695
  if (raw !== void 0) {
706
696
  try {
707
697
  const request = parseRequest(JSON.parse(raw));
708
- void dispatch(bridge, request).then(respond);
698
+ void dispatch(bridge, request, nativePointers).then(respond);
709
699
  } catch (error) {
710
700
  respond({
711
701
  error: { message: error instanceof Error ? error.message : String(error) },
@@ -715,11 +705,28 @@ function connectNativeMailbox(bridge) {
715
705
  }
716
706
  frame = globalThis.requestAnimationFrame(poll);
717
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);
718
724
  respond({ id: "ready", result: null });
719
725
  frame = globalThis.requestAnimationFrame(poll);
720
726
  return {
721
727
  close: () => {
722
728
  closed = true;
729
+ clearInterval(pollWatchdog);
723
730
  if (frame !== void 0) globalThis.cancelAnimationFrame(frame);
724
731
  }
725
732
  };
@@ -728,10 +735,10 @@ function readPlaytestEndpoint() {
728
735
  const value = globalThis.TN_PLAYTEST_ENDPOINT;
729
736
  return typeof value === "string" && value.length > 0 ? value : void 0;
730
737
  }
731
- async function dispatch(bridge, request) {
738
+ async function dispatch(bridge, request, nativePointers) {
732
739
  try {
733
740
  if (request.method.startsWith("input.")) {
734
- return { id: request.id, result: dispatchInput(request.method, request.argument) };
741
+ return { id: request.id, result: dispatchInput(request.method, request.argument, nativePointers) };
735
742
  }
736
743
  if (!BRIDGE_METHODS.has(request.method)) {
737
744
  throw new Error(`Bridge operation '${request.method}' is unavailable.`);
@@ -745,7 +752,7 @@ async function dispatch(bridge, request) {
745
752
  return { error: { message: error instanceof Error ? error.message : String(error) }, id: request.id };
746
753
  }
747
754
  }
748
- function dispatchInput(method, argument) {
755
+ function dispatchInput(method, argument, nativePointers) {
749
756
  const host = globalThis.__THREENATIVE_NATIVE__?.playtestInput;
750
757
  if (!isRecord(argument)) throw new Error(`Device ${method} requires an object argument.`);
751
758
  if (method === "input.keyDown" || method === "input.keyUp") {
@@ -765,8 +772,75 @@ function dispatchInput(method, argument) {
765
772
  host.pointer(type, argument.x, argument.y, argument.buttons);
766
773
  return null;
767
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
+ }
768
823
  throw new Error(`Device input operation '${method}' is unavailable.`);
769
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
+ }
770
844
  function parseRequest(value) {
771
845
  assertBounded(value);
772
846
  if (!isRecord(value) || typeof value.id !== "string" || typeof value.method !== "string") {
@@ -816,6 +890,8 @@ function installThreePlaytestBridge(options) {
816
890
  ...options.gameplay === void 0 ? [] : ["runtime.animation", "runtime.state"],
817
891
  ...options.physics === void 0 ? [] : ["runtime.physics"],
818
892
  ...options.runtimeDiagnosticsSeries === void 0 ? [] : ["runtime.performance"],
893
+ ...options.renderChain === void 0 ? [] : ["runtime.renderChain"],
894
+ ...options.startup === void 0 ? [] : ["runtime.startup"],
819
895
  ...options.gameplayChannels?.().includes("runtime.contacts") === true ? ["runtime.contacts"] : [],
820
896
  ...options.gameplayChannels?.().includes("runtime.tags") === true ? ["runtime.tags"] : [],
821
897
  ...options.gameplayChannels?.().includes("runtime.world") === true ? ["runtime.world"] : []
@@ -833,7 +909,10 @@ function installThreePlaytestBridge(options) {
833
909
  return { clock: { mode: "fixed-step", tick }, ticks: advanced };
834
910
  }
835
911
  },
836
- applySetup: async (request) => applySetup(registry, options.resources, request),
912
+ applySetup: async (request) => {
913
+ syncEntities(registry, options.entities);
914
+ applySetup(registry, options.resources, request);
915
+ },
837
916
  ...options.events === void 0 ? {} : {
838
917
  drainEvents: async (limit = PLAYTEST_PROTOCOL_LIMITS.maxEventsPerDrain) => {
839
918
  if (!Number.isInteger(limit) || limit < 0) throw new Error("drainEvents limit must be a non-negative integer.");
@@ -848,7 +927,12 @@ function installThreePlaytestBridge(options) {
848
927
  name: "@threenative/playtest/three",
849
928
  protocolVersion: PLAYTEST_PROTOCOL_VERSION
850
929
  }),
851
- 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
+ },
852
936
  sample: (request) => {
853
937
  syncEntities(registry, options.entities);
854
938
  const snapshot = sampleThreeObservations({
@@ -857,6 +941,7 @@ function installThreePlaytestBridge(options) {
857
941
  diagnostics: options.diagnostics,
858
942
  gameplay: options.gameplay,
859
943
  runtimeDiagnosticsSeries: options.runtimeDiagnosticsSeries,
944
+ renderChain: options.renderChain,
860
945
  registry,
861
946
  renderer: options.renderer,
862
947
  resources: options.resources === void 0 ? void 0 : () => options.resources.read(),
@@ -891,12 +976,13 @@ function syncEntities(registry, entities) {
891
976
  registry.replace(typeof entities === "function" ? entities() : entities);
892
977
  }
893
978
  function applySetup(registry, resources, request) {
894
- request.entities?.forEach(({ entity, transform }) => {
979
+ request.entities?.forEach(({ entity, frozen, transform }) => {
895
980
  const object = registry.get(entity)?.object;
896
981
  if (object === void 0) throw new Error(`Setup entity '${entity}' is not registered.`);
897
982
  if (transform.position !== void 0) object.position.fromArray(transform.position);
898
983
  if (transform.rotation !== void 0) object.quaternion.fromArray(transform.rotation);
899
984
  if (transform.scale !== void 0) object.scale.fromArray(transform.scale);
985
+ if (frozen === true) object.userData[PLAYTEST_FROZEN_MARKER] = true;
900
986
  object.updateMatrix();
901
987
  });
902
988
  request.resources?.forEach(({ id, path, value }) => {
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "@threenative/playtest",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
+ "license": "MIT",
4
5
  "description": "Scenario-driven playtest harness for Three.js games. Runs on plain Three.js with zero ThreeNative dependencies.",
5
6
  "type": "module",
6
7
  "files": [
7
- "dist"
8
+ "dist",
9
+ "README.md"
8
10
  ],
9
11
  "main": "./dist/index.js",
10
12
  "module": "./dist/index.js",
@@ -14,10 +16,18 @@
14
16
  "types": "./dist/index.d.ts",
15
17
  "import": "./dist/index.js"
16
18
  },
19
+ "./protocol": {
20
+ "types": "./dist/protocol.d.ts",
21
+ "import": "./dist/protocol.js"
22
+ },
17
23
  "./three": {
18
24
  "types": "./dist/three/index.d.ts",
19
25
  "import": "./dist/three/index.js"
20
26
  },
27
+ "./capture": {
28
+ "types": "./dist/capture.d.ts",
29
+ "import": "./dist/capture.js"
30
+ },
21
31
  "./runner": {
22
32
  "types": "./dist/runner/index.d.ts",
23
33
  "import": "./dist/runner/index.js"
@@ -58,6 +68,6 @@
58
68
  "scripts": {
59
69
  "build": "tsup --config tsup.config.ts && publint",
60
70
  "typecheck": "tsc --noEmit",
61
- "test": "pnpm run build && pnpm --dir ../.. exec vitest run --config vitest.config.ts && bash __tests__/orphan-cleanup.sh"
71
+ "test": "bash __tests__/orphan-cleanup.sh && publint --strict"
62
72
  }
63
73
  }