@series-inc/rundot-syncplay 6.0.0-rc.27 → 6.0.0-rc.29

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.
@@ -23,7 +23,7 @@ export const physicsProfileWasmMetadata = Object.freeze({
23
23
  "sourceHash": "13bc7e6c473b9a773bbb0f77d1c2126df59a074759ebb5efb90b8dde1ff4d10a",
24
24
  "wasmSha256": "d398c126e4da59324d6e28f14132173a9f980f9fc429f632baffacbae4744fef",
25
25
  "artifact": "profile",
26
- "packageVersion": "6.0.0-rc.27",
26
+ "packageVersion": "6.0.0-rc.29",
27
27
  "compilerFlags": [
28
28
  "-std=c++20",
29
29
  "-O3",
@@ -23,7 +23,7 @@ export const physicsWasmMetadata = Object.freeze({
23
23
  "sourceHash": "4bb02a55da437ff3075d5350d48f319bd8b89a6dd31d9a34d9b0cb3677ed4914",
24
24
  "wasmSha256": "76ea5a82d4e84d0e3bc3fd93dd54992b54c09614f7024e4f8b5bf91445db1955",
25
25
  "artifact": "production",
26
- "packageVersion": "6.0.0-rc.27",
26
+ "packageVersion": "6.0.0-rc.29",
27
27
  "compilerFlags": [
28
28
  "-std=c++20",
29
29
  "-O3",
@@ -50,7 +50,7 @@ export const physics2dWasmMetadata = Object.freeze({
50
50
  "sourceHash": "faa090a03a6fddaf79c704fb1d76f810955ff35597449c8cec9541a75905a37e",
51
51
  "wasmSha256": "49cb90541deed40f5fff1015bb578e13ec9a793d51931c1227e3e5a11bbfa3f7",
52
52
  "artifact": "production",
53
- "packageVersion": "6.0.0-rc.27",
53
+ "packageVersion": "6.0.0-rc.29",
54
54
  "compilerFlags": [
55
55
  "-std=c++20",
56
56
  "-O3",
@@ -1,7 +1,7 @@
1
1
  import { PhysicsBodyId3D, PhysicsWorld3D } from './physics/3d.js';
2
2
  import { type FrameGravity } from './physics/units.js';
3
3
  export { type FrameGravity, frameGravity } from './physics/units.js';
4
- export type { PhysicsBodyId3D, PhysicsCastHit3D, PhysicsShapeCastQuery3D, PhysicsWorld3D } from './physics/3d.js';
4
+ export type { PhysicsBodyId3D, PhysicsCastHit3D, PhysicsShapeCastQuery3D, PhysicsWorld3D, RegisteredPortalPair3D } from './physics/3d.js';
5
5
  export type DeterministicKccBehaviorRevision = 1 | 2;
6
6
  export type DeterministicKccChecksumMode = 'required' | 'disabled';
7
7
  export interface DeterministicKccBody3D {
@@ -389,6 +389,9 @@ function stepDeterministicKccRevision2_3D(body, input, world, options, gravityPe
389
389
  let supportClaimed = false;
390
390
  if (externalImpulse.applied)
391
391
  events.push('external-impulse');
392
+ const portals = options.portals !== undefined
393
+ ? options.portals
394
+ : (options.physics?.portalPairs ?? []);
392
395
  const geometry = normalizeKccGeometry3D(next);
393
396
  const ignoredBodyIds = new Set(options.ignoredPhysicsBodyIds ?? []);
394
397
  const collisionFilters = options.collisionFilters ?? [];
@@ -399,7 +402,7 @@ function stepDeterministicKccRevision2_3D(body, input, world, options, gravityPe
399
402
  swept: false,
400
403
  sample: 0,
401
404
  collisionFilters,
402
- portals: options.portals,
405
+ portals,
403
406
  };
404
407
  if (options.physics !== undefined) {
405
408
  const recovered = depenetrateKccCapsule(options.physics, x, y, z, geometry, context, stats, events);
@@ -423,7 +426,7 @@ function stepDeterministicKccRevision2_3D(body, input, world, options, gravityPe
423
426
  stats.rejectedHits += forwardOverlap.collisionFilterRejectedHits;
424
427
  let obstructed = forwardOverlap.length > 0;
425
428
  if (!obstructed) {
426
- const sweep = sweepPhysicsKcc3D(options.physics, recoveredPose, { x: targetX, y, z: targetZ, vx, vz }, ignoredBodyIds, options.frame, collisionFilters, options.portals);
429
+ const sweep = sweepPhysicsKcc3D(options.physics, recoveredPose, { x: targetX, y, z: targetZ, vx, vz }, ignoredBodyIds, options.frame, collisionFilters, portals);
427
430
  stats.queries += sweep.queryCount;
428
431
  stats.filterCalls += sweep.collisionFilterCalls;
429
432
  stats.rejectedHits += sweep.collisionFilterRejectedHits;
@@ -466,7 +469,7 @@ function stepDeterministicKccRevision2_3D(body, input, world, options, gravityPe
466
469
  }
467
470
  }
468
471
  if (obstructed && !stepped && !headBlocked) {
469
- const resolved = resolvePhysicsSlide3D(options.physics, recoveredPose, { x: targetX, y, z: targetZ, vx, vz }, ignoredBodyIds, options.frame, collisionFilters, options.portals);
472
+ const resolved = resolvePhysicsSlide3D(options.physics, recoveredPose, { x: targetX, y, z: targetZ, vx, vz }, ignoredBodyIds, options.frame, collisionFilters, portals);
470
473
  stats.queries += resolved.queryCount;
471
474
  stats.filterCalls += resolved.collisionFilterCalls;
472
475
  stats.rejectedHits += resolved.collisionFilterRejectedHits;
@@ -606,8 +609,8 @@ function stepDeterministicKccRevision2_3D(body, input, world, options, gravityPe
606
609
  events.push('push-dynamic');
607
610
  }
608
611
  let portalCrossed = undefined;
609
- if (options.portals && options.portals.length > 0) {
610
- for (const pair of options.portals) {
612
+ if (portals && portals.length > 0) {
613
+ for (const pair of portals) {
611
614
  if (pair.open === false)
612
615
  continue;
613
616
  for (const [entryKey, exitKey] of [
@@ -2206,20 +2209,86 @@ function sweepPhysicsKcc3D(physics, previous, candidate, ignoredBodyIds, frame,
2206
2209
  assertKccCollisionFiltersUnchanged(collisionFilters, filterStateBefore);
2207
2210
  return { ...candidate, corrected: false, slid: false, swept: false, correctionCount: 0, queryCount, collisionFilterCalls, collisionFilterRejectedHits };
2208
2211
  }
2212
+ const APERTURE_CONTAINMENT_TOLERANCE = 0.05;
2213
+ function resolveKccHostBodyId(physics, ref) {
2214
+ if (ref === undefined || ref === null)
2215
+ return undefined;
2216
+ if (typeof ref === "bigint")
2217
+ return ref;
2218
+ if (typeof ref === "number")
2219
+ return BigInt(ref);
2220
+ if (typeof ref === "string") {
2221
+ try {
2222
+ return BigInt(ref);
2223
+ }
2224
+ catch {
2225
+ return undefined;
2226
+ }
2227
+ }
2228
+ if (typeof ref === "object") {
2229
+ if (physics && typeof physics.resolveBody === "function") {
2230
+ try {
2231
+ const handle = physics.resolveBody(ref);
2232
+ if (handle && typeof handle.id === "bigint")
2233
+ return handle.id;
2234
+ }
2235
+ catch {
2236
+ // Fall through
2237
+ }
2238
+ }
2239
+ if ("id" in ref) {
2240
+ const id = ref.id;
2241
+ if (typeof id === "bigint")
2242
+ return id;
2243
+ if (typeof id === "number")
2244
+ return BigInt(id);
2245
+ if (typeof id === "string") {
2246
+ try {
2247
+ return BigInt(id);
2248
+ }
2249
+ catch {
2250
+ return undefined;
2251
+ }
2252
+ }
2253
+ if (typeof id === "object" && id !== null && physics && typeof physics.resolveBody === "function") {
2254
+ try {
2255
+ const handle = physics.resolveBody(id);
2256
+ if (handle && typeof handle.id === "bigint")
2257
+ return handle.id;
2258
+ }
2259
+ catch {
2260
+ // Fall through
2261
+ }
2262
+ }
2263
+ }
2264
+ if ("key" in ref && physics && typeof physics.resolveBody === "function") {
2265
+ try {
2266
+ const handle = physics.resolveBody(ref);
2267
+ if (handle && typeof handle.id === "bigint")
2268
+ return handle.id;
2269
+ }
2270
+ catch {
2271
+ // Fall through
2272
+ }
2273
+ }
2274
+ }
2275
+ return undefined;
2276
+ }
2209
2277
  function kccCapsuleFitsAperture(x, y, z, geometry, portalEnd) {
2210
2278
  const rotNorm = quatNormalizePure(portalEnd.rotation);
2211
2279
  const localCenter = invRotateVec3Pure(rotNorm, subVec3Pure({ x, y, z }, portalEnd.position));
2212
2280
  const halfW = portalEnd.opening.width * 0.5;
2213
2281
  const halfH = portalEnd.opening.height * 0.5;
2214
2282
  const halfSeg = geometry.halfHeight;
2283
+ const skin = geometry.skinWidth ?? 0;
2215
2284
  const localUp = invRotateVec3Pure(rotNorm, { x: 0, y: 1, z: 0 });
2216
- const extX = Math.abs(localUp.x) * halfSeg + geometry.radius;
2217
- const extY = Math.abs(localUp.y) * halfSeg + geometry.radius;
2218
- const extZ = Math.abs(localUp.z) * halfSeg + geometry.radius;
2219
- const fitsOpeningX = Math.abs(localCenter.x) + extX <= halfW;
2220
- const inOpeningY = Math.abs(localCenter.y) <= halfH + halfSeg;
2285
+ const extX = Math.abs(localUp.x) * halfSeg + geometry.radius + skin;
2286
+ const extY = Math.abs(localUp.y) * halfSeg + geometry.radius + skin;
2287
+ const extZ = Math.abs(localUp.z) * halfSeg + geometry.radius + skin;
2288
+ const fitsOpeningX = Math.abs(localCenter.x) + extX <= halfW + APERTURE_CONTAINMENT_TOLERANCE;
2289
+ const fitsOpeningY = Math.abs(localCenter.y) + extY <= halfH + APERTURE_CONTAINMENT_TOLERANCE;
2221
2290
  const inCorridor = Math.abs(localCenter.z) <= Math.max(1.0, extZ + 0.5);
2222
- return fitsOpeningX && inOpeningY && inCorridor;
2291
+ return fitsOpeningX && fitsOpeningY && inCorridor;
2223
2292
  }
2224
2293
  function physicsOverlapsKcc(physics, x, y, z, context) {
2225
2294
  const filterStateBefore = snapshotCollisionFilters(context.collisionFilters);
@@ -2246,9 +2315,8 @@ function physicsOverlapsKcc(physics, x, y, z, context) {
2246
2315
  continue;
2247
2316
  for (const end of [pair.portalA, pair.portalB]) {
2248
2317
  if (end.hostBodyId !== undefined) {
2249
- const hostId = typeof end.hostBodyId === "object" && end.hostBodyId !== null && "id" in end.hostBodyId
2250
- ? end.hostBodyId.id : end.hostBodyId;
2251
- if (hostId === bodyId || BigInt(hostId) === BigInt(bodyId)) {
2318
+ const hostId = resolveKccHostBodyId(physics, end.hostBodyId);
2319
+ if (hostId !== undefined && (hostId === bodyId || hostId === BigInt(bodyId))) {
2252
2320
  if (kccCapsuleFitsAperture(x, y, z, geometry, end)) {
2253
2321
  return false;
2254
2322
  }
@@ -2289,15 +2357,14 @@ function filterKccHits(physics, hits, ignoredBodyIds, collisionFilters, context,
2289
2357
  continue;
2290
2358
  for (const end of [pair.portalA, pair.portalB]) {
2291
2359
  if (end.hostBodyId !== undefined) {
2292
- const hostId = typeof end.hostBodyId === "object" && end.hostBodyId !== null && "id" in end.hostBodyId
2293
- ? end.hostBodyId.id : end.hostBodyId;
2294
- if (hostId === hit.bodyId || BigInt(hostId) === BigInt(hit.bodyId)) {
2360
+ const hostId = resolveKccHostBodyId(physics, end.hostBodyId);
2361
+ if (hostId !== undefined && (hostId === hit.bodyId || hostId === BigInt(hit.bodyId))) {
2295
2362
  const rotNorm = quatNormalizePure(end.rotation);
2296
2363
  const localHit = invRotateVec3Pure(rotNorm, subVec3Pure(hit.point, end.position));
2297
2364
  const halfW = end.opening.width * 0.5;
2298
2365
  const halfH = end.opening.height * 0.5;
2299
- if (Math.abs(localHit.x) <= halfW &&
2300
- Math.abs(localHit.y) <= halfH &&
2366
+ if (Math.abs(localHit.x) <= halfW + APERTURE_CONTAINMENT_TOLERANCE &&
2367
+ Math.abs(localHit.y) <= halfH + APERTURE_CONTAINMENT_TOLERANCE &&
2301
2368
  kccCapsuleFitsAperture(x, y, z, geometry, end)) {
2302
2369
  isHostApertureHit = true;
2303
2370
  break;
@@ -675,7 +675,30 @@ export interface PhysicsCheckpointMotionBatch3D {
675
675
  readonly count: number;
676
676
  readonly frame: bigint;
677
677
  }
678
+ export interface RegisteredPortalPair3D {
679
+ readonly id: number;
680
+ readonly open: boolean;
681
+ readonly portalA: {
682
+ readonly position: PhysicsVector3D<number>;
683
+ readonly rotation: PhysicsQuaternion3D;
684
+ readonly opening: {
685
+ readonly width: number;
686
+ readonly height: number;
687
+ };
688
+ readonly hostBodyId?: PhysicsBodyId3D;
689
+ };
690
+ readonly portalB: {
691
+ readonly position: PhysicsVector3D<number>;
692
+ readonly rotation: PhysicsQuaternion3D;
693
+ readonly opening: {
694
+ readonly width: number;
695
+ readonly height: number;
696
+ };
697
+ readonly hostBodyId?: PhysicsBodyId3D;
698
+ };
699
+ }
678
700
  export interface PhysicsWorld3D {
701
+ readonly portalPairs?: readonly RegisteredPortalPair3D[];
679
702
  edit<T = unknown>(build: (ops: PhysicsEditOps3D) => T): PhysicsEditResult3D<T>;
680
703
  step(): void;
681
704
  applyImpulse(handle: PhysicsBodyHandle3D, impulse: PhysicsVector3D<NewtonSeconds>, point?: PhysicsVector3D<Meters>): void;
@@ -950,6 +950,10 @@ function defaultInertia(shape, mass) {
950
950
  zz: kilogramMetersSquared(mass * (3 * shape.radius ** 2 + height ** 2) / 12),
951
951
  };
952
952
  }
953
+ const PORTAL_HOST_LAYER_BASE = 24;
954
+ const PORTAL_HOST_LAYER_COUNT = 7;
955
+ const ALL_PORTAL_HOST_LAYERS = (0x7f << PORTAL_HOST_LAYER_BASE) >>> 0;
956
+ const APERTURE_CONTAINMENT_TOLERANCE = 0.05;
953
957
  function encodeBody(body) {
954
958
  const values = new Float64Array(bodyStride);
955
959
  const kind = body.kind ?? 'dynamic';
@@ -972,8 +976,8 @@ function encodeBody(body) {
972
976
  | (body.trigger === true ? 4 : 0) | (body.sensor === true ? 8 : 0)
973
977
  | (kind === 'dynamic' && body.sleeping === true ? 16 : 0) | 32;
974
978
  values[10] = shapeKind;
975
- values[11] = u32(body.layer ?? 1, 'layer');
976
- values[12] = u32(body.mask ?? 1, 'mask') | ALL_PORTAL_HOST_LAYERS;
979
+ values[11] = u32(body.layer ?? 1, 'layer') >>> 0;
980
+ values[12] = (u32(body.mask ?? 1, 'mask') | ALL_PORTAL_HOST_LAYERS) >>> 0;
977
981
  values[13] = finite(body.gravityScale ?? 1, 'gravityScale');
978
982
  values[14] = nonnegative(body.linearDamping ?? 0.995, 'linearDamping');
979
983
  values[18] = mass;
@@ -1114,7 +1118,7 @@ function decodeMotionShape(values) {
1114
1118
  return Object.freeze({ type: 'heightfield' });
1115
1119
  return decodeShape(values);
1116
1120
  }
1117
- function decodeBody(id, values, shape) {
1121
+ function decodeBody(id, values, shape, originalMask) {
1118
1122
  const motion = values[9];
1119
1123
  const kindCode = motion & 3;
1120
1124
  return Object.freeze({
@@ -1131,8 +1135,8 @@ function decodeBody(id, values, shape) {
1131
1135
  centerOfMass: Object.freeze(metersVector({ x: values[37], y: values[38], z: values[39] })),
1132
1136
  gravityScale: values[13], linearDamping: values[14], angularDamping: values[26],
1133
1137
  friction: values[27], restitution: values[28], rollingResistance: values[43],
1134
- layer: (values[11] & ALL_PORTAL_HOST_LAYERS) !== 0 ? 1 : values[11],
1135
- mask: values[12] & ~ALL_PORTAL_HOST_LAYERS,
1138
+ layer: (values[11] & ALL_PORTAL_HOST_LAYERS) !== 0 ? 1 : (values[11] >>> 0),
1139
+ mask: originalMask !== undefined ? (originalMask >>> 0) : ((values[12] & ~ALL_PORTAL_HOST_LAYERS) >>> 0),
1136
1140
  trigger: (motion & 4) !== 0,
1137
1141
  sensor: (motion & 8) !== 0, sleeping: (motion & 16) !== 0,
1138
1142
  sleepEnabled: values[41] !== 0, sleepThreshold: metersPerSecond(values[40]), sleepTime: seconds(values[42]),
@@ -1464,7 +1468,7 @@ function decodeJoint(id, bodyA, bodyB, values) {
1464
1468
  reactionAngularImpulse: newtonMeterSeconds(values[149]), });
1465
1469
  }
1466
1470
  function queryInput(query) {
1467
- const layerMask = query.layerMask !== undefined ? (query.layerMask | ALL_PORTAL_HOST_LAYERS) : undefined;
1471
+ const layerMask = query.layerMask !== undefined ? (((u32(query.layerMask, 'layerMask') >>> 0) | ALL_PORTAL_HOST_LAYERS) >>> 0) : undefined;
1468
1472
  return {
1469
1473
  ...query,
1470
1474
  ...(layerMask !== undefined ? { layerMask } : {}),
@@ -1640,9 +1644,7 @@ function quatNormalize(q) {
1640
1644
  const inv = 1 / Math.sqrt(lenSq);
1641
1645
  return { x: q.x * inv, y: q.y * inv, z: q.z * inv, w: q.w * inv };
1642
1646
  }
1643
- const PORTAL_HOST_LAYER_BASE = 24;
1644
- const PORTAL_HOST_LAYER_COUNT = 7;
1645
- const ALL_PORTAL_HOST_LAYERS = (0x7f << PORTAL_HOST_LAYER_BASE);
1647
+ // Portal host layer constants declared above
1646
1648
  function normalizeZero(v) {
1647
1649
  return Object.is(v, -0) ? 0 : v;
1648
1650
  }
@@ -1686,6 +1688,23 @@ function computeOrientedExtents(shapeKind, values, bodyOri, portalRotNorm) {
1686
1688
  extZ: Math.abs(m20) * hx + Math.abs(m21) * hy + Math.abs(m22) * hz,
1687
1689
  };
1688
1690
  }
1691
+ if (shapeKind === 2) {
1692
+ const r = values[6];
1693
+ const hh = values[7];
1694
+ const qLocal = quatMultiply(quatConjugate(portalRotNorm), bodyOri);
1695
+ const x = qLocal.x;
1696
+ const y = qLocal.y;
1697
+ const z = qLocal.z;
1698
+ const w = qLocal.w;
1699
+ const m01 = 2 * (x * y - w * z);
1700
+ const m11 = 1 - 2 * (x * x + z * z);
1701
+ const m21 = 2 * (y * z + w * x);
1702
+ return {
1703
+ extX: Math.abs(m01) * hh + r,
1704
+ extY: Math.abs(m11) * hh + r,
1705
+ extZ: Math.abs(m21) * hh + r,
1706
+ };
1707
+ }
1689
1708
  const r = values[6];
1690
1709
  const h = values[7] ?? 0;
1691
1710
  const maxDim = r + h;
@@ -1796,7 +1815,7 @@ function wrapRuntimeController(rawController, portalManager, portalCheckpoints)
1796
1815
  portalManager.restoreState(saved);
1797
1816
  }
1798
1817
  else {
1799
- portalManager.clearEphemeralState();
1818
+ portalManager.clearAllState();
1800
1819
  }
1801
1820
  }
1802
1821
  return rawController.restoreCheckpoint(checkpoint);
@@ -1833,7 +1852,7 @@ function wrapRuntimeController(rawController, portalManager, portalCheckpoints)
1833
1852
  };
1834
1853
  return Object.freeze(wrapped);
1835
1854
  }
1836
- function resolveHostBodyId(ref) {
1855
+ function resolveHostBodyId(ref, committedPendingBodies, committedPendingRefs) {
1837
1856
  if (ref === undefined || ref === null)
1838
1857
  return undefined;
1839
1858
  if (typeof ref === "bigint")
@@ -1848,18 +1867,33 @@ function resolveHostBodyId(ref) {
1848
1867
  return undefined;
1849
1868
  }
1850
1869
  }
1851
- if (typeof ref === "object" && "id" in ref) {
1852
- const id = ref.id;
1853
- if (typeof id === "bigint")
1854
- return id;
1855
- if (typeof id === "number")
1856
- return BigInt(id);
1857
- if (typeof id === "string") {
1858
- try {
1870
+ if (typeof ref === "object") {
1871
+ if (committedPendingRefs && committedPendingRefs.has(ref)) {
1872
+ return committedPendingRefs.get(ref).id;
1873
+ }
1874
+ if ("key" in ref && typeof ref.key === "number") {
1875
+ const handle = committedPendingBodies?.get(ref.key);
1876
+ if (handle)
1877
+ return handle.id;
1878
+ }
1879
+ if ("id" in ref) {
1880
+ const id = ref.id;
1881
+ if (typeof id === "bigint")
1882
+ return id;
1883
+ if (typeof id === "number")
1859
1884
  return BigInt(id);
1885
+ if (typeof id === "string") {
1886
+ try {
1887
+ return BigInt(id);
1888
+ }
1889
+ catch {
1890
+ return undefined;
1891
+ }
1860
1892
  }
1861
- catch {
1862
- return undefined;
1893
+ if (typeof id === "object" && id !== null && "key" in id && typeof id.key === "number") {
1894
+ const handle = committedPendingBodies?.get(id.key);
1895
+ if (handle)
1896
+ return handle.id;
1863
1897
  }
1864
1898
  }
1865
1899
  }
@@ -1883,6 +1917,14 @@ class PortalSimulatorManager {
1883
1917
  this.bodySuppressedLayers.clear();
1884
1918
  this.lastCrossings = [];
1885
1919
  }
1920
+ clearAllState() {
1921
+ this.nextId = 1;
1922
+ this.pairs.clear();
1923
+ this.hostBodies.clear();
1924
+ this.hostLayerMap.clear();
1925
+ this.originalHostLayers.clear();
1926
+ this.clearEphemeralState();
1927
+ }
1886
1928
  registerHost(hostId, raw, world) {
1887
1929
  this.hostBodies.add(hostId);
1888
1930
  let layer = this.hostLayerMap.get(hostId);
@@ -1896,7 +1938,10 @@ class PortalSimulatorManager {
1896
1938
  }
1897
1939
  }
1898
1940
  if (layer === undefined) {
1899
- layer = 1 << PORTAL_HOST_LAYER_BASE;
1941
+ throw new SyncplayError("Maximum number of portal host bodies (7) exceeded.", {
1942
+ code: "physics.capacity-exceeded",
1943
+ operation: "registerHost",
1944
+ });
1900
1945
  }
1901
1946
  this.hostLayerMap.set(hostId, layer);
1902
1947
  }
@@ -1924,7 +1969,7 @@ class PortalSimulatorManager {
1924
1969
  try {
1925
1970
  const handle = world.resolveBody(bodyId);
1926
1971
  const bVals = new Float64Array(raw.readBody(handle));
1927
- bVals[12] = bVals[12] | suppressedMask;
1972
+ bVals[12] = ((bVals[12] | suppressedMask) >>> 0);
1928
1973
  raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
1929
1974
  }
1930
1975
  catch (err) {
@@ -2008,7 +2053,7 @@ class PortalSimulatorManager {
2008
2053
  w: this.scratchPoses[i * 7 + 6],
2009
2054
  };
2010
2055
  const ext = computeOrientedExtents(shapeKind, bVals, bodyOri, entryRotNorm);
2011
- if (Math.abs(localPos.x) + ext.extX <= halfW && Math.abs(localPos.y) + ext.extY <= halfH) {
2056
+ if (Math.abs(localPos.x) + ext.extX <= halfW + APERTURE_CONTAINMENT_TOLERANCE && Math.abs(localPos.y) + ext.extY <= halfH + APERTURE_CONTAINMENT_TOLERANCE) {
2012
2057
  if (localPos.z >= -ext.extZ * 2.5 && localPos.z <= trackingRadius) {
2013
2058
  desiredSuppressed.set(bodyId, (desiredSuppressed.get(bodyId) ?? 0) | hostLayer);
2014
2059
  }
@@ -2023,7 +2068,7 @@ class PortalSimulatorManager {
2023
2068
  try {
2024
2069
  const handle = world.resolveBody(bodyId);
2025
2070
  const bVals = new Float64Array(raw.readBody(handle));
2026
- bVals[12] = (bVals[12] | ALL_PORTAL_HOST_LAYERS) & ~desiredMask;
2071
+ bVals[12] = (((bVals[12] | ALL_PORTAL_HOST_LAYERS) & ~desiredMask) >>> 0);
2027
2072
  raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
2028
2073
  }
2029
2074
  catch (err) {
@@ -2037,7 +2082,7 @@ class PortalSimulatorManager {
2037
2082
  try {
2038
2083
  const handle = world.resolveBody(bodyId);
2039
2084
  const bVals = new Float64Array(raw.readBody(handle));
2040
- bVals[12] = bVals[12] | currentMask;
2085
+ bVals[12] = ((bVals[12] | currentMask) >>> 0);
2041
2086
  raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
2042
2087
  }
2043
2088
  catch (err) {
@@ -2099,6 +2144,8 @@ class PortalSimulatorManager {
2099
2144
  },
2100
2145
  })),
2101
2146
  cutoutSuppressedBodies: Array.from(this.bodySuppressedLayers.keys()).map((id) => id.toString()),
2147
+ bodySuppressedLayers: Array.from(this.bodySuppressedLayers.entries()).map(([k, v]) => [k.toString(), v]),
2148
+ hostLayerMap: Array.from(this.hostLayerMap.entries()).map(([k, v]) => [k.toString(), v]),
2102
2149
  originalHostLayers: Array.from(this.originalHostLayers.entries()).map(([k, v]) => [k.toString(), v]),
2103
2150
  };
2104
2151
  }
@@ -2125,10 +2172,23 @@ class PortalSimulatorManager {
2125
2172
  open: p.open,
2126
2173
  });
2127
2174
  if (p.portalA.hostBodyId !== undefined) {
2128
- this.registerHost(BigInt(p.portalA.hostBodyId));
2175
+ this.hostBodies.add(BigInt(p.portalA.hostBodyId));
2129
2176
  }
2130
2177
  if (p.portalB.hostBodyId !== undefined) {
2131
- this.registerHost(BigInt(p.portalB.hostBodyId));
2178
+ this.hostBodies.add(BigInt(p.portalB.hostBodyId));
2179
+ }
2180
+ }
2181
+ if (state.hostLayerMap) {
2182
+ for (const [k, v] of state.hostLayerMap) {
2183
+ this.hostLayerMap.set(BigInt(k), v);
2184
+ }
2185
+ }
2186
+ else {
2187
+ for (const p of state.pairs) {
2188
+ if (p.portalA.hostBodyId !== undefined)
2189
+ this.registerHost(BigInt(p.portalA.hostBodyId));
2190
+ if (p.portalB.hostBodyId !== undefined)
2191
+ this.registerHost(BigInt(p.portalB.hostBodyId));
2132
2192
  }
2133
2193
  }
2134
2194
  this.priorBodyPlanes.clear();
@@ -2150,7 +2210,12 @@ class PortalSimulatorManager {
2150
2210
  this.poseJumpBodyIds.add(BigInt(idStr));
2151
2211
  }
2152
2212
  this.bodySuppressedLayers.clear();
2153
- if (state.cutoutSuppressedBodies) {
2213
+ if (state.bodySuppressedLayers) {
2214
+ for (const [idStr, mask] of state.bodySuppressedLayers) {
2215
+ this.bodySuppressedLayers.set(BigInt(idStr), mask >>> 0);
2216
+ }
2217
+ }
2218
+ else if (state.cutoutSuppressedBodies) {
2154
2219
  for (const idStr of state.cutoutSuppressedBodies) {
2155
2220
  this.bodySuppressedLayers.set(BigInt(idStr), ALL_PORTAL_HOST_LAYERS);
2156
2221
  }
@@ -2169,6 +2234,24 @@ class PortalSimulatorManager {
2169
2234
  }
2170
2235
  }
2171
2236
  }
2237
+ getRegisteredPortalPairs() {
2238
+ return Object.freeze(Array.from(this.pairs.values()).map((p) => Object.freeze({
2239
+ id: p.id,
2240
+ open: p.open,
2241
+ portalA: Object.freeze({
2242
+ position: Object.freeze({ ...p.portalA.position }),
2243
+ rotation: Object.freeze({ ...p.portalA.rotation }),
2244
+ opening: Object.freeze({ width: p.portalA.opening.width, height: p.portalA.opening.height }),
2245
+ hostBodyId: p.portalA.hostBodyId !== undefined ? BigInt(p.portalA.hostBodyId) : undefined,
2246
+ }),
2247
+ portalB: Object.freeze({
2248
+ position: Object.freeze({ ...p.portalB.position }),
2249
+ rotation: Object.freeze({ ...p.portalB.rotation }),
2250
+ opening: Object.freeze({ width: p.portalB.opening.width, height: p.portalB.opening.height }),
2251
+ hostBodyId: p.portalB.hostBodyId !== undefined ? BigInt(p.portalB.hostBodyId) : undefined,
2252
+ }),
2253
+ })));
2254
+ }
2172
2255
  computeDigest(rawDigest, state) {
2173
2256
  const s = state ?? this.captureState();
2174
2257
  if (s.pairs.length === 0 &&
@@ -2258,7 +2341,7 @@ class PortalSimulatorManager {
2258
2341
  view.setUint32(result.length - 4, view.getUint32(result.length - 4, true) ^ high, true);
2259
2342
  return result;
2260
2343
  }
2261
- createPortalPair(def, raw, world) {
2344
+ createPortalPair(def, raw, world, committedPendingBodies, committedPendingRefs) {
2262
2345
  if (!def.portalA || !def.portalB) {
2263
2346
  throw new SyncplayError('PortalPairDefinition requires portalA and portalB.', {
2264
2347
  code: 'physics.definition-invalid',
@@ -2272,13 +2355,13 @@ class PortalSimulatorManager {
2272
2355
  position: { ...def.portalA.position },
2273
2356
  rotation: quatNormalize(def.portalA.rotation),
2274
2357
  opening: { width: Number(def.portalA.opening.width), height: Number(def.portalA.opening.height) },
2275
- hostBodyId: resolveHostBodyId(def.portalA.hostBodyId),
2358
+ hostBodyId: resolveHostBodyId(def.portalA.hostBodyId, committedPendingBodies, committedPendingRefs),
2276
2359
  },
2277
2360
  portalB: {
2278
2361
  position: { ...def.portalB.position },
2279
2362
  rotation: quatNormalize(def.portalB.rotation),
2280
2363
  opening: { width: Number(def.portalB.opening.width), height: Number(def.portalB.opening.height) },
2281
- hostBodyId: resolveHostBodyId(def.portalB.hostBodyId),
2364
+ hostBodyId: resolveHostBodyId(def.portalB.hostBodyId, committedPendingBodies, committedPendingRefs),
2282
2365
  },
2283
2366
  open: def.open ?? true,
2284
2367
  };
@@ -2309,7 +2392,7 @@ class PortalSimulatorManager {
2309
2392
  try {
2310
2393
  const handle = world.resolveBody(bodyId);
2311
2394
  const bVals = new Float64Array(raw.readBody(handle));
2312
- bVals[12] = bVals[12] | suppressedMask;
2395
+ bVals[12] = ((bVals[12] | suppressedMask) >>> 0);
2313
2396
  raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
2314
2397
  }
2315
2398
  catch (err) {
@@ -2330,11 +2413,20 @@ class PortalSimulatorManager {
2330
2413
  });
2331
2414
  }
2332
2415
  if (world) {
2333
- this.ejectStraddlingBodies(pair, world, ops, raw);
2416
+ this.ejectStraddlingBodies(pair, world, ops, raw, end === 'A' ? 'portalA' : 'portalB');
2334
2417
  }
2335
2418
  const targetEnd = end === 'A' ? pair.portalA : pair.portalB;
2336
2419
  targetEnd.position = { ...pose.position };
2337
2420
  targetEnd.rotation = quatNormalize(pose.rotation);
2421
+ const prefix = `${handle.id}:${end}:`;
2422
+ for (const k of this.priorBodyPlanes.keys()) {
2423
+ if (k.startsWith(prefix))
2424
+ this.priorBodyPlanes.delete(k);
2425
+ }
2426
+ for (const k of this.priorBodyVelocities.keys()) {
2427
+ if (k.startsWith(prefix))
2428
+ this.priorBodyVelocities.delete(k);
2429
+ }
2338
2430
  }
2339
2431
  removePortalPair(handle, world, ops, raw) {
2340
2432
  const pair = this.pairs.get(handle.id);
@@ -2382,7 +2474,7 @@ class PortalSimulatorManager {
2382
2474
  try {
2383
2475
  const bHandle = world.resolveBody(bodyId);
2384
2476
  const bVals = new Float64Array(raw.readBody(bHandle));
2385
- bVals[12] = bVals[12] | suppressedMask;
2477
+ bVals[12] = ((bVals[12] | suppressedMask) >>> 0);
2386
2478
  raw.applyBatch([{ type: "editBody", body: bHandle, values: bVals, geometry: { type: "keep" } }]);
2387
2479
  }
2388
2480
  catch (err) {
@@ -2400,12 +2492,13 @@ class PortalSimulatorManager {
2400
2492
  this.priorBodyVelocities.delete(k);
2401
2493
  }
2402
2494
  }
2403
- ejectStraddlingBodies(pair, world, ops, raw) {
2495
+ ejectStraddlingBodies(pair, world, ops, raw, specificEnd) {
2404
2496
  const topology = world.info();
2405
2497
  if (topology.bodyCount === 0)
2406
2498
  return;
2407
2499
  const bodyIds = raw ? raw.topology().bodies : [];
2408
- for (const endKey of ['portalA', 'portalB']) {
2500
+ const ends = specificEnd ? [specificEnd] : ['portalA', 'portalB'];
2501
+ for (const endKey of ends) {
2409
2502
  const portalEnd = pair[endKey];
2410
2503
  const otherEnd = endKey === 'portalA' ? pair.portalB : pair.portalA;
2411
2504
  const endRotNorm = quatNormalize(portalEnd.rotation);
@@ -2565,7 +2658,7 @@ class PortalSimulatorManager {
2565
2658
  this.bodySuppressedLayers.delete(bodyId);
2566
2659
  try {
2567
2660
  const bVals = new Float64Array(raw.readBody(handle));
2568
- bVals[12] = bVals[12] | suppressedMask;
2661
+ bVals[12] = ((bVals[12] | suppressedMask) >>> 0);
2569
2662
  raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
2570
2663
  }
2571
2664
  catch (err) {
@@ -2824,7 +2917,36 @@ function facade(raw, definition) {
2824
2917
  });
2825
2918
  const portalManager = new PortalSimulatorManager();
2826
2919
  const portalCheckpoints = new WeakMap();
2920
+ const originalBodyMasks = new Map();
2921
+ let nextWorldBodyKey = 1;
2922
+ let nextWorldJointKey = 1;
2923
+ let nextWorldFluidKey = 1;
2924
+ const committedPendingBodies = new Map();
2925
+ const committedPendingRefs = new WeakMap();
2926
+ const resolveBodyHandle = (ref) => {
2927
+ if (ref && typeof ref === "object") {
2928
+ if (committedPendingRefs.has(ref))
2929
+ return committedPendingRefs.get(ref);
2930
+ if ("key" in ref && typeof ref.key === "number") {
2931
+ const h = committedPendingBodies.get(ref.key);
2932
+ if (h)
2933
+ return h;
2934
+ }
2935
+ if ("id" in ref) {
2936
+ const id = ref.id;
2937
+ if (typeof id === "object" && id !== null && "key" in id && typeof id.key === "number") {
2938
+ const h = committedPendingBodies.get(id.key);
2939
+ if (h)
2940
+ return h;
2941
+ }
2942
+ }
2943
+ }
2944
+ return ref;
2945
+ };
2827
2946
  const world = {
2947
+ get portalPairs() {
2948
+ return portalManager.getRegisteredPortalPairs();
2949
+ },
2828
2950
  edit(build) {
2829
2951
  return invokeWorld("edit", () => {
2830
2952
  let isSealed = false;
@@ -2832,11 +2954,16 @@ function facade(raw, definition) {
2832
2954
  if (isSealed)
2833
2955
  fail("physics.sealed-ops", "edit", "edit operations are sealed.");
2834
2956
  };
2957
+ const portalStateBefore = portalManager.captureState();
2958
+ const originalMasksBefore = new Map(originalBodyMasks);
2835
2959
  const commands = [];
2836
- const pending = new WeakMap();
2960
+ const pending = new Map();
2837
2961
  const pendingPortalHosts = [];
2838
2962
  const removedPending = new Set();
2839
2963
  const removedLive = new Set();
2964
+ const stagedBodyMasks = new Map();
2965
+ const stagedLiveMaskUpdates = new Map();
2966
+ const stagedSuppressionDeletions = new Set();
2840
2967
  const topologyBefore = raw.topology();
2841
2968
  const simulatedBodies = new Set(topologyBefore.bodies.map((id) => "body:" + id));
2842
2969
  const simulatedJoints = new Map(topologyBefore.joints.map((joint) => [
@@ -2844,9 +2971,6 @@ function facade(raw, definition) {
2844
2971
  { bodyA: "body:" + joint.bodyA, bodyB: "body:" + joint.bodyB },
2845
2972
  ]));
2846
2973
  const simulatedFluids = new Set((topologyBefore.fluids ?? []).map((id) => "fluid:" + id));
2847
- let nextBodyKey = 1;
2848
- let nextJointKey = 1;
2849
- let nextFluidKey = 1;
2850
2974
  const makePending = (kind, key) => {
2851
2975
  const reference = Object.freeze({
2852
2976
  kind,
@@ -2867,15 +2991,16 @@ function facade(raw, definition) {
2867
2991
  fail("physics.definition-invalid", "edit", "expected a " + kind + " reference.");
2868
2992
  return staged;
2869
2993
  }
2870
- if ("createdBody" in ref || "createdJoint" in ref || "createdFluid" in ref) {
2994
+ const resolved = kind === "body" ? resolveBodyHandle(ref) : ref;
2995
+ if ("createdBody" in resolved || "createdJoint" in resolved || "createdFluid" in resolved) {
2871
2996
  fail("physics.definition-invalid", "edit", "invalid handle reference.");
2872
2997
  }
2873
2998
  if (kind === "body")
2874
- raw.validateBody(ref);
2999
+ raw.validateBody(resolved);
2875
3000
  else if (kind === "joint")
2876
- raw.validateJoint(ref);
3001
+ raw.validateJoint(resolved);
2877
3002
  else
2878
- raw.validateFluid(ref);
3003
+ raw.validateFluid(resolved);
2879
3004
  return undefined;
2880
3005
  };
2881
3006
  const simulationKey = (reference, kind) => {
@@ -2885,12 +3010,13 @@ function facade(raw, definition) {
2885
3010
  fail("physics.definition-invalid", "edit", "expected a " + kind + " reference.");
2886
3011
  return kind + "-pending:" + staged.key;
2887
3012
  }
2888
- return kind + ":" + reference.id;
3013
+ const resolved = kind === "body" ? resolveBodyHandle(reference) : reference;
3014
+ return kind + ":" + resolved.id;
2889
3015
  };
2890
3016
  const nativeRef = (reference, kind) => {
2891
3017
  const staged = validateReference(reference, kind);
2892
3018
  if (staged === undefined)
2893
- return reference;
3019
+ return kind === "body" ? resolveBodyHandle(reference) : reference;
2894
3020
  return kind === "body" ? { createdBody: staged.key }
2895
3021
  : kind === "joint" ? { createdJoint: staged.key } : { createdFluid: staged.key };
2896
3022
  };
@@ -2899,9 +3025,10 @@ function facade(raw, definition) {
2899
3025
  const ops = Object.freeze({
2900
3026
  createBody(body) {
2901
3027
  assertActiveOps();
2902
- const key = nextBodyKey++;
3028
+ const key = nextWorldBodyKey++;
2903
3029
  commands.push({ type: "createBody", key, ...encodeBody(body) });
2904
3030
  const reference = makePending("body", key);
3031
+ stagedBodyMasks.set(key, (u32(body.mask ?? 1, "mask") >>> 0));
2905
3032
  simulatedBodies.add(simulationKey(reference, "body"));
2906
3033
  return reference;
2907
3034
  },
@@ -2911,6 +3038,16 @@ function facade(raw, definition) {
2911
3038
  const encoded = encodeBody(body);
2912
3039
  commands.push({ type: "editBody", body: ref, ...encoded,
2913
3040
  geometry: encoded.geometry ?? { type: "clear" } });
3041
+ const normalizedMask = (u32(body.mask ?? 1, "mask") >>> 0);
3042
+ const staged = validateReference(reference, "body");
3043
+ if (staged !== undefined) {
3044
+ stagedBodyMasks.set(staged.key, normalizedMask);
3045
+ }
3046
+ else {
3047
+ const bodyHandle = ref;
3048
+ stagedLiveMaskUpdates.set(bodyHandle.id, normalizedMask);
3049
+ stagedSuppressionDeletions.add(bodyHandle.id);
3050
+ }
2914
3051
  return reference;
2915
3052
  },
2916
3053
  removeBody(reference) {
@@ -2930,7 +3067,7 @@ function facade(raw, definition) {
2930
3067
  },
2931
3068
  createJoint(joint) {
2932
3069
  assertActiveOps();
2933
- const key = nextJointKey++;
3070
+ const key = nextWorldJointKey++;
2934
3071
  const bodyA = nativeRef(joint.bodyA, "body");
2935
3072
  const bodyB = nativeRef(joint.bodyB, "body");
2936
3073
  commands.push({ type: "createJoint", key,
@@ -2972,7 +3109,7 @@ function facade(raw, definition) {
2972
3109
  },
2973
3110
  createFluid(fluid) {
2974
3111
  assertActiveOps();
2975
- const key = nextFluidKey++;
3112
+ const key = nextWorldFluidKey++;
2976
3113
  commands.push({ type: "createFluid", key, values: encodeFluid(fluid) });
2977
3114
  const reference = makePending("fluid", key);
2978
3115
  simulatedFluids.add(simulationKey(reference, "fluid"));
@@ -3040,10 +3177,10 @@ function facade(raw, definition) {
3040
3177
  }
3041
3178
  else {
3042
3179
  commands.push({ type: "editBody", body: ref, values, geometry: { type: "keep" } });
3043
- portalManager.poseJumpBodyIds.add(reference.id);
3180
+ portalManager.poseJumpBodyIds.add(ref.id);
3044
3181
  if (dropContacts) {
3045
3182
  teleportsToDropContacts.push({
3046
- handle: reference,
3183
+ handle: ref,
3047
3184
  position: pose.position,
3048
3185
  orientation: normOri,
3049
3186
  });
@@ -3065,33 +3202,32 @@ function facade(raw, definition) {
3065
3202
  else {
3066
3203
  values = new Float64Array(raw.readBody(ref));
3067
3204
  }
3068
- values[11] = u32(layer, "layer");
3069
- values[12] = u32(mask, "mask") | ALL_PORTAL_HOST_LAYERS;
3205
+ const normalizedMask = (u32(mask, "mask") >>> 0);
3206
+ values[11] = (u32(layer, "layer") >>> 0);
3207
+ values[12] = ((normalizedMask | ALL_PORTAL_HOST_LAYERS) >>> 0);
3070
3208
  if (staged) {
3071
3209
  const cmd = commands.find((c) => c.type === "createBody" && c.key === staged.key);
3072
3210
  if (cmd)
3073
3211
  cmd.values = values;
3212
+ stagedBodyMasks.set(staged.key, normalizedMask);
3074
3213
  }
3075
3214
  else {
3076
3215
  commands.push({ type: "editBody", body: ref, values, geometry: { type: "keep" } });
3216
+ const bodyHandle = ref;
3217
+ stagedLiveMaskUpdates.set(bodyHandle.id, normalizedMask);
3218
+ stagedSuppressionDeletions.add(bodyHandle.id);
3077
3219
  }
3078
3220
  },
3079
3221
  createPortalPair(def) {
3080
3222
  assertActiveOps();
3081
- const pairHandle = portalManager.createPortalPair(def, raw, world);
3223
+ const pairHandle = portalManager.createPortalPair(def, undefined, world, committedPendingBodies, committedPendingRefs);
3082
3224
  const checkPending = (end, hostRef) => {
3083
3225
  if (hostRef !== undefined && hostRef !== null && typeof hostRef === "object") {
3084
- let key;
3085
- if ("key" in hostRef && typeof hostRef.key === "number") {
3086
- key = hostRef.key;
3087
- }
3088
- else if ("id" in hostRef && typeof hostRef.id === "object" && hostRef.id !== null) {
3089
- const inner = hostRef.id;
3090
- if (typeof inner.key === "number")
3091
- key = inner.key;
3092
- }
3093
- if (key !== undefined) {
3094
- pendingPortalHosts.push({ pairId: pairHandle.id, end, key });
3226
+ if (pending.has(hostRef)) {
3227
+ const staged = pending.get(hostRef);
3228
+ if (staged.kind === "body") {
3229
+ pendingPortalHosts.push({ pairId: pairHandle.id, end, key: staged.key });
3230
+ }
3095
3231
  }
3096
3232
  }
3097
3233
  };
@@ -3101,107 +3237,176 @@ function facade(raw, definition) {
3101
3237
  },
3102
3238
  setPortalOpen(handle, open) {
3103
3239
  assertActiveOps();
3104
- portalManager.setPortalOpen(handle, open, world, ops, raw);
3240
+ portalManager.setPortalOpen(handle, open, world, ops, undefined);
3105
3241
  },
3106
3242
  movePortalEnd(handle, end, pose) {
3107
3243
  assertActiveOps();
3108
- portalManager.movePortalEnd(handle, end, pose, world, ops, raw);
3244
+ portalManager.movePortalEnd(handle, end, pose, world, ops, undefined);
3109
3245
  },
3110
3246
  removePortalPair(handle) {
3111
3247
  assertActiveOps();
3112
- portalManager.removePortalPair(handle, world, ops, raw);
3248
+ portalManager.removePortalPair(handle, world, ops, undefined);
3113
3249
  },
3114
3250
  });
3115
- const created = build(ops);
3116
- isSealed = true;
3117
- const template = snapshotEditResult(created, (obj) => {
3118
- if (pending.has(obj)) {
3119
- const staged = pending.get(obj);
3120
- if (removedPending.has(staged))
3121
- fail("physics.handle-stale", "edit", "a returned pending reference was removed.");
3122
- return { type: "pending", kind: staged.kind, key: staged.key };
3251
+ try {
3252
+ const created = build(ops);
3253
+ isSealed = true;
3254
+ const template = snapshotEditResult(created, (obj) => {
3255
+ if (pending.has(obj)) {
3256
+ const staged = pending.get(obj);
3257
+ if (removedPending.has(staged))
3258
+ fail("physics.handle-stale", "edit", "a returned pending reference was removed.");
3259
+ return { type: "pending", kind: staged.kind, key: staged.key };
3260
+ }
3261
+ const info = raw.handleInfo(obj);
3262
+ if (info !== undefined) {
3263
+ if (removedLive.has(obj))
3264
+ fail("physics.handle-stale", "edit", "a returned handle was removed.");
3265
+ return { type: "handle", kind: info.kind, id: info.id, handle: obj };
3266
+ }
3267
+ return undefined;
3268
+ });
3269
+ if (simulatedBodies.size > definition.capacity.bodies
3270
+ || simulatedJoints.size > definition.capacity.joints
3271
+ || simulatedFluids.size > (definition.capacity.fluids ?? 0)) {
3272
+ fail("physics.capacity-exceeded", "edit", "the edit exceeds the world capacity.");
3123
3273
  }
3124
- const info = raw.handleInfo(obj);
3125
- if (info !== undefined) {
3126
- if (removedLive.has(obj))
3127
- fail("physics.handle-stale", "edit", "a returned handle was removed.");
3128
- return { type: "handle", kind: info.kind, id: info.id, handle: obj };
3274
+ const result = raw.applyBatch(commands);
3275
+ for (const entry of result.bodies) {
3276
+ committedPendingBodies.set(entry.key, entry.handle);
3277
+ if (stagedBodyMasks.has(entry.key)) {
3278
+ originalBodyMasks.set(entry.handle.id, stagedBodyMasks.get(entry.key));
3279
+ }
3129
3280
  }
3130
- return undefined;
3131
- });
3132
- if (simulatedBodies.size > definition.capacity.bodies
3133
- || simulatedJoints.size > definition.capacity.joints
3134
- || simulatedFluids.size > (definition.capacity.fluids ?? 0)) {
3135
- fail("physics.capacity-exceeded", "edit", "the edit exceeds the world capacity.");
3136
- }
3137
- const result = raw.applyBatch(commands);
3138
- for (const item of pendingPortalHosts) {
3139
- const entry = result.bodies.find((b) => b.key === item.key);
3140
- if (entry) {
3141
- const pair = portalManager.pairs.get(item.pairId);
3142
- if (pair) {
3143
- if (item.end === "A")
3144
- pair.portalA.hostBodyId = entry.handle.id;
3145
- else
3146
- pair.portalB.hostBodyId = entry.handle.id;
3147
- portalManager.registerHost(entry.handle.id, raw, world);
3281
+ for (const [ref, staged] of pending) {
3282
+ if (staged.kind === "body") {
3283
+ const handle = committedPendingBodies.get(staged.key);
3284
+ if (handle)
3285
+ committedPendingRefs.set(ref, handle);
3148
3286
  }
3149
3287
  }
3150
- }
3151
- for (const key of stagedTeleportKeys) {
3152
- const entry = result.bodies.find((b) => b.key === key);
3153
- if (entry) {
3154
- portalManager.poseJumpBodyIds.add(entry.handle.id);
3288
+ for (const item of pendingPortalHosts) {
3289
+ const entry = result.bodies.find((b) => b.key === item.key);
3290
+ if (entry) {
3291
+ const pair = portalManager.pairs.get(item.pairId);
3292
+ if (pair) {
3293
+ if (item.end === "A")
3294
+ pair.portalA.hostBodyId = entry.handle.id;
3295
+ else
3296
+ pair.portalB.hostBodyId = entry.handle.id;
3297
+ portalManager.registerHost(entry.handle.id, raw, world);
3298
+ }
3299
+ }
3155
3300
  }
3156
- }
3157
- for (const item of teleportsToDropContacts) {
3158
- try {
3159
- raw.setBodyTransform(item.handle, {
3160
- x: Number(item.position.x),
3161
- y: Number(item.position.y),
3162
- z: Number(item.position.z),
3163
- }, item.orientation);
3164
- raw.wakeBody(item.handle);
3301
+ for (const hostId of portalManager.hostBodies) {
3302
+ portalManager.registerHost(hostId, raw, world);
3303
+ }
3304
+ const prevHostIds = new Set((portalStateBefore.hostLayerMap ?? []).map(([k]) => BigInt(k)));
3305
+ const prevOriginalLayers = new Map((portalStateBefore.originalHostLayers ?? []).map(([k, v]) => [BigInt(k), v]));
3306
+ for (const prevHostId of prevHostIds) {
3307
+ if (!portalManager.hostBodies.has(prevHostId)) {
3308
+ try {
3309
+ const bHandle = world.resolveBody(prevHostId);
3310
+ const bVals = new Float64Array(raw.readBody(bHandle));
3311
+ if ((bVals[11] & ALL_PORTAL_HOST_LAYERS) !== 0) {
3312
+ bVals[11] = prevOriginalLayers.get(prevHostId) ?? 1;
3313
+ raw.applyBatch([{ type: "editBody", body: bHandle, values: bVals, geometry: { type: "keep" } }]);
3314
+ }
3315
+ }
3316
+ catch {
3317
+ // Best-effort restoration
3318
+ }
3319
+ }
3320
+ }
3321
+ if (portalManager.bodySuppressedLayers.size === 0 && portalStateBefore.bodySuppressedLayers && portalStateBefore.bodySuppressedLayers.length > 0) {
3322
+ for (const [bodyIdStr, suppressedMask] of portalStateBefore.bodySuppressedLayers) {
3323
+ const bodyId = BigInt(bodyIdStr);
3324
+ if (!portalManager.bodySuppressedLayers.has(bodyId)) {
3325
+ try {
3326
+ const bHandle = world.resolveBody(bodyId);
3327
+ const bVals = new Float64Array(raw.readBody(bHandle));
3328
+ bVals[12] = ((bVals[12] | suppressedMask) >>> 0);
3329
+ raw.applyBatch([{ type: "editBody", body: bHandle, values: bVals, geometry: { type: "keep" } }]);
3330
+ }
3331
+ catch {
3332
+ // Best-effort restoration
3333
+ }
3334
+ }
3335
+ }
3336
+ }
3337
+ for (const [id, m] of stagedLiveMaskUpdates) {
3338
+ originalBodyMasks.set(id, m);
3339
+ }
3340
+ for (const id of stagedSuppressionDeletions) {
3341
+ portalManager.bodySuppressedLayers.delete(id);
3342
+ }
3343
+ for (const key of stagedTeleportKeys) {
3344
+ const entry = result.bodies.find((b) => b.key === key);
3345
+ if (entry) {
3346
+ portalManager.poseJumpBodyIds.add(entry.handle.id);
3347
+ }
3348
+ }
3349
+ for (const item of teleportsToDropContacts) {
3350
+ try {
3351
+ raw.setBodyTransform(item.handle, {
3352
+ x: Number(item.position.x),
3353
+ y: Number(item.position.y),
3354
+ z: Number(item.position.z),
3355
+ }, item.orientation);
3356
+ raw.wakeBody(item.handle);
3357
+ }
3358
+ catch {
3359
+ // body may have been removed or inactive
3360
+ }
3165
3361
  }
3166
- catch {
3167
- // body may have been removed or inactive
3362
+ const topologyAfter = raw.topology();
3363
+ const bodyIdsAfter = new Set(topologyAfter.bodies);
3364
+ const jointIdsAfter = new Set(topologyAfter.joints.map((joint) => joint.id));
3365
+ const fluidIdsAfter = new Set((topologyAfter.fluids ?? []));
3366
+ const removed = [
3367
+ ...topologyBefore.bodies
3368
+ .filter((id) => !bodyIdsAfter.has(id))
3369
+ .map((id) => ({ kind: "body", id })),
3370
+ ...topologyBefore.joints
3371
+ .filter((joint) => !jointIdsAfter.has(joint.id))
3372
+ .map((joint) => ({ kind: "joint", id: joint.id })),
3373
+ ...(topologyBefore.fluids ?? [])
3374
+ .filter((id) => !fluidIdsAfter.has(id))
3375
+ .map((id) => ({ kind: "fluid", id })),
3376
+ ];
3377
+ for (const entry of removed) {
3378
+ if (entry.kind === "body") {
3379
+ originalBodyMasks.delete(entry.id);
3380
+ }
3168
3381
  }
3382
+ const bodyHandles = new Map(result.bodies.map((entry) => [entry.key, entry.handle]));
3383
+ const jointHandles = new Map(result.joints.map((entry) => [entry.key, entry.handle]));
3384
+ const fluidHandles = new Map((result.fluids ?? []).map((entry) => [entry.key, entry.handle]));
3385
+ const materialized = materializeEditResult(template, (reference) => {
3386
+ if (reference.type === "handle")
3387
+ return reference.handle;
3388
+ const handle = reference.kind === "body" ? bodyHandles.get(reference.key)
3389
+ : reference.kind === "joint" ? jointHandles.get(reference.key)
3390
+ : fluidHandles.get(reference.key);
3391
+ if (handle === undefined)
3392
+ fail("physics.edit-failed", "edit", "failed to resolve created handle.");
3393
+ return handle;
3394
+ });
3395
+ return Object.freeze({
3396
+ created: materialized,
3397
+ handles: Object.freeze([...result.bodies.map((entry) => entry.handle),
3398
+ ...result.joints.map((entry) => entry.handle),
3399
+ ...(result.fluids ?? []).map((entry) => entry.handle)]),
3400
+ removed: Object.freeze(removed.map((entry) => Object.freeze(entry))),
3401
+ });
3402
+ }
3403
+ catch (err) {
3404
+ portalManager.restoreState(portalStateBefore);
3405
+ originalBodyMasks.clear();
3406
+ for (const [k, v] of originalMasksBefore)
3407
+ originalBodyMasks.set(k, v);
3408
+ throw err;
3169
3409
  }
3170
- const topologyAfter = raw.topology();
3171
- const bodyIdsAfter = new Set(topologyAfter.bodies);
3172
- const jointIdsAfter = new Set(topologyAfter.joints.map((joint) => joint.id));
3173
- const fluidIdsAfter = new Set((topologyAfter.fluids ?? []));
3174
- const removed = [
3175
- ...topologyBefore.bodies
3176
- .filter((id) => !bodyIdsAfter.has(id))
3177
- .map((id) => ({ kind: "body", id })),
3178
- ...topologyBefore.joints
3179
- .filter((joint) => !jointIdsAfter.has(joint.id))
3180
- .map((joint) => ({ kind: "joint", id: joint.id })),
3181
- ...(topologyBefore.fluids ?? [])
3182
- .filter((id) => !fluidIdsAfter.has(id))
3183
- .map((id) => ({ kind: "fluid", id })),
3184
- ];
3185
- const bodyHandles = new Map(result.bodies.map((entry) => [entry.key, entry.handle]));
3186
- const jointHandles = new Map(result.joints.map((entry) => [entry.key, entry.handle]));
3187
- const fluidHandles = new Map((result.fluids ?? []).map((entry) => [entry.key, entry.handle]));
3188
- const materialized = materializeEditResult(template, (reference) => {
3189
- if (reference.type === "handle")
3190
- return reference.handle;
3191
- const handle = reference.kind === "body" ? bodyHandles.get(reference.key)
3192
- : reference.kind === "joint" ? jointHandles.get(reference.key)
3193
- : fluidHandles.get(reference.key);
3194
- if (handle === undefined)
3195
- fail("physics.edit-failed", "edit", "failed to resolve created handle.");
3196
- return handle;
3197
- });
3198
- return Object.freeze({
3199
- created: materialized,
3200
- handles: Object.freeze([...result.bodies.map((entry) => entry.handle),
3201
- ...result.joints.map((entry) => entry.handle),
3202
- ...(result.fluids ?? []).map((entry) => entry.handle)]),
3203
- removed: Object.freeze(removed.map((entry) => Object.freeze(entry))),
3204
- });
3205
3410
  });
3206
3411
  },
3207
3412
  step: () => invokeWorld("step", () => {
@@ -3332,22 +3537,27 @@ function facade(raw, definition) {
3332
3537
  });
3333
3538
  }),
3334
3539
  readBody: (handle) => invokeWorld("read-body", () => {
3335
- const values = raw.readBody(handle);
3540
+ const bodyHandle = resolveBodyHandle(handle);
3541
+ const values = raw.readBody(bodyHandle);
3336
3542
  const shapeKind = values[10];
3337
3543
  const shape = (shapeKind >= 3 && shapeKind <= 6)
3338
3544
  ? (() => {
3339
- const geometry = raw.readGeometry(handle);
3545
+ const geometry = raw.readGeometry(bodyHandle);
3340
3546
  return decodeGeometryShape(geometry.kind, geometry.format, geometry.values);
3341
3547
  })()
3342
3548
  : decodeShape(values);
3343
- return decodeBody(handle.id, values, shape);
3549
+ const originalMask = originalBodyMasks.get(bodyHandle.id);
3550
+ return decodeBody(bodyHandle.id, values, shape, originalMask);
3344
3551
  }),
3345
3552
  readMotion: (handle) => invokeWorld("read-body", () => {
3346
- const values = raw.readBody(handle);
3347
- return decodeBody(handle.id, values, decodeMotionShape(values));
3553
+ const bodyHandle = resolveBodyHandle(handle);
3554
+ const values = raw.readBody(bodyHandle);
3555
+ const originalMask = originalBodyMasks.get(bodyHandle.id);
3556
+ return decodeBody(bodyHandle.id, values, decodeMotionShape(values), originalMask);
3348
3557
  }),
3349
3558
  readGeometry: (handle) => invokeWorld("read-body", () => {
3350
- const geometry = raw.readGeometry(handle);
3559
+ const bodyHandle = resolveBodyHandle(handle);
3560
+ const geometry = raw.readGeometry(bodyHandle);
3351
3561
  return decodeGeometryShape(geometry.kind, geometry.format, geometry.values);
3352
3562
  }),
3353
3563
  readJoint: (handle) => invokeWorld("read-joint", () => {
@@ -3355,7 +3565,10 @@ function facade(raw, definition) {
3355
3565
  return decodeJoint(handle.id, joint.bodyA, joint.bodyB, joint.values);
3356
3566
  }),
3357
3567
  readFluid: (handle) => invokeWorld("read-fluid", () => decodeFluid(handle.id, raw.readFluid(handle))),
3358
- resolveBody: (id) => invokeWorld("resolve-body", () => raw.body(id)),
3568
+ resolveBody: (id) => invokeWorld("resolve-body", () => {
3569
+ const resolved = resolveHostBodyId(id, committedPendingBodies, committedPendingRefs);
3570
+ return raw.body((resolved !== undefined ? resolved : id));
3571
+ }),
3359
3572
  resolveJoint: (id) => invokeWorld("resolve-joint", () => raw.joint(id)),
3360
3573
  resolveFluid: (id) => invokeWorld("resolve-fluid", () => raw.fluid(id)),
3361
3574
  latest: () => invokeWorld("latest", () => {
@@ -3419,7 +3632,8 @@ function facade(raw, definition) {
3419
3632
  portalManager.restoreState(saved);
3420
3633
  }
3421
3634
  else {
3422
- portalManager.clearEphemeralState();
3635
+ portalManager.clearAllState();
3636
+ originalBodyMasks.clear();
3423
3637
  }
3424
3638
  return raw.restoreCheckpoint(checkpoint);
3425
3639
  }),
@@ -3456,7 +3670,8 @@ function facade(raw, definition) {
3456
3670
  portalManager.restoreState(portalState);
3457
3671
  }
3458
3672
  else {
3459
- portalManager.clearEphemeralState();
3673
+ portalManager.clearAllState();
3674
+ originalBodyMasks.clear();
3460
3675
  }
3461
3676
  return raw.restore(rawBytes);
3462
3677
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@series-inc/rundot-syncplay",
3
- "version": "6.0.0-rc.27",
3
+ "version": "6.0.0-rc.29",
4
4
  "description": "Kinetix orchestration, rollback, replay, late-join, and deterministic networking for RUN.game",
5
5
  "repository": {
6
6
  "type": "git",