@octanejs/three 0.1.23 → 0.1.25

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octanejs/three",
3
- "version": "0.1.23",
3
+ "version": "0.1.25",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -51,7 +51,7 @@
51
51
  "peerDependencies": {
52
52
  "@types/three": ">=0.156.0",
53
53
  "three": ">=0.156.0",
54
- "octane": "0.1.30"
54
+ "octane": "0.1.32"
55
55
  },
56
56
  "peerDependenciesMeta": {
57
57
  "@types/three": {
@@ -72,10 +72,10 @@
72
72
  "typescript": "^5.9.3",
73
73
  "vite": "^8.1.5",
74
74
  "vitest": "^4.1.10",
75
- "@octanejs/rsbuild-plugin": "0.1.25",
76
- "@octanejs/rspack-plugin": "0.1.25",
77
- "@octanejs/vite-plugin": "0.1.30",
78
- "octane": "0.1.30"
75
+ "@octanejs/rsbuild-plugin": "0.1.27",
76
+ "@octanejs/rspack-plugin": "0.1.27",
77
+ "@octanejs/vite-plugin": "0.1.32",
78
+ "octane": "0.1.32"
79
79
  },
80
80
  "scripts": {
81
81
  "test": "pnpm upstream:check && vitest run --root ../.. --project three",
@@ -7,6 +7,7 @@
7
7
  import * as THREE from 'three';
8
8
  import {
9
9
  defineUniversalComponent,
10
+ markUniversalHostComponent,
10
11
  type UniversalComponent,
11
12
  universalPlan,
12
13
  universalProps,
@@ -261,6 +262,7 @@ export function extend<T extends Catalogue | ConstructorRepresentation>(
261
262
  (props) => universalValue(plan, [universalProps([['spread', props]])]),
262
263
  { module: '@octanejs/three' },
263
264
  );
265
+ markUniversalHostComponent(component, THREE_RENDERER_ID, plan);
264
266
  constructorComponents.set(objects, component);
265
267
  return component as UniversalComponent<any>;
266
268
  }
@@ -29,6 +29,7 @@ import {
29
29
  registerThreeNamespace,
30
30
  resolveThreeConstructor,
31
31
  THREE_RENDERER_ID,
32
+ type ConstructorRepresentation,
32
33
  } from './catalogue.js';
33
34
  import {
34
35
  attachString,
@@ -48,6 +49,10 @@ const THREE_PORTAL_TARGET = Symbol('octane.three.portal-target');
48
49
  const EXTERNAL_PORTAL_TARGET_LEASES = new WeakMap<THREE.Object3D, ExternalTargetLease>();
49
50
  const EMPTY_THREE_EVENTS = new Map<string, UniversalEventListenerDescriptor>();
50
51
  const EMPTY_THREE_CALLBACKS = new Map<string, UniversalListenerDescriptor>();
52
+ const THREE_OBJECT3D_ADD = THREE.Object3D.prototype.add;
53
+ const THREE_OBJECT3D_REMOVE = THREE.Object3D.prototype.remove;
54
+ const THREE_OBJECT3D_REMOVE_FROM_PARENT = THREE.Object3D.prototype.removeFromParent;
55
+ const THREE_OBJECT3D_DISPATCH = THREE.Object3D.prototype.dispatchEvent;
51
56
  const THREE_VECTOR3_FROM_ARRAY = THREE.Vector3.prototype.fromArray;
52
57
 
53
58
  const THREE_EVENT_PRIORITIES: Readonly<Record<string, UniversalEventPriority>> = Object.freeze({
@@ -105,7 +110,7 @@ interface ThreePortalTargetDomain {
105
110
  type PhysicalPlacement =
106
111
  | {
107
112
  readonly kind: 'object3d';
108
- readonly object: THREE.Object3D;
113
+ object: THREE.Object3D;
109
114
  readonly parent: THREE.Object3D;
110
115
  }
111
116
  | {
@@ -170,7 +175,7 @@ interface ThreeDriverState {
170
175
  readonly portalChildren: Map<string | number, number[]>;
171
176
  readonly portalTargets: Map<string | number, ThreePortalTargetDomain>;
172
177
  readonly portalTargetCache: WeakMap<RootStore, WeakMap<THREE.Object3D, ThreePortalTargetDomain>>;
173
- readonly disposalQueue: Array<() => void>;
178
+ readonly disposalQueue: any[];
174
179
  nextPortalTarget: number;
175
180
  disposalScheduled: boolean;
176
181
  }
@@ -291,7 +296,19 @@ export function createThreeContainer(
291
296
  flushDisposals() {
292
297
  state.disposalScheduled = false;
293
298
  const queue = state.disposalQueue.splice(0);
294
- runAll(queue);
299
+ let failed = false;
300
+ let firstError: unknown;
301
+ for (const object of queue) {
302
+ try {
303
+ disposeOwnedNow(object);
304
+ } catch (error) {
305
+ if (!failed) {
306
+ failed = true;
307
+ firstError = error;
308
+ }
309
+ }
310
+ }
311
+ if (failed) throw firstError;
295
312
  },
296
313
  [THREE_DRIVER_STATE]: state,
297
314
  };
@@ -301,7 +318,7 @@ export function createThreeContainer(
301
318
 
302
319
  function enqueueDisposal(container: ThreeHostContainer, object: any): void {
303
320
  const state = container[THREE_DRIVER_STATE];
304
- state.disposalQueue.push(() => disposeOwnedNow(object));
321
+ state.disposalQueue.push(object);
305
322
  if (state.disposalScheduled) return;
306
323
  state.disposalScheduled = true;
307
324
  const schedule = container.environment.scheduleDispose ?? defaultScheduleDispose;
@@ -343,7 +360,6 @@ interface DirectMeshProps extends Readonly<Record<string, unknown>> {
343
360
  function isDirectMeshProps(props: Readonly<Record<string, unknown>>): props is DirectMeshProps {
344
361
  let nextName = 'name';
345
362
  for (const name in props) {
346
- if (!Object.prototype.hasOwnProperty.call(props, name)) continue;
347
363
  if (name !== nextName) return false;
348
364
  nextName = name === 'name' ? 'position' : '';
349
365
  }
@@ -353,6 +369,25 @@ function isDirectMeshProps(props: Readonly<Record<string, unknown>>): props is D
353
369
  return nextName === '' && typeof props.name === 'string' && Array.isArray(position);
354
370
  }
355
371
 
372
+ function canSilentlyMutateRootScene(scene: THREE.Scene, removing = false): boolean {
373
+ const children = scene.children;
374
+ return (
375
+ scene.add === THREE_OBJECT3D_ADD &&
376
+ (!removing || scene.remove === THREE_OBJECT3D_REMOVE) &&
377
+ scene.dispatchEvent === THREE_OBJECT3D_DISPATCH &&
378
+ !Object.hasOwn(scene, '_listeners') &&
379
+ !('_listeners' in Object.getPrototypeOf(scene)) &&
380
+ Array.isArray(children) &&
381
+ Object.getPrototypeOf(children) === Array.prototype &&
382
+ children.push === Array.prototype.push &&
383
+ (!removing ||
384
+ (children.splice === Array.prototype.splice &&
385
+ children.indexOf === Array.prototype.indexOf)) &&
386
+ Object.isExtensible(children) &&
387
+ Object.getOwnPropertyDescriptor(children, 'length')?.writable === true
388
+ );
389
+ }
390
+
356
391
  function prepareDirectLeafMountBatch(
357
392
  container: ThreeHostContainer,
358
393
  batch: UniversalHostBatch,
@@ -392,6 +427,8 @@ function prepareDirectLeafMountBatch(
392
427
  ids.add(create.id);
393
428
  }
394
429
 
430
+ const scene = container.scene;
431
+ let addSilently = canSilentlyMutateRootScene(scene);
395
432
  const staged: ThreeHostInstance[] = [];
396
433
  try {
397
434
  for (let index = 0; index < createCount; index++) {
@@ -409,9 +446,24 @@ function prepareDirectLeafMountBatch(
409
446
  true,
410
447
  ),
411
448
  );
412
- applyThreeProps(object, command.props, undefined, {
413
- colorSpace: container.environment.linear !== true,
414
- });
449
+ if (object.position.fromArray === THREE_VECTOR3_FROM_ARRAY) {
450
+ const props = command.props as DirectMeshProps;
451
+ object.name = props.name;
452
+ object.position.fromArray(props.position);
453
+ } else {
454
+ applyThreeProps(object, command.props, undefined, {
455
+ colorSpace: container.environment.linear !== true,
456
+ });
457
+ }
458
+ if (
459
+ addSilently &&
460
+ (Object.hasOwn(object, '_listeners') ||
461
+ object.dispatchEvent !== THREE_OBJECT3D_DISPATCH ||
462
+ object.removeFromParent !== THREE_OBJECT3D_REMOVE_FROM_PARENT ||
463
+ object.parent !== null)
464
+ ) {
465
+ addSilently = false;
466
+ }
415
467
  }
416
468
  } catch (error) {
417
469
  for (const instance of staged) disposeOwnedNow(instance.object);
@@ -423,6 +475,7 @@ function prepareDirectLeafMountBatch(
423
475
  apply() {
424
476
  if (status !== 'prepared') return;
425
477
  status = 'applied';
478
+ addSilently &&= canSilentlyMutateRootScene(scene);
426
479
  state.directInstances = staged;
427
480
  let failed = false;
428
481
  let firstError: unknown;
@@ -433,11 +486,16 @@ function prepareDirectLeafMountBatch(
433
486
  instance.parent = null;
434
487
  OBJECT_INSTANCES.set(instance.object, instance);
435
488
  try {
436
- container.scene.add(instance.object);
489
+ if (addSilently) {
490
+ instance.object.parent = scene;
491
+ scene.children.push(instance.object);
492
+ } else {
493
+ scene.add(instance.object);
494
+ }
437
495
  instance.physical = {
438
496
  kind: 'object3d',
439
497
  object: instance.object,
440
- parent: container.scene,
498
+ parent: scene,
441
499
  };
442
500
  } catch (error) {
443
501
  if (!failed) {
@@ -464,7 +522,10 @@ function prepareDirectLeafMountBatch(
464
522
  firstError = error;
465
523
  }
466
524
  }
467
- if (failed) throw firstError;
525
+ if (failed) {
526
+ state.directInstances = null;
527
+ throw firstError;
528
+ }
468
529
  },
469
530
  abort() {
470
531
  if (status !== 'prepared') return;
@@ -497,22 +558,25 @@ function prepareUpdateOnlyBatch(
497
558
  if (command.op !== 'update') return null;
498
559
  const instance = instances[index];
499
560
  if (command.id !== instance.id) return null;
500
- const nameDescriptor = Object.getOwnPropertyDescriptor(instance.object, 'name');
501
561
  if (
502
- !instance.directLeaf ||
503
- instance.physical?.kind !== 'object3d' ||
504
- instance.physical.parent !== container.scene ||
505
562
  instance.object.parent !== container.scene ||
506
563
  container.scene.children[index] !== instance.object ||
507
564
  instance.object.visible !== true ||
508
- nameDescriptor === undefined ||
509
- !('value' in nameDescriptor) ||
510
- nameDescriptor.writable !== true ||
511
565
  instance.object.position.fromArray !== THREE_VECTOR3_FROM_ARRAY
512
566
  ) {
513
567
  return null;
514
568
  }
515
569
  if (!isDirectMeshProps(command.props)) return null;
570
+ if ((instance.props as DirectMeshProps).name !== command.props.name) {
571
+ const nameDescriptor = Object.getOwnPropertyDescriptor(instance.object, 'name');
572
+ if (
573
+ nameDescriptor === undefined ||
574
+ !('value' in nameDescriptor) ||
575
+ nameDescriptor.writable !== true
576
+ ) {
577
+ return null;
578
+ }
579
+ }
516
580
  }
517
581
 
518
582
  let status: 'prepared' | 'applied' | 'aborted' = 'prepared';
@@ -565,7 +629,581 @@ function prepareUpdateOnlyBatch(
565
629
  firstError = error;
566
630
  }
567
631
  }
568
- if (failed) throw firstError;
632
+ if (failed) {
633
+ state.directInstances = null;
634
+ throw firstError;
635
+ }
636
+ },
637
+ abort() {
638
+ if (status === 'prepared') status = 'aborted';
639
+ },
640
+ };
641
+ }
642
+
643
+ interface AcceptedFlatBatchResult {
644
+ failed: boolean;
645
+ error: unknown;
646
+ }
647
+
648
+ function retainFlatBatchError(result: AcceptedFlatBatchResult, error: unknown): void {
649
+ if (result.failed) return;
650
+ result.failed = true;
651
+ result.error = error;
652
+ }
653
+
654
+ function finishFlatRootBatch(
655
+ container: ThreeHostContainer,
656
+ batch: UniversalHostBatch,
657
+ result: AcceptedFlatBatchResult,
658
+ ): void {
659
+ if (container.environment.recordCommits !== false) {
660
+ try {
661
+ container.commits.push(batch);
662
+ } catch (error) {
663
+ retainFlatBatchError(result, error);
664
+ }
665
+ }
666
+ try {
667
+ container.environment.invalidate?.();
668
+ } catch (error) {
669
+ retainFlatBatchError(result, error);
670
+ }
671
+ if (result.failed) {
672
+ container[THREE_DRIVER_STATE].directInstances = null;
673
+ throw result.error;
674
+ }
675
+ }
676
+
677
+ /**
678
+ * A flat, callback-free root has no attachment, portal, visibility, or
679
+ * interaction relationships to simulate. Verify the live graph first so public
680
+ * Object3D mutations still fall back to the full synchronizing driver.
681
+ */
682
+ function getFlatRootInstances(container: ThreeHostContainer): readonly ThreeHostInstance[] | null {
683
+ const state = container[THREE_DRIVER_STATE];
684
+ const count = state.rootChildren.length;
685
+ if (
686
+ count === 0 ||
687
+ state.instances.size !== count ||
688
+ state.portalTargets.size !== 0 ||
689
+ state.portalChildren.size !== 0 ||
690
+ container.scene.parent !== null ||
691
+ container.scene.children.length !== count
692
+ ) {
693
+ return null;
694
+ }
695
+
696
+ const store = container.environment.store;
697
+ if (store !== undefined) {
698
+ const interaction = store.getState().internal;
699
+ if (
700
+ interaction.interaction.length !== 0 ||
701
+ interaction.initialHits.length !== 0 ||
702
+ interaction.hovered.size !== 0 ||
703
+ interaction.capturedMap.size !== 0
704
+ ) {
705
+ return null;
706
+ }
707
+ }
708
+
709
+ const direct = state.directInstances;
710
+ if (direct !== null && direct.length !== count) return null;
711
+ if (direct !== null) {
712
+ // This private array is retained only after an entirely successful direct
713
+ // commit. Structural work and accepted faults clear it, so logical maps,
714
+ // ownership, and placement descriptors cannot drift independently. Public
715
+ // Three objects remain mutable and must still be checked every time.
716
+ for (let index = 0; index < count; index++) {
717
+ const instance = direct[index];
718
+ if (
719
+ instance.id !== state.rootChildren[index] ||
720
+ instance.object.parent !== container.scene ||
721
+ instance.object.visible !== true ||
722
+ container.scene.children[index] !== instance.object
723
+ ) {
724
+ return null;
725
+ }
726
+ }
727
+ return direct;
728
+ }
729
+
730
+ const instances = new Array<ThreeHostInstance>(count);
731
+ for (let index = 0; index < count; index++) {
732
+ const instance = state.instances.get(state.rootChildren[index]);
733
+ if (
734
+ instance === undefined ||
735
+ instance.id !== state.rootChildren[index] ||
736
+ instance.parent !== null ||
737
+ instance.children.length !== 0 ||
738
+ !instance.visible ||
739
+ instance.events.size !== 0 ||
740
+ instance.lifecycles.size !== 0 ||
741
+ instance.localCallbacks.size !== 0 ||
742
+ instance.localCleanups.size !== 0 ||
743
+ instance.store !== store ||
744
+ instance.physical?.kind !== 'object3d' ||
745
+ instance.physical.object !== instance.object ||
746
+ instance.physical.parent !== container.scene ||
747
+ instance.object.parent !== container.scene ||
748
+ instance.object.visible !== (instance.props.visible !== false) ||
749
+ container.scene.children[index] !== instance.object
750
+ ) {
751
+ return null;
752
+ }
753
+ instances[index] = instance;
754
+ }
755
+ return instances;
756
+ }
757
+
758
+ function stageFlatRootObject(
759
+ container: ThreeHostContainer,
760
+ Constructor: ConstructorRepresentation,
761
+ props: Readonly<Record<string, unknown>>,
762
+ ): any {
763
+ const args = props.args;
764
+ if (args !== undefined && !Array.isArray(args)) {
765
+ throw new Error('@octanejs/three: The args prop must be an array.');
766
+ }
767
+ const object = new Constructor(...((args as readonly unknown[] | undefined) ?? []));
768
+ try {
769
+ for (const prop in props) {
770
+ if (prop === 'args') continue;
771
+ applyThreeProps(object as object, props, undefined, {
772
+ colorSpace: container.environment.linear !== true,
773
+ });
774
+ break;
775
+ }
776
+ } catch (error) {
777
+ disposeOwnedNow(object);
778
+ throw error;
779
+ }
780
+ return object;
781
+ }
782
+
783
+ /**
784
+ * Recreate root Object3D leaves without cloning the complete logical graph.
785
+ * All replacements are constructed while the transaction remains rejectable;
786
+ * abort disposes only those unpublished replacements.
787
+ */
788
+ function prepareFlatRootRecreationBatch(
789
+ container: ThreeHostContainer,
790
+ batch: UniversalHostBatch,
791
+ ): UniversalPreparedHostBatch | null {
792
+ const state = container[THREE_DRIVER_STATE];
793
+ const count = state.rootChildren.length;
794
+ if (
795
+ count === 0 ||
796
+ batch.commands.length !== count ||
797
+ batch.commands[0]?.op !== 'recreate' ||
798
+ batch.commands[count - 1]?.op !== 'recreate'
799
+ ) {
800
+ return null;
801
+ }
802
+ const instances = getFlatRootInstances(container);
803
+ if (instances === null) return null;
804
+
805
+ const constructors = new Map<string, ConstructorRepresentation>();
806
+ const scene = container.scene;
807
+ const children = scene.children;
808
+ let replaceSilently = canSilentlyMutateRootScene(scene, true);
809
+ let previousConstructorType: string | undefined;
810
+ let previousConstructor: ConstructorRepresentation | undefined;
811
+ for (let index = 0; index < count; index++) {
812
+ const command = batch.commands[index];
813
+ const instance = instances[index];
814
+ if (
815
+ command.op !== 'recreate' ||
816
+ command.id !== instance.id ||
817
+ command.type !== instance.type ||
818
+ !instance.owned ||
819
+ command.props.attach != null
820
+ ) {
821
+ return null;
822
+ }
823
+ let Constructor =
824
+ command.type === previousConstructorType
825
+ ? previousConstructor
826
+ : constructors.get(command.type);
827
+ if (Constructor === undefined) {
828
+ const resolved = resolveThreeConstructor(command.type);
829
+ if (
830
+ resolved === null ||
831
+ (resolved !== THREE.Object3D && !(resolved.prototype instanceof THREE.Object3D))
832
+ ) {
833
+ return null;
834
+ }
835
+ Constructor = resolved;
836
+ constructors.set(command.type, Constructor);
837
+ if (
838
+ '_listeners' in Constructor.prototype ||
839
+ Constructor.prototype.dispatchEvent !== THREE_OBJECT3D_DISPATCH ||
840
+ Constructor.prototype.removeFromParent !== THREE_OBJECT3D_REMOVE_FROM_PARENT
841
+ ) {
842
+ replaceSilently = false;
843
+ }
844
+ }
845
+ previousConstructorType = command.type;
846
+ previousConstructor = Constructor;
847
+ if (instance.object.constructor !== Constructor) return null;
848
+ }
849
+
850
+ const replacements: THREE.Object3D[] = [];
851
+ try {
852
+ for (let index = 0; index < count; index++) {
853
+ const command = batch.commands[index] as Extract<
854
+ UniversalHostCommand,
855
+ { readonly op: 'recreate' }
856
+ >;
857
+ const replacement = stageFlatRootObject(
858
+ container,
859
+ command.type === previousConstructorType
860
+ ? previousConstructor!
861
+ : constructors.get(command.type)!,
862
+ command.props,
863
+ );
864
+ replacements.push(replacement);
865
+ if (!isObject3D(replacement)) {
866
+ throw new Error(`@octanejs/three: Recreate type mismatch for ${command.id}.`);
867
+ }
868
+ }
869
+ } catch (error) {
870
+ for (const replacement of replacements) disposeOwnedNow(replacement);
871
+ throw error;
872
+ }
873
+
874
+ let status: 'prepared' | 'applied' | 'aborted' = 'prepared';
875
+ return {
876
+ apply() {
877
+ if (status !== 'prepared') return;
878
+ status = 'applied';
879
+ replaceSilently &&= scene.children === children && canSilentlyMutateRootScene(scene, true);
880
+ if (replaceSilently) {
881
+ for (const Constructor of constructors.values()) {
882
+ if (
883
+ '_listeners' in Constructor.prototype ||
884
+ Constructor.prototype.dispatchEvent !== THREE_OBJECT3D_DISPATCH ||
885
+ Constructor.prototype.removeFromParent !== THREE_OBJECT3D_REMOVE_FROM_PARENT
886
+ ) {
887
+ replaceSilently = false;
888
+ break;
889
+ }
890
+ }
891
+ }
892
+ const result: AcceptedFlatBatchResult = { failed: false, error: undefined };
893
+
894
+ for (let index = 0; index < count; index++) {
895
+ try {
896
+ const instance = instances[index];
897
+ const previousObject = instance.object as THREE.Object3D;
898
+ const previousProps = instance.props;
899
+ const replacement = replacements[index];
900
+ const command = batch.commands[index] as Extract<
901
+ UniversalHostCommand,
902
+ { readonly op: 'recreate' }
903
+ >;
904
+ if (
905
+ replaceSilently &&
906
+ (Object.hasOwn(previousObject, '_listeners') ||
907
+ Object.hasOwn(replacement, '_listeners') ||
908
+ previousObject.dispatchEvent !== THREE_OBJECT3D_DISPATCH ||
909
+ replacement.dispatchEvent !== THREE_OBJECT3D_DISPATCH ||
910
+ replacement.removeFromParent !== THREE_OBJECT3D_REMOVE_FROM_PARENT ||
911
+ replacement.parent !== null ||
912
+ previousObject.parent !== scene ||
913
+ children[index] !== previousObject)
914
+ ) {
915
+ replaceSilently = false;
916
+ }
917
+ OBJECT_INSTANCES.delete(previousObject);
918
+ instance.object = replacement;
919
+ instance.props = command.props;
920
+ OBJECT_INSTANCES.set(replacement, instance);
921
+ previousObject.visible = previousProps.visible !== false;
922
+ if (state.disposalScheduled) state.disposalQueue.push(previousObject);
923
+ else enqueueDisposal(container, previousObject);
924
+ } catch (error) {
925
+ retainFlatBatchError(result, error);
926
+ }
927
+ }
928
+
929
+ if (replaceSilently && canSilentlyMutateRootScene(scene, true)) {
930
+ for (let index = 0; index < count; index++) {
931
+ try {
932
+ const instance = instances[index];
933
+ const placement = instance.physical as Extract<PhysicalPlacement, { kind: 'object3d' }>;
934
+ placement.object.parent = null;
935
+ instance.object.parent = scene;
936
+ children[index] = instance.object;
937
+ placement.object = instance.object;
938
+ instance.object.visible = instance.props.visible !== false;
939
+ } catch (error) {
940
+ retainFlatBatchError(result, error);
941
+ }
942
+ }
943
+ } else {
944
+ for (let index = 0; index < count; index++) {
945
+ try {
946
+ const placement = instances[index].physical as Extract<
947
+ PhysicalPlacement,
948
+ { kind: 'object3d' }
949
+ >;
950
+ instances[index].physical = null;
951
+ scene.remove(placement.object);
952
+ } catch (error) {
953
+ retainFlatBatchError(result, error);
954
+ }
955
+ }
956
+
957
+ for (let index = 0; index < count; index++) {
958
+ try {
959
+ const instance = instances[index];
960
+ scene.add(instance.object);
961
+ instance.physical = {
962
+ kind: 'object3d',
963
+ object: instance.object,
964
+ parent: scene,
965
+ };
966
+ instance.object.visible = instance.props.visible !== false;
967
+ } catch (error) {
968
+ retainFlatBatchError(result, error);
969
+ }
970
+ }
971
+ }
972
+ finishFlatRootBatch(container, batch, result);
973
+ },
974
+ abort() {
975
+ if (status !== 'prepared') return;
976
+ status = 'aborted';
977
+ for (const replacement of replacements) disposeOwnedNow(replacement);
978
+ },
979
+ };
980
+ }
981
+
982
+ /** Reorder a root-only mesh list in linear time, including ordinary prop updates. */
983
+ function prepareFlatRootReorderBatch(
984
+ container: ThreeHostContainer,
985
+ batch: UniversalHostBatch,
986
+ ): UniversalPreparedHostBatch | null {
987
+ const state = container[THREE_DRIVER_STATE];
988
+ const count = state.rootChildren.length;
989
+ if (
990
+ count < 2 ||
991
+ state.directInstances === null ||
992
+ batch.commands.length === 0 ||
993
+ batch.commands[batch.commands.length - 1]?.op !== 'move'
994
+ ) {
995
+ return null;
996
+ }
997
+ const instances = getFlatRootInstances(container);
998
+ if (instances === null) return null;
999
+ const scene = container.scene;
1000
+ const children = scene.children;
1001
+ const reorderSilently = canSilentlyMutateRootScene(scene, true);
1002
+
1003
+ const positions = new Map<number, number>();
1004
+ const previous = new Int32Array(count);
1005
+ const next = new Int32Array(count);
1006
+ for (let index = 0; index < count; index++) {
1007
+ const instance = instances[index];
1008
+ if (!instance.directLeaf) return null;
1009
+ positions.set(instance.id, index);
1010
+ previous[index] = index - 1;
1011
+ next[index] = index + 1 === count ? -1 : index + 1;
1012
+ }
1013
+ let first = 0;
1014
+ let last = count - 1;
1015
+ let updates = 0;
1016
+ const updated = new Set<number>();
1017
+ while (updates < batch.commands.length && batch.commands[updates].op === 'update') {
1018
+ const command = batch.commands[updates] as Extract<
1019
+ UniversalHostCommand,
1020
+ { readonly op: 'update' }
1021
+ >;
1022
+ const position = positions.get(command.id);
1023
+ if (position === undefined || updated.has(command.id)) return null;
1024
+ const instance = instances[position];
1025
+ if (
1026
+ instance.object.position.fromArray !== THREE_VECTOR3_FROM_ARRAY ||
1027
+ !isDirectMeshProps(command.props)
1028
+ ) {
1029
+ return null;
1030
+ }
1031
+ if ((instance.props as DirectMeshProps).name !== command.props.name) {
1032
+ const descriptor = Object.getOwnPropertyDescriptor(instance.object, 'name');
1033
+ if (descriptor === undefined || !('value' in descriptor) || descriptor.writable !== true) {
1034
+ return null;
1035
+ }
1036
+ }
1037
+ updated.add(command.id);
1038
+ updates++;
1039
+ }
1040
+ if (updates === batch.commands.length) return null;
1041
+
1042
+ for (let index = updates; index < batch.commands.length; index++) {
1043
+ const command = batch.commands[index];
1044
+ if (command.op !== 'move' || command.parent !== null) return null;
1045
+ const moved = positions.get(command.id);
1046
+ const before = command.before === null ? -1 : positions.get(command.before);
1047
+ if (moved === undefined || before === undefined || moved === before) return null;
1048
+
1049
+ const preceding = previous[moved];
1050
+ const following = next[moved];
1051
+ if (preceding === -1) first = following;
1052
+ else next[preceding] = following;
1053
+ if (following === -1) last = preceding;
1054
+ else previous[following] = preceding;
1055
+
1056
+ if (before === -1) {
1057
+ previous[moved] = last;
1058
+ next[moved] = -1;
1059
+ if (last === -1) first = moved;
1060
+ else next[last] = moved;
1061
+ last = moved;
1062
+ } else {
1063
+ const beforePrevious = previous[before];
1064
+ previous[moved] = beforePrevious;
1065
+ next[moved] = before;
1066
+ previous[before] = moved;
1067
+ if (beforePrevious === -1) first = moved;
1068
+ else next[beforePrevious] = moved;
1069
+ }
1070
+ }
1071
+
1072
+ const ordered = new Array<ThreeHostInstance>(count);
1073
+ for (let index = 0, position = first; index < count; index++, position = next[position]) {
1074
+ if (position === -1) return null;
1075
+ ordered[index] = instances[position];
1076
+ }
1077
+
1078
+ let status: 'prepared' | 'applied' | 'aborted' = 'prepared';
1079
+ return {
1080
+ apply() {
1081
+ if (status !== 'prepared') return;
1082
+ status = 'applied';
1083
+ const result: AcceptedFlatBatchResult = { failed: false, error: undefined };
1084
+ for (let index = 0; index < updates; index++) {
1085
+ try {
1086
+ const command = batch.commands[index] as Extract<
1087
+ UniversalHostCommand,
1088
+ { readonly op: 'update' }
1089
+ >;
1090
+ const instance = instances[positions.get(command.id)!];
1091
+ const previousProps = instance.props as DirectMeshProps;
1092
+ const nextProps = command.props as DirectMeshProps;
1093
+ instance.props = nextProps;
1094
+ if (previousProps.name !== nextProps.name) instance.object.name = nextProps.name;
1095
+ const previousPosition = previousProps.position;
1096
+ const nextPosition = nextProps.position;
1097
+ if (
1098
+ previousPosition[0] !== nextPosition[0] ||
1099
+ previousPosition[1] !== nextPosition[1] ||
1100
+ previousPosition[2] !== nextPosition[2]
1101
+ ) {
1102
+ instance.object.position.fromArray(nextPosition);
1103
+ }
1104
+ } catch (error) {
1105
+ retainFlatBatchError(result, error);
1106
+ }
1107
+ }
1108
+
1109
+ try {
1110
+ state.directInstances = ordered;
1111
+ for (let index = 0; index < count; index++) {
1112
+ state.rootChildren[index] = ordered[index].id;
1113
+ }
1114
+ } catch (error) {
1115
+ retainFlatBatchError(result, error);
1116
+ }
1117
+ if (
1118
+ reorderSilently &&
1119
+ scene.children === children &&
1120
+ children.length === count &&
1121
+ canSilentlyMutateRootScene(scene, true)
1122
+ ) {
1123
+ try {
1124
+ for (let index = 0; index < count; index++) children[index] = ordered[index].object;
1125
+ } catch (error) {
1126
+ retainFlatBatchError(result, error);
1127
+ }
1128
+ } else {
1129
+ for (const instance of ordered) {
1130
+ try {
1131
+ scene.add(instance.object);
1132
+ } catch (error) {
1133
+ retainFlatBatchError(result, error);
1134
+ }
1135
+ }
1136
+ }
1137
+ finishFlatRootBatch(container, batch, result);
1138
+ },
1139
+ abort() {
1140
+ if (status === 'prepared') status = 'aborted';
1141
+ },
1142
+ };
1143
+ }
1144
+
1145
+ /** Clear a callback-free, root-only Object3D list without a scene-wide clone. */
1146
+ function prepareFlatRootRemovalBatch(
1147
+ container: ThreeHostContainer,
1148
+ batch: UniversalHostBatch,
1149
+ ): UniversalPreparedHostBatch | null {
1150
+ const state = container[THREE_DRIVER_STATE];
1151
+ const count = state.rootChildren.length;
1152
+ if (
1153
+ count === 0 ||
1154
+ batch.commands.length !== count * 2 ||
1155
+ batch.commands[0]?.op !== 'remove' ||
1156
+ batch.commands[batch.commands.length - 1]?.op !== 'destroy'
1157
+ ) {
1158
+ return null;
1159
+ }
1160
+ const instances = getFlatRootInstances(container);
1161
+ if (instances === null) return null;
1162
+ for (let index = 0; index < count; index++) {
1163
+ const remove = batch.commands[index];
1164
+ const destroy = batch.commands[count + index];
1165
+ if (
1166
+ remove.op !== 'remove' ||
1167
+ remove.parent !== null ||
1168
+ remove.id !== instances[index].id ||
1169
+ destroy.op !== 'destroy' ||
1170
+ destroy.id !== remove.id
1171
+ ) {
1172
+ return null;
1173
+ }
1174
+ }
1175
+
1176
+ let status: 'prepared' | 'applied' | 'aborted' = 'prepared';
1177
+ return {
1178
+ apply() {
1179
+ if (status !== 'prepared') return;
1180
+ status = 'applied';
1181
+ const result: AcceptedFlatBatchResult = { failed: false, error: undefined };
1182
+ state.directInstances = null;
1183
+ state.rootChildren.length = 0;
1184
+ for (const instance of instances) {
1185
+ try {
1186
+ instance.physical = null;
1187
+ container.scene.remove(instance.object);
1188
+ } catch (error) {
1189
+ retainFlatBatchError(result, error);
1190
+ }
1191
+ }
1192
+ for (const instance of instances) {
1193
+ try {
1194
+ instance.object.visible = instance.props.visible !== false;
1195
+ if (instance.owned && instance.type !== 'primitive' && instance.props.dispose !== null) {
1196
+ enqueueDisposal(container, instance.object);
1197
+ }
1198
+ OBJECT_INSTANCES.delete(instance.object);
1199
+ instance.store = undefined;
1200
+ instance.parent = undefined;
1201
+ state.instances.delete(instance.id);
1202
+ } catch (error) {
1203
+ retainFlatBatchError(result, error);
1204
+ }
1205
+ }
1206
+ finishFlatRootBatch(container, batch, result);
569
1207
  },
570
1208
  abort() {
571
1209
  if (status === 'prepared') status = 'aborted';
@@ -707,6 +1345,10 @@ function storeForInstance(
707
1345
  portalTargets: ReadonlyMap<string | number, ThreePortalTargetDomain>,
708
1346
  rootStore: RootStore | undefined,
709
1347
  ): RootStore | undefined {
1348
+ const rootChild = instances.get(id);
1349
+ if (rootChild === undefined || rootChild.parent === undefined) return undefined;
1350
+ if (rootChild.parent === null) return rootStore;
1351
+ if (isPortalParent(rootChild.parent)) return portalTargets.get(rootChild.parent.id)?.store;
710
1352
  const seen = new Set<number>();
711
1353
  let currentId = id;
712
1354
  while (true) {
@@ -728,6 +1370,10 @@ function hasLiveRootConnection(
728
1370
  instances: ReadonlyMap<number, LogicalInteractionInstance>,
729
1371
  portalTargets: ReadonlyMap<string | number, ThreePortalTargetDomain>,
730
1372
  ): boolean {
1373
+ const rootChild = instances.get(id);
1374
+ if (rootChild === undefined || !rootChild.visible) return false;
1375
+ if (rootChild.parent === null) return true;
1376
+ if (rootChild.parent === undefined) return false;
731
1377
  const seen = new Set<number>();
732
1378
  let currentId = id;
733
1379
  while (true) {
@@ -1142,7 +1788,10 @@ export function hasThreeEventListeners(object: object, types?: readonly string[]
1142
1788
  const events = OBJECT_INSTANCES.get(object)?.events;
1143
1789
  if (events === undefined) return false;
1144
1790
  if (types === undefined) return events.size > 0;
1145
- return types.some((type) => events.has(type));
1791
+ for (let index = 0; index < types.length; index++) {
1792
+ if (events.has(types[index])) return true;
1793
+ }
1794
+ return false;
1146
1795
  }
1147
1796
 
1148
1797
  /** Return the configured root store that owns a managed Three object. */
@@ -1395,6 +2044,12 @@ export function createThreeDriver(
1395
2044
  if (directLeafMount !== null) return directLeafMount;
1396
2045
  const updateOnly = prepareUpdateOnlyBatch(container, batch);
1397
2046
  if (updateOnly !== null) return updateOnly;
2047
+ const flatRecreation = prepareFlatRootRecreationBatch(container, batch);
2048
+ if (flatRecreation !== null) return flatRecreation;
2049
+ const flatReorder = prepareFlatRootReorderBatch(container, batch);
2050
+ if (flatReorder !== null) return flatReorder;
2051
+ const flatRemoval = prepareFlatRootRemovalBatch(container, batch);
2052
+ if (flatRemoval !== null) return flatRemoval;
1398
2053
  const simulation = cloneSimulation(state);
1399
2054
  const rootChildren = [...state.rootChildren];
1400
2055
  const portalChildren = clonePortalChildren(state);
@@ -1847,6 +2502,43 @@ export function createThreeDriver(
1847
2502
  }
1848
2503
  tasks.push(() => container.environment.invalidate?.());
1849
2504
  runAll(tasks);
2505
+
2506
+ // Constructor-only Object3D leaves currently mount through the general
2507
+ // graph because their constructors and scene listeners remain public.
2508
+ // Once that entire mount has succeeded, retain its proven flat layout so
2509
+ // later args reconstruction can use the same private ordering cache as
2510
+ // direct meshes without changing any mount or callback semantics.
2511
+ const createdCount = stagedCreates.size;
2512
+ if (
2513
+ createdCount !== 0 &&
2514
+ createdCount === state.instances.size &&
2515
+ createdCount === state.rootChildren.length &&
2516
+ batch.commands.length === createdCount * 2 &&
2517
+ batch.commands[0]?.op === 'create' &&
2518
+ batch.commands[createdCount]?.op === 'insert'
2519
+ ) {
2520
+ let constructorLeaves = true;
2521
+ for (const { instance } of stagedCreates.values()) {
2522
+ const args = Object.getOwnPropertyDescriptor(instance.props, 'args');
2523
+ if (
2524
+ !isObject3D(instance.object) ||
2525
+ args === undefined ||
2526
+ !('value' in args) ||
2527
+ !Array.isArray(args.value)
2528
+ ) {
2529
+ constructorLeaves = false;
2530
+ break;
2531
+ }
2532
+ for (const prop in instance.props) {
2533
+ if (prop !== 'args') {
2534
+ constructorLeaves = false;
2535
+ break;
2536
+ }
2537
+ }
2538
+ if (!constructorLeaves) break;
2539
+ }
2540
+ if (constructorLeaves) state.directInstances = getFlatRootInstances(container);
2541
+ }
1850
2542
  },
1851
2543
  afterAccept() {
1852
2544
  if (status !== 'applied' || callbacksRan) return;
@@ -143,6 +143,15 @@ const POINTER_MOVE_LISTENERS = [
143
143
  'onPointerLeave',
144
144
  ] as const;
145
145
 
146
+ const POINTER_HOVER_LISTENERS = [
147
+ 'onPointerOver',
148
+ 'onPointerEnter',
149
+ 'onPointerOut',
150
+ 'onPointerLeave',
151
+ ] as const;
152
+
153
+ const STANDARD_MESH_RAYCAST = THREE.Mesh.prototype.raycast;
154
+
146
155
  const NATIVE_EVENT_NAMES: Readonly<Record<keyof Events, true>> = Object.freeze({
147
156
  onClick: true,
148
157
  onContextMenu: true,
@@ -220,9 +229,7 @@ export function createEvents(store: RootStore): {
220
229
  }
221
230
 
222
231
  function filterPointerEvents(objects: THREE.Object3D[]): THREE.Object3D[] {
223
- return objects.filter((object) =>
224
- POINTER_MOVE_LISTENERS.some((name) => getThreeEventListener(object, name) !== undefined),
225
- );
232
+ return objects.filter((object) => hasThreeEventListeners(object, POINTER_MOVE_LISTENERS));
226
233
  }
227
234
 
228
235
  function intersect(
@@ -235,53 +242,89 @@ export function createEvents(store: RootStore): {
235
242
  const eventObjects = filter
236
243
  ? filter(rootState.internal.interaction)
237
244
  : rootState.internal.interaction;
245
+ let sharedEventStore: RootStore | undefined;
246
+ let singleEventStore = true;
247
+ let previousEventStore: RootStore | undefined;
238
248
 
239
249
  // Each event layer computes its ray lazily, once, for this native event.
240
250
  for (const object of eventObjects) {
241
251
  const objectStore = getThreeEventStore(object);
242
- if (objectStore !== undefined) objectStore.getState().raycaster.camera = undefined!;
252
+ if (objectStore === undefined) {
253
+ singleEventStore = false;
254
+ continue;
255
+ }
256
+ if (sharedEventStore === undefined) sharedEventStore = objectStore;
257
+ else if (sharedEventStore !== objectStore) singleEventStore = false;
258
+ if (objectStore !== previousEventStore) {
259
+ objectStore.getState().raycaster.camera = undefined!;
260
+ previousEventStore = objectStore;
261
+ }
243
262
  }
244
263
 
245
264
  if (!rootState.previousRoot) {
246
265
  rootState.events.compute?.(event, rootState);
247
266
  }
248
267
 
249
- function handleRaycast(object: THREE.Object3D): THREE.Intersection<THREE.Object3D>[] {
268
+ const rawHits: THREE.Intersection<THREE.Object3D>[] = [];
269
+ for (const object of eventObjects) {
250
270
  const objectStore = getThreeEventStore(object);
251
- if (objectStore === undefined) return [];
271
+ if (objectStore === undefined) continue;
272
+ if (objectStore !== sharedEventStore) singleEventStore = false;
252
273
  const state = objectStore.getState();
253
- if (!state.events.enabled || state.raycaster.camera === null) return [];
274
+ if (!state.events.enabled || state.raycaster.camera === null) continue;
254
275
 
255
276
  if (state.raycaster.camera === undefined) {
256
277
  state.events.compute?.(event, state, state.previousRoot?.getState());
257
278
  if (state.raycaster.camera === undefined) state.raycaster.camera = null!;
258
279
  }
259
280
 
260
- if (!state.raycaster.camera) return [];
261
- const intersections: THREE.Intersection<THREE.Object3D>[] = [];
262
- raycastLiveObject(state.raycaster, object, intersections);
263
- return intersections.filter((intersection) => isThreeEventHitLive(intersection.object));
281
+ if (!state.raycaster.camera) continue;
282
+ const sharesHitArray =
283
+ Object.getPrototypeOf(object) === THREE.Mesh.prototype &&
284
+ !Object.prototype.hasOwnProperty.call(object, 'raycast') &&
285
+ THREE.Mesh.prototype.raycast === STANDARD_MESH_RAYCAST &&
286
+ object.children.length === 0;
287
+ const objectHits = sharesHitArray ? rawHits : [];
288
+ const firstHit = objectHits.length;
289
+ raycastLiveObject(state.raycaster, object, objectHits);
290
+ let retainedHits = firstHit;
291
+ for (let index = firstHit; index < objectHits.length; index++) {
292
+ const hit = objectHits[index];
293
+ if (!isThreeEventHitLive(hit.object)) continue;
294
+ if (singleEventStore && getThreeEventStore(hit.object) !== sharedEventStore) {
295
+ singleEventStore = false;
296
+ }
297
+ if (sharesHitArray) rawHits[retainedHits++] = hit;
298
+ else rawHits.push(hit);
299
+ }
300
+ if (sharesHitArray) rawHits.length = retainedHits;
264
301
  }
265
302
 
266
- let hits = eventObjects
267
- .flatMap(handleRaycast)
268
- .sort((left, right) => {
269
- const leftStore = findEventStore(left.object);
270
- const rightStore = findEventStore(right.object);
271
- if (leftStore === undefined || rightStore === undefined) {
272
- return left.distance - right.distance;
273
- }
274
- return (
275
- rightStore.getState().events.priority - leftStore.getState().events.priority ||
276
- left.distance - right.distance
277
- );
278
- })
279
- .filter((item) => {
280
- const id = makeIntersectionId(item as Intersection);
281
- if (duplicates.has(id)) return false;
282
- duplicates.add(id);
283
- return true;
284
- });
303
+ rawHits.sort(
304
+ singleEventStore
305
+ ? (left, right) => left.distance - right.distance
306
+ : (left, right) => {
307
+ const leftStore = findEventStore(left.object);
308
+ const rightStore = findEventStore(right.object);
309
+ if (leftStore === undefined || rightStore === undefined) {
310
+ return left.distance - right.distance;
311
+ }
312
+ return (
313
+ rightStore.getState().events.priority - leftStore.getState().events.priority ||
314
+ left.distance - right.distance
315
+ );
316
+ },
317
+ );
318
+
319
+ let hitCount = 0;
320
+ for (const hit of rawHits) {
321
+ const id = makeIntersectionId(hit as Intersection);
322
+ if (duplicates.has(id)) continue;
323
+ duplicates.add(id);
324
+ rawHits[hitCount++] = hit;
325
+ }
326
+ rawHits.length = hitCount;
327
+ let hits = rawHits;
285
328
 
286
329
  if (rootState.events.filter !== undefined) {
287
330
  hits = rootState.events.filter(hits, rootState);
@@ -347,10 +390,13 @@ export function createEvents(store: RootStore): {
347
390
  intersections: Intersection[],
348
391
  event: DomEvent,
349
392
  delta: number,
350
- callback: (event: ThreeEvent<DomEvent>) => void,
393
+ callback: (event: ThreeEvent<DomEvent>, retainPointerCapture: () => void) => void,
351
394
  ): Intersection[] {
352
395
  if (intersections.length === 0) return intersections;
353
396
  const localState = { stopped: false };
397
+ let nativeProperties: Record<string, unknown> | undefined;
398
+ let ownNativeProperties: string[] | undefined;
399
+ let reusableNativeProperties = false;
354
400
 
355
401
  for (const hit of intersections) {
356
402
  const eventStore = findEventStore(hit.object);
@@ -359,18 +405,27 @@ export function createEvents(store: RootStore): {
359
405
  const { raycaster, pointer, camera, internal } = state;
360
406
  const unprojectedPoint = new THREE.Vector3(pointer.x, pointer.y, 0).unproject(camera);
361
407
 
362
- const captureIdentity = createPointerCaptureIdentity(hit);
408
+ let captureIdentity: ReturnType<typeof createPointerCaptureIdentity> | undefined;
409
+ const ensurePointerCaptureIdentity = () => {
410
+ if (captureIdentity !== undefined) return captureIdentity;
411
+ captureIdentity = createPointerCaptureIdentity(hit);
412
+ registerPointerCaptureFacade(target, captureIdentity);
413
+ registerPointerCaptureFacade(currentTarget, captureIdentity);
414
+ return captureIdentity;
415
+ };
363
416
  const hasPointerCapture = (pointerId: number): boolean =>
364
- internal.capturedMap.get(pointerId)?.has(captureIdentity.eventObject) ?? false;
417
+ internal.capturedMap.get(pointerId)?.has(captureIdentity?.eventObject ?? hit.eventObject) ??
418
+ false;
365
419
 
366
420
  const setPointerCapture = (pointerId: number): void => {
421
+ const identity = ensurePointerCaptureIdentity();
367
422
  const target = event.target as Element;
368
- const capture = { intersection: captureIdentity.intersection, target };
423
+ const capture = { intersection: identity.intersection, target };
369
424
  setInternalPointerCapture(
370
425
  internal.capturedMap,
371
- captureIdentity.eventObject,
426
+ identity.eventObject,
372
427
  capture,
373
- captureIdentity,
428
+ identity,
374
429
  pointerId,
375
430
  );
376
431
  target.setPointerCapture(pointerId);
@@ -381,25 +436,73 @@ export function createEvents(store: RootStore): {
381
436
  if (captures !== undefined) {
382
437
  releaseInternalPointerCapture(
383
438
  internal.capturedMap,
384
- captureIdentity.eventObject,
439
+ captureIdentity?.eventObject ?? hit.eventObject,
385
440
  captures,
386
441
  pointerId,
387
442
  );
388
443
  }
389
444
  };
390
445
 
391
- const nativeProperties: Record<string, unknown> = {};
392
- // Native event values commonly live on the prototype; enumerate both own
393
- // and inherited atomics while leaving methods on nativeEvent.
394
- for (const property in event) {
395
- const value = event[property as keyof DomEvent];
396
- if (typeof value !== 'function') nativeProperties[property] = value;
446
+ if (nativeProperties === undefined) {
447
+ nativeProperties = {};
448
+ const prototype = Object.getPrototypeOf(event);
449
+ reusableNativeProperties =
450
+ (typeof PointerEvent !== 'undefined' && prototype === PointerEvent.prototype) ||
451
+ (typeof MouseEvent !== 'undefined' && prototype === MouseEvent.prototype) ||
452
+ (typeof WheelEvent !== 'undefined' && prototype === WheelEvent.prototype);
453
+ // Inherited native-event getters are stable during this dispatch. Snapshot
454
+ // ordinary event prototypes once; custom subclasses can expose changing
455
+ // inherited getters and retain the complete per-hit extraction.
456
+ for (const property in event) {
457
+ const value = event[property as keyof DomEvent];
458
+ if (typeof value !== 'function') nativeProperties[property] = value;
459
+ }
460
+ // The native event exposes dozens of inherited fields. Building this
461
+ // snapshot dynamically puts it in dictionary mode; clone it once so
462
+ // the per-hit spreads retain a compact, reusable property shape.
463
+ nativeProperties = { ...nativeProperties };
464
+ ownNativeProperties = Object.keys(event);
465
+ } else if (!reusableNativeProperties) {
466
+ nativeProperties = {};
467
+ for (const property in event) {
468
+ const value = event[property as keyof DomEvent];
469
+ if (typeof value !== 'function') nativeProperties[property] = value;
470
+ }
471
+ } else {
472
+ for (const property of ownNativeProperties!) {
473
+ if (Object.prototype.propertyIsEnumerable.call(event, property)) continue;
474
+ delete nativeProperties[property];
475
+
476
+ if (Object.prototype.hasOwnProperty.call(event, property)) continue;
477
+ let prototype = Object.getPrototypeOf(event);
478
+ while (prototype !== null) {
479
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, property);
480
+ if (descriptor !== undefined) {
481
+ if (descriptor.enumerable) {
482
+ const value = event[property as keyof DomEvent];
483
+ if (typeof value !== 'function') nativeProperties[property] = value;
484
+ }
485
+ break;
486
+ }
487
+ prototype = Object.getPrototypeOf(prototype);
488
+ }
489
+ }
490
+
491
+ ownNativeProperties = Object.keys(event);
492
+ for (const property of ownNativeProperties) {
493
+ const value = event[property as keyof DomEvent];
494
+ if (typeof value === 'function') delete nativeProperties[property];
495
+ else nativeProperties[property] = value;
496
+ }
497
+ if ('defaultPrevented' in nativeProperties) {
498
+ nativeProperties.defaultPrevented = event.defaultPrevented;
499
+ }
500
+ if ('cancelBubble' in nativeProperties) nativeProperties.cancelBubble = event.cancelBubble;
501
+ if ('returnValue' in nativeProperties) nativeProperties.returnValue = event.returnValue;
397
502
  }
398
503
 
399
504
  const target = { hasPointerCapture, setPointerCapture, releasePointerCapture };
400
505
  const currentTarget = { hasPointerCapture, setPointerCapture, releasePointerCapture };
401
- registerPointerCaptureFacade(target, captureIdentity);
402
- registerPointerCaptureFacade(currentTarget, captureIdentity);
403
506
 
404
507
  const raycastEvent = {
405
508
  ...hit,
@@ -430,7 +533,7 @@ export function createEvents(store: RootStore): {
430
533
  nativeEvent: event,
431
534
  } as unknown as ThreeEvent<DomEvent>;
432
535
 
433
- callback(raycastEvent);
536
+ callback(raycastEvent, ensurePointerCaptureIdentity);
434
537
  if (localState.stopped) break;
435
538
  }
436
539
  return intersections;
@@ -458,20 +561,17 @@ export function createEvents(store: RootStore): {
458
561
 
459
562
  if (isPointerMove) cancelPointer(hits);
460
563
 
461
- function onIntersect(data: ThreeEvent<DomEvent>): void {
564
+ function onIntersect(data: ThreeEvent<DomEvent>, retainPointerCapture: () => void): void {
462
565
  const { eventObject } = data;
463
566
  const eventStore = findEventStore(eventObject) ?? store;
464
567
 
465
568
  if (isPointerMove) {
466
- const hasHoverHandler =
467
- getThreeEventListener(eventObject, 'onPointerOver') !== undefined ||
468
- getThreeEventListener(eventObject, 'onPointerEnter') !== undefined ||
469
- getThreeEventListener(eventObject, 'onPointerOut') !== undefined ||
470
- getThreeEventListener(eventObject, 'onPointerLeave') !== undefined;
569
+ const hasHoverHandler = hasThreeEventListeners(eventObject, POINTER_HOVER_LISTENERS);
471
570
  if (hasHoverHandler) {
472
571
  const id = makeIntersectionId(data);
473
572
  const hovered = internal.hovered.get(id);
474
573
  if (hovered === undefined) {
574
+ retainPointerCapture();
475
575
  internal.hovered.set(id, data);
476
576
  invokeListener(eventStore, getThreeEventListener(eventObject, 'onPointerOver'), data);
477
577
  invokeListener(eventStore, getThreeEventListener(eventObject, 'onPointerEnter'), data);
package/src/core/hooks.ts CHANGED
@@ -131,7 +131,11 @@ export function useFrame(callback: RenderCallback, ...args: unknown[]): null {
131
131
  const [userArgs, slot] = splitSlot(args);
132
132
  const renderPriority = typeof userArgs[0] === 'number' ? userArgs[0] : 0;
133
133
  const store = useStore();
134
- const callbackRef = useRef(callback, subSlot(slot, 'useFrame:callback'));
134
+ const callbackRef = useMemo(
135
+ () => ({ current: callback }),
136
+ [],
137
+ subSlot(slot, 'useFrame:callback'),
138
+ );
135
139
 
136
140
  useLayoutEffect(
137
141
  () => {
package/src/core/store.ts CHANGED
@@ -181,7 +181,7 @@ const ROOT_OBJECT_STORES = new WeakMap<object, RootStore>();
181
181
  interface PointerCaptureIdentity {
182
182
  eventObject: THREE.Object3D;
183
183
  intersection: Intersection;
184
- pointerIds: Set<number>;
184
+ pointerIds: Set<number> | null;
185
185
  }
186
186
 
187
187
  const POINTER_CAPTURE_IDENTITIES = new WeakMap<object, PointerCaptureIdentity>();
@@ -196,7 +196,7 @@ const POINTER_CAPTURE_TARGET_IDENTITIES = new WeakMap<
196
196
 
197
197
  /** Create the mutable identity cell used by an event's pointer-capture facade. */
198
198
  export function createPointerCaptureIdentity(intersection: Intersection): PointerCaptureIdentity {
199
- return { eventObject: intersection.eventObject, intersection, pointerIds: new Set() };
199
+ return { eventObject: intersection.eventObject, intersection, pointerIds: null };
200
200
  }
201
201
 
202
202
  /** Associate a public capture facade with its renderer-owned identity cell. */
@@ -230,7 +230,7 @@ function pointerCaptureIdentityObjects(identity: PointerCaptureIdentity): Set<TH
230
230
  }
231
231
 
232
232
  function indexPointerCaptureIdentity(identity: PointerCaptureIdentity): void {
233
- if (identity.pointerIds.size === 0) return;
233
+ if (identity.pointerIds === null || identity.pointerIds.size === 0) return;
234
234
  for (const object of pointerCaptureIdentityObjects(identity)) {
235
235
  const identities = ACTIVE_POINTER_CAPTURE_IDENTITIES.get(object);
236
236
  if (identities === undefined) {
@@ -256,14 +256,21 @@ function activatePointerCaptureIdentity(
256
256
  pointerId: number,
257
257
  ): void {
258
258
  POINTER_CAPTURE_TARGET_IDENTITIES.set(capture, identity);
259
- if (identity.pointerIds.has(pointerId)) return;
260
- identity.pointerIds.add(pointerId);
261
- if (identity.pointerIds.size === 1) indexPointerCaptureIdentity(identity);
259
+ const pointerIds = (identity.pointerIds ??= new Set());
260
+ if (pointerIds.has(pointerId)) return;
261
+ pointerIds.add(pointerId);
262
+ if (pointerIds.size === 1) indexPointerCaptureIdentity(identity);
262
263
  }
263
264
 
264
265
  function deactivatePointerCaptureIdentity(capture: PointerCaptureTarget, pointerId: number): void {
265
266
  const identity = POINTER_CAPTURE_TARGET_IDENTITIES.get(capture);
266
- if (identity === undefined || !identity.pointerIds.delete(pointerId)) return;
267
+ if (
268
+ identity === undefined ||
269
+ identity.pointerIds === null ||
270
+ !identity.pointerIds.delete(pointerId)
271
+ ) {
272
+ return;
273
+ }
267
274
  if (identity.pointerIds.size === 0) unindexPointerCaptureIdentity(identity);
268
275
  }
269
276
 
@@ -276,7 +283,7 @@ function transferPointerCaptureIdentity(
276
283
  const eventObject = identity.eventObject === previous ? next : identity.eventObject;
277
284
  if (intersection === identity.intersection && eventObject === identity.eventObject) return;
278
285
 
279
- const active = identity.pointerIds.size > 0;
286
+ const active = identity.pointerIds !== null && identity.pointerIds.size > 0;
280
287
  if (active) unindexPointerCaptureIdentity(identity);
281
288
  identity.eventObject = eventObject;
282
289
  identity.intersection = intersection;
@@ -548,6 +555,7 @@ export function createPortalStore(initialState: RootState): RootStore {
548
555
 
549
556
  /** Walk a portal chain to the one root that owns scheduling and native events. */
550
557
  export function getInitialRootStore(store: RootStore): RootStore {
558
+ if (store.getState().previousRoot === undefined) return store;
551
559
  const seen = new Set<RootStore>();
552
560
  let current = store;
553
561
  while (current.getState().previousRoot !== undefined) {
@@ -705,10 +713,12 @@ export function createRootStore(invalidate: Invalidate, advance: Advance): RootS
705
713
  subscribe(ref, priority, subscriptionStore) {
706
714
  const internal = get().internal;
707
715
  if (priority > 0) internal.priority++;
708
- internal.subscribers = [
709
- ...internal.subscribers,
710
- { ref, priority, store: subscriptionStore },
711
- ].sort((left, right) => left.priority - right.priority);
716
+ const previous = internal.subscribers;
717
+ const subscribers = [...previous, { ref, priority, store: subscriptionStore }];
718
+ if (previous.length !== 0 && !(previous[previous.length - 1].priority <= priority)) {
719
+ subscribers.sort((left, right) => left.priority - right.priority);
720
+ }
721
+ internal.subscribers = subscribers;
712
722
  return () => {
713
723
  const current = get().internal;
714
724
  if (priority > 0) current.priority--;
package/src/scheduling.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import * as Octane from 'octane';
2
+ import { flushSync as clientFlushSync } from 'octane';
2
3
  import { flushUniversalAct, flushUniversalSync, type UniversalSyncFlusher } from 'octane/universal';
3
4
 
4
5
  export type Act = typeof import('octane').act;
@@ -66,14 +67,15 @@ function runClientAct<T>(callback: () => T | Promise<T>, clientAct: Act): Promis
66
67
 
67
68
  /** Flushes both the DOM scheduler and mounted universal Three roots. */
68
69
  export const flushSync: FlushSync = (callback) => {
69
- const clientFlushSync = Reflect.get(Octane, 'flushSync') as FlushSync | undefined;
70
70
  return flushUniversalSync(callback, clientFlushSync);
71
71
  };
72
72
 
73
73
  /** R3F-compatible test helper backed by Octane's client scheduler when available. */
74
74
  export const act: Act = (callback) => {
75
+ // The server entry has flushSync but deliberately does not export act. Keep
76
+ // this optional namespace lookup inside the cold test-only export so bundles
77
+ // using only flushSync can still remove the rest of Octane's public surface.
75
78
  const clientAct = Reflect.get(Octane, 'act') as Act | undefined;
76
- const clientFlushSync = Reflect.get(Octane, 'flushSync') as FlushSync | undefined;
77
79
  if (typeof clientAct === 'function') return runClientAct(callback, clientAct);
78
80
  try {
79
81
  return Promise.resolve(runActCallback(callback, clientFlushSync));