@umicat/three-sdk 1.7.0 → 1.9.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.
@@ -54,6 +54,11 @@ export interface LoadedScene3D {
54
54
  update(dt: number): void;
55
55
  dispose(): void;
56
56
  }
57
+ export declare function applyTransform(obj: THREE.Object3D, e: Entity3D): void;
58
+ export declare const MATERIAL_LIBRARY: Record<string, {
59
+ color: string;
60
+ roughness: string;
61
+ }>;
57
62
  export declare function makePrimitive(e: Entity3D): THREE.Mesh;
58
63
  /**
59
64
  * Turn scene3d design data into a running three.js scene.
@@ -20,7 +20,7 @@ function isRigged(root) {
20
20
  rigged = true; });
21
21
  return rigged;
22
22
  }
23
- function applyTransform(obj, e) {
23
+ export function applyTransform(obj, e) {
24
24
  const t = e.transform;
25
25
  obj.position.copy(toVec(t.position));
26
26
  const q = t.rotation ?? IDENTITY_QUAT;
@@ -37,12 +37,53 @@ function applyTransform(obj, e) {
37
37
  * `computeVertexNormals()` yields one flat normal per FACE rather than
38
38
  * blending across a shared vertex between two faces at different angles
39
39
  * (which would wrongly soften the wedge's sharp ridge edge into a curve).
40
+ *
41
+ * ADR-044 — also assigns a UV per vertex, dominant-axis PLANAR per face
42
+ * (box/sphere/cylinder/plane all already have usable UVs from three.js's
43
+ * own geometry constructors; these two hand-built shapes had none at all
44
+ * before this). Each face is flat by construction, so the face's own
45
+ * normal (computed directly from its 3 points — BEFORE
46
+ * `computeVertexNormals()` blends anything) picks which two of the three
47
+ * local axes to project onto: a face whose normal is mostly ±X reads its
48
+ * UV from (y,z), mostly ±Y from (x,z), mostly ±Z from (x,y). `size` scales
49
+ * the projection so UV spans ~0..1 per face — the SAME convention
50
+ * `BoxGeometry`'s own per-face UVs already use, which is what lets
51
+ * `makePrimitive`'s `texture.repeat` math treat every primitive kind
52
+ * uniformly regardless of which one actually has native UVs.
40
53
  */
41
- function triangleListGeometry(triangles) {
54
+ function triangleListGeometry(triangles, size) {
42
55
  const positions = new Float32Array(triangles.length * 3);
56
+ const uvs = new Float32Array(triangles.length * 2);
43
57
  triangles.forEach((v, i) => { positions[i * 3] = v.x; positions[i * 3 + 1] = v.y; positions[i * 3 + 2] = v.z; });
58
+ for (let i = 0; i < triangles.length; i += 3) {
59
+ const a = triangles[i], b = triangles[i + 1], c = triangles[i + 2];
60
+ const ab = new THREE.Vector3(b.x - a.x, b.y - a.y, b.z - a.z);
61
+ const ac = new THREE.Vector3(c.x - a.x, c.y - a.y, c.z - a.z);
62
+ const n = new THREE.Vector3().crossVectors(ab, ac);
63
+ const ax = Math.abs(n.x), ay = Math.abs(n.y), az = Math.abs(n.z);
64
+ for (let k = 0; k < 3; k++) {
65
+ const v = triangles[i + k];
66
+ let u, w;
67
+ if (ax >= ay && ax >= az) {
68
+ u = v.y / size.y;
69
+ w = v.z / size.z;
70
+ }
71
+ else if (ay >= ax && ay >= az) {
72
+ u = v.x / size.x;
73
+ w = v.z / size.z;
74
+ }
75
+ else {
76
+ u = v.x / size.x;
77
+ w = v.y / size.y;
78
+ }
79
+ const idx = i + k;
80
+ uvs[idx * 2] = u + 0.5;
81
+ uvs[idx * 2 + 1] = w + 0.5;
82
+ }
83
+ }
44
84
  const geom = new THREE.BufferGeometry();
45
85
  geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));
86
+ geom.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));
46
87
  geom.computeVertexNormals();
47
88
  return geom;
48
89
  }
@@ -56,7 +97,7 @@ function wedgeGeometry(size) {
56
97
  v0, v3, v4, // left end cap
57
98
  v1, v5, v2, // right end cap
58
99
  v3, v2, v4, v2, v5, v4, // slope (hypotenuse)
59
- ]);
100
+ ], size);
60
101
  }
61
102
  /** Winding verified by hand the same way as `wedgeGeometry` — see
62
103
  * `scene3d.ts`'s `cornerWedgeVertices` doc comment for the vertex layout. */
@@ -68,7 +109,78 @@ function cornerWedgeGeometry(size) {
68
109
  v1, v4, v2, // right side
69
110
  v2, v4, v3, // front side
70
111
  v3, v4, v0, // left side
71
- ]);
112
+ ], size);
113
+ }
114
+ /**
115
+ * ADR-044 — the built-in Parts material library. A NAME resolves to two
116
+ * CDN-hosted maps (Color + Roughness only — see the ADR's own "game-grade,
117
+ * not showcase-grade" scoping for why Normal/Displacement/AO aren't here),
118
+ * re-hosted (not linked to the source) under the platform-wide, already-
119
+ * public `platform/` S3 prefix (`cdn.umicat.ai/platform/...` — the same
120
+ * prefix `platform/canonical-rig/v1/...` already uses for the Model
121
+ * Editor's auto-rig skeleton; no bucket-policy change was needed). Sourced
122
+ * from ambientCG (CC0), reprocessed to 512×512 JPEG.
123
+ */
124
+ const MATERIAL_BASE = 'https://cdn.umicat.ai/platform/three-sdk-materials';
125
+ export const MATERIAL_LIBRARY = Object.fromEntries(['concrete', 'brick', 'wood', 'metal', 'cardboard', 'rock', 'grass', 'tile'].map((name) => [
126
+ name, { color: `${MATERIAL_BASE}/${name}/color.jpg`, roughness: `${MATERIAL_BASE}/${name}/roughness.jpg` },
127
+ ]));
128
+ /** How many world units one tile of a material's source photo covers —
129
+ * matched loosely to each photo's own real-world scale so e.g. brick
130
+ * courses read as actual brick-sized, not a wall-sized or postage-stamp-
131
+ * sized repeat. Same role `groundRestOffset` plays for placement: a
132
+ * small per-kind constant rather than a universal formula, because there
133
+ * isn't one — these are real photos at real physical scales. */
134
+ const MATERIAL_TILE_UNIT = {
135
+ concrete: 1, brick: 0.5, wood: 1, metal: 1, cardboard: 0.6, rock: 1, grass: 1, tile: 0.5,
136
+ };
137
+ const materialTextures = new Map();
138
+ let materialLoader = null;
139
+ /** Load (and cache) one material-library texture. `colorSpace` distinguishes
140
+ * the Color map (sRGB — it's a photographed colour) from Roughness (a data
141
+ * map — tagging it sRGB would wrongly remap its own numeric values, the
142
+ * same class of mistake `Skin.ts`'s texture loader already guards against
143
+ * for the opposite reason). Unlike `Skin.ts`'s `loadSkinTexture`, `flipY`
144
+ * is left at the `TextureLoader` DEFAULT (`true`) — these primitives use
145
+ * three.js's own standard UV convention (both the native box/sphere/
146
+ * cylinder/plane geometries AND `triangleListGeometry`'s hand-rolled UVs
147
+ * above), not GLTFLoader's inverted one; copying Skin.ts's `flipY=false`
148
+ * here would flip every Parts material upside down. */
149
+ function loadMaterialTexture(url, colorSpace) {
150
+ const key = `${url}|${colorSpace}`;
151
+ const hit = materialTextures.get(key);
152
+ if (hit)
153
+ return hit;
154
+ materialLoader ?? (materialLoader = new THREE.TextureLoader());
155
+ const p = materialLoader.loadAsync(url).then((t) => {
156
+ t.colorSpace = colorSpace;
157
+ t.wrapS = t.wrapT = THREE.RepeatWrapping;
158
+ return t;
159
+ });
160
+ materialTextures.set(key, p);
161
+ // A failed fetch must not be remembered as the answer — same reasoning
162
+ // Skin.ts's cache already documents.
163
+ p.catch(() => materialTextures.delete(key));
164
+ return p;
165
+ }
166
+ /**
167
+ * ADR-044 — how many times a material's texture repeats across a Part,
168
+ * per axis. box/plane/wedge/corner-wedge all use width×depth (the closest
169
+ * single approximation to "looks right" across a shape with several
170
+ * differently-sized faces — a perfect per-face repeat would need a scale
171
+ * baked in per face, not worth it for a blockout tool); cylinder uses
172
+ * diameter×height; sphere uses diameter on both axes (no clean width-vs-
173
+ * depth distinction on a sphere for tiling purposes).
174
+ */
175
+ function materialRepeatFor(kind, size, tileUnit) {
176
+ const u = (n) => Math.max(0.1, n / tileUnit);
177
+ if (kind === 'cylinder')
178
+ return new THREE.Vector2(u(size.x), u(size.y));
179
+ if (kind === 'sphere') {
180
+ const d = u(size.x);
181
+ return new THREE.Vector2(d, d);
182
+ }
183
+ return new THREE.Vector2(u(size.x), u(size.z));
72
184
  }
73
185
  export function makePrimitive(e) {
74
186
  const p = e.primitive;
@@ -87,7 +199,7 @@ export function makePrimitive(e) {
87
199
  // measurement still says the character is dead centre, because it is —
88
200
  // behind a 40x40 wall.
89
201
  : new THREE.PlaneGeometry(s.x, s.z).rotateX(-Math.PI / 2);
90
- const mesh = new THREE.Mesh(geom, new THREE.MeshStandardMaterial({
202
+ const material = new THREE.MeshStandardMaterial({
91
203
  color: new THREE.Color(p.color ?? '#c8c8c8'), roughness: 0.85,
92
204
  // The wedge/corner-wedge faces' winding was verified by hand (no
93
205
  // browser available to render and visually confirm it in this pass) —
@@ -95,9 +207,42 @@ export function makePrimitive(e) {
95
207
  // making a face invisible from its intended viewing side; it costs a
96
208
  // little backface-culling perf on two low-poly shapes, not correctness.
97
209
  side: (p.kind === 'wedge' || p.kind === 'corner-wedge') ? THREE.DoubleSide : THREE.FrontSide,
98
- }));
210
+ });
211
+ const mesh = new THREE.Mesh(geom, material);
99
212
  mesh.castShadow = p.kind !== 'plane';
100
213
  mesh.receiveShadow = true;
214
+ // ADR-044 — flat color renders IMMEDIATELY above; a material's textures
215
+ // arrive async and patch the material in place once loaded (same "good
216
+ // default now, real thing when it's ready" shape as every other
217
+ // CDN-texture consumer in this SDK). A missing/renamed material name, or
218
+ // a failed fetch, silently keeps the flat color rather than erroring —
219
+ // this is cosmetic, not a thing worth surfacing as a broken scene.
220
+ const libEntry = p.material ? MATERIAL_LIBRARY[p.material] : undefined;
221
+ if (libEntry) {
222
+ const repeat = materialRepeatFor(p.kind, s, MATERIAL_TILE_UNIT[p.material] ?? 1);
223
+ void Promise.all([
224
+ loadMaterialTexture(libEntry.color, THREE.SRGBColorSpace),
225
+ loadMaterialTexture(libEntry.roughness, THREE.NoColorSpace),
226
+ ]).then(([colorTex, roughTex]) => {
227
+ // Cloned, not assigned directly — the cache shares ONE texture per
228
+ // url across every Part using this material, and `.repeat` is
229
+ // per-INSTANCE (a 1×1 block and a 10×10 platform using the same
230
+ // "brick" material need different repeat counts). Assigning the
231
+ // cached texture directly would make every Part sharing a material
232
+ // fight over the last-set repeat value — the exact "clones share
233
+ // materials" trap `Skin.ts` already documents, one level up (here
234
+ // it's the TEXTURE being shared, not the material).
235
+ const map = colorTex.clone();
236
+ const roughnessMap = roughTex.clone();
237
+ map.repeat.copy(repeat);
238
+ roughnessMap.repeat.copy(repeat);
239
+ map.needsUpdate = true;
240
+ roughnessMap.needsUpdate = true;
241
+ material.map = map;
242
+ material.roughnessMap = roughnessMap;
243
+ material.needsUpdate = true;
244
+ }).catch(() => { });
245
+ }
101
246
  return mesh;
102
247
  }
103
248
  /**
@@ -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 } from '../SceneLoader3D.js';
3
+ import { loadScene3D, loadModelAsset, makePrimitive, 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';
@@ -393,6 +393,49 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
393
393
  scale: { x: o.scale.x, y: o.scale.y, z: o.scale.z },
394
394
  };
395
395
  };
396
+ // ADR-045 — test-only readback of an entity's WORLD position, distinct
397
+ // from `__umicatEntityTransform` above which returns LOCAL (parent-
398
+ // relative) position. Needed because `Object3D.attach()` (reparenting)
399
+ // deliberately CHANGES local position to preserve world position — a
400
+ // test asserting "position unchanged across a reparent" must check
401
+ // world, not local, or it fails on perfectly correct behavior.
402
+ globalThis.__umicatEntityWorldPosition =
403
+ (entityId) => {
404
+ const o = objectByEntity.get(entityId);
405
+ if (!o)
406
+ return null;
407
+ const p = o.getWorldPosition(new THREE.Vector3());
408
+ return { x: p.x, y: p.y, z: p.z };
409
+ };
410
+ // ADR-044 — test-only readback of a Part's live material state: whether
411
+ // its async-loaded textures actually landed (`hasMap`/`hasRoughnessMap`),
412
+ // what repeat they resolved to (proves `materialRepeatFor`'s size-based
413
+ // math reached the live object, not just that SOME texture loaded), and
414
+ // the map's own source url (proves the right material NAME resolved to
415
+ // the right CDN file). No pixel-level visual check is possible without a
416
+ // real screenshot; this is what a test CAN assert without one.
417
+ globalThis.__umicatPrimitiveMaterial =
418
+ (entityId) => {
419
+ const o = objectByEntity.get(entityId);
420
+ if (!o || !(o instanceof THREE.Mesh))
421
+ return null;
422
+ const mat = o.material;
423
+ const geom = o.geometry;
424
+ const posAttr = geom.getAttribute('position');
425
+ const uvAttr = geom.getAttribute('uv');
426
+ return {
427
+ hasMap: !!mat.map,
428
+ hasRoughnessMap: !!mat.roughnessMap,
429
+ mapRepeat: mat.map ? { x: mat.map.repeat.x, y: mat.map.repeat.y } : null,
430
+ mapUrl: mat.map?.source?.data?.currentSrc
431
+ ?? mat.map?.source?.data?.src ?? null,
432
+ vertexCount: posAttr ? posAttr.count : 0,
433
+ // 0 (no uv attribute at all — the pre-ADR-044 state for wedge/
434
+ // corner-wedge) vs a real count, matching position's, is exactly
435
+ // the distinction this exists to prove.
436
+ uvCount: uvAttr ? uvAttr.count : 0,
437
+ };
438
+ };
396
439
  // Test-only — the MAIN camera's current pose, for the desktop camera
397
440
  // controls test suite (left-select/right-look/WASD/QE) to assert against
398
441
  // without hand-deriving projection math — same posture as every other
@@ -434,6 +477,14 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
434
477
  let lookDragging = false;
435
478
  let lastLookX = 0;
436
479
  let lastLookY = 0;
480
+ // ADR-045 — right-click-NO-drag opens the context menu; right-click-DRAG
481
+ // orbits the camera (the look-drag state just above). Same "orbit-vs-
482
+ // click" distinction `downX`/`downY`/`moved` already draws for the LEFT
483
+ // button, tracked separately because `onPointerDown`'s button===2 branch
484
+ // returns before ever touching those.
485
+ let rightDownX = 0;
486
+ let rightDownY = 0;
487
+ let rightMoved = false;
437
488
  // Entity drag — Phase 1 of real editing (translate only, ground-plane
438
489
  // constrained). Grabbing on an entity moves it; grabbing empty space/sky
439
490
  // still orbits, same convention as Unity/Blender. Whether THIS gesture is
@@ -568,6 +619,9 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
568
619
  lookDragging = true;
569
620
  lastLookX = e.clientX;
570
621
  lastLookY = e.clientY;
622
+ rightDownX = e.clientX;
623
+ rightDownY = e.clientY;
624
+ rightMoved = false;
571
625
  try {
572
626
  renderer.domElement.setPointerCapture(e.pointerId);
573
627
  }
@@ -646,6 +700,8 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
646
700
  };
647
701
  const onPointerMove = (e) => {
648
702
  if (lookDragging) {
703
+ if (Math.abs(e.clientX - rightDownX) > 4 || Math.abs(e.clientY - rightDownY) > 4)
704
+ rightMoved = true;
649
705
  applyLookDelta(e.clientX - lastLookX, e.clientY - lastLookY);
650
706
  lastLookX = e.clientX;
651
707
  lastLookY = e.clientY;
@@ -686,6 +742,33 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
686
742
  catch {
687
743
  // Already released, or never captured.
688
744
  }
745
+ // ADR-045 — a right-click that didn't rotate the camera opens the
746
+ // context menu. Same hit-test + selection side effects a left click
747
+ // already runs (marker/selectionBox/gizmo + `pickPoint3d`) — Roblox
748
+ // itself selects-on-right-click too, so right-clicking an unselected
749
+ // Part both selects it AND opens its menu in one action, rather than
750
+ // requiring a left-click first. Empty space still deselects, but
751
+ // still posts the menu message (with `entityId: null`) — the host
752
+ // decides whether an empty-space menu is worth showing (e.g. Paste).
753
+ if (!scene || rightMoved)
754
+ return;
755
+ const hit = pickEntityAt(e);
756
+ if (!hit) {
757
+ clearWorldSelection();
758
+ if (hudSelectedId)
759
+ selectHudEntity(null);
760
+ window.parent.postMessage({ type: 'umicat:editor:contextMenu3d', entityId: null, clientX: e.clientX, clientY: e.clientY }, '*');
761
+ return;
762
+ }
763
+ if (hudSelectedId)
764
+ selectHudEntity(null);
765
+ marker.position.copy(hit.point);
766
+ marker.visible = true;
767
+ selectionBox.setFromObject(hit.entityRoot);
768
+ selectionBox.visible = true;
769
+ gizmo.attach(hit.entityRoot, camera);
770
+ window.parent.postMessage({ type: 'umicat:editor:pickPoint3d', x: hit.point.x, y: hit.point.y, z: hit.point.z, entityId: hit.entityId }, '*');
771
+ window.parent.postMessage({ type: 'umicat:editor:contextMenu3d', entityId: hit.entityId, clientX: e.clientX, clientY: e.clientY }, '*');
689
772
  return;
690
773
  }
691
774
  if (e.button !== 0)
@@ -803,6 +886,8 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
803
886
  return onDropModel3d(data);
804
887
  if (data.type === 'umicat:editor:dropPrimitive3d')
805
888
  return onDropPrimitive3d(data);
889
+ if (data.type === 'umicat:editor:createEntity3d')
890
+ return onCreateEntity3d(data);
806
891
  if (data.type === 'umicat:editor:deleteEntity3d')
807
892
  return onDeleteEntity3d(data);
808
893
  if (data.type === 'umicat:editor:setGizmoMode3d') {
@@ -906,6 +991,26 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
906
991
  // explicit refresh here, same as a live drag already does.
907
992
  selectionBox.setFromObject(object);
908
993
  }
994
+ if (m.patch?.parent !== undefined) {
995
+ // ADR-045 Phase 2 — reparent. `Object3D.attach` (standard three.js
996
+ // API) moves `object` under the new parent AND recomputes its local
997
+ // transform so its WORLD position/rotation/scale is unchanged —
998
+ // grouping an entity must not visually move it. `null` means attach
999
+ // to the scene root.
1000
+ const newParentObject = m.patch.parent === null ? scene : objectByEntity.get(m.patch.parent);
1001
+ if (!newParentObject)
1002
+ return done(`no parent entity '${m.patch.parent}' in the scene being shown`);
1003
+ newParentObject.attach(object);
1004
+ const authored = sceneData?.entities.find((en) => en.id === m.entityId);
1005
+ if (authored) {
1006
+ if (m.patch.parent === null)
1007
+ delete authored.parent;
1008
+ else
1009
+ authored.parent = m.patch.parent;
1010
+ }
1011
+ if (gizmo.attached === object)
1012
+ selectionBox.setFromObject(object);
1013
+ }
909
1014
  if (m.patch?.attachments !== undefined) {
910
1015
  const authored = sceneData?.entities.find((e) => e.id === m.entityId);
911
1016
  const asset = manifest?.models?.find((x) => x.id === authored?.modelAssetId);
@@ -950,16 +1055,36 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
950
1055
  const authored = sceneData?.entities.find((e) => e.id === m.entityId);
951
1056
  if (!authored?.primitive)
952
1057
  return done(`entity '${m.entityId}' is not a primitive Part`);
953
- authored.primitive = { ...authored.primitive, ...m.patch.primitive };
1058
+ // `material: null` (explicit clear) and `material: undefined` (key
1059
+ // omitted, don't touch) both arrive through the same patch bag, but
1060
+ // the STORED entity only ever has `material` present-with-a-string
1061
+ // or absent — `null` is a wire-only sentinel, never written to disk.
1062
+ const { material: materialPatch, ...restPatch } = m.patch.primitive;
1063
+ const merged = { ...authored.primitive, ...restPatch };
1064
+ if (materialPatch === null)
1065
+ delete merged.material;
1066
+ else if (materialPatch !== undefined)
1067
+ merged.material = materialPatch;
1068
+ authored.primitive = merged;
954
1069
  const fresh = makePrimitive(authored);
955
1070
  fresh.position.copy(object.position);
956
1071
  fresh.quaternion.copy(object.quaternion);
957
1072
  fresh.scale.copy(object.scale);
958
- fresh.castShadow = authored.primitive.kind !== 'plane';
1073
+ fresh.castShadow = merged.kind !== 'plane';
959
1074
  fresh.receiveShadow = true;
960
1075
  if (object instanceof THREE.Mesh) {
961
1076
  object.geometry.dispose();
962
- (Array.isArray(object.material) ? object.material : [object.material]).forEach((mat) => mat.dispose());
1077
+ (Array.isArray(object.material) ? object.material : [object.material]).forEach((mat) => {
1078
+ // ADR-044 — `map`/`roughnessMap` on a Parts material are PER-
1079
+ // INSTANCE clones (`makePrimitive`'s own doc comment), never the
1080
+ // shared cached texture — `Material.dispose()` does not reach
1081
+ // into its own maps, so leaving this out would leak one texture
1082
+ // per rebuild (every resize/recolor of a materialed Part).
1083
+ const std = mat;
1084
+ std.map?.dispose();
1085
+ std.roughnessMap?.dispose();
1086
+ mat.dispose();
1087
+ });
963
1088
  }
964
1089
  scene?.remove(object);
965
1090
  scene?.add(fresh);
@@ -1079,6 +1204,101 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1079
1204
  sceneData?.entities.push(entity);
1080
1205
  done(undefined, { x: object.position.x, y: object.position.y, z: object.position.z }, collider);
1081
1206
  }
1207
+ /**
1208
+ * ADR-045 — spawn a COMPLETE, host-supplied entity at its OWN authored
1209
+ * transform. The generic counterpart to `dropModel3d`/`dropPrimitive3d`
1210
+ * (both raycast-based: host sends a screen pixel, SDK finds where it
1211
+ * lands on the ground) — Paste/Duplicate need the opposite: place at an
1212
+ * EXPLICIT position (the original's, or a small offset from it), never
1213
+ * a raycast. Registers into the same `entityByObject`/`objectByEntity`/
1214
+ * `scene`/`sceneData` as every other creation path, so the result is
1215
+ * immediately pickable/draggable with zero changes to `pickEntityAt` or
1216
+ * the gizmo.
1217
+ *
1218
+ * Reuses `applyTransform` (position AND rotation AND scale — unlike a
1219
+ * fresh drop, a copy must preserve the ORIGINAL's full transform, not
1220
+ * just land at a ground point with identity rotation/scale) and, for a
1221
+ * model entity carrying a `skin`/`attachments`, best-effort re-applies
1222
+ * them too (logged, not fatal — a cosmetic miss on a re-skin must not
1223
+ * block the entity from existing at all, unlike a direct user-initiated
1224
+ * patch where failing loudly is correct).
1225
+ */
1226
+ async function onCreateEntity3d(m) {
1227
+ const e = m.entity;
1228
+ const done = (error) => {
1229
+ if (error)
1230
+ console.warn('[umicat/editor] 3D entity create failed:', e.id, error);
1231
+ window.parent.postMessage({ type: 'umicat:editor:entityCreated3d', entityId: e.id, ok: !error, error }, '*');
1232
+ };
1233
+ if (!scene)
1234
+ return done('no scene loaded yet');
1235
+ if (objectByEntity.has(e.id))
1236
+ return done(`entity '${e.id}' already exists in this scene`);
1237
+ let object;
1238
+ if (e.modelAssetId) {
1239
+ const asset = manifest?.models?.find((x) => x.id === e.modelAssetId);
1240
+ if (!asset)
1241
+ return done(`entity references model '${e.modelAssetId}', which the manifest does not define`);
1242
+ try {
1243
+ const loaded = await loadModelAsset(singleModelManifest(asset), e.modelAssetId, { assetBase: '' });
1244
+ object = loaded.object;
1245
+ }
1246
+ catch (err) {
1247
+ return done(err instanceof Error ? err.message : String(err));
1248
+ }
1249
+ object.traverse((n) => { n.castShadow = e.castShadow !== false; n.receiveShadow = true; });
1250
+ if (e.skin) {
1251
+ const path = asset.skins?.[e.skin];
1252
+ if (path) {
1253
+ try {
1254
+ await applySkin(object, path, { assetBase: '' });
1255
+ }
1256
+ catch (err) {
1257
+ console.warn('[umicat/editor] re-skin on create failed (kept base texture):', e.id, err);
1258
+ }
1259
+ }
1260
+ }
1261
+ if (e.attachments?.length) {
1262
+ try {
1263
+ const worn_ = await applyAttachments(object, asset, manifest, e.attachments, { assetBase: '', label: e.id });
1264
+ worn.set(e.id, worn_);
1265
+ }
1266
+ catch (err) {
1267
+ console.warn('[umicat/editor] re-attaching props on create failed (created bare):', e.id, err);
1268
+ }
1269
+ }
1270
+ }
1271
+ else if (e.primitive) {
1272
+ object = makePrimitive(e);
1273
+ object.castShadow = e.primitive.kind !== 'plane';
1274
+ object.receiveShadow = true;
1275
+ }
1276
+ else {
1277
+ // Neither model nor primitive — an empty transform/pivot node.
1278
+ // ADR-045 Phase 2's "Group as Model" container is exactly this.
1279
+ object = new THREE.Group();
1280
+ }
1281
+ applyTransform(object, e);
1282
+ // Honor an authored `parent` the same way `loadScene3D`'s own spawn loop
1283
+ // does — a pasted copy of a grouped entity carries its `parent` field
1284
+ // along (Copy reads the full entity JSON verbatim), and the authored
1285
+ // `transform` on such an entity is PARENT-LOCAL, not world. Defaulting
1286
+ // to `scene.add` here would silently place it at scene root with its
1287
+ // local offset misread as a world position — right on screen until the
1288
+ // next load, which WOULD honor `parent` and jump it.
1289
+ let parentObject = scene;
1290
+ if (e.parent) {
1291
+ const resolved = objectByEntity.get(e.parent);
1292
+ if (!resolved)
1293
+ return done(`entity references parent '${e.parent}', which does not exist in this scene`);
1294
+ parentObject = resolved;
1295
+ }
1296
+ parentObject.add(object);
1297
+ entityByObject.set(object, e.id);
1298
+ objectByEntity.set(e.id, object);
1299
+ sceneData?.entities.push(e);
1300
+ done();
1301
+ }
1082
1302
  /**
1083
1303
  * Frees a subtree's GPU resources the same way the whole-scene `dispose()`
1084
1304
  * in `SceneLoader3D.ts` does (geometry + material + every texture field a
@@ -1195,6 +1415,34 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1195
1415
  e.preventDefault();
1196
1416
  window.parent.postMessage({ type: 'umicat:editor:requestUndo3d' }, '*');
1197
1417
  }
1418
+ else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'c' && gizmo.attached) {
1419
+ // ADR-045 — same "ask, don't act" shape as Undo above: the CLIPBOARD
1420
+ // lives on the host (Copy is a pure read of the host's own scene
1421
+ // copy), so this player can't act on it locally the way Delete does.
1422
+ const entityId = entityByObject.get(gizmo.attached);
1423
+ if (entityId) {
1424
+ e.preventDefault();
1425
+ window.parent.postMessage({ type: 'umicat:editor:requestCopy3d', entityId }, '*');
1426
+ }
1427
+ }
1428
+ else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'x' && gizmo.attached) {
1429
+ const entityId = entityByObject.get(gizmo.attached);
1430
+ if (entityId) {
1431
+ e.preventDefault();
1432
+ window.parent.postMessage({ type: 'umicat:editor:requestCut3d', entityId }, '*');
1433
+ }
1434
+ }
1435
+ else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'v') {
1436
+ e.preventDefault();
1437
+ window.parent.postMessage({ type: 'umicat:editor:requestPaste3d' }, '*');
1438
+ }
1439
+ else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'd' && gizmo.attached) {
1440
+ const entityId = entityByObject.get(gizmo.attached);
1441
+ if (entityId) {
1442
+ e.preventDefault();
1443
+ window.parent.postMessage({ type: 'umicat:editor:requestDuplicate3d', entityId }, '*');
1444
+ }
1445
+ }
1198
1446
  });
1199
1447
  // WASD/QE fly-camera + Shift speed boost — held-STATE, not a discrete
1200
1448
  // action, so this is a separate keydown/keyup PAIR rather than folded
package/dist/scene3d.d.ts CHANGED
@@ -114,6 +114,17 @@ export interface Entity3D {
114
114
  kind: 'box' | 'sphere' | 'plane' | 'cylinder' | 'wedge' | 'corner-wedge';
115
115
  size?: Vec3;
116
116
  color?: string;
117
+ /**
118
+ * ADR-044 — a NAME from the built-in material library
119
+ * (`MATERIAL_LIBRARY` in `SceneLoader3D.ts`), not a URL: same
120
+ * convention as a model's `skin` (the SDK resolves it, nothing is
121
+ * authored per-scene). Omitted = flat `color` only, today's behavior
122
+ * — every Part authored before this field existed keeps rendering
123
+ * identically. `color` still applies when `material` is set (it
124
+ * tints the material's own color map, same as `MeshStandardMaterial`
125
+ * already does when both `color` and `map` are present).
126
+ */
127
+ material?: string;
117
128
  };
118
129
  collider?: Collider3D;
119
130
  /** Which clip to play on spawn, by SEMANTIC name — see `AnimationMap`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umicat/three-sdk",
3
- "version": "1.7.0",
3
+ "version": "1.9.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",