@threenative/core 0.3.13 → 0.3.15

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.
Files changed (50) hide show
  1. package/capabilities.json +299 -10
  2. package/dist/{chunk-4SRAQFTU.js → chunk-2GPHICV6.js} +1 -1
  3. package/dist/{chunk-DIPIJICH.js → chunk-GEMQJBY4.js} +70 -18
  4. package/dist/{chunk-EFWZWLPY.js → chunk-QAMSM3Z5.js} +354 -12
  5. package/dist/{chunk-SV4QVUTQ.js → chunk-QAQHYOWY.js} +1 -1
  6. package/dist/{chunk-EEABDLUC.js → chunk-VBBYWGAT.js} +2 -2
  7. package/dist/{chunk-GYUZJQ7U.js → chunk-VQRPEOKY.js} +4 -1
  8. package/dist/index.d.ts +605 -7
  9. package/dist/index.js +1973 -609
  10. package/dist/playtest.js +3 -3
  11. package/dist/{quality-BYqKGAwo.d.ts → quality-BADStsTn.d.ts} +2 -2
  12. package/dist/render-environment.d.ts +1 -1
  13. package/dist/ui-layer.js +2 -2
  14. package/dist/worker.js +2 -2
  15. package/dist/world.d.ts +13 -3
  16. package/dist/world.js +179 -36
  17. package/mcp/animation-server.mjs +1 -1
  18. package/mcp/engine-server.mjs +32 -6
  19. package/mcp/servers.mjs +3 -3
  20. package/package.json +5 -5
  21. package/scripts/ensure-mcp.mjs +6 -1
  22. package/src/clustered-batch.ts +146 -3
  23. package/src/clustered-mesh.ts +548 -20
  24. package/src/debug.ts +16 -0
  25. package/src/displaced-surface.ts +428 -0
  26. package/src/frame-budget.ts +16 -0
  27. package/src/generated/console-markers.ts +1 -0
  28. package/src/grass-field.ts +628 -0
  29. package/src/index.ts +112 -0
  30. package/src/render/material-key.ts +21 -1
  31. package/src/render/screen-probe-gather.ts +303 -0
  32. package/src/render/short-range-ao.ts +274 -0
  33. package/src/render/world-impostor-surface.ts +98 -3
  34. package/src/render-camera-cull.ts +9 -3
  35. package/src/renderer.ts +26 -4
  36. package/src/scatter-field.ts +496 -0
  37. package/src/startup-offscreen-bytes.ts +11 -5
  38. package/src/state.ts +16 -3
  39. package/src/static-transform.ts +75 -6
  40. package/src/tile-ring.ts +294 -0
  41. package/src/version.ts +1 -1
  42. package/src/warmup.ts +15 -2
  43. package/src/world-cell-batches.ts +4 -0
  44. package/src/world-cell-data.ts +7 -0
  45. package/src/world-cell-models.ts +36 -8
  46. package/src/world-cell-render-gpu-dress.ts +4 -2
  47. package/src/world-cell-render-util.ts +2 -2
  48. package/src/world-cells.ts +1 -1
  49. package/src/world-river-ribbon.ts +13 -22
  50. package/src/world-water-bodies.ts +113 -3
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { realpathSync, readFileSync, existsSync, mkdirSync, rmSync, writeFileSync, appendFileSync, mkdtempSync, renameSync, readdirSync } from 'fs';
2
+ import { realpathSync, statSync, readFileSync, existsSync, mkdirSync, rmSync, writeFileSync, appendFileSync, mkdtempSync, renameSync, readdirSync } from 'fs';
3
3
  import path from 'path';
4
4
  import { createInterface } from 'readline';
5
5
  import { fileURLToPath } from 'url';
@@ -673,15 +673,23 @@ function validateManifest(value, file) {
673
673
  }
674
674
  return value;
675
675
  }
676
+ var manifestCache = /* @__PURE__ */ new Map();
676
677
  function loadCapabilityManifest(file = defaultManifestPath()) {
677
678
  let raw;
679
+ let stamp;
678
680
  try {
681
+ const stat = statSync(file);
682
+ stamp = `${stat.mtimeMs}:${stat.size}`;
683
+ const cached = manifestCache.get(file);
684
+ if (cached?.stamp === stamp) return cached.manifest;
679
685
  raw = readFileSync(file, "utf8");
680
686
  } catch (error) {
681
687
  throw manifestError(file, `cannot read committed manifest: ${String(error)}`);
682
688
  }
683
689
  try {
684
- return validateManifest(JSON.parse(raw), file);
690
+ const manifest = validateManifest(JSON.parse(raw), file);
691
+ manifestCache.set(file, { stamp, manifest });
692
+ return manifest;
685
693
  } catch (error) {
686
694
  if (error instanceof Error && error.message.startsWith("TN_ENGINE_CAPABILITIES_MANIFEST:"))
687
695
  throw error;
@@ -710,7 +718,17 @@ function splitSymbolCase(value) {
710
718
  function capabilitySituationTokens(value) {
711
719
  return splitSymbolCase(value).toLocaleLowerCase().split(/[^a-z0-9]+/u).filter((token) => token.length > 1 && !STOP_WORDS.has(token)).map(stem).filter((token) => !STOP_WORD_STEMS.has(token));
712
720
  }
713
- var tokens = capabilitySituationTokens;
721
+ var tokenCache = /* @__PURE__ */ new Map();
722
+ var TOKEN_CACHE_LIMIT = 2e4;
723
+ function tokens(value) {
724
+ let cached = tokenCache.get(value);
725
+ if (cached === void 0) {
726
+ if (tokenCache.size >= TOKEN_CACHE_LIMIT) tokenCache.clear();
727
+ cached = Object.freeze(capabilitySituationTokens(value));
728
+ tokenCache.set(value, cached);
729
+ }
730
+ return cached;
731
+ }
714
732
  function tokenWeights(entries) {
715
733
  const frequency = /* @__PURE__ */ new Map();
716
734
  let situations = 0;
@@ -970,11 +988,19 @@ function withReferenceTools(situation, response) {
970
988
  guidance: `Reverse engineer the game with engine_search_references, then engine_reference_detail for its pinned cards. ${response.guidance}`
971
989
  };
972
990
  }
991
+ var weightCache = /* @__PURE__ */ new WeakMap();
992
+ function manifestWeights(entries) {
993
+ let cached = weightCache.get(entries);
994
+ if (cached === void 0) {
995
+ cached = { weights: tokenWeights(entries), nameWeights: nameTokenWeights(entries) };
996
+ weightCache.set(entries, cached);
997
+ }
998
+ return cached;
999
+ }
973
1000
  function searchMechanics(situation, manifest, scope) {
974
1001
  const query = tokens(situation);
975
1002
  const limit = scope === "request" ? MAX_COMPLETE_REQUEST_RESULTS : MAX_SITUATION_RESULTS;
976
- const weights = tokenWeights(manifest.entries);
977
- const nameWeights = nameTokenWeights(manifest.entries);
1003
+ const { weights, nameWeights } = manifestWeights(manifest.entries);
978
1004
  const notOwned = notOwnedMatch(manifest, query);
979
1005
  if (notOwned !== void 0 && isSpecificNotOwnedMatch(query, notOwned.matchedSituation)) {
980
1006
  return {
@@ -1359,7 +1385,7 @@ async function handleLine(line2, manifestFile) {
1359
1385
  capabilities: { tools: { listChanged: false } },
1360
1386
  instructions: AUTHORING_INSTRUCTIONS,
1361
1387
  protocolVersion: "2025-06-18",
1362
- serverInfo: { name: "threenative-engine-mcp", version: "0.2.13" }
1388
+ serverInfo: { name: "threenative-engine-mcp", version: "0.2.15" }
1363
1389
  });
1364
1390
  }
1365
1391
  if (request.method === "tools/list") {
package/mcp/servers.mjs CHANGED
@@ -52,10 +52,10 @@ export const MCP_SERVERS = Object.freeze({
52
52
  * checkout whose bundle has not been built. */
53
53
  export const MCP_PACKAGES = Object.freeze({
54
54
  assets: Object.freeze({ name: "threenative-asset-mcp", version: "0.16.0" }),
55
- terrain: Object.freeze({ name: "@threenative/terrain", version: "0.1.9" }),
55
+ terrain: Object.freeze({ name: "@threenative/terrain", version: "0.1.11" }),
56
56
  sculpt: Object.freeze({ name: "threenative-sculpt-mcp", version: "0.2.2" }),
57
- engine: Object.freeze({ name: "threenative-engine-mcp", version: "0.2.13" }),
58
- animation: Object.freeze({ name: "threenative-animation-mcp", version: "0.1.10" }),
57
+ engine: Object.freeze({ name: "threenative-engine-mcp", version: "0.2.15" }),
58
+ animation: Object.freeze({ name: "threenative-animation-mcp", version: "0.1.12" }),
59
59
  // `args` fixes the launch for every host. The Chrome flags are `WEBGPU_BROWSER_ARGS` from
60
60
  // `@threenative/playtest`, so a DevTools trace profiles the same adapter a playtest does and not
61
61
  // SwiftShader. An isolated profile keeps the user's own Chrome profile out, and the two opt-outs
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/core",
3
- "version": "0.3.13",
3
+ "version": "0.3.15",
4
4
  "license": "MIT AND GPL-2.0-or-later",
5
5
  "description": "The small vanilla Three.js game runtime foundation.",
6
6
  "keywords": [
@@ -111,12 +111,12 @@
111
111
  "tsup": "8.5.1",
112
112
  "typescript": "npm:@typescript/typescript6@6.0.2",
113
113
  "@typescript/native": "npm:typescript@7.0.2",
114
- "@threenative/playtest": "0.3.13",
115
- "threenative-engine-mcp": "0.2.13",
116
- "threenative-animation-mcp": "0.1.10"
114
+ "@threenative/playtest": "0.3.15",
115
+ "threenative-engine-mcp": "0.2.15",
116
+ "threenative-animation-mcp": "0.1.12"
117
117
  },
118
118
  "peerDependencies": {
119
- "@threenative/playtest": ">=0.3.13 <0.4.0",
119
+ "@threenative/playtest": ">=0.3.15 <0.4.0",
120
120
  "react": ">=19.2.0 <20",
121
121
  "react-reconciler": ">=0.33.0 <0.34"
122
122
  },
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { realpathSync } from "node:fs";
2
3
  import path from "node:path";
3
4
  import { pathToFileURL } from "node:url";
4
5
  // Installing ThreeNative wires its MCP servers into the project. An agent authoring a game here
@@ -39,5 +40,9 @@ export function runMcpSetup(environment = process.env, cwd = process.cwd()) {
39
40
  }
40
41
 
41
42
  const entry = process.argv[1];
42
- if (entry !== undefined && pathToFileURL(path.resolve(entry)).href === import.meta.url)
43
+ // Node resolves the main module's symlinks, and pnpm links core into node_modules, so compare real paths.
44
+ if (
45
+ entry !== undefined &&
46
+ pathToFileURL(realpathSync(path.resolve(entry))).href === import.meta.url
47
+ )
43
48
  runMcpSetup();
@@ -3,6 +3,7 @@ import {
3
3
  BufferGeometry,
4
4
  type Camera,
5
5
  Euler,
6
+ Frustum,
6
7
  InstancedMesh,
7
8
  type Material,
8
9
  Matrix4,
@@ -10,7 +11,17 @@ import {
10
11
  Quaternion,
11
12
  Vector3,
12
13
  } from "three";
13
- import { type IClusterTable, pixelsPerUnit, selectClusterCut } from "./clustered-mesh.js";
14
+ import {
15
+ ClusterView,
16
+ DEFAULT_VIEW_MARGIN,
17
+ type IClusterTable,
18
+ assertViewMargin,
19
+ clusterTableRadius,
20
+ outsideFrustum,
21
+ pixelsPerUnit,
22
+ selectClusterCut,
23
+ worldFrustum,
24
+ } from "./clustered-mesh.js";
14
25
 
15
26
  /**
16
27
  * Many copies of one clustered body, each drawn at the detail its own distance earns.
@@ -57,6 +68,16 @@ export interface IClusteredBatchOptions {
57
68
  readonly distanceRatio?: number;
58
69
  /** Screen-space error budget in pixels, as {@link ClusteredMesh}. Default 1. */
59
70
  readonly errorPixels?: number;
71
+ /**
72
+ * Whether copies the camera cannot see are skipped.
73
+ *
74
+ * On by default. A batch that casts shadows keeps every copy regardless — a copy out of the main
75
+ * view can still cast into it — until shadows have a cut of their own. The batch reports what it
76
+ * did through {@link ClusteredBatch.viewCullReport}.
77
+ */
78
+ readonly viewCull?: boolean;
79
+ /** How far the camera may turn, in radians, before the bands are taken again. Default two degrees. */
80
+ readonly viewMargin?: number;
60
81
  /** The shape every copy draws, carrying the baked cluster table. */
61
82
  readonly geometry: BufferGeometry;
62
83
  /** The surface every copy draws with, supplied by the game and used by reference. */
@@ -99,6 +120,8 @@ const DEFAULT_RECUT_FRACTION = 0.01;
99
120
  const DEFAULT_ERROR_PIXELS = 1;
100
121
  /** A copy nearer than this is treated as this far away, rather than taking log of zero. */
101
122
  const MIN_DISTANCE = 1e-3;
123
+ /** A copy the view does not hold: it joins no band, anchors no cut, and submits nothing. */
124
+ const CULLED = -2147483648;
102
125
 
103
126
  interface IPlaced {
104
127
  readonly matrix: Matrix4;
@@ -163,14 +186,34 @@ export class ClusteredBatch {
163
186
  readonly #cameraWorld = new Vector3();
164
187
  readonly #cameraLocal = new Vector3();
165
188
  readonly #lastCut = new Vector3();
189
+ readonly #rotation = new Quaternion();
190
+ readonly #lastRotation = new Quaternion();
191
+ readonly #view = new ClusterView();
166
192
  #hasCut = false;
167
193
  #lastScale = 0;
194
+ /** The projection the bands were chosen by: an aspect or zoom change keeps the pixel scale. */
195
+ readonly #lastProjection = new Matrix4();
196
+ #culled = false;
168
197
  readonly #distanceRatio: number;
198
+ /** Radians the camera may turn before the bands are taken again. */
199
+ readonly viewMargin: number;
200
+ /**
201
+ * Whether copies the camera cannot see are skipped. Writable; the batch reports what it did
202
+ * through {@link ClusteredBatch.viewCullReport}.
203
+ */
204
+ viewCull: boolean;
169
205
  /** Bands this camera wants that are not built yet; while any remain the cut cannot settle. */
170
206
  #pending = 0;
171
207
  #root: Object3D | null = null;
172
208
  #built: IClusteredBatchBuildOptions | null = null;
173
209
  #drawnTriangles = 0;
210
+ readonly #meshRadius: number;
211
+ readonly #frustum = new Frustum();
212
+ readonly #viewMatrix = new Matrix4();
213
+ /** The band each copy was drawn in this update, or `CULLED` when it was not drawn at all. */
214
+ #bandKey: Int32Array;
215
+ #drawnCopiesOutsideView = 0;
216
+ #drawnTrianglesOutsideView = 0;
174
217
 
175
218
  constructor(options: IClusteredBatchOptions) {
176
219
  this.#options = options;
@@ -179,8 +222,13 @@ export class ClusteredBatch {
179
222
  throw new Error(
180
223
  `ClusteredBatch distanceRatio must be above one, got ${this.#distanceRatio}.`,
181
224
  );
225
+ this.viewCull = options.viewCull ?? true;
226
+ this.viewMargin = options.viewMargin ?? DEFAULT_VIEW_MARGIN;
227
+ assertViewMargin(this.viewMargin);
182
228
  this.#selection = new Uint32Array(options.table.ranges.length / 2);
183
229
  this.#wantedKey = new Int32Array(0);
230
+ this.#bandKey = new Int32Array(0);
231
+ this.#meshRadius = clusterTableRadius(options.table);
184
232
  }
185
233
 
186
234
  /** How many copies are placed. */
@@ -200,6 +248,33 @@ export class ClusteredBatch {
200
248
  return this.#drawnTriangles;
201
249
  }
202
250
 
251
+ /**
252
+ * Copies the current cut submits whose own bounding sphere lies wholly outside the view volume.
253
+ *
254
+ * A measurement, not a cull: see {@link ClusteredMesh.drawnTrianglesOutsideView}.
255
+ */
256
+ get drawnCopiesOutsideView(): number {
257
+ return this.#drawnCopiesOutsideView;
258
+ }
259
+
260
+ /** Triangles those copies submit: their own band's cut, times how many copies are outside. */
261
+ get drawnTrianglesOutsideView(): number {
262
+ return this.#drawnTrianglesOutsideView;
263
+ }
264
+
265
+ /**
266
+ * What this batch does about copies outside the view, and why.
267
+ *
268
+ * `"on"` when copies the camera cannot see are skipped, and a reason when they are not — a batch
269
+ * that silently kept drawing a whole copy behind the camera would be a cost with no symptom, and
270
+ * one that silently dropped what a shadow camera can see would be a missing shadow with no cause.
271
+ */
272
+ get viewCullReport(): string {
273
+ if (!this.viewCull) return "off (viewCull = false)";
274
+ if (this.#built?.castShadow === true) return "off (castShadow)";
275
+ return "on";
276
+ }
277
+
203
278
  /** Adds one copy. Returns its index, so the game can move it later. */
204
279
  place(placement: IClusteredPlacement): number {
205
280
  if (this.#built !== null)
@@ -238,32 +313,67 @@ export class ClusteredBatch {
238
313
  const scale = pixelsPerUnit(camera, viewportHeight);
239
314
  camera.updateWorldMatrix(true, false);
240
315
  this.#cameraWorld.setFromMatrixPosition(camera.matrixWorld);
316
+ camera.getWorldQuaternion(this.#rotation);
317
+
318
+ // A culled batch is a batch whose bands were chosen for a view, so the turn it was widened by is
319
+ // part of what makes the previous cut still right. `castShadow` keeps every copy: one outside
320
+ // the main view can still be cast into it.
321
+ const culled = this.viewCull && this.#built?.castShadow !== true;
322
+ if (culled) {
323
+ this.#view.setFromCamera(camera, this.viewMargin);
324
+ // Copies are placed in the batch root's space; a parent that moves the batch moves them too.
325
+ root.updateWorldMatrix(true, false);
326
+ this.#view.setTransform(root.matrixWorld);
327
+ }
241
328
 
242
329
  // Everything below walks every cluster of every occupied band. Skip it outright when the camera
243
- // has not moved enough to change a cut, and when every band this camera needs is already built.
330
+ // has not moved or turned enough to change a cut, and when every band this camera needs is
331
+ // already built.
244
332
  let nearestCopy = Number.POSITIVE_INFINITY;
245
333
  for (const placed of this.#placed)
246
334
  nearestCopy = Math.min(nearestCopy, this.#cameraWorld.distanceTo(placed.position));
247
335
  const settled =
248
336
  this.#hasCut &&
337
+ culled === this.#culled &&
249
338
  scale === this.#lastScale &&
339
+ camera.projectionMatrix.equals(this.#lastProjection) &&
250
340
  this.#pending === 0 &&
341
+ this.#rotation.angleTo(this.#lastRotation) <= this.viewMargin &&
251
342
  this.#cameraWorld.distanceTo(this.#lastCut) <=
252
343
  Math.max(nearestCopy, MIN_DISTANCE) *
253
344
  (this.#options.recutFraction ?? DEFAULT_RECUT_FRACTION);
254
345
  if (settled) return this.#drawnTriangles;
255
346
  this.#lastCut.copy(this.#cameraWorld);
347
+ this.#lastRotation.copy(this.#rotation);
256
348
  this.#lastScale = scale;
349
+ this.#lastProjection.copy(camera.projectionMatrix);
350
+ this.#culled = culled;
257
351
  this.#hasCut = true;
258
352
 
259
- if (this.#wantedKey.length !== this.#placed.length)
353
+ if (this.#wantedKey.length !== this.#placed.length) {
260
354
  this.#wantedKey = new Int32Array(this.#placed.length);
355
+ this.#bandKey = new Int32Array(this.#placed.length);
356
+ }
261
357
  for (const group of this.#groups.values()) group.copies.length = 0;
262
358
 
263
359
  // Which band each copy belongs to, before any borrowing.
264
360
  const wantedKeys = new Set<number>();
265
361
  for (let copy = 0; copy < this.#placed.length; copy += 1) {
266
362
  const placed = this.#placed[copy] as IPlaced;
363
+ // A copy no camera can see joins no band, anchors no cut and submits nothing. Its own bounding
364
+ // sphere is the test, the same sphere three would cull it by.
365
+ if (
366
+ culled &&
367
+ !this.#view.touches(
368
+ placed.position.x,
369
+ placed.position.y,
370
+ placed.position.z,
371
+ this.#meshRadius * placed.scale,
372
+ )
373
+ ) {
374
+ this.#wantedKey[copy] = CULLED;
375
+ continue;
376
+ }
267
377
  const distance = Math.max(this.#cameraWorld.distanceTo(placed.position), MIN_DISTANCE);
268
378
  // Grouped on distance measured in the body's own units, so two copies at different scales
269
379
  // that cover the same screen area land in the same group.
@@ -291,7 +401,12 @@ export class ClusteredBatch {
291
401
 
292
402
  for (let copy = 0; copy < this.#placed.length; copy += 1) {
293
403
  const wanted = this.#wantedKey[copy] as number;
404
+ if (wanted === CULLED) {
405
+ this.#bandKey[copy] = CULLED;
406
+ continue;
407
+ }
294
408
  const key = open.has(wanted) ? wanted : this.#nearestOpenKey(wanted, open);
409
+ this.#bandKey[copy] = key;
295
410
  let group = this.#groups.get(key);
296
411
  if (group === undefined) {
297
412
  group = { copies: [], cut: new Uint32Array(0), empty: 0, mesh: null };
@@ -308,9 +423,33 @@ export class ClusteredBatch {
308
423
  this.#groups.delete(key);
309
424
  }
310
425
  }
426
+ this.#countOutsideView(camera);
311
427
  return this.#drawnTriangles;
312
428
  }
313
429
 
430
+ /**
431
+ * Records how many copies of this batch, and how many of their triangles, lie wholly out of view.
432
+ *
433
+ * A copy is tested on its own bounding sphere — the body's radius at the copy's scale — which is
434
+ * the sphere three itself would cull it by. Read-only, and taken only on a frame that re-cut.
435
+ */
436
+ #countOutsideView(camera: Camera): void {
437
+ const frustum = worldFrustum(camera, this.#frustum, this.#viewMatrix);
438
+ let copies = 0;
439
+ let triangles = 0;
440
+ for (let copy = 0; copy < this.#placed.length; copy += 1) {
441
+ if ((this.#bandKey[copy] as number) === CULLED) continue;
442
+ const placed = this.#placed[copy] as IPlaced;
443
+ if (!outsideFrustum(frustum, placed.position, this.#meshRadius * placed.scale)) continue;
444
+ copies += 1;
445
+ const group = this.#groups.get(this.#bandKey[copy] as number);
446
+ const mesh = group?.mesh;
447
+ if (mesh?.visible === true) triangles += mesh.geometry.drawRange.count / 3;
448
+ }
449
+ this.#drawnCopiesOutsideView = copies;
450
+ this.#drawnTrianglesOutsideView = triangles;
451
+ }
452
+
314
453
  /**
315
454
  * Gives one group's index buffer back.
316
455
  *
@@ -388,6 +527,10 @@ export class ClusteredBatch {
388
527
  this.#options.errorPixels ?? DEFAULT_ERROR_PIXELS,
389
528
  this.#selection,
390
529
  );
530
+ // Every band's cut is taken unpruned, on purpose. One cut serves every copy in the band, and
531
+ // those copies face the camera from different directions: pruning it by the view would drop the
532
+ // clusters the copies either side of the band are looking at. What a band does not hold is
533
+ // culled per copy, above.
391
534
  let indices = 0;
392
535
  for (let slot = 0; slot < selected; slot += 1)
393
536
  indices += this.#options.table.ranges[(this.#selection[slot] as number) * 2 + 1] as number;