@umicat/three-sdk 1.19.0 → 1.20.0

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.
@@ -1,5 +1,5 @@
1
1
  import * as THREE from 'three';
2
- import { type Scene3D, type Manifest3D, type Entity3D, type Vec3, type Sky3D } from './scene3d.js';
2
+ import { type Scene3D, type Manifest3D, type Entity3D, type Vec3, type Sky3D, type Heightfield3D } from './scene3d.js';
3
3
  import { type WornMap } from './Attachments.js';
4
4
  export interface LoadSceneOptions {
5
5
  /** Base url assets resolve against (the project's asset host). */
@@ -70,6 +70,29 @@ export declare const MATERIAL_LIBRARY: Record<string, {
70
70
  * when they drag one in.
71
71
  */
72
72
  export declare function heightfieldGeometry(heights: Float32Array, n: number, size: Vec3): THREE.BufferGeometry;
73
+ /**
74
+ * ADR-050 — build one heightfield's surface and its collider grid.
75
+ *
76
+ * Exported because THREE callers need it and must not each reimplement it:
77
+ * `loadScene3D` below, the editor's live create, and the editor's live patch
78
+ * (a resize or a resolution change rebuilds the whole surface — there is no
79
+ * incremental edit of a heightmap-derived mesh). A second implementation is
80
+ * how the drawn surface and the walked surface drift apart, which is the one
81
+ * failure terrain cannot afford.
82
+ *
83
+ * The decoded pixels are cached per url, so calling this repeatedly for the
84
+ * same heightmap costs one fetch.
85
+ */
86
+ export declare function makeHeightfield(hf: Heightfield3D, manifest: Manifest3D, opts?: {
87
+ assetBase?: string;
88
+ }): Promise<{
89
+ mesh: THREE.Mesh;
90
+ grid: {
91
+ heights: Float32Array;
92
+ n: number;
93
+ size: Vec3;
94
+ };
95
+ }>;
73
96
  export declare function makePrimitive(e: Entity3D): THREE.Mesh;
74
97
  /**
75
98
  * Turn scene3d design data into a running three.js scene.
@@ -343,6 +343,46 @@ function heightmapPixels(url) {
343
343
  p.catch(() => heightmapPixelCache.delete(url));
344
344
  return p;
345
345
  }
346
+ /**
347
+ * ADR-050 — build one heightfield's surface and its collider grid.
348
+ *
349
+ * Exported because THREE callers need it and must not each reimplement it:
350
+ * `loadScene3D` below, the editor's live create, and the editor's live patch
351
+ * (a resize or a resolution change rebuilds the whole surface — there is no
352
+ * incremental edit of a heightmap-derived mesh). A second implementation is
353
+ * how the drawn surface and the walked surface drift apart, which is the one
354
+ * failure terrain cannot afford.
355
+ *
356
+ * The decoded pixels are cached per url, so calling this repeatedly for the
357
+ * same heightmap costs one fetch.
358
+ */
359
+ export async function makeHeightfield(hf, manifest, opts = {}) {
360
+ const entry = (manifest.heightmaps ?? []).find((h) => h.id === hf.assetId);
361
+ if (!entry) {
362
+ const have = (manifest.heightmaps ?? []).map((h) => h.id).join(', ');
363
+ throw new Error(`[umicat] manifest has no heightmap '${hf.assetId}'. It has: ${have || '(none)'}`);
364
+ }
365
+ const px = await heightmapPixels((opts.assetBase ?? '') + entry.path);
366
+ const seg = heightfieldSegments(hf);
367
+ const heights = resampleHeights(px.data, px.width, px.height, seg.render);
368
+ const material = new THREE.MeshStandardMaterial({ color: hf.color ?? '#ffffff' });
369
+ const mesh = new THREE.Mesh(heightfieldGeometry(heights, seg.render, hf.size), material);
370
+ // Terrain receives shadows and does not cast them. A surface this large
371
+ // casting into its own shadow map spends the map's whole resolution on one
372
+ // object and self-shadows into acne — the same reasoning that already turns
373
+ // shadow casting off for flat ground tiles.
374
+ mesh.castShadow = false;
375
+ mesh.receiveShadow = true;
376
+ applyMaterialLibrary(material, hf.material, hf.size, 'heightfield');
377
+ // The COLLIDER grid is resampled separately from the same heightmap.
378
+ // Collision wants the coarsest grid a player cannot feel; rendering wants
379
+ // the finest one that is affordable. Sharing one grid would tie them
380
+ // together for no reason beyond convenience.
381
+ const colliderHeights = seg.collider === seg.render
382
+ ? heights
383
+ : resampleHeights(px.data, px.width, px.height, seg.collider);
384
+ return { mesh, grid: { heights: colliderHeights, n: seg.collider, size: hf.size } };
385
+ }
346
386
  /** Resolution actually used, with the documented defaults applied. */
347
387
  function heightfieldSegments(h) {
348
388
  const render = h.segments ?? 128;
@@ -733,30 +773,9 @@ export async function loadScene3D(scene3d, manifest, opts = {}) {
733
773
  if (e.attachments?.length) {
734
774
  throw new Error(`entity '${e.id}' has attachments but no model to hang them on`);
735
775
  }
736
- const hf = e.heightfield;
737
- const px = heightmapPixelsById.get(hf.assetId);
738
- const seg = heightfieldSegments(hf);
739
- const heights = resampleHeights(px.data, px.width, px.height, seg.render);
740
- const material = new THREE.MeshStandardMaterial({ color: hf.color ?? '#ffffff' });
741
- const mesh = new THREE.Mesh(heightfieldGeometry(heights, seg.render, hf.size), material);
742
- // Terrain receives shadows and does not cast them. A surface this large
743
- // casting into its own shadow map spends the whole map's resolution on
744
- // one object and self-shadows into acne; the same reasoning already
745
- // turns shadow casting off for flat ground tiles.
746
- mesh.castShadow = false;
747
- mesh.receiveShadow = true;
748
- applyMaterialLibrary(material, hf.material, {
749
- x: hf.size.x, y: hf.size.y, z: hf.size.z,
750
- }, 'heightfield');
751
- // The COLLIDER grid is resampled separately — same heightmap, its own
752
- // resolution. Collision wants the coarsest grid a player cannot feel;
753
- // rendering wants the finest one that is affordable. Sharing one grid
754
- // would tie them together for no reason other than convenience.
755
- const colliderHeights = seg.collider === seg.render
756
- ? heights
757
- : resampleHeights(px.data, px.width, px.height, seg.collider);
758
- heightfieldGrids.set(e.id, { heights: colliderHeights, n: seg.collider, size: hf.size });
759
- obj = mesh;
776
+ const built = await makeHeightfield(e.heightfield, manifest, { assetBase: opts.assetBase });
777
+ heightfieldGrids.set(e.id, built.grid);
778
+ obj = built.mesh;
760
779
  }
761
780
  else {
762
781
  if (e.attachments?.length) {
@@ -1,6 +1,6 @@
1
1
  import * as THREE from 'three';
2
2
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
3
- import { loadScene3D, loadModelAsset, makePrimitive, applyTransform } from '../SceneLoader3D.js';
3
+ import { loadScene3D, loadModelAsset, makePrimitive, makeHeightfield, applyTransform } from '../SceneLoader3D.js';
4
4
  import { applySkin } from '../Skin.js';
5
5
  import { applyAttachments } from '../Attachments.js';
6
6
  import { singleModelManifest, defaultColliderForPrimitive, groundRestOffset } from '../scene3d.js';
@@ -531,6 +531,24 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
531
531
  // grid frames 100 units around a 20-unit scene, which reads as "the
532
532
  // editor opens zoomed out" rather than as a bug, and no assertion about
533
533
  // snapping itself would ever catch it.
534
+ // ADR-050 — test-only readback of a heightfield's live state. `gizmoAttached`
535
+ // is here because the thing most likely to break on a rebuild is not the
536
+ // geometry (visibly wrong) but the instance SWAP: a gizmo still pointing at
537
+ // the disposed mesh renders its handles and moves nothing.
538
+ globalThis.__umicatEntityMesh =
539
+ (entityId) => {
540
+ const o = objectByEntity.get(entityId);
541
+ if (!o)
542
+ return null;
543
+ const mesh = o;
544
+ const pos = mesh.geometry?.getAttribute?.('position');
545
+ const mat = mesh.material;
546
+ return {
547
+ vertexCount: pos ? pos.count : 0,
548
+ hasMaterialMap: !!(mat && !Array.isArray(mat) && mat.map),
549
+ gizmoAttached: gizmo.attached === o,
550
+ };
551
+ };
534
552
  globalThis.__umicatSnapState =
535
553
  () => ({
536
554
  enabled: snapEnabled,
@@ -1735,54 +1753,34 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1735
1753
  fresh.scale.copy(object.scale);
1736
1754
  fresh.castShadow = merged.kind !== 'plane';
1737
1755
  fresh.receiveShadow = true;
1738
- if (object instanceof THREE.Mesh) {
1739
- object.geometry.dispose();
1740
- (Array.isArray(object.material) ? object.material : [object.material]).forEach((mat) => {
1741
- // ADR-044 — `map`/`roughnessMap` on a Parts material are PER-
1742
- // INSTANCE clones (`makePrimitive`'s own doc comment), never the
1743
- // shared cached texture — `Material.dispose()` does not reach
1744
- // into its own maps, so leaving this out would leak one texture
1745
- // per rebuild (every resize/recolor of a materialed Part).
1746
- const std = mat;
1747
- std.map?.dispose();
1748
- std.roughnessMap?.dispose();
1749
- mat.dispose();
1750
- });
1751
- }
1752
- scene?.remove(object);
1753
- scene?.add(fresh);
1754
- entityByObject.delete(object);
1755
- entityByObject.set(fresh, m.entityId);
1756
- objectByEntity.set(m.entityId, fresh);
1757
- // Same object-instance swap the position/rotation/scale branch
1758
- // above already handles for the single-select visuals — `object`
1759
- // itself is being replaced, so anything keyed by the OLD instance
1760
- // (gizmo attachment, AND now `multiSelected`/`multiBoxes` — ADR-046)
1761
- // has to move to `fresh` or it silently points at a disposed object.
1762
- if (gizmo.attached === object) {
1763
- gizmo.detach();
1764
- gizmo.attach(fresh, camera);
1765
- selectionBox.setFromObject(fresh);
1766
- }
1767
- if (multiSelected.has(object)) {
1768
- multiSelected.delete(object);
1769
- multiSelected.add(fresh);
1770
- const box = multiBoxes.get(object);
1771
- if (box) {
1772
- multiBoxes.delete(object);
1773
- multiBoxes.set(fresh, box);
1774
- box.setFromObject(fresh);
1775
- }
1756
+ disposeMeshInPlace(object);
1757
+ object = swapEntityObject(object, fresh, m.entityId);
1758
+ }
1759
+ if (m.patch?.heightfield !== undefined) {
1760
+ // ADR-050 — a heightfield has no incremental edit: every patchable
1761
+ // field (size, either resolution, material, colour) changes the vertex
1762
+ // buffer or the material wholesale, so the surface is rebuilt through
1763
+ // the SAME `makeHeightfield` the scene load and the live create both
1764
+ // use. A second build path here is exactly how the drawn surface and
1765
+ // the walked surface drift apart, which is the one thing terrain cannot
1766
+ // afford to get wrong.
1767
+ const authored = sceneData?.entities.find((e) => e.id === m.entityId);
1768
+ if (!authored?.heightfield)
1769
+ return done(`entity '${m.entityId}' is not a heightfield`);
1770
+ const merged = { ...authored.heightfield, ...m.patch.heightfield };
1771
+ authored.heightfield = merged;
1772
+ let fresh;
1773
+ try {
1774
+ fresh = (await makeHeightfield(merged, manifest, { assetBase: '' })).mesh;
1776
1775
  }
1777
- {
1778
- const box = negatedBoxes.get(object);
1779
- if (box) {
1780
- negatedBoxes.delete(object);
1781
- negatedBoxes.set(fresh, box);
1782
- box.setFromObject(fresh);
1783
- }
1776
+ catch (err) {
1777
+ return done(err instanceof Error ? err.message : String(err));
1784
1778
  }
1785
- object = fresh;
1779
+ fresh.position.copy(object.position);
1780
+ fresh.quaternion.copy(object.quaternion);
1781
+ fresh.scale.copy(object.scale);
1782
+ disposeMeshInPlace(object);
1783
+ object = swapEntityObject(object, fresh, m.entityId);
1786
1784
  }
1787
1785
  done();
1788
1786
  }
@@ -1961,6 +1959,14 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1961
1959
  object.castShadow = e.primitive.kind !== 'plane';
1962
1960
  object.receiveShadow = true;
1963
1961
  }
1962
+ else if (e.heightfield) {
1963
+ try {
1964
+ object = (await makeHeightfield(e.heightfield, manifest, { assetBase: '' })).mesh;
1965
+ }
1966
+ catch (err) {
1967
+ return err instanceof Error ? err.message : String(err);
1968
+ }
1969
+ }
1964
1970
  else {
1965
1971
  // Neither model nor primitive — an empty transform/pivot node.
1966
1972
  // ADR-045 Phase 2's "Group as Model" container is exactly this.
@@ -1989,6 +1995,65 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1989
1995
  setNegatedVisual(object, true);
1990
1996
  return undefined;
1991
1997
  }
1998
+ /**
1999
+ * Free a rebuilt mesh's own GPU resources.
2000
+ *
2001
+ * `map`/`roughnessMap` on a library material are PER-INSTANCE clones (see
2002
+ * `applyMaterialLibrary`), never the shared cached texture, and
2003
+ * `Material.dispose()` does not reach into its own maps — so leaving these
2004
+ * out leaks one texture per rebuild, i.e. per resize or recolour.
2005
+ */
2006
+ function disposeMeshInPlace(object) {
2007
+ if (!(object instanceof THREE.Mesh))
2008
+ return;
2009
+ object.geometry.dispose();
2010
+ (Array.isArray(object.material) ? object.material : [object.material]).forEach((mat) => {
2011
+ const std = mat;
2012
+ std.map?.dispose();
2013
+ std.roughnessMap?.dispose();
2014
+ mat.dispose();
2015
+ });
2016
+ }
2017
+ /**
2018
+ * Put `fresh` in `old`'s place everywhere the editor keys things by object
2019
+ * INSTANCE — the scene graph, both id maps, the gizmo attachment, the
2020
+ * multi-select set and its boxes (ADR-046), and the negated-Part box
2021
+ * (ADR-047). A rebuild that misses one of these leaves that map pointing at
2022
+ * a disposed object: no error, just a gizmo that moves nothing or a
2023
+ * selection box frozen where the old mesh used to be.
2024
+ *
2025
+ * Shared by every rebuild-in-place path rather than written per path, which
2026
+ * is the only way the list stays complete as more get added.
2027
+ */
2028
+ function swapEntityObject(old, fresh, entityId) {
2029
+ scene?.remove(old);
2030
+ scene?.add(fresh);
2031
+ entityByObject.delete(old);
2032
+ entityByObject.set(fresh, entityId);
2033
+ objectByEntity.set(entityId, fresh);
2034
+ if (gizmo.attached === old) {
2035
+ gizmo.detach();
2036
+ gizmo.attach(fresh, camera);
2037
+ selectionBox.setFromObject(fresh);
2038
+ }
2039
+ if (multiSelected.has(old)) {
2040
+ multiSelected.delete(old);
2041
+ multiSelected.add(fresh);
2042
+ const box = multiBoxes.get(old);
2043
+ if (box) {
2044
+ multiBoxes.delete(old);
2045
+ multiBoxes.set(fresh, box);
2046
+ box.setFromObject(fresh);
2047
+ }
2048
+ }
2049
+ const negated = negatedBoxes.get(old);
2050
+ if (negated) {
2051
+ negatedBoxes.delete(old);
2052
+ negatedBoxes.set(fresh, negated);
2053
+ negated.setFromObject(fresh);
2054
+ }
2055
+ return fresh;
2056
+ }
1992
2057
  async function onCreateEntity3d(m) {
1993
2058
  const error = await createEntityLive(m.entity);
1994
2059
  if (error)
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { ThreeUmicat } from './ThreeUmicat.js';
2
2
  export type { UmicatInitOptions } from './ThreeUmicat.js';
3
3
  export * from './scene3d.js';
4
- export { loadScene3D, loadModelAsset, heightfieldGeometry } from './SceneLoader3D.js';
4
+ export { loadScene3D, loadModelAsset, heightfieldGeometry, makeHeightfield } from './SceneLoader3D.js';
5
5
  export { CharacterController3D } from './CharacterController3D.js';
6
6
  export type { CharacterOptions, CharacterState, CharacterInput } from './CharacterController3D.js';
7
7
  export { CharacterAnimator } from './CharacterAnimator.js';
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // that turns it into a three.js scene with physics, and the runtime glue.
6
6
  export { ThreeUmicat } from './ThreeUmicat.js';
7
7
  export * from './scene3d.js';
8
- export { loadScene3D, loadModelAsset, heightfieldGeometry } from './SceneLoader3D.js';
8
+ export { loadScene3D, loadModelAsset, heightfieldGeometry, makeHeightfield } from './SceneLoader3D.js';
9
9
  export { CharacterController3D } from './CharacterController3D.js';
10
10
  export { CharacterAnimator } from './CharacterAnimator.js';
11
11
  export { Input3D } from './Input3D.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umicat/three-sdk",
3
- "version": "1.19.0",
3
+ "version": "1.20.0",
4
4
  "description": "Three.js runtime for Umicat games: the scene3d design format, its loader with physics, a kinematic character controller, and the Umicat platform via @umicat/platform-sdk.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",