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

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.26",
26
+ "packageVersion": "6.0.0-rc.27",
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.26",
26
+ "packageVersion": "6.0.0-rc.27",
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.26",
53
+ "packageVersion": "6.0.0-rc.27",
54
54
  "compilerFlags": [
55
55
  "-std=c++20",
56
56
  "-O3",
@@ -282,6 +282,7 @@ export interface DeterministicKccStepOptions3D {
282
282
  readonly width: number;
283
283
  readonly height: number;
284
284
  };
285
+ readonly hostBodyId?: PhysicsBodyId3D | bigint | unknown;
285
286
  };
286
287
  readonly portalB: {
287
288
  readonly position: {
@@ -299,6 +300,7 @@ export interface DeterministicKccStepOptions3D {
299
300
  readonly width: number;
300
301
  readonly height: number;
301
302
  };
303
+ readonly hostBodyId?: PhysicsBodyId3D | bigint | unknown;
302
304
  };
303
305
  readonly open?: boolean;
304
306
  }[];
@@ -399,6 +399,7 @@ function stepDeterministicKccRevision2_3D(body, input, world, options, gravityPe
399
399
  swept: false,
400
400
  sample: 0,
401
401
  collisionFilters,
402
+ portals: options.portals,
402
403
  };
403
404
  if (options.physics !== undefined) {
404
405
  const recovered = depenetrateKccCapsule(options.physics, x, y, z, geometry, context, stats, events);
@@ -422,7 +423,7 @@ function stepDeterministicKccRevision2_3D(body, input, world, options, gravityPe
422
423
  stats.rejectedHits += forwardOverlap.collisionFilterRejectedHits;
423
424
  let obstructed = forwardOverlap.length > 0;
424
425
  if (!obstructed) {
425
- const sweep = sweepPhysicsKcc3D(options.physics, recoveredPose, { x: targetX, y, z: targetZ, vx, vz }, ignoredBodyIds, options.frame, collisionFilters);
426
+ const sweep = sweepPhysicsKcc3D(options.physics, recoveredPose, { x: targetX, y, z: targetZ, vx, vz }, ignoredBodyIds, options.frame, collisionFilters, options.portals);
426
427
  stats.queries += sweep.queryCount;
427
428
  stats.filterCalls += sweep.collisionFilterCalls;
428
429
  stats.rejectedHits += sweep.collisionFilterRejectedHits;
@@ -465,7 +466,7 @@ function stepDeterministicKccRevision2_3D(body, input, world, options, gravityPe
465
466
  }
466
467
  }
467
468
  if (obstructed && !stepped && !headBlocked) {
468
- const resolved = resolvePhysicsSlide3D(options.physics, recoveredPose, { x: targetX, y, z: targetZ, vx, vz }, ignoredBodyIds, options.frame, collisionFilters);
469
+ const resolved = resolvePhysicsSlide3D(options.physics, recoveredPose, { x: targetX, y, z: targetZ, vx, vz }, ignoredBodyIds, options.frame, collisionFilters, options.portals);
469
470
  stats.queries += resolved.queryCount;
470
471
  stats.filterCalls += resolved.collisionFilterCalls;
471
472
  stats.rejectedHits += resolved.collisionFilterRejectedHits;
@@ -2013,7 +2014,7 @@ function estimateKccCollisionNormal(previous, attemptedX, attemptedY, attemptedZ
2013
2014
  }
2014
2015
  return { x: 0, y: 0, z: -1 };
2015
2016
  }
2016
- function resolvePhysicsSlide3D(physics, previous, candidate, ignoredBodyIds, frame, collisionFilters) {
2017
+ function resolvePhysicsSlide3D(physics, previous, candidate, ignoredBodyIds, frame, collisionFilters, portals) {
2017
2018
  const filterStateBefore = snapshotCollisionFilters(collisionFilters);
2018
2019
  let collisionFilterCalls = 0;
2019
2020
  let collisionFilterRejectedHits = 0;
@@ -2024,11 +2025,12 @@ function resolvePhysicsSlide3D(physics, previous, candidate, ignoredBodyIds, fra
2024
2025
  swept: false,
2025
2026
  sample: 0,
2026
2027
  collisionFilters,
2028
+ portals,
2027
2029
  });
2028
2030
  collisionFilterCalls += fullOverlaps.collisionFilterCalls;
2029
2031
  collisionFilterRejectedHits += fullOverlaps.collisionFilterRejectedHits;
2030
2032
  if (fullOverlaps.length === 0) {
2031
- const sweep = sweepPhysicsKcc3D(physics, previous, candidate, ignoredBodyIds, frame, collisionFilters);
2033
+ const sweep = sweepPhysicsKcc3D(physics, previous, candidate, ignoredBodyIds, frame, collisionFilters, portals);
2032
2034
  assertKccCollisionFiltersUnchanged(collisionFilters, filterStateBefore);
2033
2035
  if (sweep.corrected) {
2034
2036
  return {
@@ -2057,6 +2059,7 @@ function resolvePhysicsSlide3D(physics, previous, candidate, ignoredBodyIds, fra
2057
2059
  swept: false,
2058
2060
  sample: 0,
2059
2061
  collisionFilters,
2062
+ portals,
2060
2063
  });
2061
2064
  const zOverlaps = physicsOverlapsKcc(physics, zOnly.x, candidate.y, zOnly.z, {
2062
2065
  ignoredBodyIds,
@@ -2065,6 +2068,7 @@ function resolvePhysicsSlide3D(physics, previous, candidate, ignoredBodyIds, fra
2065
2068
  swept: false,
2066
2069
  sample: 0,
2067
2070
  collisionFilters,
2071
+ portals,
2068
2072
  });
2069
2073
  collisionFilterCalls += xOverlaps.collisionFilterCalls + zOverlaps.collisionFilterCalls;
2070
2074
  collisionFilterRejectedHits += xOverlaps.collisionFilterRejectedHits + zOverlaps.collisionFilterRejectedHits;
@@ -2102,7 +2106,7 @@ function resolvePhysicsSlide3D(physics, previous, candidate, ignoredBodyIds, fra
2102
2106
  collisionFilterRejectedHits,
2103
2107
  };
2104
2108
  }
2105
- function sweepPhysicsKcc3D(physics, previous, candidate, ignoredBodyIds, frame, collisionFilters) {
2109
+ function sweepPhysicsKcc3D(physics, previous, candidate, ignoredBodyIds, frame, collisionFilters, portals) {
2106
2110
  const deltaX = candidate.x - previous.x;
2107
2111
  const deltaZ = candidate.z - previous.z;
2108
2112
  const rawSamples = Math.max(1, Math.ceil(Math.max(Math.abs(deltaX), Math.abs(deltaZ)) * 2));
@@ -2124,6 +2128,7 @@ function sweepPhysicsKcc3D(physics, previous, candidate, ignoredBodyIds, frame,
2124
2128
  swept: true,
2125
2129
  sample,
2126
2130
  collisionFilters,
2131
+ portals,
2127
2132
  });
2128
2133
  queryCount += 1;
2129
2134
  collisionFilterCalls += overlaps.collisionFilterCalls;
@@ -2136,6 +2141,7 @@ function sweepPhysicsKcc3D(physics, previous, candidate, ignoredBodyIds, frame,
2136
2141
  swept: true,
2137
2142
  sample,
2138
2143
  collisionFilters,
2144
+ portals,
2139
2145
  });
2140
2146
  const zOnlyOverlaps = physicsOverlapsKcc(physics, lastSafeX, candidate.y, sampleZ, {
2141
2147
  ignoredBodyIds,
@@ -2144,6 +2150,7 @@ function sweepPhysicsKcc3D(physics, previous, candidate, ignoredBodyIds, frame,
2144
2150
  swept: true,
2145
2151
  sample,
2146
2152
  collisionFilters,
2153
+ portals,
2147
2154
  });
2148
2155
  queryCount += 2;
2149
2156
  collisionFilterCalls += xOnlyOverlaps.collisionFilterCalls + zOnlyOverlaps.collisionFilterCalls;
@@ -2199,6 +2206,21 @@ function sweepPhysicsKcc3D(physics, previous, candidate, ignoredBodyIds, frame,
2199
2206
  assertKccCollisionFiltersUnchanged(collisionFilters, filterStateBefore);
2200
2207
  return { ...candidate, corrected: false, slid: false, swept: false, correctionCount: 0, queryCount, collisionFilterCalls, collisionFilterRejectedHits };
2201
2208
  }
2209
+ function kccCapsuleFitsAperture(x, y, z, geometry, portalEnd) {
2210
+ const rotNorm = quatNormalizePure(portalEnd.rotation);
2211
+ const localCenter = invRotateVec3Pure(rotNorm, subVec3Pure({ x, y, z }, portalEnd.position));
2212
+ const halfW = portalEnd.opening.width * 0.5;
2213
+ const halfH = portalEnd.opening.height * 0.5;
2214
+ const halfSeg = geometry.halfHeight;
2215
+ 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;
2221
+ const inCorridor = Math.abs(localCenter.z) <= Math.max(1.0, extZ + 0.5);
2222
+ return fitsOpeningX && inOpeningY && inCorridor;
2223
+ }
2202
2224
  function physicsOverlapsKcc(physics, x, y, z, context) {
2203
2225
  const filterStateBefore = snapshotCollisionFilters(context.collisionFilters);
2204
2226
  const geometry = normalizeKccGeometry3D(context.previous);
@@ -2218,6 +2240,23 @@ function physicsOverlapsKcc(physics, x, y, z, context) {
2218
2240
  if (context.ignoredBodyIds.has(bodyId)) {
2219
2241
  return false;
2220
2242
  }
2243
+ if (context.portals && context.portals.length > 0) {
2244
+ for (const pair of context.portals) {
2245
+ if (pair.open === false)
2246
+ continue;
2247
+ for (const end of [pair.portalA, pair.portalB]) {
2248
+ 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)) {
2252
+ if (kccCapsuleFitsAperture(x, y, z, geometry, end)) {
2253
+ return false;
2254
+ }
2255
+ }
2256
+ }
2257
+ }
2258
+ }
2259
+ }
2221
2260
  const body = readKccPhysicsBody(physics, bodyId);
2222
2261
  const hit = createKccCollisionCandidate(bodyId, body, context, x, y, z);
2223
2262
  for (const filter of filters) {
@@ -2242,6 +2281,36 @@ function filterKccHits(physics, hits, ignoredBodyIds, collisionFilters, context,
2242
2281
  if (ignoredBodyIds.has(hit.bodyId)) {
2243
2282
  continue;
2244
2283
  }
2284
+ if (context.portals && context.portals.length > 0) {
2285
+ let isHostApertureHit = false;
2286
+ const geometry = normalizeKccGeometry3D(context.previous);
2287
+ for (const pair of context.portals) {
2288
+ if (pair.open === false)
2289
+ continue;
2290
+ for (const end of [pair.portalA, pair.portalB]) {
2291
+ 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)) {
2295
+ const rotNorm = quatNormalizePure(end.rotation);
2296
+ const localHit = invRotateVec3Pure(rotNorm, subVec3Pure(hit.point, end.position));
2297
+ const halfW = end.opening.width * 0.5;
2298
+ const halfH = end.opening.height * 0.5;
2299
+ if (Math.abs(localHit.x) <= halfW &&
2300
+ Math.abs(localHit.y) <= halfH &&
2301
+ kccCapsuleFitsAperture(x, y, z, geometry, end)) {
2302
+ isHostApertureHit = true;
2303
+ break;
2304
+ }
2305
+ }
2306
+ }
2307
+ }
2308
+ if (isHostApertureHit)
2309
+ break;
2310
+ }
2311
+ if (isHostApertureHit)
2312
+ continue;
2313
+ }
2245
2314
  const body = readKccPhysicsBody(physics, hit.bodyId);
2246
2315
  const candidate = createKccCollisionCandidate(hit.bodyId, body, context, x, y, z);
2247
2316
  let keep = true;
@@ -808,7 +808,7 @@ export interface PortalEndDefinition {
808
808
  readonly position: PhysicsVector3D<number>;
809
809
  readonly rotation: PhysicsQuaternion3D;
810
810
  readonly opening: PortalOpeningDefinition;
811
- readonly hostBodyId?: PhysicsBodyId3D | bigint;
811
+ readonly hostBodyId?: PhysicsBodyId3D | bigint | PhysicsBodyReference3D;
812
812
  }
813
813
  export interface PortalPairDefinition {
814
814
  readonly portalA: PortalEndDefinition;
@@ -20,7 +20,11 @@ function metersVector(value) {
20
20
  return { x: meters(value.x), y: meters(value.y), z: meters(value.z) };
21
21
  }
22
22
  function speedVector(value) {
23
- return { x: metersPerSecond(value.x), y: metersPerSecond(value.y), z: metersPerSecond(value.z) };
23
+ return {
24
+ x: metersPerSecond(value.x === 0 ? 0 : value.x),
25
+ y: metersPerSecond(value.y === 0 ? 0 : value.y),
26
+ z: metersPerSecond(value.z === 0 ? 0 : value.z),
27
+ };
24
28
  }
25
29
  function newtonSecondsVector(value) {
26
30
  return { x: newtonSeconds(value.x), y: newtonSeconds(value.y), z: newtonSeconds(value.z) };
@@ -36,7 +40,11 @@ function accelerationVector(value) {
36
40
  };
37
41
  }
38
42
  function angularSpeedVector(value) {
39
- return { x: radiansPerSecond(value.x), y: radiansPerSecond(value.y), z: radiansPerSecond(value.z) };
43
+ return {
44
+ x: radiansPerSecond(value.x === 0 ? 0 : value.x),
45
+ y: radiansPerSecond(value.y === 0 ? 0 : value.y),
46
+ z: radiansPerSecond(value.z === 0 ? 0 : value.z),
47
+ };
40
48
  }
41
49
  function brandLatestOutputs3D(data) {
42
50
  const reactions = new Map(data.reactions.map((reaction) => [reaction.jointId, reaction]));
@@ -965,7 +973,7 @@ function encodeBody(body) {
965
973
  | (kind === 'dynamic' && body.sleeping === true ? 16 : 0) | 32;
966
974
  values[10] = shapeKind;
967
975
  values[11] = u32(body.layer ?? 1, 'layer');
968
- values[12] = u32(body.mask ?? 1, 'mask');
976
+ values[12] = u32(body.mask ?? 1, 'mask') | ALL_PORTAL_HOST_LAYERS;
969
977
  values[13] = finite(body.gravityScale ?? 1, 'gravityScale');
970
978
  values[14] = nonnegative(body.linearDamping ?? 0.995, 'linearDamping');
971
979
  values[18] = mass;
@@ -1123,7 +1131,9 @@ function decodeBody(id, values, shape) {
1123
1131
  centerOfMass: Object.freeze(metersVector({ x: values[37], y: values[38], z: values[39] })),
1124
1132
  gravityScale: values[13], linearDamping: values[14], angularDamping: values[26],
1125
1133
  friction: values[27], restitution: values[28], rollingResistance: values[43],
1126
- layer: values[11], mask: values[12], trigger: (motion & 4) !== 0,
1134
+ layer: (values[11] & ALL_PORTAL_HOST_LAYERS) !== 0 ? 1 : values[11],
1135
+ mask: values[12] & ~ALL_PORTAL_HOST_LAYERS,
1136
+ trigger: (motion & 4) !== 0,
1127
1137
  sensor: (motion & 8) !== 0, sleeping: (motion & 16) !== 0,
1128
1138
  sleepEnabled: values[41] !== 0, sleepThreshold: metersPerSecond(values[40]), sleepTime: seconds(values[42]),
1129
1139
  motionLocks: values[29],
@@ -1454,7 +1464,12 @@ function decodeJoint(id, bodyA, bodyB, values) {
1454
1464
  reactionAngularImpulse: newtonMeterSeconds(values[149]), });
1455
1465
  }
1456
1466
  function queryInput(query) {
1457
- return { ...query, ...(query.excludeBody === undefined ? {} : { excludeBody: query.excludeBody.id }) };
1467
+ const layerMask = query.layerMask !== undefined ? (query.layerMask | ALL_PORTAL_HOST_LAYERS) : undefined;
1468
+ return {
1469
+ ...query,
1470
+ ...(layerMask !== undefined ? { layerMask } : {}),
1471
+ ...(query.excludeBody === undefined ? {} : { excludeBody: query.excludeBody.id }),
1472
+ };
1458
1473
  }
1459
1474
  function castHits(hits) {
1460
1475
  return Object.freeze(hits.map((hit) => Object.freeze({
@@ -1625,11 +1640,56 @@ function quatNormalize(q) {
1625
1640
  const inv = 1 / Math.sqrt(lenSq);
1626
1641
  return { x: q.x * inv, y: q.y * inv, z: q.z * inv, w: q.w * inv };
1627
1642
  }
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);
1646
+ function normalizeZero(v) {
1647
+ return Object.is(v, -0) ? 0 : v;
1648
+ }
1628
1649
  function rotateVec3(q, v) {
1629
1650
  const qv = { x: q.x, y: q.y, z: q.z };
1630
1651
  const uv = crossVec3(qv, v);
1631
1652
  const uuv = crossVec3(qv, uv);
1632
- return addVec3(v, scaleVec3(addVec3(scaleVec3(uv, q.w), uuv), 2.0));
1653
+ const res = addVec3(v, scaleVec3(addVec3(scaleVec3(uv, q.w), uuv), 2.0));
1654
+ return {
1655
+ x: res.x === 0 ? 0 : res.x,
1656
+ y: res.y === 0 ? 0 : res.y,
1657
+ z: res.z === 0 ? 0 : res.z,
1658
+ };
1659
+ }
1660
+ function computeOrientedExtents(shapeKind, values, bodyOri, portalRotNorm) {
1661
+ if (shapeKind === 1) {
1662
+ const r = values[6];
1663
+ return { extX: r, extY: r, extZ: r };
1664
+ }
1665
+ if (shapeKind === 0) {
1666
+ const hx = values[6];
1667
+ const hy = values[7];
1668
+ const hz = values[8];
1669
+ const qLocal = quatMultiply(quatConjugate(portalRotNorm), bodyOri);
1670
+ const x = qLocal.x;
1671
+ const y = qLocal.y;
1672
+ const z = qLocal.z;
1673
+ const w = qLocal.w;
1674
+ const m00 = 1 - 2 * (y * y + z * z);
1675
+ const m01 = 2 * (x * y - w * z);
1676
+ const m02 = 2 * (x * z + w * y);
1677
+ const m10 = 2 * (x * y + w * z);
1678
+ const m11 = 1 - 2 * (x * x + z * z);
1679
+ const m12 = 2 * (y * z - w * x);
1680
+ const m20 = 2 * (x * z - w * y);
1681
+ const m21 = 2 * (y * z + w * x);
1682
+ const m22 = 1 - 2 * (x * x + y * y);
1683
+ return {
1684
+ extX: Math.abs(m00) * hx + Math.abs(m01) * hy + Math.abs(m02) * hz,
1685
+ extY: Math.abs(m10) * hx + Math.abs(m11) * hy + Math.abs(m12) * hz,
1686
+ extZ: Math.abs(m20) * hx + Math.abs(m21) * hy + Math.abs(m22) * hz,
1687
+ };
1688
+ }
1689
+ const r = values[6];
1690
+ const h = values[7] ?? 0;
1691
+ const maxDim = r + h;
1692
+ return { extX: maxDim, extY: maxDim, extZ: maxDim };
1633
1693
  }
1634
1694
  function invRotateVec3(q, v) {
1635
1695
  return rotateVec3(quatConjugate(q), v);
@@ -1654,8 +1714,9 @@ function transformPointAcrossPortal(entryEnd, exitEnd, point) {
1654
1714
  const exitRotNorm = quatNormalize(exitEnd.rotation);
1655
1715
  // Transform world point to local entry coordinates
1656
1716
  const localPos = invRotateVec3(entryRotNorm, subVec3(point, entryEnd.position));
1657
- // Flip through aperture plane: x -> -x, y -> y, z -> -z
1658
- const flippedLocal = { x: -localPos.x, y: localPos.y, z: -localPos.z };
1717
+ // Flip through aperture plane: x -> -x, y -> y
1718
+ // Emerging bodies must always emerge in front of the exit aperture (local z >= 0).
1719
+ const flippedLocal = { x: -localPos.x, y: localPos.y, z: Math.abs(localPos.z) };
1659
1720
  // Transform flipped local into exit portal world position
1660
1721
  return addVec3(exitEnd.position, rotateVec3(exitRotNorm, flippedLocal));
1661
1722
  }
@@ -1673,10 +1734,14 @@ const PORTAL_TRAILER_MAGIC = 0x504f5254; // 'PORT'
1673
1734
  const PORTAL_TRAILER_VERSION = 1;
1674
1735
  const PORTAL_TRAILER_FOOTER_BYTES = 9;
1675
1736
  function serializeWithPortalTrailer(rawBytes, portalState) {
1676
- if (!portalState || (portalState.pairs.length === 0 && portalState.priorBodyPlanes.length === 0)) {
1737
+ if (!portalState ||
1738
+ (portalState.pairs.length === 0 &&
1739
+ portalState.priorBodyPlanes.length === 0 &&
1740
+ (!portalState.priorBodyVelocities || portalState.priorBodyVelocities.length === 0) &&
1741
+ (!portalState.cutoutSuppressedBodies || portalState.cutoutSuppressedBodies.length === 0))) {
1677
1742
  return rawBytes;
1678
1743
  }
1679
- const payloadStr = JSON.stringify(portalState);
1744
+ const payloadStr = JSON.stringify(portalState, (_key, val) => typeof val === "bigint" ? val.toString() : val);
1680
1745
  const textEncoder = new TextEncoder();
1681
1746
  const payloadBytes = textEncoder.encode(payloadStr);
1682
1747
  const payloadLen = payloadBytes.length;
@@ -1731,9 +1796,7 @@ function wrapRuntimeController(rawController, portalManager, portalCheckpoints)
1731
1796
  portalManager.restoreState(saved);
1732
1797
  }
1733
1798
  else {
1734
- portalManager.priorBodyPlanes.clear();
1735
- portalManager.poseJumpBodyIds.clear();
1736
- portalManager.lastCrossings = [];
1799
+ portalManager.clearEphemeralState();
1737
1800
  }
1738
1801
  }
1739
1802
  return rawController.restoreCheckpoint(checkpoint);
@@ -1770,12 +1833,219 @@ function wrapRuntimeController(rawController, portalManager, portalCheckpoints)
1770
1833
  };
1771
1834
  return Object.freeze(wrapped);
1772
1835
  }
1836
+ function resolveHostBodyId(ref) {
1837
+ if (ref === undefined || ref === null)
1838
+ return undefined;
1839
+ if (typeof ref === "bigint")
1840
+ return ref;
1841
+ if (typeof ref === "number")
1842
+ return BigInt(ref);
1843
+ if (typeof ref === "string") {
1844
+ try {
1845
+ return BigInt(ref);
1846
+ }
1847
+ catch {
1848
+ return undefined;
1849
+ }
1850
+ }
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 {
1859
+ return BigInt(id);
1860
+ }
1861
+ catch {
1862
+ return undefined;
1863
+ }
1864
+ }
1865
+ }
1866
+ return undefined;
1867
+ }
1773
1868
  class PortalSimulatorManager {
1774
1869
  nextId = 1;
1775
1870
  pairs = new Map();
1776
1871
  poseJumpBodyIds = new Set();
1777
1872
  priorBodyPlanes = new Map();
1873
+ priorBodyVelocities = new Map();
1874
+ hostBodies = new Set();
1875
+ hostLayerMap = new Map();
1876
+ originalHostLayers = new Map();
1877
+ bodySuppressedLayers = new Map();
1778
1878
  lastCrossings = [];
1879
+ clearEphemeralState() {
1880
+ this.priorBodyPlanes.clear();
1881
+ this.priorBodyVelocities.clear();
1882
+ this.poseJumpBodyIds.clear();
1883
+ this.bodySuppressedLayers.clear();
1884
+ this.lastCrossings = [];
1885
+ }
1886
+ registerHost(hostId, raw, world) {
1887
+ this.hostBodies.add(hostId);
1888
+ let layer = this.hostLayerMap.get(hostId);
1889
+ if (layer === undefined) {
1890
+ const usedLayers = new Set(this.hostLayerMap.values());
1891
+ for (let i = 0; i < PORTAL_HOST_LAYER_COUNT; i++) {
1892
+ const candidate = 1 << (PORTAL_HOST_LAYER_BASE + i);
1893
+ if (!usedLayers.has(candidate)) {
1894
+ layer = candidate;
1895
+ break;
1896
+ }
1897
+ }
1898
+ if (layer === undefined) {
1899
+ layer = 1 << PORTAL_HOST_LAYER_BASE;
1900
+ }
1901
+ this.hostLayerMap.set(hostId, layer);
1902
+ }
1903
+ if (raw && world) {
1904
+ try {
1905
+ const handle = world.resolveBody(hostId);
1906
+ const bVals = new Float64Array(raw.readBody(handle));
1907
+ if ((bVals[11] & ALL_PORTAL_HOST_LAYERS) === 0 && !this.originalHostLayers.has(hostId)) {
1908
+ this.originalHostLayers.set(hostId, bVals[11]);
1909
+ }
1910
+ if (bVals[11] !== layer) {
1911
+ bVals[11] = layer;
1912
+ raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
1913
+ }
1914
+ }
1915
+ catch (err) {
1916
+ // Best-effort handle resolution: host body handle might not be initialized in raw world
1917
+ }
1918
+ }
1919
+ }
1920
+ beforeStep(world, raw, bodyCapacity) {
1921
+ if (this.pairs.size === 0 || this.hostBodies.size === 0) {
1922
+ if (this.bodySuppressedLayers.size > 0) {
1923
+ for (const [bodyId, suppressedMask] of this.bodySuppressedLayers) {
1924
+ try {
1925
+ const handle = world.resolveBody(bodyId);
1926
+ const bVals = new Float64Array(raw.readBody(handle));
1927
+ bVals[12] = bVals[12] | suppressedMask;
1928
+ raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
1929
+ }
1930
+ catch (err) {
1931
+ // Best-effort restoration: dynamic body may have been removed
1932
+ }
1933
+ }
1934
+ this.bodySuppressedLayers.clear();
1935
+ }
1936
+ return;
1937
+ }
1938
+ for (const hostId of this.hostBodies) {
1939
+ const hostLayer = this.hostLayerMap.get(hostId) ?? (1 << PORTAL_HOST_LAYER_BASE);
1940
+ try {
1941
+ const handle = world.resolveBody(hostId);
1942
+ const bVals = new Float64Array(raw.readBody(handle));
1943
+ if ((bVals[11] & ALL_PORTAL_HOST_LAYERS) === 0 && !this.originalHostLayers.has(hostId)) {
1944
+ this.originalHostLayers.set(hostId, bVals[11]);
1945
+ }
1946
+ if (bVals[11] !== hostLayer) {
1947
+ bVals[11] = hostLayer;
1948
+ raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
1949
+ }
1950
+ }
1951
+ catch (err) {
1952
+ // Best-effort update: host body handle might be invalid or deleted
1953
+ }
1954
+ }
1955
+ this.ensureScratchBuffers(bodyCapacity ?? 128);
1956
+ const res = raw.writeBodyMotionInto(this.scratchPoses, this.scratchVelocities, this.scratchIds, this.scratchStatus);
1957
+ const count = res.count;
1958
+ if (count === 0)
1959
+ return;
1960
+ const desiredSuppressed = new Map();
1961
+ for (const pair of this.pairs.values()) {
1962
+ if (!pair.open)
1963
+ continue;
1964
+ for (const [endKey, hostIdVal] of [
1965
+ [pair.portalA, pair.portalA.hostBodyId],
1966
+ [pair.portalB, pair.portalB.hostBodyId],
1967
+ ]) {
1968
+ if (hostIdVal === undefined)
1969
+ continue;
1970
+ const hostId = BigInt(hostIdVal);
1971
+ const hostLayer = this.hostLayerMap.get(hostId) ?? (1 << PORTAL_HOST_LAYER_BASE);
1972
+ const entryEnd = endKey;
1973
+ const entryRotNorm = quatNormalize(entryEnd.rotation);
1974
+ const halfW = entryEnd.opening.width * 0.5;
1975
+ const halfH = entryEnd.opening.height * 0.5;
1976
+ const maxDim = Math.max(entryEnd.opening.width, entryEnd.opening.height);
1977
+ const trackingRadius = maxDim * 1.5 + 2.0;
1978
+ const trackingRadiusSq = trackingRadius * trackingRadius;
1979
+ for (let i = 0; i < count; i++) {
1980
+ if ((this.scratchStatus[i] & 0x03) === 0)
1981
+ continue;
1982
+ const bodyId = this.scratchIds[i];
1983
+ if (this.hostBodies.has(bodyId))
1984
+ continue;
1985
+ const posX = this.scratchPoses[i * 7];
1986
+ const posY = this.scratchPoses[i * 7 + 1];
1987
+ const posZ = this.scratchPoses[i * 7 + 2];
1988
+ const dx = posX - entryEnd.position.x;
1989
+ const dy = posY - entryEnd.position.y;
1990
+ const dz = posZ - entryEnd.position.z;
1991
+ if (dx * dx + dy * dy + dz * dz > trackingRadiusSq)
1992
+ continue;
1993
+ const localPos = invRotateVec3(entryRotNorm, { x: dx, y: dy, z: dz });
1994
+ let handle;
1995
+ try {
1996
+ handle = world.resolveBody(bodyId);
1997
+ }
1998
+ catch (err) {
1999
+ // Best-effort handle resolution: body may not be resolvable in world facade
2000
+ continue;
2001
+ }
2002
+ const bVals = raw.readBody(handle);
2003
+ const shapeKind = bVals[10];
2004
+ const bodyOri = {
2005
+ x: this.scratchPoses[i * 7 + 3],
2006
+ y: this.scratchPoses[i * 7 + 4],
2007
+ z: this.scratchPoses[i * 7 + 5],
2008
+ w: this.scratchPoses[i * 7 + 6],
2009
+ };
2010
+ const ext = computeOrientedExtents(shapeKind, bVals, bodyOri, entryRotNorm);
2011
+ if (Math.abs(localPos.x) + ext.extX <= halfW && Math.abs(localPos.y) + ext.extY <= halfH) {
2012
+ if (localPos.z >= -ext.extZ * 2.5 && localPos.z <= trackingRadius) {
2013
+ desiredSuppressed.set(bodyId, (desiredSuppressed.get(bodyId) ?? 0) | hostLayer);
2014
+ }
2015
+ }
2016
+ }
2017
+ }
2018
+ }
2019
+ for (const [bodyId, desiredMask] of desiredSuppressed) {
2020
+ const currentMask = this.bodySuppressedLayers.get(bodyId) ?? 0;
2021
+ if (currentMask !== desiredMask) {
2022
+ this.bodySuppressedLayers.set(bodyId, desiredMask);
2023
+ try {
2024
+ const handle = world.resolveBody(bodyId);
2025
+ const bVals = new Float64Array(raw.readBody(handle));
2026
+ bVals[12] = (bVals[12] | ALL_PORTAL_HOST_LAYERS) & ~desiredMask;
2027
+ raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
2028
+ }
2029
+ catch (err) {
2030
+ // Best-effort update: dynamic body may have been removed
2031
+ }
2032
+ }
2033
+ }
2034
+ for (const [bodyId, currentMask] of this.bodySuppressedLayers) {
2035
+ if (!desiredSuppressed.has(bodyId)) {
2036
+ this.bodySuppressedLayers.delete(bodyId);
2037
+ try {
2038
+ const handle = world.resolveBody(bodyId);
2039
+ const bVals = new Float64Array(raw.readBody(handle));
2040
+ bVals[12] = bVals[12] | currentMask;
2041
+ raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
2042
+ }
2043
+ catch (err) {
2044
+ // Best-effort restoration: dynamic body may have been removed
2045
+ }
2046
+ }
2047
+ }
2048
+ }
1779
2049
  scratchPoses = new Float64Array(0);
1780
2050
  scratchVelocities = new Float64Array(0);
1781
2051
  scratchIds = new BigUint64Array(0);
@@ -1812,19 +2082,31 @@ class PortalSimulatorManager {
1812
2082
  nextId: this.nextId,
1813
2083
  pairs: pairsCopy,
1814
2084
  priorBodyPlanes: Array.from(this.priorBodyPlanes.entries()),
2085
+ priorBodyVelocities: Array.from(this.priorBodyVelocities.entries()).map(([k, v]) => [
2086
+ k,
2087
+ { x: normalizeZero(v.x), y: normalizeZero(v.y), z: normalizeZero(v.z) },
2088
+ ]),
1815
2089
  poseJumpBodyIds: Array.from(this.poseJumpBodyIds).map((id) => id.toString()),
1816
2090
  lastCrossings: this.lastCrossings.map((c) => ({
1817
2091
  bodyId: c.bodyId,
1818
2092
  portalId: c.portalId,
1819
2093
  enteredEnd: c.enteredEnd,
1820
2094
  exitEnd: c.exitEnd,
1821
- turnedVelocity: { ...c.turnedVelocity },
2095
+ turnedVelocity: {
2096
+ x: normalizeZero(c.turnedVelocity.x),
2097
+ y: normalizeZero(c.turnedVelocity.y),
2098
+ z: normalizeZero(c.turnedVelocity.z),
2099
+ },
1822
2100
  })),
2101
+ cutoutSuppressedBodies: Array.from(this.bodySuppressedLayers.keys()).map((id) => id.toString()),
2102
+ originalHostLayers: Array.from(this.originalHostLayers.entries()).map(([k, v]) => [k.toString(), v]),
1823
2103
  };
1824
2104
  }
1825
2105
  restoreState(state) {
1826
2106
  this.nextId = state.nextId;
1827
2107
  this.pairs.clear();
2108
+ this.hostBodies.clear();
2109
+ this.hostLayerMap.clear();
1828
2110
  for (const p of state.pairs) {
1829
2111
  this.pairs.set(p.id, {
1830
2112
  id: p.id,
@@ -1842,15 +2124,37 @@ class PortalSimulatorManager {
1842
2124
  },
1843
2125
  open: p.open,
1844
2126
  });
2127
+ if (p.portalA.hostBodyId !== undefined) {
2128
+ this.registerHost(BigInt(p.portalA.hostBodyId));
2129
+ }
2130
+ if (p.portalB.hostBodyId !== undefined) {
2131
+ this.registerHost(BigInt(p.portalB.hostBodyId));
2132
+ }
1845
2133
  }
1846
2134
  this.priorBodyPlanes.clear();
1847
2135
  for (const [k, v] of state.priorBodyPlanes) {
1848
2136
  this.priorBodyPlanes.set(k, v);
1849
2137
  }
2138
+ this.priorBodyVelocities.clear();
2139
+ if (state.priorBodyVelocities) {
2140
+ for (const [k, v] of state.priorBodyVelocities) {
2141
+ this.priorBodyVelocities.set(k, {
2142
+ x: normalizeZero(v.x),
2143
+ y: normalizeZero(v.y),
2144
+ z: normalizeZero(v.z),
2145
+ });
2146
+ }
2147
+ }
1850
2148
  this.poseJumpBodyIds.clear();
1851
2149
  for (const idStr of state.poseJumpBodyIds) {
1852
2150
  this.poseJumpBodyIds.add(BigInt(idStr));
1853
2151
  }
2152
+ this.bodySuppressedLayers.clear();
2153
+ if (state.cutoutSuppressedBodies) {
2154
+ for (const idStr of state.cutoutSuppressedBodies) {
2155
+ this.bodySuppressedLayers.set(BigInt(idStr), ALL_PORTAL_HOST_LAYERS);
2156
+ }
2157
+ }
1854
2158
  this.lastCrossings = state.lastCrossings.map((c) => ({
1855
2159
  bodyId: BigInt(c.bodyId),
1856
2160
  portalId: c.portalId,
@@ -1858,10 +2162,19 @@ class PortalSimulatorManager {
1858
2162
  exitEnd: c.exitEnd,
1859
2163
  turnedVelocity: { ...c.turnedVelocity },
1860
2164
  }));
2165
+ this.originalHostLayers.clear();
2166
+ if (state.originalHostLayers) {
2167
+ for (const [k, v] of state.originalHostLayers) {
2168
+ this.originalHostLayers.set(BigInt(k), v);
2169
+ }
2170
+ }
1861
2171
  }
1862
2172
  computeDigest(rawDigest, state) {
1863
2173
  const s = state ?? this.captureState();
1864
- if (s.pairs.length === 0 && s.priorBodyPlanes.length === 0) {
2174
+ if (s.pairs.length === 0 &&
2175
+ s.priorBodyPlanes.length === 0 &&
2176
+ (!s.priorBodyVelocities || s.priorBodyVelocities.length === 0) &&
2177
+ (!s.cutoutSuppressedBodies || s.cutoutSuppressedBodies.length === 0)) {
1865
2178
  return rawDigest;
1866
2179
  }
1867
2180
  let hash = 0xcbf29ce484222325n ^ rawDigest;
@@ -1907,11 +2220,31 @@ class PortalSimulatorManager {
1907
2220
  mixString(k);
1908
2221
  mixFloat(z);
1909
2222
  }
2223
+ if (s.priorBodyVelocities && s.priorBodyVelocities.length > 0) {
2224
+ const sortedVels = [...s.priorBodyVelocities].sort(([ka], [kb]) => ka.localeCompare(kb));
2225
+ mixInt(sortedVels.length);
2226
+ for (const [k, v] of sortedVels) {
2227
+ mixString(k);
2228
+ mixFloat(v.x);
2229
+ mixFloat(v.y);
2230
+ mixFloat(v.z);
2231
+ }
2232
+ }
2233
+ if (s.cutoutSuppressedBodies && s.cutoutSuppressedBodies.length > 0) {
2234
+ const sortedSuppressed = [...s.cutoutSuppressedBodies].sort();
2235
+ mixInt(sortedSuppressed.length);
2236
+ for (const idStr of sortedSuppressed) {
2237
+ mixString(idStr);
2238
+ }
2239
+ }
1910
2240
  return hash;
1911
2241
  }
1912
2242
  computeStrongDigest(rawStrongDigest, state) {
1913
2243
  const s = state ?? this.captureState();
1914
- if (s.pairs.length === 0 && s.priorBodyPlanes.length === 0) {
2244
+ if (s.pairs.length === 0 &&
2245
+ s.priorBodyPlanes.length === 0 &&
2246
+ (!s.priorBodyVelocities || s.priorBodyVelocities.length === 0) &&
2247
+ (!s.cutoutSuppressedBodies || s.cutoutSuppressedBodies.length === 0)) {
1915
2248
  return rawStrongDigest;
1916
2249
  }
1917
2250
  const digest64 = this.computeDigest(0n, s);
@@ -1925,7 +2258,7 @@ class PortalSimulatorManager {
1925
2258
  view.setUint32(result.length - 4, view.getUint32(result.length - 4, true) ^ high, true);
1926
2259
  return result;
1927
2260
  }
1928
- createPortalPair(def) {
2261
+ createPortalPair(def, raw, world) {
1929
2262
  if (!def.portalA || !def.portalB) {
1930
2263
  throw new SyncplayError('PortalPairDefinition requires portalA and portalB.', {
1931
2264
  code: 'physics.definition-invalid',
@@ -1939,16 +2272,22 @@ class PortalSimulatorManager {
1939
2272
  position: { ...def.portalA.position },
1940
2273
  rotation: quatNormalize(def.portalA.rotation),
1941
2274
  opening: { width: Number(def.portalA.opening.width), height: Number(def.portalA.opening.height) },
1942
- hostBodyId: def.portalA.hostBodyId,
2275
+ hostBodyId: resolveHostBodyId(def.portalA.hostBodyId),
1943
2276
  },
1944
2277
  portalB: {
1945
2278
  position: { ...def.portalB.position },
1946
2279
  rotation: quatNormalize(def.portalB.rotation),
1947
2280
  opening: { width: Number(def.portalB.opening.width), height: Number(def.portalB.opening.height) },
1948
- hostBodyId: def.portalB.hostBodyId,
2281
+ hostBodyId: resolveHostBodyId(def.portalB.hostBodyId),
1949
2282
  },
1950
2283
  open: def.open ?? true,
1951
2284
  };
2285
+ if (pair.portalA.hostBodyId !== undefined) {
2286
+ this.registerHost(BigInt(pair.portalA.hostBodyId), raw, world);
2287
+ }
2288
+ if (pair.portalB.hostBodyId !== undefined) {
2289
+ this.registerHost(BigInt(pair.portalB.hostBodyId), raw, world);
2290
+ }
1952
2291
  this.pairs.set(id, pair);
1953
2292
  return Object.freeze({ id });
1954
2293
  }
@@ -1960,9 +2299,25 @@ class PortalSimulatorManager {
1960
2299
  operation: 'setPortalOpen',
1961
2300
  });
1962
2301
  }
1963
- if (pair.open && !open && world) {
1964
- // Eject any bodies currently straddling the aperture before closing
1965
- this.ejectStraddlingBodies(pair, world, ops, raw);
2302
+ if (pair.open && !open) {
2303
+ if (world) {
2304
+ // Eject any bodies currently straddling the aperture before closing
2305
+ this.ejectStraddlingBodies(pair, world, ops, raw);
2306
+ }
2307
+ if (this.bodySuppressedLayers.size > 0 && raw && world) {
2308
+ for (const [bodyId, suppressedMask] of this.bodySuppressedLayers) {
2309
+ try {
2310
+ const handle = world.resolveBody(bodyId);
2311
+ const bVals = new Float64Array(raw.readBody(handle));
2312
+ bVals[12] = bVals[12] | suppressedMask;
2313
+ raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
2314
+ }
2315
+ catch (err) {
2316
+ // Best-effort restoration on portal close
2317
+ }
2318
+ }
2319
+ this.bodySuppressedLayers.clear();
2320
+ }
1966
2321
  }
1967
2322
  pair.open = open;
1968
2323
  }
@@ -1987,6 +2342,63 @@ class PortalSimulatorManager {
1987
2342
  this.ejectStraddlingBodies(pair, world, ops, raw);
1988
2343
  }
1989
2344
  this.pairs.delete(handle.id);
2345
+ const candidateHosts = [];
2346
+ if (pair) {
2347
+ if (pair.portalA.hostBodyId !== undefined)
2348
+ candidateHosts.push(BigInt(pair.portalA.hostBodyId));
2349
+ if (pair.portalB.hostBodyId !== undefined)
2350
+ candidateHosts.push(BigInt(pair.portalB.hostBodyId));
2351
+ }
2352
+ const activeHosts = new Set();
2353
+ for (const p of this.pairs.values()) {
2354
+ if (p.portalA.hostBodyId !== undefined)
2355
+ activeHosts.add(BigInt(p.portalA.hostBodyId));
2356
+ if (p.portalB.hostBodyId !== undefined)
2357
+ activeHosts.add(BigInt(p.portalB.hostBodyId));
2358
+ }
2359
+ for (const hostId of candidateHosts) {
2360
+ if (!activeHosts.has(hostId)) {
2361
+ this.hostBodies.delete(hostId);
2362
+ this.hostLayerMap.delete(hostId);
2363
+ const origLayer = this.originalHostLayers.get(hostId) ?? 1;
2364
+ this.originalHostLayers.delete(hostId);
2365
+ if (raw && world) {
2366
+ try {
2367
+ const bHandle = world.resolveBody(hostId);
2368
+ const bVals = new Float64Array(raw.readBody(bHandle));
2369
+ if ((bVals[11] & ALL_PORTAL_HOST_LAYERS) !== 0) {
2370
+ bVals[11] = origLayer;
2371
+ raw.applyBatch([{ type: "editBody", body: bHandle, values: bVals, geometry: { type: "keep" } }]);
2372
+ }
2373
+ }
2374
+ catch (err) {
2375
+ // Best-effort restoration: host body handle might have been destroyed
2376
+ }
2377
+ }
2378
+ }
2379
+ }
2380
+ if (this.bodySuppressedLayers.size > 0 && raw && world) {
2381
+ for (const [bodyId, suppressedMask] of this.bodySuppressedLayers) {
2382
+ try {
2383
+ const bHandle = world.resolveBody(bodyId);
2384
+ const bVals = new Float64Array(raw.readBody(bHandle));
2385
+ bVals[12] = bVals[12] | suppressedMask;
2386
+ raw.applyBatch([{ type: "editBody", body: bHandle, values: bVals, geometry: { type: "keep" } }]);
2387
+ }
2388
+ catch (err) {
2389
+ // Best-effort restoration on portal removal
2390
+ }
2391
+ }
2392
+ this.bodySuppressedLayers.clear();
2393
+ }
2394
+ for (const k of this.priorBodyPlanes.keys()) {
2395
+ if (k.startsWith(`${handle.id}:`))
2396
+ this.priorBodyPlanes.delete(k);
2397
+ }
2398
+ for (const k of this.priorBodyVelocities.keys()) {
2399
+ if (k.startsWith(`${handle.id}:`))
2400
+ this.priorBodyVelocities.delete(k);
2401
+ }
1990
2402
  }
1991
2403
  ejectStraddlingBodies(pair, world, ops, raw) {
1992
2404
  const topology = world.info();
@@ -2075,6 +2487,7 @@ class PortalSimulatorManager {
2075
2487
  }
2076
2488
  const crossings = [];
2077
2489
  const teleportedThisStep = new Set();
2490
+ const latestContacts = world.latest().contacts ?? [];
2078
2491
  if (raw) {
2079
2492
  this.ensureScratchBuffers(bodyCapacity ?? 128);
2080
2493
  const res = raw.writeBodyMotionInto(this.scratchPoses, this.scratchVelocities, this.scratchIds, this.scratchStatus);
@@ -2115,7 +2528,14 @@ class PortalSimulatorManager {
2115
2528
  const trackingKey = `${pair.id}:${entryLabel}:${bodyId}`;
2116
2529
  const localPos = invRotateVec3(entryRotNorm, { x: dx, y: dy, z: dz });
2117
2530
  const priorZ = this.priorBodyPlanes.get(trackingKey);
2531
+ const priorVel = this.priorBodyVelocities.get(trackingKey);
2118
2532
  this.priorBodyPlanes.set(trackingKey, localPos.z);
2533
+ const linVel = {
2534
+ x: this.scratchVelocities[i * 6],
2535
+ y: this.scratchVelocities[i * 6 + 1],
2536
+ z: this.scratchVelocities[i * 6 + 2],
2537
+ };
2538
+ this.priorBodyVelocities.set(trackingKey, linVel);
2119
2539
  if (Math.abs(localPos.x) <= halfW && Math.abs(localPos.y) <= halfH) {
2120
2540
  const crossed = priorZ !== undefined && priorZ > 0 && localPos.z <= 0;
2121
2541
  if (crossed) {
@@ -2128,11 +2548,6 @@ class PortalSimulatorManager {
2128
2548
  w: this.scratchPoses[i * 7 + 6],
2129
2549
  },
2130
2550
  };
2131
- const linVel = {
2132
- x: this.scratchVelocities[i * 6],
2133
- y: this.scratchVelocities[i * 6 + 1],
2134
- z: this.scratchVelocities[i * 6 + 2],
2135
- };
2136
2551
  const angVel = {
2137
2552
  x: this.scratchVelocities[i * 6 + 3],
2138
2553
  y: this.scratchVelocities[i * 6 + 4],
@@ -2142,16 +2557,39 @@ class PortalSimulatorManager {
2142
2557
  const turnedVel = transformVelocityAcrossPortal(entryEnd, exitEnd, linVel);
2143
2558
  const turnedAngVel = transformVelocityAcrossPortal(entryEnd, exitEnd, angVel);
2144
2559
  const exitNorm = normalizeVec3(rotateVec3(quatNormalize(exitEnd.rotation), { x: 0, y: 0, z: 1 }));
2145
- const nudgedPos = addVec3(newPose.position, scaleVec3(exitNorm, 0.05));
2560
+ const nudgeDist = Math.max(0.05, Math.abs(localPos.z));
2561
+ const nudgedPos = addVec3(newPose.position, scaleVec3(exitNorm, nudgeDist));
2146
2562
  const handle = world.resolveBody(bodyId);
2563
+ if (this.bodySuppressedLayers.has(bodyId)) {
2564
+ const suppressedMask = this.bodySuppressedLayers.get(bodyId);
2565
+ this.bodySuppressedLayers.delete(bodyId);
2566
+ try {
2567
+ const bVals = new Float64Array(raw.readBody(handle));
2568
+ bVals[12] = bVals[12] | suppressedMask;
2569
+ raw.applyBatch([{ type: "editBody", body: handle, values: bVals, geometry: { type: "keep" } }]);
2570
+ }
2571
+ catch (err) {
2572
+ // Best-effort mask restoration on teleport crossing
2573
+ }
2574
+ }
2147
2575
  raw.setBodyTransform(handle, { x: nudgedPos.x, y: nudgedPos.y, z: nudgedPos.z }, newPose.orientation);
2148
- raw.setBodyLinearVelocity(handle, { x: turnedVel.x, y: turnedVel.y, z: turnedVel.z });
2149
- raw.setBodyAngularVelocity(handle, { x: turnedAngVel.x, y: turnedAngVel.y, z: turnedAngVel.z });
2576
+ raw.setBodyLinearVelocity(handle, {
2577
+ x: normalizeZero(turnedVel.x),
2578
+ y: normalizeZero(turnedVel.y),
2579
+ z: normalizeZero(turnedVel.z),
2580
+ });
2581
+ raw.setBodyAngularVelocity(handle, {
2582
+ x: normalizeZero(turnedAngVel.x),
2583
+ y: normalizeZero(turnedAngVel.y),
2584
+ z: normalizeZero(turnedAngVel.z),
2585
+ });
2150
2586
  raw.wakeBody(handle);
2151
2587
  this.poseJumpBodyIds.add(bodyId);
2152
2588
  teleportedThisStep.add(bodyId);
2153
2589
  this.priorBodyPlanes.delete(trackingKey);
2154
- this.priorBodyPlanes.set(`${pair.id}:${exitLabel}:${bodyId}`, 0.05);
2590
+ this.priorBodyVelocities.delete(trackingKey);
2591
+ this.priorBodyPlanes.set(`${pair.id}:${exitLabel}:${bodyId}`, nudgeDist);
2592
+ this.priorBodyVelocities.set(`${pair.id}:${exitLabel}:${bodyId}`, turnedVel);
2155
2593
  crossings.push({
2156
2594
  bodyId,
2157
2595
  portalId: pair.id,
@@ -2196,7 +2634,9 @@ class PortalSimulatorManager {
2196
2634
  const trackingKey = `${pair.id}:${entryLabel}:${bodyId}`;
2197
2635
  const localPos = invRotateVec3(entryRotNorm, subVec3(motion.position, entryEnd.position));
2198
2636
  const priorZ = this.priorBodyPlanes.get(trackingKey);
2637
+ const priorVel = this.priorBodyVelocities.get(trackingKey);
2199
2638
  this.priorBodyPlanes.set(trackingKey, localPos.z);
2639
+ this.priorBodyVelocities.set(trackingKey, { ...motion.linearVelocity });
2200
2640
  if (Math.abs(localPos.x) <= halfW && Math.abs(localPos.y) <= halfH) {
2201
2641
  const crossed = priorZ !== undefined && priorZ > 0 && localPos.z <= 0;
2202
2642
  if (crossed) {
@@ -2204,14 +2644,25 @@ class PortalSimulatorManager {
2204
2644
  const turnedVel = transformVelocityAcrossPortal(entryEnd, exitEnd, motion.linearVelocity);
2205
2645
  const turnedAngVel = transformVelocityAcrossPortal(entryEnd, exitEnd, motion.angularVelocity);
2206
2646
  const exitNorm = normalizeVec3(rotateVec3(quatNormalize(exitEnd.rotation), { x: 0, y: 0, z: 1 }));
2207
- const nudgedPos = addVec3(newPose.position, scaleVec3(exitNorm, 0.05));
2647
+ const nudgeDist = Math.max(0.05, Math.abs(localPos.z));
2648
+ const nudgedPos = addVec3(newPose.position, scaleVec3(exitNorm, nudgeDist));
2208
2649
  world.setBodyTransform(handle, { position: nudgedPos, orientation: newPose.orientation });
2209
- world.setBodyLinearVelocity(handle, turnedVel);
2210
- world.setBodyAngularVelocity(handle, turnedAngVel);
2650
+ world.setBodyLinearVelocity(handle, {
2651
+ x: normalizeZero(turnedVel.x),
2652
+ y: normalizeZero(turnedVel.y),
2653
+ z: normalizeZero(turnedVel.z),
2654
+ });
2655
+ world.setBodyAngularVelocity(handle, {
2656
+ x: normalizeZero(turnedAngVel.x),
2657
+ y: normalizeZero(turnedAngVel.y),
2658
+ z: normalizeZero(turnedAngVel.z),
2659
+ });
2211
2660
  this.poseJumpBodyIds.add(bodyId);
2212
2661
  teleportedThisStep.add(bodyId);
2213
2662
  this.priorBodyPlanes.delete(trackingKey);
2214
- this.priorBodyPlanes.set(`${pair.id}:${exitLabel}:${bodyId}`, 0.05);
2663
+ this.priorBodyVelocities.delete(trackingKey);
2664
+ this.priorBodyPlanes.set(`${pair.id}:${exitLabel}:${bodyId}`, nudgeDist);
2665
+ this.priorBodyVelocities.set(`${pair.id}:${exitLabel}:${bodyId}`, turnedVel);
2215
2666
  crossings.push({
2216
2667
  bodyId,
2217
2668
  portalId: pair.id,
@@ -2234,8 +2685,11 @@ class PortalSimulatorManager {
2234
2685
  function splitPortalRaycast(portals, query, nativeRaycast, maxDepth = 2) {
2235
2686
  const baseHits = nativeRaycast(query);
2236
2687
  let closestDist = Infinity;
2688
+ let closestBodyId = undefined;
2237
2689
  if (baseHits.length > 0) {
2238
2690
  closestDist = Number(baseHits[0].distance);
2691
+ const firstHit = baseHits[0];
2692
+ closestBodyId = firstHit.bodyId ?? firstHit.body?.id;
2239
2693
  }
2240
2694
  if (maxDepth <= 0) {
2241
2695
  return baseHits;
@@ -2263,7 +2717,11 @@ function splitPortalRaycast(portals, query, nativeRaycast, maxDepth = 2) {
2263
2717
  if (denom < -1e-6) {
2264
2718
  const toOrigin = subVec3(entryEnd.position, origin);
2265
2719
  const distAlongRay = dotVec3(toOrigin, normal) / denom;
2266
- if (distAlongRay > 1e-4 && distAlongRay < rayLen && distAlongRay < closestDist) {
2720
+ const isHostBodyHit = entryEnd.hostBodyId !== undefined &&
2721
+ closestBodyId !== undefined &&
2722
+ BigInt(entryEnd.hostBodyId) === closestBodyId;
2723
+ const maxAllowedDist = isHostBodyHit ? closestDist + 0.05 : closestDist;
2724
+ if (distAlongRay > 1e-4 && distAlongRay < rayLen && distAlongRay <= maxAllowedDist) {
2267
2725
  if (bestAperture === undefined || distAlongRay < bestAperture.distAlongRay) {
2268
2726
  const hitPos = addVec3(origin, scaleVec3(rayDirNorm, distAlongRay));
2269
2727
  const localHit = invRotateVec3(entryRotNorm, subVec3(hitPos, entryEnd.position));
@@ -2302,14 +2760,12 @@ function splitPortalRaycast(portals, query, nativeRaycast, maxDepth = 2) {
2302
2760
  maxDistance: remainingDist,
2303
2761
  };
2304
2762
  const throughHits = splitPortalRaycast(portals, subQuery, nativeRaycast, maxDepth - 1);
2305
- if (throughHits.length > 0) {
2306
- return throughHits.map((hit) => ({
2307
- ...hit,
2308
- distance: (hit.distance + distAlongRay),
2309
- portalHops: (hit.portalHops ?? 0) + 1,
2310
- portalPath: [...(hit.portalPath ?? []), pairId],
2311
- }));
2312
- }
2763
+ return throughHits.map((hit) => ({
2764
+ ...hit,
2765
+ distance: (hit.distance + distAlongRay),
2766
+ portalHops: (hit.portalHops ?? 0) + 1,
2767
+ portalPath: [...(hit.portalPath ?? []), pairId],
2768
+ }));
2313
2769
  }
2314
2770
  return baseHits;
2315
2771
  }
@@ -2378,6 +2834,7 @@ function facade(raw, definition) {
2378
2834
  };
2379
2835
  const commands = [];
2380
2836
  const pending = new WeakMap();
2837
+ const pendingPortalHosts = [];
2381
2838
  const removedPending = new Set();
2382
2839
  const removedLive = new Set();
2383
2840
  const topologyBefore = raw.topology();
@@ -2391,7 +2848,11 @@ function facade(raw, definition) {
2391
2848
  let nextJointKey = 1;
2392
2849
  let nextFluidKey = 1;
2393
2850
  const makePending = (kind, key) => {
2394
- const reference = Object.freeze({ kind, key });
2851
+ const reference = Object.freeze({
2852
+ kind,
2853
+ key,
2854
+ id: Object.freeze({ kind, key }),
2855
+ });
2395
2856
  pending.set(reference, reference);
2396
2857
  return reference;
2397
2858
  };
@@ -2559,13 +3020,13 @@ function facade(raw, definition) {
2559
3020
  if (velocityRotation !== undefined) {
2560
3021
  const rot = quatNormalizePure(velocityRotation);
2561
3022
  const linVel = rotateVec3Pure(rot, { x: values[3], y: values[4], z: values[5] });
2562
- values[3] = linVel.x;
2563
- values[4] = linVel.y;
2564
- values[5] = linVel.z;
3023
+ values[3] = normalizeZero(linVel.x);
3024
+ values[4] = normalizeZero(linVel.y);
3025
+ values[5] = normalizeZero(linVel.z);
2565
3026
  const angVel = rotateVec3Pure(rot, { x: values[19], y: values[20], z: values[21] });
2566
- values[19] = angVel.x;
2567
- values[20] = angVel.y;
2568
- values[21] = angVel.z;
3027
+ values[19] = normalizeZero(angVel.x);
3028
+ values[20] = normalizeZero(angVel.y);
3029
+ values[21] = normalizeZero(angVel.z);
2569
3030
  }
2570
3031
  if (dropContacts) {
2571
3032
  values[42] = 0.0;
@@ -2605,7 +3066,7 @@ function facade(raw, definition) {
2605
3066
  values = new Float64Array(raw.readBody(ref));
2606
3067
  }
2607
3068
  values[11] = u32(layer, "layer");
2608
- values[12] = u32(mask, "mask");
3069
+ values[12] = u32(mask, "mask") | ALL_PORTAL_HOST_LAYERS;
2609
3070
  if (staged) {
2610
3071
  const cmd = commands.find((c) => c.type === "createBody" && c.key === staged.key);
2611
3072
  if (cmd)
@@ -2617,7 +3078,26 @@ function facade(raw, definition) {
2617
3078
  },
2618
3079
  createPortalPair(def) {
2619
3080
  assertActiveOps();
2620
- return portalManager.createPortalPair(def);
3081
+ const pairHandle = portalManager.createPortalPair(def, raw, world);
3082
+ const checkPending = (end, hostRef) => {
3083
+ 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 });
3095
+ }
3096
+ }
3097
+ };
3098
+ checkPending("A", def.portalA.hostBodyId);
3099
+ checkPending("B", def.portalB.hostBodyId);
3100
+ return pairHandle;
2621
3101
  },
2622
3102
  setPortalOpen(handle, open) {
2623
3103
  assertActiveOps();
@@ -2655,6 +3135,19 @@ function facade(raw, definition) {
2655
3135
  fail("physics.capacity-exceeded", "edit", "the edit exceeds the world capacity.");
2656
3136
  }
2657
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);
3148
+ }
3149
+ }
3150
+ }
2658
3151
  for (const key of stagedTeleportKeys) {
2659
3152
  const entry = result.bodies.find((b) => b.key === key);
2660
3153
  if (entry) {
@@ -2714,6 +3207,7 @@ function facade(raw, definition) {
2714
3207
  step: () => invokeWorld("step", () => {
2715
3208
  portalManager.poseJumpBodyIds.clear();
2716
3209
  portalManager.lastCrossings = [];
3210
+ portalManager.beforeStep(world, raw, definition.capacity.bodies);
2717
3211
  raw.step(stepOptions);
2718
3212
  portalManager.stepPortals(world, raw, definition.capacity.bodies);
2719
3213
  }),
@@ -2768,6 +3262,10 @@ function facade(raw, definition) {
2768
3262
  if (portalManager.poseJumpBodyIds.has(bodyId)) {
2769
3263
  status[i] |= 0x40;
2770
3264
  }
3265
+ for (let vIdx = i * 6; vIdx < i * 6 + 6; vIdx++) {
3266
+ if (velocities[vIdx] === 0)
3267
+ velocities[vIdx] = 0;
3268
+ }
2771
3269
  }
2772
3270
  return Object.freeze({
2773
3271
  count: res.count,
@@ -2921,9 +3419,7 @@ function facade(raw, definition) {
2921
3419
  portalManager.restoreState(saved);
2922
3420
  }
2923
3421
  else {
2924
- portalManager.priorBodyPlanes.clear();
2925
- portalManager.poseJumpBodyIds.clear();
2926
- portalManager.lastCrossings = [];
3422
+ portalManager.clearEphemeralState();
2927
3423
  }
2928
3424
  return raw.restoreCheckpoint(checkpoint);
2929
3425
  }),
@@ -2933,7 +3429,14 @@ function facade(raw, definition) {
2933
3429
  return serializeWithPortalTrailer(rawBytes, saved);
2934
3430
  }),
2935
3431
  checkpointInfo: (checkpoint) => invokeWorld("checkpoint-info", () => raw.checkpointInfo(checkpoint)),
2936
- writeCheckpointBodyMotionInto: (checkpoint, poses, velocities, ids, status) => invokeWorld("checkpoint-motion", () => raw.writeCheckpointBodyMotionInto(checkpoint, poses, velocities, ids, status)),
3432
+ writeCheckpointBodyMotionInto: (checkpoint, poses, velocities, ids, status) => invokeWorld("checkpoint-motion", () => {
3433
+ const res = raw.writeCheckpointBodyMotionInto(checkpoint, poses, velocities, ids, status);
3434
+ for (let i = 0; i < res.count * 6; i++) {
3435
+ if (velocities[i] === 0)
3436
+ velocities[i] = 0;
3437
+ }
3438
+ return res;
3439
+ }),
2937
3440
  digestCheckpoint: (checkpoint) => invokeWorld("checkpoint", () => {
2938
3441
  const rawDigest = raw.digestCheckpoint(checkpoint);
2939
3442
  const saved = portalCheckpoints.get(checkpoint);
@@ -2953,9 +3456,7 @@ function facade(raw, definition) {
2953
3456
  portalManager.restoreState(portalState);
2954
3457
  }
2955
3458
  else {
2956
- portalManager.priorBodyPlanes.clear();
2957
- portalManager.poseJumpBodyIds.clear();
2958
- portalManager.lastCrossings = [];
3459
+ portalManager.clearEphemeralState();
2959
3460
  }
2960
3461
  return raw.restore(rawBytes);
2961
3462
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@series-inc/rundot-syncplay",
3
- "version": "6.0.0-rc.26",
3
+ "version": "6.0.0-rc.27",
4
4
  "description": "Kinetix orchestration, rollback, replay, late-join, and deterministic networking for RUN.game",
5
5
  "repository": {
6
6
  "type": "git",