@threenative/playtest 0.2.0 → 0.3.1

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,4 +1,5 @@
1
- import { Vector2, Vector3, Box3, Matrix4, Frustum } from 'three';
1
+ #!/usr/bin/env node
2
+ import { Box3, Vector3, Vector2, Matrix4, Frustum } from 'three';
2
3
 
3
4
  // src/three/renderWorkloadAdvisor.ts
4
5
  var DEFAULT_TOP_N = 10;
@@ -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,
@@ -514,12 +479,348 @@ function objectPath(object) {
514
479
  }
515
480
  return parts.join("/");
516
481
  }
482
+ var SCENE_NODE_WALK_CAP = 5e4;
483
+ var SCENE_NODE_DEFAULT_LIMIT = 50;
484
+ var SCENE_NODE_MAX_LIMIT = 500;
485
+ var SCENE_NODE_MAX_SELECTORS = 16;
486
+ var LIT_MATERIAL_PATTERN = /standard|physical|lambert|phong|toon/iu;
487
+ var MATERIAL_MAP_SLOTS = [
488
+ "alphaMap",
489
+ "anisotropyMap",
490
+ "aoMap",
491
+ "bumpMap",
492
+ "clearcoatMap",
493
+ "displacementMap",
494
+ "emissiveMap",
495
+ "envMap",
496
+ "iridescenceMap",
497
+ "lightMap",
498
+ "map",
499
+ "metalnessMap",
500
+ "normalMap",
501
+ "roughnessMap",
502
+ "sheenColorMap",
503
+ "specularMap",
504
+ "transmissionMap"
505
+ ];
506
+ function isColorLike(value) {
507
+ return typeof value === "object" && value !== null && value.isColor === true && typeof value.getHexString === "function";
508
+ }
509
+ function hexOf(value) {
510
+ return isColorLike(value) ? `#${value.getHexString()}` : void 0;
511
+ }
512
+ function finite(value) {
513
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
514
+ }
515
+ function typeNameOf(value) {
516
+ const declared = value.type;
517
+ if (typeof declared === "string" && declared.length > 0) return declared;
518
+ return value.constructor.name;
519
+ }
520
+ function sceneNodePath(object) {
521
+ const parts = [];
522
+ let current = object;
523
+ while (current !== null) {
524
+ const anonymous = current.parent === null ? typeNameOf(current) : `${typeNameOf(current)}[${current.uuid.slice(0, 8)}]`;
525
+ parts.unshift(current.name || anonymous);
526
+ current = current.parent;
527
+ }
528
+ return parts.join("/");
529
+ }
530
+ function visibleInTree(object) {
531
+ let current = object;
532
+ while (current !== null) {
533
+ if (!current.visible) return false;
534
+ current = current.parent;
535
+ }
536
+ return true;
537
+ }
538
+ function textureLoaded(value) {
539
+ if (typeof value !== "object" || value === null) return false;
540
+ const image = value.image;
541
+ if (image === null || image === void 0) {
542
+ const mipmaps = value.mipmaps;
543
+ return Array.isArray(mipmaps) && mipmaps.length > 0;
544
+ }
545
+ if (typeof image !== "object") return true;
546
+ const width = finite(image.width);
547
+ const height = finite(image.height);
548
+ if (width === void 0 || height === void 0) return true;
549
+ return width > 0 && height > 0;
550
+ }
551
+ function materialObservation(value) {
552
+ const material = value;
553
+ const type = typeNameOf(value);
554
+ const maps = [];
555
+ const mapsUnloaded = [];
556
+ for (const slot of MATERIAL_MAP_SLOTS) {
557
+ const texture = material[slot];
558
+ if (typeof texture !== "object" || texture === null) continue;
559
+ maps.push(slot);
560
+ if (!textureLoaded(texture)) mapsUnloaded.push(slot);
561
+ }
562
+ const color = hexOf(material.color);
563
+ const emissive = hexOf(material.emissive);
564
+ const metalness = finite(material.metalness);
565
+ const opacity = finite(material.opacity);
566
+ const roughness = finite(material.roughness);
567
+ const name = material.name;
568
+ return {
569
+ ...color === void 0 ? {} : { color },
570
+ ...emissive === void 0 ? {} : { emissive },
571
+ lit: LIT_MATERIAL_PATTERN.test(type),
572
+ maps,
573
+ mapsUnloaded,
574
+ ...metalness === void 0 ? {} : { metalness },
575
+ name: typeof name === "string" ? name : "",
576
+ ...opacity === void 0 ? {} : { opacity },
577
+ ...roughness === void 0 ? {} : { roughness },
578
+ transparent: material.transparent === true,
579
+ type,
580
+ visible: material.visible !== false
581
+ };
582
+ }
583
+ function materialsOf(object) {
584
+ const material = object.material;
585
+ if (material === void 0 || material === null) return void 0;
586
+ const entries = Array.isArray(material) ? material : [material];
587
+ const observed = entries.filter((entry) => typeof entry === "object" && entry !== null);
588
+ return observed.length === 0 ? void 0 : observed.map(materialObservation);
589
+ }
590
+ function geometryOf(object) {
591
+ const geometry = object.geometry;
592
+ if (typeof geometry !== "object" || geometry === null) return void 0;
593
+ const attributes = geometry.attributes;
594
+ const names = typeof attributes === "object" && attributes !== null ? Object.keys(attributes).sort() : [];
595
+ const position = geometry.attributes?.position;
596
+ const vertices = finite(position?.count) ?? 0;
597
+ const index = geometry.index;
598
+ const indexCount = finite(index?.count);
599
+ const triangles = Math.floor((indexCount ?? vertices) / 3);
600
+ return { attributes: names, triangles, vertices };
601
+ }
602
+ function animationOf(object) {
603
+ const animations = object.animations;
604
+ if (!Array.isArray(animations) || animations.length === 0) return void 0;
605
+ const clips = [];
606
+ for (const clip of animations) {
607
+ if (typeof clip !== "object" || clip === null) continue;
608
+ const name = clip.name;
609
+ clips.push(typeof name === "string" ? name : "");
610
+ }
611
+ return { clips, playing: [] };
612
+ }
613
+ function selectorMatches(object, path, selector) {
614
+ if (selector.name !== void 0 && object.name !== selector.name) return false;
615
+ if (selector.type !== void 0 && typeNameOf(object) !== selector.type) return false;
616
+ if (selector.nameContains !== void 0 && !object.name.toLowerCase().includes(selector.nameContains.toLowerCase()))
617
+ return false;
618
+ if (selector.pathContains !== void 0 && !path.toLowerCase().includes(selector.pathContains.toLowerCase()))
619
+ return false;
620
+ return true;
621
+ }
622
+ function nodeObservation(object, path, frustum) {
623
+ const position = object.getWorldPosition(new Vector3());
624
+ const scale = object.getWorldScale(new Vector3());
625
+ const box = new Box3().setFromObject(object);
626
+ const bounds = box.isEmpty() ? void 0 : {
627
+ max: [box.max.x, box.max.y, box.max.z],
628
+ min: [box.min.x, box.min.y, box.min.z]
629
+ };
630
+ const instances = finite(object.count);
631
+ const skeleton = object.skeleton;
632
+ const bones = Array.isArray(skeleton?.bones) ? skeleton.bones.length : void 0;
633
+ const materials = materialsOf(object);
634
+ const geometry = geometryOf(object);
635
+ const animation = animationOf(object);
636
+ return {
637
+ ...animation === void 0 ? {} : { animation },
638
+ ...bounds === void 0 ? {} : { bounds },
639
+ ...geometry === void 0 ? {} : { geometry },
640
+ // Frustum membership is only reported when a camera projection was available to test it
641
+ // against; an untested node is absent, never `false`.
642
+ ...frustum === void 0 || bounds === void 0 ? {} : { inFrustum: frustum.intersectsBox(box) },
643
+ ...instances === void 0 ? {} : { instances },
644
+ ...materials === void 0 ? {} : { materials },
645
+ name: object.name,
646
+ path,
647
+ position: [position.x, position.y, position.z],
648
+ scale: [scale.x, scale.y, scale.z],
649
+ ...bones === void 0 ? {} : { skinned: { bones } },
650
+ type: typeNameOf(object),
651
+ visible: object.visible,
652
+ visibleInTree: visibleInTree(object)
653
+ };
654
+ }
655
+ function cameraFrustum(camera) {
656
+ const projection = camera.projectionMatrix;
657
+ const inverse = camera.matrixWorldInverse;
658
+ if (!(projection instanceof Matrix4) || !(inverse instanceof Matrix4)) return void 0;
659
+ camera.updateMatrixWorld();
660
+ return new Frustum().setFromProjectionMatrix(new Matrix4().multiplyMatrices(projection, inverse));
661
+ }
662
+ function resolveLimit(selector) {
663
+ const requested = selector.limit ?? SCENE_NODE_DEFAULT_LIMIT;
664
+ return Math.min(Math.max(requested, 0), SCENE_NODE_MAX_LIMIT);
665
+ }
666
+ function observeSceneNodes(scene, camera, selectors) {
667
+ if (selectors.length > SCENE_NODE_MAX_SELECTORS)
668
+ throw new Error(
669
+ `A playtest sample requested ${selectors.length} scene-node selectors; the protocol allows ${SCENE_NODE_MAX_SELECTORS}.`
670
+ );
671
+ const frustum = cameraFrustum(camera);
672
+ const results = selectors.map((selector) => ({
673
+ limit: resolveLimit(selector),
674
+ matched: 0,
675
+ nodes: [],
676
+ selector,
677
+ truncated: false
678
+ }));
679
+ let walked = 0;
680
+ let walkCapped = false;
681
+ scene.traverse((object) => {
682
+ walked += 1;
683
+ if (walked > SCENE_NODE_WALK_CAP) {
684
+ walkCapped = true;
685
+ return;
686
+ }
687
+ const path = sceneNodePath(object);
688
+ for (const result of results) {
689
+ if (!selectorMatches(object, path, result.selector)) continue;
690
+ result.matched += 1;
691
+ if (result.nodes.length < result.limit) result.nodes.push(nodeObservation(object, path, frustum));
692
+ else result.truncated = true;
693
+ }
694
+ });
695
+ return results.map(({ matched, nodes, selector, truncated }) => ({
696
+ matched,
697
+ nodes,
698
+ selector,
699
+ truncated: truncated || walkCapped
700
+ }));
701
+ }
702
+ var SCENE_WALK_OBJECT_CAP = 2e4;
703
+ var SCENE_LIGHT_CAP = 64;
704
+ function isColorLike2(value) {
705
+ return typeof value === "object" && value !== null && value.isColor === true && typeof value.getHexString === "function";
706
+ }
707
+ function hexOf2(value) {
708
+ return isColorLike2(value) ? `#${value.getHexString()}` : "unobserved";
709
+ }
710
+ function finite2(value) {
711
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
712
+ }
713
+ function typeNameOf2(value) {
714
+ const declared = value.type;
715
+ if (typeof declared === "string" && declared.length > 0) return declared;
716
+ return value.constructor.name;
717
+ }
718
+ function backgroundOf(scene) {
719
+ const background = scene.background;
720
+ if (background === null || background === void 0) return "none";
721
+ if (isColorLike2(background)) return `color:${hexOf2(background)}`;
722
+ return typeof background === "object" ? typeNameOf2(background) : "unobserved";
723
+ }
724
+ function fogOf(scene) {
725
+ const fog = scene.fog;
726
+ if (typeof fog !== "object" || fog === null) return void 0;
727
+ const color = hexOf2(fog.color);
728
+ const density = fog.density;
729
+ if (typeof density === "number" && Number.isFinite(density))
730
+ return { color, density, type: "exponential" };
731
+ const near = fog.near;
732
+ const far = fog.far;
733
+ if (typeof near !== "number" || typeof far !== "number") return void 0;
734
+ if (!Number.isFinite(near) || !Number.isFinite(far)) return void 0;
735
+ return { color, far, near, type: "linear" };
736
+ }
737
+ function cameraObservation(camera) {
738
+ const position = camera.getWorldPosition(new Vector3());
739
+ const forward = camera.getWorldDirection(new Vector3());
740
+ const perspective = camera;
741
+ const near = finite2(perspective.near);
742
+ const far = finite2(perspective.far);
743
+ const fov = finite2(perspective.fov);
744
+ return {
745
+ ...far === void 0 ? {} : { far },
746
+ forward: [forward.x, forward.y, forward.z],
747
+ ...fov === void 0 ? {} : { fov },
748
+ ...near === void 0 ? {} : { near },
749
+ position: [position.x, position.y, position.z],
750
+ type: typeNameOf2(camera)
751
+ };
752
+ }
753
+ function lightObservation(object) {
754
+ const light = object;
755
+ const intensity = finite2(light.intensity);
756
+ return {
757
+ color: hexOf2(light.color),
758
+ ...intensity === void 0 ? {} : { intensity },
759
+ type: typeNameOf2(object),
760
+ visible: object.visible
761
+ };
762
+ }
763
+ function countMaterials(object, counted, counts) {
764
+ const material = object.material;
765
+ const entries = Array.isArray(material) ? material : [material];
766
+ for (const entry of entries) {
767
+ if (typeof entry !== "object" || entry === null) continue;
768
+ const uuid = entry.uuid;
769
+ const key = typeof uuid === "string" ? uuid : void 0;
770
+ if (key !== void 0) {
771
+ if (counted.has(key)) continue;
772
+ counted.add(key);
773
+ }
774
+ const name = typeNameOf2(entry);
775
+ counts[name] = (counts[name] ?? 0) + 1;
776
+ }
777
+ }
778
+ function observeSceneResources(scene, camera) {
779
+ const lights = [];
780
+ const materials = {};
781
+ const countedMaterials = /* @__PURE__ */ new Set();
782
+ let objects = 0;
783
+ let truncated = false;
784
+ scene.traverse((object) => {
785
+ objects += 1;
786
+ if (objects > SCENE_WALK_OBJECT_CAP) {
787
+ truncated = true;
788
+ return;
789
+ }
790
+ if (object.isLight === true) {
791
+ if (lights.length < SCENE_LIGHT_CAP) lights.push(lightObservation(object));
792
+ else truncated = true;
793
+ return;
794
+ }
795
+ countMaterials(object, countedMaterials, materials);
796
+ });
797
+ const bounds = new Box3().setFromObject(scene);
798
+ const fog = fogOf(scene);
799
+ return {
800
+ background: backgroundOf(scene),
801
+ camera: cameraObservation(camera),
802
+ ...fog === void 0 ? {} : { fog },
803
+ lights,
804
+ materials,
805
+ objects,
806
+ truncated,
807
+ ...bounds.isEmpty() ? {} : {
808
+ worldExtent: {
809
+ max: [bounds.max.x, bounds.max.y, bounds.max.z],
810
+ min: [bounds.min.x, bounds.min.y, bounds.min.z]
811
+ }
812
+ }
813
+ };
814
+ }
815
+
816
+ // src/three/observations.ts
517
817
  function sampleThreeObservations(input, request) {
518
818
  input.scene.updateMatrixWorld(true);
519
819
  input.camera.updateMatrixWorld(true);
520
820
  const rendererSize = input.renderer.getDrawingBufferSize(new Vector2());
521
821
  const entities = input.registry.select(request.entities).map(({ id, object }) => observeEntity(id, object, input.camera, rendererSize.x, rendererSize.y));
522
822
  const renderPerformance = rendererPerformance(input.renderer);
823
+ const renderChain = input.renderChain?.();
523
824
  return {
524
825
  clock: {
525
826
  mode: input.clockMode,
@@ -529,8 +830,14 @@ function sampleThreeObservations(input, request) {
529
830
  entities,
530
831
  ...input.gameplay === void 0 ? {} : { gameplay: input.gameplay() },
531
832
  ...renderPerformance === void 0 ? {} : { performance: renderPerformance },
833
+ ...renderChain === void 0 ? {} : { renderChain },
532
834
  ...input.runtimeDiagnosticsSeries === void 0 ? {} : { runtimeDiagnosticsSeries: input.runtimeDiagnosticsSeries().map((sample) => ({ ...sample })) },
533
- ...input.resources === void 0 ? {} : { resources: input.resources() }
835
+ ...input.resources === void 0 ? {} : { resources: input.resources() },
836
+ scene: observeSceneResources(input.scene, input.camera),
837
+ // Only walked when a scenario asks. The node walk reads geometry, materials and world
838
+ // bounds per object, which is real work on a large scene, and no run should pay for it
839
+ // when nothing is going to read it.
840
+ ...request.sceneNodes === void 0 || request.sceneNodes.length === 0 ? {} : { sceneNodes: observeSceneNodes(input.scene, input.camera, request.sceneNodes) }
534
841
  };
535
842
  }
536
843
  function rendererPerformance(renderer) {
@@ -634,7 +941,24 @@ function isFiniteVec3(value) {
634
941
  return Array.isArray(value) && value.length === 3 && value.every((component) => typeof component === "number" && Number.isFinite(component));
635
942
  }
636
943
 
944
+ // src/diagnostics.ts
945
+ function playtestDiagnostic(code, message, instruction, details = {}) {
946
+ return {
947
+ ...details.capability === void 0 ? {} : { capability: details.capability },
948
+ code,
949
+ fix: {
950
+ instruction,
951
+ ...details.nextCommand === void 0 ? {} : { nextCommand: details.nextCommand }
952
+ },
953
+ message,
954
+ ...details.path === void 0 ? {} : { path: details.path },
955
+ severity: "error"
956
+ };
957
+ }
958
+
637
959
  // src/three/device.ts
960
+ var MAILBOX_WATCHDOG_BEAT_MS = 250;
961
+ var MAILBOX_POLL_STALL_BEATS = 8;
638
962
  var BRIDGE_METHODS = /* @__PURE__ */ new Set([
639
963
  "advance",
640
964
  "applySetup",
@@ -649,6 +973,7 @@ function connectDevicePlaytestBridge(bridge, endpoint) {
649
973
  if (nativeInstallation !== void 0) return nativeInstallation;
650
974
  let closed = false;
651
975
  let reportedError = false;
976
+ const nativePointers = /* @__PURE__ */ new Map();
652
977
  let scheduled;
653
978
  const schedule = () => {
654
979
  if (closed) return;
@@ -665,7 +990,7 @@ function connectDevicePlaytestBridge(bridge, endpoint) {
665
990
  if (response.status !== 204) {
666
991
  if (!response.ok) throw new Error(`Device bridge poll failed with HTTP ${response.status}.`);
667
992
  const request = parseRequest(await response.json());
668
- await postResponse(endpoint, await dispatch(bridge, request));
993
+ await postResponse(endpoint, await dispatch(bridge, request, nativePointers));
669
994
  }
670
995
  } catch (error) {
671
996
  if (!reportedError) {
@@ -694,18 +1019,26 @@ function connectNativeMailbox(bridge) {
694
1019
  if (typeof mailbox?.request !== "string" || typeof mailbox.response !== "string" || typeof host?.receive !== "function" || typeof host.respond !== "function") return void 0;
695
1020
  let closed = false;
696
1021
  let frame;
697
- const respond = (response) => {
698
- if (!host.respond(mailbox.response, JSON.stringify(response))) {
1022
+ const nativePointers = /* @__PURE__ */ new Map();
1023
+ let requestOrder = 0;
1024
+ let watchdogBeats = 0;
1025
+ let polledAtBeat = 0;
1026
+ let stallReported = false;
1027
+ const respond = (response, method, order) => {
1028
+ const sent = method === void 0 || order === void 0 ? host.respond(mailbox.response, JSON.stringify(response), response.id) : host.respond(mailbox.response, JSON.stringify(response), response.id, method, order);
1029
+ if (!sent) {
699
1030
  console.error("TN_PLAYTEST_DEVICE_TRANSPORT: native mailbox response failed");
700
1031
  }
701
1032
  };
702
1033
  const poll = () => {
703
1034
  if (closed) return;
1035
+ polledAtBeat = watchdogBeats;
704
1036
  const raw = host.receive(mailbox.request);
705
1037
  if (raw !== void 0) {
706
1038
  try {
707
1039
  const request = parseRequest(JSON.parse(raw));
708
- void dispatch(bridge, request).then(respond);
1040
+ const order = ++requestOrder;
1041
+ void dispatch(bridge, request, nativePointers).then((response) => respond(response, request.method, order));
709
1042
  } catch (error) {
710
1043
  respond({
711
1044
  error: { message: error instanceof Error ? error.message : String(error) },
@@ -715,11 +1048,28 @@ function connectNativeMailbox(bridge) {
715
1048
  }
716
1049
  frame = globalThis.requestAnimationFrame(poll);
717
1050
  };
1051
+ const pollWatchdog = setInterval(() => {
1052
+ watchdogBeats += 1;
1053
+ if (closed || watchdogBeats - polledAtBeat < MAILBOX_POLL_STALL_BEATS) return;
1054
+ if (!stallReported) {
1055
+ stallReported = true;
1056
+ const stall = playtestDiagnostic(
1057
+ "TN_PLAYTEST_MAILBOX_POLL_STALLED",
1058
+ `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`,
1059
+ "Inspect the host for a stopped or crashed frame pump; the mailbox will keep polling while frames recover."
1060
+ );
1061
+ console.error(`${stall.code}: ${stall.message}`);
1062
+ }
1063
+ if (frame !== void 0) globalThis.cancelAnimationFrame(frame);
1064
+ frame = void 0;
1065
+ poll();
1066
+ }, MAILBOX_WATCHDOG_BEAT_MS);
718
1067
  respond({ id: "ready", result: null });
719
1068
  frame = globalThis.requestAnimationFrame(poll);
720
1069
  return {
721
1070
  close: () => {
722
1071
  closed = true;
1072
+ clearInterval(pollWatchdog);
723
1073
  if (frame !== void 0) globalThis.cancelAnimationFrame(frame);
724
1074
  }
725
1075
  };
@@ -728,10 +1078,10 @@ function readPlaytestEndpoint() {
728
1078
  const value = globalThis.TN_PLAYTEST_ENDPOINT;
729
1079
  return typeof value === "string" && value.length > 0 ? value : void 0;
730
1080
  }
731
- async function dispatch(bridge, request) {
1081
+ async function dispatch(bridge, request, nativePointers) {
732
1082
  try {
733
1083
  if (request.method.startsWith("input.")) {
734
- return { id: request.id, result: dispatchInput(request.method, request.argument) };
1084
+ return { id: request.id, result: dispatchInput(request.method, request.argument, nativePointers) };
735
1085
  }
736
1086
  if (!BRIDGE_METHODS.has(request.method)) {
737
1087
  throw new Error(`Bridge operation '${request.method}' is unavailable.`);
@@ -745,7 +1095,7 @@ async function dispatch(bridge, request) {
745
1095
  return { error: { message: error instanceof Error ? error.message : String(error) }, id: request.id };
746
1096
  }
747
1097
  }
748
- function dispatchInput(method, argument) {
1098
+ function dispatchInput(method, argument, nativePointers) {
749
1099
  const host = globalThis.__THREENATIVE_NATIVE__?.playtestInput;
750
1100
  if (!isRecord(argument)) throw new Error(`Device ${method} requires an object argument.`);
751
1101
  if (method === "input.keyDown" || method === "input.keyUp") {
@@ -765,8 +1115,75 @@ function dispatchInput(method, argument) {
765
1115
  host.pointer(type, argument.x, argument.y, argument.buttons);
766
1116
  return null;
767
1117
  }
1118
+ if (method === "input.pointers") {
1119
+ if (typeof host?.pointer !== "function") {
1120
+ throw new Error("Native playtest multi-pointer input is unavailable.");
1121
+ }
1122
+ const next = parseNativePointers(argument.pointers);
1123
+ const nextById = new Map(next.map((pointer) => [pointer.id, pointer]));
1124
+ const previousPrimary = nativePointers.keys().next().value;
1125
+ const nextPrimary = nextById.keys().next().value;
1126
+ for (const pointer of nativePointers.values()) {
1127
+ if (nextById.has(pointer.id)) continue;
1128
+ host.pointer(
1129
+ "pointerup",
1130
+ pointer.x,
1131
+ pointer.y,
1132
+ 0,
1133
+ pointer.id,
1134
+ "touch",
1135
+ pointer.id === previousPrimary
1136
+ );
1137
+ }
1138
+ for (const pointer of next) {
1139
+ const previous = nativePointers.get(pointer.id);
1140
+ if (previous === void 0) {
1141
+ host.pointer(
1142
+ "pointerdown",
1143
+ pointer.x,
1144
+ pointer.y,
1145
+ pointer.buttons,
1146
+ pointer.id,
1147
+ "touch",
1148
+ pointer.id === nextPrimary
1149
+ );
1150
+ } else if (previous.x !== pointer.x || previous.y !== pointer.y || previous.buttons !== pointer.buttons) {
1151
+ host.pointer(
1152
+ "pointermove",
1153
+ pointer.x,
1154
+ pointer.y,
1155
+ pointer.buttons,
1156
+ pointer.id,
1157
+ "touch",
1158
+ pointer.id === nextPrimary
1159
+ );
1160
+ }
1161
+ }
1162
+ nativePointers.clear();
1163
+ for (const pointer of next) nativePointers.set(pointer.id, pointer);
1164
+ return null;
1165
+ }
768
1166
  throw new Error(`Device input operation '${method}' is unavailable.`);
769
1167
  }
1168
+ function parseNativePointers(value) {
1169
+ if (!Array.isArray(value)) throw new Error("Device input.pointers requires a pointer array.");
1170
+ const pointers = value.map((pointer, index) => {
1171
+ if (!isRecord(pointer)) throw new Error(`Device input.pointers[${index}] must be an object.`);
1172
+ 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)) {
1173
+ throw new Error(`Device input.pointers[${index}] contains invalid pointer coordinates or buttons.`);
1174
+ }
1175
+ return {
1176
+ buttons: pointer.buttons === void 0 ? 1 : pointer.buttons,
1177
+ id: pointer.id,
1178
+ x: pointer.x,
1179
+ y: pointer.y
1180
+ };
1181
+ });
1182
+ if (new Set(pointers.map(({ id }) => id)).size !== pointers.length) {
1183
+ throw new Error("Device input.pointers requires unique pointer ids.");
1184
+ }
1185
+ return pointers;
1186
+ }
770
1187
  function parseRequest(value) {
771
1188
  assertBounded(value);
772
1189
  if (!isRecord(value) || typeof value.id !== "string" || typeof value.method !== "string") {
@@ -808,6 +1225,8 @@ function installThreePlaytestBridge(options) {
808
1225
  "entity.bounds",
809
1226
  "entity.observe",
810
1227
  "entity.setup",
1228
+ "scene.nodes",
1229
+ "scene.observe",
811
1230
  ...options.fixedStep === void 0 ? [] : ["runtime.fixedStep"],
812
1231
  ...options.resources === void 0 ? [] : ["runtime.resources"],
813
1232
  ...options.diagnostics === void 0 ? [] : ["runtime.diagnostics"],
@@ -816,8 +1235,11 @@ function installThreePlaytestBridge(options) {
816
1235
  ...options.gameplay === void 0 ? [] : ["runtime.animation", "runtime.state"],
817
1236
  ...options.physics === void 0 ? [] : ["runtime.physics"],
818
1237
  ...options.runtimeDiagnosticsSeries === void 0 ? [] : ["runtime.performance"],
1238
+ ...options.renderChain === void 0 ? [] : ["runtime.renderChain"],
1239
+ ...options.startup === void 0 ? [] : ["runtime.startup"],
819
1240
  ...options.gameplayChannels?.().includes("runtime.contacts") === true ? ["runtime.contacts"] : [],
820
1241
  ...options.gameplayChannels?.().includes("runtime.tags") === true ? ["runtime.tags"] : [],
1242
+ ...options.gameplayChannels?.().includes("runtime.transitions") === true ? ["runtime.transitions"] : [],
821
1243
  ...options.gameplayChannels?.().includes("runtime.world") === true ? ["runtime.world"] : []
822
1244
  ];
823
1245
  const bridge = {
@@ -833,7 +1255,10 @@ function installThreePlaytestBridge(options) {
833
1255
  return { clock: { mode: "fixed-step", tick }, ticks: advanced };
834
1256
  }
835
1257
  },
836
- applySetup: async (request) => applySetup(registry, options.resources, request),
1258
+ applySetup: async (request) => {
1259
+ syncEntities(registry, options.entities);
1260
+ return applySetup(registry, options.resources, request);
1261
+ },
837
1262
  ...options.events === void 0 ? {} : {
838
1263
  drainEvents: async (limit = PLAYTEST_PROTOCOL_LIMITS.maxEventsPerDrain) => {
839
1264
  if (!Number.isInteger(limit) || limit < 0) throw new Error("drainEvents limit must be a non-negative integer.");
@@ -848,7 +1273,12 @@ function installThreePlaytestBridge(options) {
848
1273
  name: "@threenative/playtest/three",
849
1274
  protocolVersion: PLAYTEST_PROTOCOL_VERSION
850
1275
  }),
851
- ready: () => ({ ready: true }),
1276
+ ready: () => {
1277
+ const startup = options.startup?.();
1278
+ if (startup === void 0) return { ready: true };
1279
+ assertJsonSafe(startup);
1280
+ return { ready: true, startup };
1281
+ },
852
1282
  sample: (request) => {
853
1283
  syncEntities(registry, options.entities);
854
1284
  const snapshot = sampleThreeObservations({
@@ -857,6 +1287,7 @@ function installThreePlaytestBridge(options) {
857
1287
  diagnostics: options.diagnostics,
858
1288
  gameplay: options.gameplay,
859
1289
  runtimeDiagnosticsSeries: options.runtimeDiagnosticsSeries,
1290
+ renderChain: options.renderChain,
860
1291
  registry,
861
1292
  renderer: options.renderer,
862
1293
  resources: options.resources === void 0 ? void 0 : () => options.resources.read(),
@@ -891,19 +1322,25 @@ function syncEntities(registry, entities) {
891
1322
  registry.replace(typeof entities === "function" ? entities() : entities);
892
1323
  }
893
1324
  function applySetup(registry, resources, request) {
894
- request.entities?.forEach(({ entity, transform }) => {
1325
+ const entities = [];
1326
+ const resourceIds = [];
1327
+ request.entities?.forEach(({ entity, frozen, transform }) => {
895
1328
  const object = registry.get(entity)?.object;
896
1329
  if (object === void 0) throw new Error(`Setup entity '${entity}' is not registered.`);
897
1330
  if (transform.position !== void 0) object.position.fromArray(transform.position);
898
1331
  if (transform.rotation !== void 0) object.quaternion.fromArray(transform.rotation);
899
1332
  if (transform.scale !== void 0) object.scale.fromArray(transform.scale);
1333
+ if (frozen === true) object.userData[PLAYTEST_FROZEN_MARKER] = true;
900
1334
  object.updateMatrix();
1335
+ entities.push(entity);
901
1336
  });
902
1337
  request.resources?.forEach(({ id, path, value }) => {
903
1338
  assertJsonSafe(value);
904
1339
  if (resources?.write === void 0) throw new Error(`Resource setup '${id}' requires a writable resources provider.`);
905
1340
  if (!resources.write(id, path, value)) throw new Error(`Resource setup '${id}' was rejected by the application provider.`);
1341
+ resourceIds.push(id);
906
1342
  });
1343
+ return { entities, resources: resourceIds };
907
1344
  }
908
1345
 
909
- export { PLAYTEST_PHYSICS_BODY_LIMIT, PLAYTEST_PHYSICS_SAMPLE_LIMIT, ThreePlaytestPhysicsRecorder, adviseThreeRenderWorkload, connectDevicePlaytestBridge, installThreePlaytestBridge, readPlaytestEndpoint };
1346
+ export { PLAYTEST_PHYSICS_BODY_LIMIT, PLAYTEST_PHYSICS_SAMPLE_LIMIT, SCENE_LIGHT_CAP, SCENE_WALK_OBJECT_CAP, ThreePlaytestPhysicsRecorder, adviseThreeRenderWorkload, connectDevicePlaytestBridge, installThreePlaytestBridge, observeSceneResources, readPlaytestEndpoint };