@umicat/three-sdk 0.22.0 → 0.23.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.
package/README.md CHANGED
@@ -18,11 +18,14 @@ devices and binds keys everywhere, bone sockets, swappable skins and
18
18
  attachments, hit tints, audio, the editor's screenshot/video-capture protocol,
19
19
  and a read-and-write design view
20
20
  (`EditorDesignPlayer3D`: click-to-pick, drag-to-move, a host→iframe patch
21
- channel the platform Inspector drives, and drag-and-drop model placement —
21
+ channel the platform Inspector drives, drag-and-drop model placement —
22
22
  `umicat:editor:dropModel3d` in, `umicat:editor:modelDropped3d` out — which
23
23
  raycasts the drop point against the ground plane and fetches the GLB straight
24
- from its CDN url, no manifest entry required). What it still does not have: a
25
- rotate or scale gizmo, undo, or multi-select.
24
+ from its CDN url, no manifest entry required — and a full Roblox/Unity-style
25
+ 3-axis **Move/Rotate/Scale gizmo** on the selected entity, mode switched via
26
+ `umicat:editor:setGizmoMode3d`, posting `dragEnd3d`/`rotateEnd3d`/`scaleEnd3d`
27
+ on release). What it still does not have: undo, multi-select, or a local/
28
+ global axis toggle (the gizmo is local-space only).
26
29
 
27
30
  > This paragraph said "seed, not a product — no input system, no character
28
31
  > controller, no audio, and no published package" for ten minor versions after
@@ -23,13 +23,18 @@ export interface EditorDesignPlayer3DOptions {
23
23
  * marker reads off the exact world coordinate, posted to the host so a
24
24
  * person can point at a real spot instead of guessing one blind when
25
25
  * telling the AI where to place something.
26
- * - **Drag** an entity to move it (Phase 1 of real editing, ground-plane
27
- * constrained — position only, no rotation/scale, no gizmo, no
28
- * Inspector). This function itself never writes anything — it only
29
- * moves the live THREE.Object3D and posts the final LOCAL position on
30
- * release (`umicat:editor:dragEnd3d`); the host owns turning that into a
31
- * disk write. Grabbing empty space/sky orbits instead, same convention
32
- * as Unity/Blender.
26
+ * - **Drag** an entity's body directly to move it on the ground plane
27
+ * (Phase 1 of real editing — unchanged by the gizmo below). Grabbing
28
+ * empty space/sky orbits instead, same convention as Unity/Blender.
29
+ * - **Drag a gizmo handle** (Phase 2) — a Roblox/Unity-style 3-axis
30
+ * Move/Rotate/Scale gizmo appears on the selected entity. Dragging an
31
+ * arrow moves it along that axis (any direction, not just the ground
32
+ * plane); dragging a ring rotates it around that axis; dragging a scale
33
+ * handle (or the center cube, uniformly) resizes it. Mode switches via
34
+ * `umicat:editor:setGizmoMode3d`. This function itself never writes
35
+ * anything — it only moves/rotates/scales the live `THREE.Object3D` and
36
+ * posts the final LOCAL transform on release (`dragEnd3d` / `rotateEnd3d`
37
+ * / `scaleEnd3d`); the host owns turning that into a disk write.
33
38
  *
34
39
  * Takes over `renderer`'s animation loop entirely for the rest of the page's
35
40
  * life — there is no scene-swap API and no teardown, matching how the
@@ -4,6 +4,8 @@ import { loadScene3D, loadModelAsset } from '../SceneLoader3D.js';
4
4
  import { applySkin } from '../Skin.js';
5
5
  import { applyAttachments } from '../Attachments.js';
6
6
  import { singleModelManifest } from '../scene3d.js';
7
+ import { TransformGizmo3D } from './TransformGizmo3D.js';
8
+ import { closestPointOnLineToRay, raycastPlane, angleAroundAxis } from './gizmoMath.js';
7
9
  /**
8
10
  * The 3D counterpart of `@umicat/phaser-sdk`'s `EditorDesignScene` (ADR-021)
9
11
  * — renders a scene's AUTHORED data with no game code and no save, so the
@@ -15,13 +17,18 @@ import { singleModelManifest } from '../scene3d.js';
15
17
  * marker reads off the exact world coordinate, posted to the host so a
16
18
  * person can point at a real spot instead of guessing one blind when
17
19
  * telling the AI where to place something.
18
- * - **Drag** an entity to move it (Phase 1 of real editing, ground-plane
19
- * constrained — position only, no rotation/scale, no gizmo, no
20
- * Inspector). This function itself never writes anything — it only
21
- * moves the live THREE.Object3D and posts the final LOCAL position on
22
- * release (`umicat:editor:dragEnd3d`); the host owns turning that into a
23
- * disk write. Grabbing empty space/sky orbits instead, same convention
24
- * as Unity/Blender.
20
+ * - **Drag** an entity's body directly to move it on the ground plane
21
+ * (Phase 1 of real editing — unchanged by the gizmo below). Grabbing
22
+ * empty space/sky orbits instead, same convention as Unity/Blender.
23
+ * - **Drag a gizmo handle** (Phase 2) — a Roblox/Unity-style 3-axis
24
+ * Move/Rotate/Scale gizmo appears on the selected entity. Dragging an
25
+ * arrow moves it along that axis (any direction, not just the ground
26
+ * plane); dragging a ring rotates it around that axis; dragging a scale
27
+ * handle (or the center cube, uniformly) resizes it. Mode switches via
28
+ * `umicat:editor:setGizmoMode3d`. This function itself never writes
29
+ * anything — it only moves/rotates/scales the live `THREE.Object3D` and
30
+ * posts the final LOCAL transform on release (`dragEnd3d` / `rotateEnd3d`
31
+ * / `scaleEnd3d`); the host owns turning that into a disk write.
25
32
  *
26
33
  * Takes over `renderer`'s animation loop entirely for the rest of the page's
27
34
  * life — there is no scene-swap API and no teardown, matching how the
@@ -54,6 +61,13 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
54
61
  selectionBox.visible = false;
55
62
  selectionBox.renderOrder = 998;
56
63
  selectionBox.material.depthTest = false;
64
+ // The Move/Rotate/Scale transform gizmo — shows (and is only hit-testable)
65
+ // on the current mode's handles once something is selected. `gizmo.root`
66
+ // is added to the scene once, at scene-load time, right alongside the
67
+ // marker/selection box above; `gizmo.update(camera)` runs every frame (the
68
+ // render loop below) so it follows the selected entity and keeps a
69
+ // roughly constant on-screen size as the camera orbits/zooms.
70
+ const gizmo = new TransformGizmo3D();
57
71
  // Orientation gizmo — a small corner compass tracking the main camera's
58
72
  // rotation only (never its position/zoom), same convention every 3D DCC
59
73
  // uses: X=red, Y=green, Z=blue. Rendered as a second, tiny scene into a
@@ -111,6 +125,54 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
111
125
  const point = new THREE.Vector3();
112
126
  return raycaster.ray.intersectPlane(plane, point) ? point : null;
113
127
  };
128
+ // The uniform-scale center handle drags by SCREEN distance from the
129
+ // object's projected position, not a 3D line/plane — there is no single
130
+ // "axis" a uniform scale runs along, but "how far did you drag the
131
+ // cursor away from the object" is an unambiguous 1-DOF gesture in any
132
+ // camera orientation.
133
+ const worldToClientXY = (world) => {
134
+ const ndc = world.clone().project(camera);
135
+ const rect = renderer.domElement.getBoundingClientRect();
136
+ return {
137
+ x: rect.left + (ndc.x * 0.5 + 0.5) * rect.width,
138
+ y: rect.top + (1 - (ndc.y * 0.5 + 0.5)) * rect.height,
139
+ };
140
+ };
141
+ // Test-only readback — NOT part of the host↔iframe protocol, never read by
142
+ // umicat-home-ui. A gizmo handle's clickable screen position depends on
143
+ // the live camera distance (gizmo.update's constant-apparent-size scale)
144
+ // and the selected object's current world transform, so a real headless
145
+ // test needs to ask the live scene where a handle actually is rather than
146
+ // precompute it blind. Mirrors the project's existing precedent of
147
+ // exposing small debug readbacks for verification (e.g.
148
+ // `renderer.info.render.frame`) rather than hand-deriving pixel math that
149
+ // can silently drift from the real implementation.
150
+ globalThis.__umicatGizmoHandleScreenXY =
151
+ (mode, axis) => {
152
+ if (!gizmo.attached)
153
+ return null;
154
+ const worldPos = gizmo.attached.getWorldPosition(new THREE.Vector3());
155
+ if (axis === 'xyz')
156
+ return worldToClientXY(worldPos); // center cube sits at the object's own position
157
+ const scale = gizmo.root.scale.x;
158
+ if (mode === 'rotate') {
159
+ // The ring for a given axis lies in the plane perpendicular to it —
160
+ // a point ON the ring is offset along one of the OTHER two local
161
+ // axes by the ring's radius (1, built in TransformGizmo3D.ts).
162
+ const other = axis === 'x' ? 'y' : 'x';
163
+ const dir = gizmo.axisDirectionWorld(other);
164
+ return worldToClientXY(worldPos.clone().addScaledVector(dir, scale * 1.0));
165
+ }
166
+ // move/scale handles run OUTWARD along their own axis — the shaft
167
+ // midpoint (built 0..~0.8 local units) is a safely-clickable point.
168
+ const dir = gizmo.axisDirectionWorld(axis);
169
+ return worldToClientXY(worldPos.clone().addScaledVector(dir, scale * 0.5));
170
+ };
171
+ // Test-only — the attached object's current local scale, so a test can
172
+ // snapshot it BEFORE a scale drag rather than assume a baseline of 1 (a
173
+ // dropped model's `importScale` means that's almost never true).
174
+ globalThis.__umicatGizmoAttachedScale =
175
+ () => gizmo.attached ? { x: gizmo.attached.scale.x, y: gizmo.attached.scale.y, z: gizmo.attached.scale.z } : null;
114
176
  // Only VISIBLE entity roots are ever raycast against. three.js's
115
177
  // Mesh.raycast does NOT check `.visible` on its own (confirmed against the
116
178
  // pinned three source — no such check in Raycaster.js or Object3D.raycast),
@@ -154,12 +216,118 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
154
216
  let dragEntityId = null;
155
217
  let dragPlane = null;
156
218
  let dragGrabOffset = null; // world-space, plane-point minus object position at grab time
219
+ let gizmoDrag = null;
220
+ const beginGizmoDrag = (hit, e) => {
221
+ const obj = gizmo.attached;
222
+ if (!obj)
223
+ return false;
224
+ const worldPos = obj.getWorldPosition(new THREE.Vector3());
225
+ if (hit.mode === 'move' && hit.axis !== 'xyz') {
226
+ const lineDir = gizmo.axisDirectionWorld(hit.axis);
227
+ const grab = closestPointOnLineToRay(raycaster.ray.origin, raycaster.ray.direction, worldPos, lineDir);
228
+ if (!grab)
229
+ return false; // camera looking straight down this axis
230
+ gizmoDrag = { mode: 'move', axis: hit.axis, lineOrigin: worldPos.clone(), lineDir, grabOffset: grab.clone().sub(worldPos) };
231
+ return true;
232
+ }
233
+ if (hit.mode === 'scale' && hit.axis !== 'xyz') {
234
+ const lineDir = gizmo.axisDirectionWorld(hit.axis);
235
+ const grab = closestPointOnLineToRay(raycaster.ray.origin, raycaster.ray.direction, worldPos, lineDir);
236
+ if (!grab)
237
+ return false;
238
+ const startSignedDistance = grab.clone().sub(worldPos).dot(lineDir);
239
+ if (Math.abs(startSignedDistance) < 1e-4)
240
+ return false; // grabbed essentially at the origin — no stable ratio
241
+ gizmoDrag = { mode: 'scale', axis: hit.axis, lineOrigin: worldPos.clone(), lineDir, startSignedDistance, startScale: obj.scale.clone() };
242
+ return true;
243
+ }
244
+ if (hit.mode === 'scale' && hit.axis === 'xyz') {
245
+ const originScreen = worldToClientXY(worldPos);
246
+ const startScreenDistance = Math.hypot(e.clientX - originScreen.x, e.clientY - originScreen.y);
247
+ if (startScreenDistance < 2)
248
+ return false; // grabbed on top of the object's own screen position
249
+ gizmoDrag = { mode: 'scale', axis: 'xyz', originScreen, startScreenDistance, startScale: obj.scale.clone() };
250
+ return true;
251
+ }
252
+ if (hit.mode === 'rotate' && hit.axis !== 'xyz') {
253
+ const planeNormal = gizmo.axisDirectionWorld(hit.axis);
254
+ const hitPoint = raycastPlane(raycaster.ray, worldPos, planeNormal);
255
+ if (!hitPoint)
256
+ return false; // camera edge-on to this ring's plane
257
+ const startAngle = angleAroundAxis(worldPos, planeNormal, hitPoint);
258
+ const parentWorldQuatInverse = obj.parent ? obj.parent.getWorldQuaternion(new THREE.Quaternion()).invert() : new THREE.Quaternion();
259
+ const startWorldQuaternion = obj.getWorldQuaternion(new THREE.Quaternion());
260
+ gizmoDrag = { mode: 'rotate', axis: hit.axis, planePoint: worldPos.clone(), planeNormal, startAngle, startWorldQuaternion, parentWorldQuatInverse };
261
+ return true;
262
+ }
263
+ return false;
264
+ };
265
+ const updateGizmoDrag = (e) => {
266
+ if (!gizmoDrag || !gizmo.attached)
267
+ return;
268
+ const obj = gizmo.attached;
269
+ if (gizmoDrag.mode === 'move') {
270
+ const grab = closestPointOnLineToRay(raycaster.ray.origin, raycaster.ray.direction, gizmoDrag.lineOrigin, gizmoDrag.lineDir);
271
+ if (!grab)
272
+ return;
273
+ const newWorldPos = grab.clone().sub(gizmoDrag.grabOffset);
274
+ if (obj.parent)
275
+ obj.parent.worldToLocal(newWorldPos);
276
+ obj.position.copy(newWorldPos);
277
+ }
278
+ else if (gizmoDrag.mode === 'scale' && gizmoDrag.axis !== 'xyz') {
279
+ const grab = closestPointOnLineToRay(raycaster.ray.origin, raycaster.ray.direction, gizmoDrag.lineOrigin, gizmoDrag.lineDir);
280
+ if (!grab)
281
+ return;
282
+ const signedDistance = grab.clone().sub(gizmoDrag.lineOrigin).dot(gizmoDrag.lineDir);
283
+ const ratio = THREE.MathUtils.clamp(signedDistance / gizmoDrag.startSignedDistance, 0.02, 50);
284
+ const { axis, startScale } = gizmoDrag;
285
+ if (axis === 'x')
286
+ obj.scale.x = startScale.x * ratio;
287
+ else if (axis === 'y')
288
+ obj.scale.y = startScale.y * ratio;
289
+ else
290
+ obj.scale.z = startScale.z * ratio;
291
+ }
292
+ else if (gizmoDrag.mode === 'scale' && gizmoDrag.axis === 'xyz') {
293
+ const currentScreenDistance = Math.hypot(e.clientX - gizmoDrag.originScreen.x, e.clientY - gizmoDrag.originScreen.y);
294
+ const ratio = THREE.MathUtils.clamp(currentScreenDistance / gizmoDrag.startScreenDistance, 0.02, 50);
295
+ obj.scale.copy(gizmoDrag.startScale).multiplyScalar(ratio);
296
+ }
297
+ else if (gizmoDrag.mode === 'rotate') {
298
+ const hitPoint = raycastPlane(raycaster.ray, gizmoDrag.planePoint, gizmoDrag.planeNormal);
299
+ if (!hitPoint)
300
+ return;
301
+ const currentAngle = angleAroundAxis(gizmoDrag.planePoint, gizmoDrag.planeNormal, hitPoint);
302
+ const delta = currentAngle - gizmoDrag.startAngle;
303
+ const deltaQuat = new THREE.Quaternion().setFromAxisAngle(gizmoDrag.planeNormal, delta);
304
+ const newWorldQuat = deltaQuat.multiply(gizmoDrag.startWorldQuaternion.clone());
305
+ obj.quaternion.copy(gizmoDrag.parentWorldQuatInverse.clone().multiply(newWorldQuat));
306
+ }
307
+ selectionBox.setFromObject(obj);
308
+ gizmo.update(camera);
309
+ moved = true;
310
+ };
157
311
  const onPointerDown = (e) => {
158
312
  downX = e.clientX;
159
313
  downY = e.clientY;
160
314
  moved = false;
161
315
  if (!scene)
162
316
  return;
317
+ if (gizmo.attached) {
318
+ raycaster.setFromCamera(ndcFromEvent(e), camera);
319
+ const gizmoHit = gizmo.hitTest(raycaster);
320
+ if (gizmoHit && beginGizmoDrag(gizmoHit, e)) {
321
+ controls.enabled = false;
322
+ try {
323
+ renderer.domElement.setPointerCapture(e.pointerId);
324
+ }
325
+ catch {
326
+ // See the same try/catch below — capture is an enhancement only.
327
+ }
328
+ return;
329
+ }
330
+ }
163
331
  const hit = pickEntityAt(e);
164
332
  if (!hit)
165
333
  return; // empty space — let OrbitControls own this gesture
@@ -192,6 +360,11 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
192
360
  const onPointerMove = (e) => {
193
361
  if (Math.abs(e.clientX - downX) > 4 || Math.abs(e.clientY - downY) > 4)
194
362
  moved = true;
363
+ if (gizmoDrag) {
364
+ raycaster.setFromCamera(ndcFromEvent(e), camera);
365
+ updateGizmoDrag(e);
366
+ return;
367
+ }
195
368
  if (!dragEntity || !dragPlane || !dragGrabOffset || !scene)
196
369
  return;
197
370
  raycaster.setFromCamera(ndcFromEvent(e), camera);
@@ -212,6 +385,25 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
212
385
  // Already released, or never captured (e.g. this gesture never hit an
213
386
  // entity) — nothing to do either way.
214
387
  }
388
+ if (gizmoDrag) {
389
+ const obj = gizmo.attached;
390
+ const entityId = obj ? entityByObject.get(obj) : undefined;
391
+ if (moved && obj && entityId) {
392
+ if (gizmoDrag.mode === 'move') {
393
+ window.parent.postMessage({ type: 'umicat:editor:dragEnd3d', sceneId: opts.sceneId, entityId, position: { x: obj.position.x, y: obj.position.y, z: obj.position.z } }, '*');
394
+ }
395
+ else if (gizmoDrag.mode === 'rotate') {
396
+ const q = obj.quaternion;
397
+ window.parent.postMessage({ type: 'umicat:editor:rotateEnd3d', sceneId: opts.sceneId, entityId, rotation: [q.x, q.y, q.z, q.w] }, '*');
398
+ }
399
+ else if (gizmoDrag.mode === 'scale') {
400
+ window.parent.postMessage({ type: 'umicat:editor:scaleEnd3d', sceneId: opts.sceneId, entityId, scale: { x: obj.scale.x, y: obj.scale.y, z: obj.scale.z } }, '*');
401
+ }
402
+ }
403
+ gizmoDrag = null;
404
+ controls.enabled = true;
405
+ return;
406
+ }
215
407
  // A drag only really happened if the pointer actually moved — grabbing
216
408
  // an entity and releasing without moving is a CLICK on it (case below),
217
409
  // not a same-position no-op save.
@@ -230,10 +422,18 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
230
422
  controls.enabled = true;
231
423
  if (moved || !scene)
232
424
  return;
233
- // A plain click (no drag) — the existing read-a-coordinate behavior.
425
+ // A plain click (no drag) — the existing read-a-coordinate behavior,
426
+ // plus attaching/detaching the transform gizmo to match selection.
234
427
  const hit = pickEntityAt(e);
235
- if (!hit)
428
+ if (!hit) {
429
+ // Clicked empty space with nothing grabbed — deselect. Previously a
430
+ // no-op (the marker/box from a PRIOR selection just stayed on
431
+ // screen); now load-bearing, since the gizmo also needs to disappear.
432
+ marker.visible = false;
433
+ selectionBox.visible = false;
434
+ gizmo.detach();
236
435
  return;
436
+ }
237
437
  marker.position.copy(hit.point);
238
438
  marker.visible = true;
239
439
  // Frame the whole entity the click landed on, not just the point on its
@@ -242,6 +442,7 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
242
442
  // all of it, matching what "entityId" actually refers to.
243
443
  selectionBox.setFromObject(hit.entityRoot);
244
444
  selectionBox.visible = true;
445
+ gizmo.attach(hit.entityRoot, camera);
245
446
  window.parent.postMessage({ type: 'umicat:editor:pickPoint3d', x: hit.point.x, y: hit.point.y, z: hit.point.z, entityId: hit.entityId }, '*');
246
447
  };
247
448
  renderer.domElement.addEventListener('pointerdown', onPointerDown);
@@ -279,6 +480,14 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
279
480
  return onPatchEntity3d(data);
280
481
  if (data.type === 'umicat:editor:dropModel3d')
281
482
  return onDropModel3d(data);
483
+ if (data.type === 'umicat:editor:setGizmoMode3d') {
484
+ const mode = data.mode;
485
+ if (mode === 'move' || mode === 'rotate' || mode === 'scale') {
486
+ gizmo.setMode(mode);
487
+ gizmo.update(camera);
488
+ }
489
+ return;
490
+ }
282
491
  }
283
492
  /**
284
493
  * `patch` is an open bag deliberately: skin is the first field, and adding
@@ -391,6 +600,7 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
391
600
  controls.update();
392
601
  if (!scene)
393
602
  return;
603
+ gizmo.update(camera);
394
604
  renderer.setScissorTest(false);
395
605
  renderer.render(scene, camera);
396
606
  // Second pass: the orientation gizmo, into a small scissored corner
@@ -433,6 +643,7 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
433
643
  scene.add(marker);
434
644
  selectionBox.visible = false;
435
645
  scene.add(selectionBox);
646
+ scene.add(gizmo.root);
436
647
  // Frame the whole scene — auto-fit, since a small template scene and a
437
648
  // real level's dozens of entities need wildly different orbit distances.
438
649
  const box = new THREE.Box3().setFromObject(scene);
@@ -0,0 +1,50 @@
1
+ import * as THREE from 'three';
2
+ export type GizmoMode = 'move' | 'rotate' | 'scale';
3
+ export type GizmoAxis = 'x' | 'y' | 'z' | 'xyz';
4
+ export interface GizmoHit {
5
+ mode: GizmoMode;
6
+ axis: GizmoAxis;
7
+ }
8
+ /**
9
+ * Builds and owns the three mode-specific handle groups (move/rotate/scale)
10
+ * plus hit-testing and per-frame follow/sizing. Everything else — what a
11
+ * drag on a given handle actually DOES to the attached object — is the
12
+ * caller's job (`EditorDesignPlayer3D.ts`): this class only answers "is the
13
+ * gizmo showing, and which handle did this ray hit."
14
+ *
15
+ * The whole gizmo is LOCAL-space: `root`'s orientation tracks the attached
16
+ * object's world rotation, not the world axes. There's no local/global
17
+ * toggle (v1) — this is also the only sane default for scale, since scale
18
+ * is always local to an object regardless of any toggle, so move/rotate
19
+ * sharing that frame keeps all three modes visually and mathematically
20
+ * consistent with each other.
21
+ */
22
+ export declare class TransformGizmo3D {
23
+ readonly root: THREE.Group<THREE.Object3DEventMap>;
24
+ mode: GizmoMode;
25
+ private target;
26
+ private readonly moveGroup;
27
+ private readonly rotateGroup;
28
+ private readonly scaleGroup;
29
+ private readonly pickableByMode;
30
+ private readonly hitByMesh;
31
+ constructor();
32
+ get attached(): THREE.Object3D | null;
33
+ setMode(mode: GizmoMode): void;
34
+ attach(object: THREE.Object3D, camera: THREE.Camera): void;
35
+ detach(): void;
36
+ private refreshVisibility;
37
+ /** Keep the gizmo glued to its target's world transform and sized roughly
38
+ * constant on screen regardless of camera distance — call every frame
39
+ * (cheap: a handful of vector ops), not just while dragging, since
40
+ * orbiting the camera changes both of those every frame too. */
41
+ update(camera: THREE.Camera): void;
42
+ /** World-space direction of a given LOCAL axis letter, honoring the
43
+ * gizmo's current (target-local) orientation. */
44
+ axisDirectionWorld(axis: 'x' | 'y' | 'z'): THREE.Vector3;
45
+ /** Only the active mode's own handles are ever candidates — sidesteps
46
+ * relying on `.visible` during raycasting, which (confirmed against the
47
+ * pinned three.js version used elsewhere in this file) is NOT checked
48
+ * automatically by `Raycaster.intersectObjects`. */
49
+ hitTest(raycaster: THREE.Raycaster): GizmoHit | null;
50
+ }
@@ -0,0 +1,162 @@
1
+ import * as THREE from 'three';
2
+ const AXIS_COLOR = { x: 0xff4d4d, y: 0x53e06a, z: 0x4d9fff };
3
+ function axisMaterial(axis, doubleSide = false) {
4
+ return new THREE.MeshBasicMaterial({
5
+ color: AXIS_COLOR[axis],
6
+ depthTest: false,
7
+ side: doubleSide ? THREE.DoubleSide : THREE.FrontSide,
8
+ });
9
+ }
10
+ /** The move/scale handles are built pointing along local +Y, then rotated
11
+ * into place — avoids writing three near-identical geometry builders. */
12
+ function orientAlongAxis(obj, axis) {
13
+ if (axis === 'x')
14
+ obj.rotation.z = -Math.PI / 2;
15
+ else if (axis === 'z')
16
+ obj.rotation.x = Math.PI / 2;
17
+ }
18
+ function buildMoveArrow(axis) {
19
+ const group = new THREE.Group();
20
+ const material = axisMaterial(axis);
21
+ const shaft = new THREE.Mesh(new THREE.CylinderGeometry(0.025, 0.025, 0.8, 8), material);
22
+ shaft.position.y = 0.4;
23
+ const head = new THREE.Mesh(new THREE.ConeGeometry(0.08, 0.22, 10), material);
24
+ head.position.y = 0.91;
25
+ group.add(shaft, head);
26
+ group.renderOrder = 1000;
27
+ orientAlongAxis(group, axis);
28
+ return { group, meshes: [shaft, head] };
29
+ }
30
+ function buildScaleHandle(axis) {
31
+ const group = new THREE.Group();
32
+ const material = axisMaterial(axis);
33
+ const shaft = new THREE.Mesh(new THREE.CylinderGeometry(0.02, 0.02, 0.7, 8), material);
34
+ shaft.position.y = 0.35;
35
+ const cap = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.12, 0.12), material);
36
+ cap.position.y = 0.76;
37
+ group.add(shaft, cap);
38
+ group.renderOrder = 1000;
39
+ orientAlongAxis(group, axis);
40
+ return { group, meshes: [shaft, cap] };
41
+ }
42
+ /** TorusGeometry is built in the XY plane (its ring normal is +Z) — rotated
43
+ * here so the final ring normal IS the requested axis, i.e. dragging around
44
+ * the ring rotates the object around that axis, matching the arrows'
45
+ * "this handle controls this axis" convention. */
46
+ function buildRotateRing(axis) {
47
+ const mesh = new THREE.Mesh(new THREE.TorusGeometry(1, 0.03, 8, 48), axisMaterial(axis, true));
48
+ mesh.renderOrder = 1000;
49
+ if (axis === 'x')
50
+ mesh.rotation.y = Math.PI / 2;
51
+ else if (axis === 'y')
52
+ mesh.rotation.x = Math.PI / 2;
53
+ return { mesh };
54
+ }
55
+ /**
56
+ * Builds and owns the three mode-specific handle groups (move/rotate/scale)
57
+ * plus hit-testing and per-frame follow/sizing. Everything else — what a
58
+ * drag on a given handle actually DOES to the attached object — is the
59
+ * caller's job (`EditorDesignPlayer3D.ts`): this class only answers "is the
60
+ * gizmo showing, and which handle did this ray hit."
61
+ *
62
+ * The whole gizmo is LOCAL-space: `root`'s orientation tracks the attached
63
+ * object's world rotation, not the world axes. There's no local/global
64
+ * toggle (v1) — this is also the only sane default for scale, since scale
65
+ * is always local to an object regardless of any toggle, so move/rotate
66
+ * sharing that frame keeps all three modes visually and mathematically
67
+ * consistent with each other.
68
+ */
69
+ export class TransformGizmo3D {
70
+ constructor() {
71
+ this.root = new THREE.Group();
72
+ this.mode = 'move';
73
+ this.target = null;
74
+ this.moveGroup = new THREE.Group();
75
+ this.rotateGroup = new THREE.Group();
76
+ this.scaleGroup = new THREE.Group();
77
+ this.pickableByMode = { move: [], rotate: [], scale: [] };
78
+ this.hitByMesh = new Map();
79
+ for (const axis of ['x', 'y', 'z']) {
80
+ const move = buildMoveArrow(axis);
81
+ this.moveGroup.add(move.group);
82
+ for (const m of move.meshes) {
83
+ this.hitByMesh.set(m, { mode: 'move', axis });
84
+ this.pickableByMode.move.push(m);
85
+ }
86
+ const rotate = buildRotateRing(axis);
87
+ this.rotateGroup.add(rotate.mesh);
88
+ this.hitByMesh.set(rotate.mesh, { mode: 'rotate', axis });
89
+ this.pickableByMode.rotate.push(rotate.mesh);
90
+ const scale = buildScaleHandle(axis);
91
+ this.scaleGroup.add(scale.group);
92
+ for (const m of scale.meshes) {
93
+ this.hitByMesh.set(m, { mode: 'scale', axis });
94
+ this.pickableByMode.scale.push(m);
95
+ }
96
+ }
97
+ // Uniform-scale center handle — scales all three axes together.
98
+ const center = new THREE.Mesh(new THREE.BoxGeometry(0.14, 0.14, 0.14), new THREE.MeshBasicMaterial({ color: 0xe8e8e8, depthTest: false }));
99
+ center.renderOrder = 1000;
100
+ this.scaleGroup.add(center);
101
+ this.hitByMesh.set(center, { mode: 'scale', axis: 'xyz' });
102
+ this.pickableByMode.scale.push(center);
103
+ this.moveGroup.visible = false;
104
+ this.rotateGroup.visible = false;
105
+ this.scaleGroup.visible = false;
106
+ this.root.add(this.moveGroup, this.rotateGroup, this.scaleGroup);
107
+ }
108
+ get attached() {
109
+ return this.target;
110
+ }
111
+ setMode(mode) {
112
+ this.mode = mode;
113
+ this.refreshVisibility();
114
+ }
115
+ attach(object, camera) {
116
+ this.target = object;
117
+ this.refreshVisibility();
118
+ this.update(camera);
119
+ }
120
+ detach() {
121
+ this.target = null;
122
+ this.refreshVisibility();
123
+ }
124
+ refreshVisibility() {
125
+ const show = this.target !== null;
126
+ this.moveGroup.visible = show && this.mode === 'move';
127
+ this.rotateGroup.visible = show && this.mode === 'rotate';
128
+ this.scaleGroup.visible = show && this.mode === 'scale';
129
+ }
130
+ /** Keep the gizmo glued to its target's world transform and sized roughly
131
+ * constant on screen regardless of camera distance — call every frame
132
+ * (cheap: a handful of vector ops), not just while dragging, since
133
+ * orbiting the camera changes both of those every frame too. */
134
+ update(camera) {
135
+ if (!this.target)
136
+ return;
137
+ const pos = this.target.getWorldPosition(new THREE.Vector3());
138
+ this.root.position.copy(pos);
139
+ this.root.quaternion.copy(this.target.getWorldQuaternion(new THREE.Quaternion()));
140
+ const dist = camera.position.distanceTo(pos);
141
+ this.root.scale.setScalar(Math.max(dist * 0.15, 0.001));
142
+ }
143
+ /** World-space direction of a given LOCAL axis letter, honoring the
144
+ * gizmo's current (target-local) orientation. */
145
+ axisDirectionWorld(axis) {
146
+ const dir = axis === 'x' ? new THREE.Vector3(1, 0, 0) : axis === 'y' ? new THREE.Vector3(0, 1, 0) : new THREE.Vector3(0, 0, 1);
147
+ return dir.applyQuaternion(this.root.quaternion).normalize();
148
+ }
149
+ /** Only the active mode's own handles are ever candidates — sidesteps
150
+ * relying on `.visible` during raycasting, which (confirmed against the
151
+ * pinned three.js version used elsewhere in this file) is NOT checked
152
+ * automatically by `Raycaster.intersectObjects`. */
153
+ hitTest(raycaster) {
154
+ if (!this.target)
155
+ return null;
156
+ const meshes = this.pickableByMode[this.mode];
157
+ const hits = raycaster.intersectObjects(meshes, false);
158
+ if (hits.length === 0)
159
+ return null;
160
+ return this.hitByMesh.get(hits[0].object) ?? null;
161
+ }
162
+ }
@@ -0,0 +1,36 @@
1
+ import * as THREE from 'three';
2
+ /**
3
+ * The point on a 3D line closest to a ray — the primitive single-axis
4
+ * move/scale handles are built on. A ray dragged across the screen rarely
5
+ * ever actually INTERSECTS the axis line (that only happens by chance), so
6
+ * "where does the cursor's ray cross the axis" is the wrong question; "what
7
+ * point on the axis is the cursor closest to pointing at" is the one that
8
+ * gives a stable, predictable 1-DOF drag.
9
+ *
10
+ * Standard closest-point-between-two-lines algebra (e.g. Ericson,
11
+ * *Real-Time Collision Detection* §5.1.9), solved for the axis line's own
12
+ * parameter only — the ray's parameter is never needed by a caller. Returns
13
+ * null when the ray runs parallel to the axis (dragging while looking
14
+ * straight down the handle you're dragging) — there is no stable answer
15
+ * there, and the caller should just hold the previous frame's point rather
16
+ * than snap somewhere arbitrary.
17
+ */
18
+ export declare function closestPointOnLineToRay(rayOrigin: THREE.Vector3, rayDir: THREE.Vector3, // must be normalized
19
+ lineOrigin: THREE.Vector3, lineDir: THREE.Vector3): THREE.Vector3 | null;
20
+ /**
21
+ * Where a ray crosses an arbitrary plane (point + normal) — the rotate
22
+ * handles' equivalent of `raycastGroundPlane`, generalized to any axis
23
+ * rather than hardcoded to a horizontal Y=0 ground.
24
+ */
25
+ export declare function raycastPlane(ray: THREE.Ray, planePoint: THREE.Vector3, planeNormal: THREE.Vector3): THREE.Vector3 | null;
26
+ /**
27
+ * The angle of `point` around `axis` through `center`, in a stable
28
+ * reference frame built FROM the axis alone — so two calls with the SAME
29
+ * axis always agree on what angle zero means, and a rotate drag's angle
30
+ * *delta* (this frame's angle minus last frame's) is the thing actually
31
+ * applied. `point` need not lie exactly in the axis's plane (it won't,
32
+ * exactly, once float error creeps in) — the component along `axis` is
33
+ * discarded before reading the angle off the remainder.
34
+ */
35
+ export declare function angleAroundAxis(center: THREE.Vector3, axis: THREE.Vector3, // must be normalized
36
+ point: THREE.Vector3): number;
@@ -0,0 +1,60 @@
1
+ import * as THREE from 'three';
2
+ /**
3
+ * The point on a 3D line closest to a ray — the primitive single-axis
4
+ * move/scale handles are built on. A ray dragged across the screen rarely
5
+ * ever actually INTERSECTS the axis line (that only happens by chance), so
6
+ * "where does the cursor's ray cross the axis" is the wrong question; "what
7
+ * point on the axis is the cursor closest to pointing at" is the one that
8
+ * gives a stable, predictable 1-DOF drag.
9
+ *
10
+ * Standard closest-point-between-two-lines algebra (e.g. Ericson,
11
+ * *Real-Time Collision Detection* §5.1.9), solved for the axis line's own
12
+ * parameter only — the ray's parameter is never needed by a caller. Returns
13
+ * null when the ray runs parallel to the axis (dragging while looking
14
+ * straight down the handle you're dragging) — there is no stable answer
15
+ * there, and the caller should just hold the previous frame's point rather
16
+ * than snap somewhere arbitrary.
17
+ */
18
+ export function closestPointOnLineToRay(rayOrigin, rayDir, // must be normalized
19
+ lineOrigin, lineDir) {
20
+ const r = new THREE.Vector3().subVectors(rayOrigin, lineOrigin);
21
+ const b = rayDir.dot(lineDir);
22
+ const f1 = rayDir.dot(r);
23
+ const f2 = lineDir.dot(r);
24
+ const denom = b * b - 1;
25
+ if (Math.abs(denom) < 1e-6)
26
+ return null; // ray ‖ axis
27
+ const s = (b * f1 - f2) / denom;
28
+ return lineOrigin.clone().addScaledVector(lineDir, s);
29
+ }
30
+ /**
31
+ * Where a ray crosses an arbitrary plane (point + normal) — the rotate
32
+ * handles' equivalent of `raycastGroundPlane`, generalized to any axis
33
+ * rather than hardcoded to a horizontal Y=0 ground.
34
+ */
35
+ export function raycastPlane(ray, planePoint, planeNormal) {
36
+ const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(planeNormal, planePoint);
37
+ const point = new THREE.Vector3();
38
+ return ray.intersectPlane(plane, point) ? point : null;
39
+ }
40
+ /**
41
+ * The angle of `point` around `axis` through `center`, in a stable
42
+ * reference frame built FROM the axis alone — so two calls with the SAME
43
+ * axis always agree on what angle zero means, and a rotate drag's angle
44
+ * *delta* (this frame's angle minus last frame's) is the thing actually
45
+ * applied. `point` need not lie exactly in the axis's plane (it won't,
46
+ * exactly, once float error creeps in) — the component along `axis` is
47
+ * discarded before reading the angle off the remainder.
48
+ */
49
+ export function angleAroundAxis(center, axis, // must be normalized
50
+ point) {
51
+ // Any vector not parallel to `axis` works as a seed; Y unless the axis
52
+ // basically IS Y, in which case X is never parallel to it.
53
+ const seed = Math.abs(axis.y) < 0.99 ? new THREE.Vector3(0, 1, 0) : new THREE.Vector3(1, 0, 0);
54
+ const u = new THREE.Vector3().crossVectors(seed, axis).normalize();
55
+ const w = new THREE.Vector3().crossVectors(axis, u).normalize();
56
+ const rel = new THREE.Vector3().subVectors(point, center);
57
+ const onAxis = axis.clone().multiplyScalar(rel.dot(axis));
58
+ const inPlane = rel.clone().sub(onAxis);
59
+ return Math.atan2(inPlane.dot(w), inPlane.dot(u));
60
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umicat/three-sdk",
3
- "version": "0.22.0",
3
+ "version": "0.23.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",