spoint 0.1.80 → 0.1.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spoint",
3
- "version": "0.1.80",
3
+ "version": "0.1.81",
4
4
  "description": "Physics and netcode SDK for multiplayer game servers",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -64,7 +64,7 @@ export class AppRuntime {
64
64
  }
65
65
  if (config.autoTrimesh && entity.model && this._physics) {
66
66
  entity.collider = { type: 'trimesh', model: entity.model }
67
- this._physics.addStaticTrimeshAsync(this.resolveAssetPath(entity.model), 0)
67
+ this._physics.addStaticTrimeshAsync(this.resolveAssetPath(entity.model), 0, entity.position || [0,0,0])
68
68
  .then(id => { entity._physicsBodyId = id })
69
69
  .catch(e => console.error(`[AppRuntime] Failed to create trimesh for ${entity.model}:`, e.message))
70
70
  }
@@ -364,6 +364,164 @@ async function extractMeshWithMeshopt(buf, json, prim, binOffset, meshName) {
364
364
  }
365
365
  }
366
366
 
367
+ /**
368
+ * Extract ALL meshes and ALL primitives from a GLB file and combine them into
369
+ * a single flat vertex/index buffer suitable for a trimesh collider.
370
+ * Handles Draco-compressed primitives. Used for map collision where the GLB
371
+ * may have dozens of meshes each with many primitives.
372
+ *
373
+ * @param {string} filepath - Path to GLB file
374
+ * @returns {Promise<Object>} {vertices: Float32Array, indices: Uint32Array, vertexCount, triangleCount}
375
+ */
376
+ export async function extractAllMeshesFromGLBAsync(filepath) {
377
+ console.log(`[GLBLoader] Extracting ALL meshes from: ${filepath}`)
378
+ const buf = readFileSync(filepath)
379
+ if (buf.toString('ascii', 0, 4) !== 'glTF') throw new Error('Not a GLB file')
380
+
381
+ const jsonLen = buf.readUInt32LE(12)
382
+ const json = JSON.parse(buf.toString('utf-8', 20, 20 + jsonLen))
383
+ const binOffset = 20 + jsonLen + 8
384
+
385
+ const allVertices = []
386
+ const allIndices = []
387
+ let vertexOffset = 0
388
+ let totalTriangles = 0
389
+
390
+ // Build a node->transform map for node hierarchy
391
+ const nodeTransforms = buildNodeTransforms(json)
392
+
393
+ for (let meshIdx = 0; meshIdx < (json.meshes || []).length; meshIdx++) {
394
+ const mesh = json.meshes[meshIdx]
395
+ // Find node referencing this mesh to get its world transform
396
+ const nodeIdx = (json.nodes || []).findIndex(n => n.mesh === meshIdx)
397
+ const worldTransform = nodeIdx >= 0 ? nodeTransforms[nodeIdx] : null
398
+
399
+ for (let primIdx = 0; primIdx < mesh.primitives.length; primIdx++) {
400
+ const prim = mesh.primitives[primIdx]
401
+ let result
402
+ try {
403
+ if (prim.extensions?.KHR_draco_mesh_compression) {
404
+ result = await decompressDracoMesh(buf, json, prim, binOffset, mesh.name)
405
+ } else {
406
+ result = extractStandardMesh(buf, json, prim, binOffset, mesh.name)
407
+ }
408
+ } catch (e) {
409
+ console.warn(`[GLBLoader] Skipping mesh[${meshIdx}] prim[${primIdx}]: ${e.message}`)
410
+ continue
411
+ }
412
+
413
+ if (!result.indices || result.triangleCount === 0) continue
414
+
415
+ // Apply world transform to vertices if present
416
+ let verts = result.vertices
417
+ if (worldTransform) {
418
+ verts = applyTransformMatrix(result.vertices, worldTransform)
419
+ }
420
+
421
+ allVertices.push(verts)
422
+ // Remap indices by current vertex offset
423
+ const remapped = new Uint32Array(result.indices.length)
424
+ for (let i = 0; i < result.indices.length; i++) {
425
+ remapped[i] = result.indices[i] + vertexOffset
426
+ }
427
+ allIndices.push(remapped)
428
+ vertexOffset += result.vertexCount
429
+ totalTriangles += result.triangleCount
430
+ }
431
+ }
432
+
433
+ if (allVertices.length === 0) throw new Error('No valid mesh primitives found in GLB')
434
+
435
+ // Concatenate all vertex and index arrays
436
+ const totalVerts = vertexOffset
437
+ const combinedVertices = new Float32Array(totalVerts * 3)
438
+ let vOff = 0
439
+ for (const v of allVertices) { combinedVertices.set(v, vOff); vOff += v.length }
440
+
441
+ const combinedIndices = new Uint32Array(totalTriangles * 3)
442
+ let iOff = 0
443
+ for (const idx of allIndices) { combinedIndices.set(idx, iOff); iOff += idx.length }
444
+
445
+ console.log(`[GLBLoader] Combined: ${totalVerts} vertices, ${totalTriangles} triangles from ${allIndices.length} primitives`)
446
+ return { vertices: combinedVertices, indices: combinedIndices, vertexCount: totalVerts, triangleCount: totalTriangles }
447
+ }
448
+
449
+ /**
450
+ * Build world-space 4x4 transform matrices for every node in the scene graph.
451
+ * Returns an array indexed by node index.
452
+ */
453
+ function buildNodeTransforms(json) {
454
+ const nodes = json.nodes || []
455
+ const matrices = new Array(nodes.length).fill(null)
456
+
457
+ function getMatrix(nodeIdx) {
458
+ if (matrices[nodeIdx] !== null) return matrices[nodeIdx]
459
+ const node = nodes[nodeIdx]
460
+ let local = mat4Identity()
461
+ if (node.matrix) {
462
+ local = node.matrix.slice()
463
+ } else {
464
+ const t = node.translation || [0, 0, 0]
465
+ const r = node.rotation || [0, 0, 0, 1]
466
+ const s = node.scale || [1, 1, 1]
467
+ local = mat4TRS(t, r, s)
468
+ }
469
+ // Find parent
470
+ const parentIdx = nodes.findIndex((n, i) => i !== nodeIdx && (n.children || []).includes(nodeIdx))
471
+ if (parentIdx >= 0) {
472
+ local = mat4Mul(getMatrix(parentIdx), local)
473
+ }
474
+ matrices[nodeIdx] = local
475
+ return local
476
+ }
477
+
478
+ for (let i = 0; i < nodes.length; i++) getMatrix(i)
479
+ return matrices
480
+ }
481
+
482
+ function mat4Identity() {
483
+ return [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]
484
+ }
485
+
486
+ function mat4TRS(t, r, s) {
487
+ const [qx, qy, qz, qw] = r
488
+ const [sx, sy, sz] = s
489
+ const x2=qx+qx, y2=qy+qy, z2=qz+qz
490
+ const xx=qx*x2, xy=qx*y2, xz=qx*z2
491
+ const yy=qy*y2, yz=qy*z2, zz=qz*z2
492
+ const wx=qw*x2, wy=qw*y2, wz=qw*z2
493
+ return [
494
+ (1-(yy+zz))*sx, (xy+wz)*sx, (xz-wy)*sx, 0,
495
+ (xy-wz)*sy, (1-(xx+zz))*sy,(yz+wx)*sy, 0,
496
+ (xz+wy)*sz, (yz-wx)*sz, (1-(xx+yy))*sz,0,
497
+ t[0], t[1], t[2], 1
498
+ ]
499
+ }
500
+
501
+ function mat4Mul(a, b) {
502
+ const out = new Array(16)
503
+ for (let row = 0; row < 4; row++) {
504
+ for (let col = 0; col < 4; col++) {
505
+ let sum = 0
506
+ for (let k = 0; k < 4; k++) sum += a[row + k*4] * b[k + col*4]
507
+ out[row + col*4] = sum
508
+ }
509
+ }
510
+ return out
511
+ }
512
+
513
+ function applyTransformMatrix(vertices, m) {
514
+ const count = vertices.length / 3
515
+ const out = new Float32Array(vertices.length)
516
+ for (let i = 0; i < count; i++) {
517
+ const x = vertices[i*3], y = vertices[i*3+1], z = vertices[i*3+2]
518
+ out[i*3] = m[0]*x + m[4]*y + m[8]*z + m[12]
519
+ out[i*3+1] = m[1]*x + m[5]*y + m[9]*z + m[13]
520
+ out[i*3+2] = m[2]*x + m[6]*y + m[10]*z + m[14]
521
+ }
522
+ return out
523
+ }
524
+
367
525
  /**
368
526
  * Check if a GLB file has Draco-compressed meshes without attempting extraction.
369
527
  * Useful for validation and error reporting.
@@ -1,5 +1,5 @@
1
- import initJolt from 'jolt-physics/wasm-compat'
2
- import { extractMeshFromGLB, extractMeshFromGLBAsync } from './GLBLoader.js'
1
+ import initJolt from 'jolt-physics/wasm-compat'
2
+ import { extractMeshFromGLB, extractMeshFromGLBAsync, extractAllMeshesFromGLBAsync } from './GLBLoader.js'
3
3
  const LAYER_STATIC = 0, LAYER_DYNAMIC = 1, NUM_LAYERS = 2
4
4
  let joltInstance = null
5
5
  async function getJolt() { if (!joltInstance) joltInstance = await initJolt(); return joltInstance }
@@ -71,110 +71,92 @@ export class PhysicsWorld {
71
71
  layer = motionType === 'static' ? LAYER_STATIC : LAYER_DYNAMIC
72
72
  return this._addBody(shape, position, mt, layer, { ...opts, meta: { type: motionType, shape: shapeType } })
73
73
  }
74
- addStaticTrimesh(glbPath, meshIndex = 0) {
75
- const J = this.Jolt
76
- const mesh = extractMeshFromGLB(glbPath, meshIndex)
77
-
78
- // Apply node transform if present (scale, rotation, translation)
79
- let vertices = mesh.vertices
80
- const nodeT = mesh.nodeTransform
81
- if (nodeT) {
82
- const numVerts = mesh.vertexCount
83
- vertices = new Float32Array(numVerts * 3)
84
-
85
- const scale = nodeT.scale || [1, 1, 1]
86
- const translation = nodeT.translation || [0, 0, 0]
87
- const rotation = nodeT.rotation
88
-
89
- for (let i = 0; i < numVerts; i++) {
90
- let x = mesh.vertices[i * 3] * scale[0]
91
- let y = mesh.vertices[i * 3 + 1] * scale[1]
92
- let z = mesh.vertices[i * 3 + 2] * scale[2]
93
-
94
- if (rotation) {
95
- const [qx, qy, qz, qw] = rotation
96
- const ix = qw * x + qy * z - qz * y
97
- const iy = qw * y + qz * x - qx * z
98
- const iz = qw * z + qx * y - qy * x
99
- const iw = -qx * x - qy * y - qz * z
100
- x = ix * qw - iw * qx - iy * qz + iz * qy
101
- y = iy * qw - iw * qy - iz * qx + ix * qz
102
- z = iz * qw - iw * qz - ix * qy + iy * qx
103
- }
104
-
105
- vertices[i * 3] = x + translation[0]
106
- vertices[i * 3 + 1] = y + translation[1]
107
- vertices[i * 3 + 2] = z + translation[2]
108
- }
109
- }
110
-
111
- const triangles = new J.TriangleList(); triangles.resize(mesh.triangleCount)
112
- for (let t = 0; t < mesh.triangleCount; t++) {
113
- const tri = triangles.at(t)
114
- for (let v = 0; v < 3; v++) {
115
- const idx = mesh.indices[t * 3 + v]
116
- tri.set_mV(v, new J.Float3(vertices[idx * 3], vertices[idx * 3 + 1], vertices[idx * 3 + 2]))
117
- }
118
- }
119
- const shape = new J.MeshShapeSettings(triangles).Create().Get()
120
- return this._addBody(shape, [0, 0, 0], J.EMotionType_Static, LAYER_STATIC, { meta: { type: 'static', shape: 'trimesh', mesh: mesh.name, triangles: mesh.triangleCount } })
121
- }
74
+ addStaticTrimesh(glbPath, meshIndex = 0) {
75
+ const J = this.Jolt
76
+ const mesh = extractMeshFromGLB(glbPath, meshIndex)
77
+
78
+ // Apply node transform if present (scale, rotation, translation)
79
+ let vertices = mesh.vertices
80
+ const nodeT = mesh.nodeTransform
81
+ if (nodeT) {
82
+ const numVerts = mesh.vertexCount
83
+ vertices = new Float32Array(numVerts * 3)
84
+
85
+ const scale = nodeT.scale || [1, 1, 1]
86
+ const translation = nodeT.translation || [0, 0, 0]
87
+ const rotation = nodeT.rotation
88
+
89
+ for (let i = 0; i < numVerts; i++) {
90
+ let x = mesh.vertices[i * 3] * scale[0]
91
+ let y = mesh.vertices[i * 3 + 1] * scale[1]
92
+ let z = mesh.vertices[i * 3 + 2] * scale[2]
93
+
94
+ if (rotation) {
95
+ const [qx, qy, qz, qw] = rotation
96
+ const ix = qw * x + qy * z - qz * y
97
+ const iy = qw * y + qz * x - qx * z
98
+ const iz = qw * z + qx * y - qy * x
99
+ const iw = -qx * x - qy * y - qz * z
100
+ x = ix * qw - iw * qx - iy * qz + iz * qy
101
+ y = iy * qw - iw * qy - iz * qx + ix * qz
102
+ z = iz * qw - iw * qz - ix * qy + iy * qx
103
+ }
104
+
105
+ vertices[i * 3] = x + translation[0]
106
+ vertices[i * 3 + 1] = y + translation[1]
107
+ vertices[i * 3 + 2] = z + translation[2]
108
+ }
109
+ }
110
+
111
+ const triangles = new J.TriangleList(); triangles.resize(mesh.triangleCount)
112
+ const f3 = new J.Float3(0, 0, 0)
113
+ for (let t = 0; t < mesh.triangleCount; t++) {
114
+ const tri = triangles.at(t)
115
+ for (let v = 0; v < 3; v++) {
116
+ const idx = mesh.indices[t * 3 + v]
117
+ f3.x = vertices[idx * 3]; f3.y = vertices[idx * 3 + 1]; f3.z = vertices[idx * 3 + 2]
118
+ tri.set_mV(v, f3)
119
+ }
120
+ }
121
+ const settings = new J.MeshShapeSettings(triangles)
122
+ const shape = settings.Create().Get()
123
+ J.destroy(f3)
124
+ J.destroy(triangles)
125
+ J.destroy(settings)
126
+ return this._addBody(shape, [0, 0, 0], J.EMotionType_Static, LAYER_STATIC, { meta: { type: 'static', shape: 'trimesh', mesh: mesh.name, triangles: mesh.triangleCount } })
127
+ }
122
128
 
123
- addStaticTrimeshAsync(glbPath, meshIndex = 0, position = [0, 0, 0]) {
124
- return new Promise(async (resolve, reject) => {
125
- try {
126
- const J = this.Jolt
127
- const mesh = await extractMeshFromGLBAsync(glbPath, meshIndex)
128
-
129
- // Apply node transform if present (scale, rotation, translation)
130
- let vertices = mesh.vertices
131
- const nodeT = mesh.nodeTransform
132
- if (nodeT) {
133
- const numVerts = mesh.vertexCount
134
- vertices = new Float32Array(numVerts * 3)
135
-
136
- const scale = nodeT.scale || [1, 1, 1]
137
- const translation = nodeT.translation || [0, 0, 0]
138
- const rotation = nodeT.rotation
139
-
140
- for (let i = 0; i < numVerts; i++) {
141
- let x = mesh.vertices[i * 3] * scale[0]
142
- let y = mesh.vertices[i * 3 + 1] * scale[1]
143
- let z = mesh.vertices[i * 3 + 2] * scale[2]
144
-
145
- if (rotation) {
146
- const [qx, qy, qz, qw] = rotation
147
- const ix = qw * x + qy * z - qz * y
148
- const iy = qw * y + qz * x - qx * z
149
- const iz = qw * z + qx * y - qy * x
150
- const iw = -qx * x - qy * y - qz * z
151
- x = ix * qw - iw * qx - iy * qz + iz * qy
152
- y = iy * qw - iw * qy - iz * qx + ix * qz
153
- z = iz * qw - iw * qz - ix * qy + iy * qx
154
- }
155
-
156
- vertices[i * 3] = x + translation[0]
157
- vertices[i * 3 + 1] = y + translation[1]
158
- vertices[i * 3 + 2] = z + translation[2]
159
- }
160
- }
161
-
162
- const triangles = new J.TriangleList(); triangles.resize(mesh.triangleCount)
163
- for (let t = 0; t < mesh.triangleCount; t++) {
164
- const tri = triangles.at(t)
165
- for (let v = 0; v < 3; v++) {
166
- const idx = mesh.indices[t * 3 + v]
167
- tri.set_mV(v, new J.Float3(vertices[idx * 3], vertices[idx * 3 + 1], vertices[idx * 3 + 2]))
168
- }
169
- }
170
- const shape = new J.MeshShapeSettings(triangles).Create().Get()
171
- const id = this._addBody(shape, position, J.EMotionType_Static, LAYER_STATIC, { meta: { type: 'static', shape: 'trimesh', mesh: mesh.name, triangles: mesh.triangleCount } })
172
- resolve(id)
173
- } catch (e) {
174
- reject(e)
175
- }
176
- })
177
- }
129
+ addStaticTrimeshAsync(glbPath, meshIndex = 0, position = [0, 0, 0]) {
130
+ return new Promise(async (resolve, reject) => {
131
+ try {
132
+ const J = this.Jolt
133
+ // Use combined extraction: all meshes + all primitives (handles Draco, multi-mesh maps)
134
+ const mesh = await extractAllMeshesFromGLBAsync(glbPath)
135
+ const { vertices, indices, triangleCount } = mesh
136
+
137
+ const triangles = new J.TriangleList(); triangles.resize(triangleCount)
138
+ // Reuse a single Float3 to avoid WASM heap growth from per-vertex allocations
139
+ const f3 = new J.Float3(0, 0, 0)
140
+ for (let t = 0; t < triangleCount; t++) {
141
+ const tri = triangles.at(t)
142
+ for (let v = 0; v < 3; v++) {
143
+ const idx = indices[t * 3 + v]
144
+ f3.x = vertices[idx * 3]; f3.y = vertices[idx * 3 + 1]; f3.z = vertices[idx * 3 + 2]
145
+ tri.set_mV(v, f3)
146
+ }
147
+ }
148
+ const settings = new J.MeshShapeSettings(triangles)
149
+ const shape = settings.Create().Get()
150
+ J.destroy(f3)
151
+ J.destroy(triangles)
152
+ J.destroy(settings)
153
+ const id = this._addBody(shape, position, J.EMotionType_Static, LAYER_STATIC, { meta: { type: 'static', shape: 'trimesh', triangles: triangleCount } })
154
+ resolve(id)
155
+ } catch (e) {
156
+ reject(e)
157
+ }
158
+ })
159
+ }
178
160
  addPlayerCharacter(radius, halfHeight, position, mass) {
179
161
  const J = this.Jolt
180
162
  const cvs = new J.CharacterVirtualSettings()
@@ -232,9 +214,7 @@ export class PhysicsWorld {
232
214
  getCharacterPosition(charId) {
233
215
  const ch = this.characters?.get(charId); if (!ch) return [0, 0, 0]
234
216
  const p = ch.GetPosition()
235
- const r = [p.GetX(), p.GetY(), p.GetZ()]
236
- this.Jolt.destroy(p)
237
- return r
217
+ return [p.GetX(), p.GetY(), p.GetZ()]
238
218
  }
239
219
  getCharacterVelocity(charId) {
240
220
  const ch = this.characters?.get(charId); if (!ch) return [0, 0, 0]
@@ -320,8 +300,8 @@ export class PhysicsWorld {
320
300
  const dir = len > 0 ? [direction[0] / len, direction[1] / len, direction[2] / len] : direction
321
301
  const ray = new J.RRayCast(new J.RVec3(origin[0], origin[1], origin[2]), new J.Vec3(dir[0] * maxDistance, dir[1] * maxDistance, dir[2] * maxDistance))
322
302
  const rs = new J.RayCastSettings(), col = new J.CastRayClosestHitCollisionCollector()
323
- const bp = new J.DefaultBroadPhaseLayerFilter(this._ovbp)
324
- const ol = new J.DefaultObjectLayerFilter(this._objFilter)
303
+ const bp = new J.DefaultBroadPhaseLayerFilter(this.jolt.GetObjectVsBroadPhaseLayerFilter(), LAYER_DYNAMIC)
304
+ const ol = new J.DefaultObjectLayerFilter(this.jolt.GetObjectLayerPairFilter(), LAYER_DYNAMIC)
325
305
  const eb = excludeBodyId != null ? this._getBody(excludeBodyId) : null
326
306
  const bf = eb ? new J.IgnoreSingleBodyFilter(eb.GetID()) : new J.BodyFilter()
327
307
  const sf = new J.ShapeFilter()
@@ -335,13 +315,25 @@ export class PhysicsWorld {
335
315
  return result
336
316
  }
337
317
  destroy() {
318
+ if (!this.Jolt) return
319
+ const J = this.Jolt
338
320
  if (this.characters) {
339
- for (const [id, ch] of this.characters) {
340
- this.Jolt.destroy(ch)
341
- }
321
+ for (const ch of this.characters.values()) J.destroy(ch)
342
322
  this.characters.clear()
343
323
  }
324
+ if (this._charFilters) {
325
+ J.destroy(this._charFilters.bp)
326
+ J.destroy(this._charFilters.ol)
327
+ J.destroy(this._charFilters.body)
328
+ J.destroy(this._charFilters.shape)
329
+ this._charFilters = null
330
+ }
331
+ if (this._charUpdateSettings) { J.destroy(this._charUpdateSettings); this._charUpdateSettings = null }
332
+ if (this._charGravity) { J.destroy(this._charGravity); this._charGravity = null }
344
333
  for (const [id] of this.bodies) this.removeBody(id)
345
- if (this.jolt) { this.Jolt.destroy(this.jolt); this.jolt = null }
334
+ if (this._tmpVec3) { J.destroy(this._tmpVec3); this._tmpVec3 = null }
335
+ if (this._tmpRVec3) { J.destroy(this._tmpRVec3); this._tmpRVec3 = null }
336
+ if (this.jolt) { J.destroy(this.jolt); this.jolt = null }
337
+ this.physicsSystem = null; this.bodyInterface = null
346
338
  }
347
339
  }
@@ -102,8 +102,7 @@ export function createTickHandler(deps) {
102
102
  const entitySnap = appRuntime.getSnapshotForPlayer(pos, stageLoader.getActiveStage().spatial.relevanceRadius)
103
103
  const combined = { tick: playerSnap.tick, timestamp: playerSnap.timestamp, players: playerSnap.players, entities: entitySnap.entities }
104
104
  if (isKeyframe || !playerEntityMaps.has(player.id)) {
105
- const encoded = SnapshotEncoder.encode(combined)
106
- const { entityMap } = SnapshotEncoder.encodeDelta(combined, new Map())
105
+ const { encoded, entityMap } = SnapshotEncoder.encodeDelta(combined, new Map())
107
106
  playerEntityMaps.set(player.id, entityMap)
108
107
  connections.send(player.id, MSG.SNAPSHOT, { seq: snapshotSeq, ...encoded })
109
108
  } else {