From cd01b01edd12faddf6d0f6760e74992fd61607a2 Mon Sep 17 00:00:00 2001 From: alowpoly Date: Thu, 3 Dec 2026 18:15:33 -0300 Subject: [PATCH 1/5] refactor(runtime): consolidate controls, select, leaf helpers, and dist chunk splitting --- .github/architecture/repo-map.md | 22 +- .../polycss/src/api/cameraSnapshotAttrs.ts | 191 +++ .../polycss/src/api/controls/gizmoEngine.ts | 719 ++++++++++ .../src/api/controls/selectionEngine.ts | 131 ++ packages/polycss/src/api/createPolyScene.ts | 14 +- packages/polycss/src/api/createSelect.ts | 164 +-- .../src/api/createTransformControls.ts | 826 +++-------- packages/polycss/src/api/meshHitTest.ts | 123 ++ .../polycss/src/api/runtimeHelpers.test.ts | 479 +++++++ packages/polycss/src/api/standaloneMesh.ts | 68 + .../polycss/src/render/polyLeafDescriptor.ts | 212 +++ packages/polycss/src/runtime.ts | 90 ++ packages/polycss/src/three.ts | 6 +- packages/polycss/tsup.config.ts | 4 +- packages/react/src/camera/useCamera.ts | 152 +- .../react/src/controls/TransformControls.tsx | 1239 ++--------------- packages/react/src/scene/PolyMesh.tsx | 43 +- packages/react/src/scene/events.ts | 183 +-- .../react/src/scene/mesh/useMeshEvents.ts | 106 +- packages/react/src/select/Select.tsx | 267 +--- packages/react/src/shapes/Poly.tsx | 233 +--- packages/vue/src/camera/useCamera.ts | 148 +- .../vue/src/controls/PolyTransformControls.ts | 811 +++-------- packages/vue/src/scene/PolyMesh.ts | 39 +- packages/vue/src/scene/events.ts | 130 +- packages/vue/src/scene/mesh/useMeshEvents.ts | 68 +- packages/vue/src/select/PolySelect.ts | 118 +- packages/vue/src/select/Select.test.ts | 5 +- packages/vue/src/shapes/Poly.ts | 206 +-- 29 files changed, 2900 insertions(+), 3897 deletions(-) create mode 100644 packages/polycss/src/api/cameraSnapshotAttrs.ts create mode 100644 packages/polycss/src/api/controls/gizmoEngine.ts create mode 100644 packages/polycss/src/api/controls/selectionEngine.ts create mode 100644 packages/polycss/src/api/runtimeHelpers.test.ts create mode 100644 packages/polycss/src/api/standaloneMesh.ts create mode 100644 packages/polycss/src/render/polyLeafDescriptor.ts diff --git a/.github/architecture/repo-map.md b/.github/architecture/repo-map.md index a1369ff63..30402f5e1 100644 --- a/.github/architecture/repo-map.md +++ b/.github/architecture/repo-map.md @@ -1,7 +1,7 @@ # PolyCSS Repository Map -Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **421 files**, **101,578 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. +Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **426 files**, **100,105 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. ## 1. Packages & Entry Points @@ -11,10 +11,10 @@ Tracked production code scanned across `packages/*/src`, `bench/`, and `website/ | `packages/domformat` (`@layoutit/polycss-domformat`) | private | `., ./browser` | — | 36 | 13,165 | 0 | | `packages/fonts` (`@layoutit/polycss-fonts`) | npm | `.` | `@layoutit/polycss-core` | 7 | 1,661 | 4 | | `packages/morph` (`@layoutit/polycss-morph`) | npm | `., ./prepare` | `@layoutit/polycss`, `@layoutit/polycss-core` | 49 | 7,633 | 14 | -| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./elements, ./three` | `@layoutit/polycss-core` | 62 | 16,582 | 40 | -| `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 6,398 | 31 | +| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./elements, ./three` | `@layoutit/polycss-core` | 67 | 17,562 | 41 | +| `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 4,835 | 31 | | `packages/skills` (`@layoutit/polycss-skills`) | npm | `.` | — | 1 | 415 | 1 | -| `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 5,560 | 29 | +| `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 4,670 | 29 | ## 2. Canonical Workspace Source Aliases @@ -44,17 +44,17 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | Fan-in | Lines | File | |---:|---:|---| -| 108 | 642 | `packages/core/src/index.ts` | +| 112 | 642 | `packages/core/src/index.ts` | | 65 | 248 | `packages/core/src/types.ts` | +| 32 | 237 | `packages/polycss/src/runtime.ts` | | 32 | 301 | `packages/react/src/index.ts` | | 31 | 119 | `website/src/components/types.ts` | -| 24 | 147 | `packages/polycss/src/runtime.ts` | -| 18 | 218 | `packages/polycss/src/index.ts` | | 18 | 88 | `website/src/components/GalleryWorkbench/types.ts` | +| 17 | 218 | `packages/polycss/src/index.ts` | +| 15 | 45 | `packages/polycss/src/render/textureAtlas.ts` | +| 14 | 1,386 | `packages/polycss/src/api/createPolyScene.ts` | | 13 | 283 | `packages/polycss/src/elements/PolySceneElement.ts` | -| 13 | 45 | `packages/polycss/src/render/textureAtlas.ts` | | 13 | 41 | `packages/react/src/camera/context.ts` | -| 12 | 1,396 | `packages/polycss/src/api/createPolyScene.ts` | | 11 | 101 | `packages/core/src/atlas/constants.ts` | ### Largest production source files @@ -68,11 +68,11 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | 1,935 | `packages/domformat/src/state/polycss.ts` | | 1,592 | `packages/core/src/merge/seamRepair.ts` | | 1,527 | `website/src/components/GalleryWorkbench/GalleryWorkbench.tsx` | -| 1,396 | `packages/polycss/src/api/createPolyScene.ts` | +| 1,386 | `packages/polycss/src/api/createPolyScene.ts` | | 1,283 | `website/src/components/VanillaScene/VanillaScene.tsx` | -| 1,227 | `packages/react/src/controls/TransformControls.tsx` | | 1,214 | `website/src/components/WordArtWorkbench/WordArtWorkbench.tsx` | | 1,198 | `bench/visual-gate.mjs` | +| 1,178 | `packages/domformat/src/browser.ts` | ## 4. Core Render & Control Pipelines diff --git a/packages/polycss/src/api/cameraSnapshotAttrs.ts b/packages/polycss/src/api/cameraSnapshotAttrs.ts new file mode 100644 index 000000000..5bbcb93d3 --- /dev/null +++ b/packages/polycss/src/api/cameraSnapshotAttrs.ts @@ -0,0 +1,191 @@ +/** + * Shared camera DOM snapshot-attribute writer and framework camera-store sync. + * + * Used by: + * - `createPolyScene` (`@layoutit/polycss`) + * - `usePolyCamera` (`@layoutit/polycss-react` & `@layoutit/polycss-vue`) + */ +import { + buildPolyCameraSceneTransform, + capturePolyCameraSnapshot, + type CameraHandle, + type CameraState, + type PolyCameraProjection, + type PolyCameraSnapshot, + type PolyCameraSnapshotOptions, + type PolyCameraSnapshotSource, + type Vec3, +} from "@layoutit/polycss-core"; +import { + createPolyOrthographicCamera, + createPolyPerspectiveCamera, + type PolyOrthographicCameraHandle, + type PolyPerspectiveCameraHandle, +} from "./createPolyCamera"; +import type { PolySceneHandle } from "./createPolyScene"; + +export interface WriteCameraSnapshotAttrsOptions extends PolyCameraSnapshotOptions { + /** Also write `el.style.perspective = snapshot.appliedPerspectiveStyle`. */ + applyPerspective?: boolean; +} + +/** + * Write canonical `data-polycss-camera-*` dataset attributes (and optionally + * CSS `perspective`) onto a `.polycss-camera` element. + */ +export function writeCameraSnapshotAttrs( + el: HTMLElement | null, + camera: PolyCameraSnapshotSource, + options?: WriteCameraSnapshotAttrsOptions, +): PolyCameraSnapshot | null { + if (!el) return null; + const snapshot = capturePolyCameraSnapshot(camera, options); + if (options?.applyPerspective) { + el.style.perspective = snapshot.appliedPerspectiveStyle; + } + el.dataset.polycssCameraProjection = snapshot.projection; + el.dataset.polycssCameraPerspective = snapshot.perspectiveStyle; + el.dataset.polycssCameraAppliedPerspective = snapshot.appliedPerspectiveStyle; + el.dataset.polycssCameraZoom = String(snapshot.state.zoom); + el.dataset.polycssCameraDistance = String(snapshot.state.distance); + el.dataset.polycssCameraRotX = String(snapshot.state.rotX); + el.dataset.polycssCameraRotY = String(snapshot.state.rotY); + el.dataset.polycssCameraTarget = snapshot.state.target.join(","); + return snapshot; +} + +export interface LiveRuntimeCameraOptions { + zoom?: number; + target?: Vec3; + rotX?: number; + rotY?: number; + distance?: number; + initialProjection?: PolyCameraProjection; + initialPerspectiveStyle?: string; + getProjection: () => PolyCameraProjection; + getPerspectiveStyle: () => string; +} + +/** + * Create a runtime camera handle whose `type` and `perspectiveStyle` getters + * reflect live framework props so `createPolyScene.applyCamera()` stays in sync. + */ +export function createLiveRuntimeCamera( + options: LiveRuntimeCameraOptions, +): PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle { + const baseOpts = { + zoom: options.zoom, + target: options.target, + rotX: options.rotX, + rotY: options.rotY, + distance: options.distance, + }; + const inner = + options.initialProjection === "perspective" + ? createPolyPerspectiveCamera({ + ...baseOpts, + perspective: parseFloat(options.initialPerspectiveStyle ?? "32000px") || 32000, + }) + : createPolyOrthographicCamera(baseOpts); + + return { + get state() { + return inner.state; + }, + update(next: Partial) { + inner.update(next); + }, + getStyle(input) { + return inner.getStyle(input); + }, + subscribe(listener) { + return inner.subscribe(listener); + }, + get type() { + return options.getProjection() as "perspective" & "orthographic"; + }, + get perspectiveStyle() { + return options.getPerspectiveStyle() as string & "none"; + }, + } as PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle; +} + +export interface CameraSyncStoreLike { + getState(): { cameraState: CameraState }; + subscribe(listener: () => void): () => void; + updateCameraFromRef(camera: CameraHandle): void; +} + +/** + * Bind bidirectional synchronization between a runtime camera handle and a + * framework reactive scene store without feedback loops. + */ +export function bindCameraStoreSync( + handle: PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle, + store: CameraSyncStoreLike, + getRuntimeScene: () => PolySceneHandle | null, +): () => void { + let syncing = false; + const unsubHandle = handle.subscribe(() => { + if (syncing) return; + syncing = true; + try { + store.updateCameraFromRef(handle); + } finally { + syncing = false; + } + }); + const unsubStore = store.subscribe(() => { + if (syncing) return; + const next = store.getState().cameraState; + const cur = handle.state; + const changed = + next.rotX !== cur.rotX || + next.rotY !== cur.rotY || + next.zoom !== cur.zoom || + next.distance !== cur.distance || + next.target[0] !== cur.target[0] || + next.target[1] !== cur.target[1] || + next.target[2] !== cur.target[2]; + if (!changed) return; + syncing = true; + try { + handle.update(next); + getRuntimeScene()?.applyCamera(); + } finally { + syncing = false; + } + }); + return () => { + unsubHandle(); + unsubStore(); + }; +} + +export function applyCameraTransformDirect(opts: { + runtimeScene: PolySceneHandle | null; + sceneEl: HTMLElement | null; + cameraEl: HTMLElement | null; + handle: CameraHandle; + autoCenterOffset: Vec3; + projection: PolyCameraProjection | undefined; + perspectiveStyle: string | undefined; +}): void { + if (opts.runtimeScene) { + opts.runtimeScene.applyCamera(); + writeCameraSnapshotAttrs(opts.cameraEl, opts.handle, { + projection: opts.projection, + perspectiveStyle: opts.perspectiveStyle, + }); + return; + } + if (opts.sceneEl) { + opts.sceneEl.style.transform = buildPolyCameraSceneTransform(opts.handle.state, { + autoCenterOffset: opts.autoCenterOffset, + }); + } + writeCameraSnapshotAttrs(opts.cameraEl, opts.handle, { + projection: opts.projection, + perspectiveStyle: opts.perspectiveStyle, + }); +} diff --git a/packages/polycss/src/api/controls/gizmoEngine.ts b/packages/polycss/src/api/controls/gizmoEngine.ts new file mode 100644 index 000000000..a828f8bab --- /dev/null +++ b/packages/polycss/src/api/controls/gizmoEngine.ts @@ -0,0 +1,719 @@ +/** + * Shared transform-controls drag, geometry, and fallback hit-test engine. + * + * Used by: + * - `createTransformControls` (`@layoutit/polycss`) + * - `` (`@layoutit/polycss-react`) + * - `` (`@layoutit/polycss-vue`) + */ +import { + ALPHA_DRAGGING, + ALPHA_HOVER, + ALPHA_IDLE, + ARROW_SPECS, + HEAD_HALF_THICKNESS_RATIO, + HEAD_LENGTH_RATIO, + PLANE_HALF_SIZE_RATIO, + PLANE_OFFSET_RATIO, + PLANE_SPECS, + RING_HALF_THICKNESS_RATIO, + RING_QUAD_OUTER_RATIO, + RING_RADIUS_RATIO, + RING_SPECS, + SCENE_TILE_SIZE, + SCREEN_AXIS_DEAD_ZONE_SQ, + SHAFT_HALF_THICKNESS_RATIO, + WORLD_AXIS_FOR_CSS, + arrowPolygons, + eulerXYZFromQuat, + gizmoCenterForMesh, + gizmoLengthForMesh, + isAxisBackFacing, + planePolygons, + quatFromAxisAngle, + quatFromEulerXYZ, + quatMultiply, + ringQuadPolygons, + screenPlaneDet, + snap, + solveAxisDragDelta, + solvePlaneDragDeltas, + unwrapAngleDelta, + userAxisLetterOf, + withAlpha, +} from "@layoutit/polycss-core"; +import type { Polygon, Vec3 } from "@layoutit/polycss-core"; +import { pointInMeshElement } from "../meshHitTest"; + +export type GizmoMode = "translate" | "rotate"; + +export type GizmoArrowSpec = (typeof ARROW_SPECS)[number]; +export type GizmoPlaneSpec = (typeof PLANE_SPECS)[number]; +export type GizmoRingSpec = (typeof RING_SPECS)[number]; + +export interface GizmoVisibility { + showX?: boolean; + showY?: boolean; + showZ?: boolean; +} + +export interface GizmoPolygonEntry { + spec: TSpec; + polygons: Polygon[]; +} + +export interface TransformGizmoEntries { + shaftLengthCss: number; + arrows: GizmoPolygonEntry[]; + planes: GizmoPolygonEntry[]; + rings: GizmoPolygonEntry[]; +} + +/** + * Visible band start/end as fractions of the ring quad edge. The quad covers + * `±RING_QUAD_OUTER_RATIO · mid-radius`; the visible band is + * `mid ± halfThickness`. Consumed by `.polycss-transform-ring`'s CSS mask. + */ +export const RING_MASK_INNER_RATIO = + (1 - RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; +export const RING_MASK_OUTER_RATIO = + (1 + RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; + +/** + * Swallow the synthesized `click` that immediately follows a gizmo drag's + * `pointerup`, so releasing a drag over a selected mesh does not toggle + * selection off in `` / `createSelect`. + */ +export function swallowNextClick(): void { + const swallow = (e: Event): void => { + e.stopPropagation(); + e.stopImmediatePropagation(); + }; + window.addEventListener("click", swallow, { capture: true, once: true }); + setTimeout(() => window.removeEventListener("click", swallow, true), 0); +} + +function probeScreenAxis( + wrapper: HTMLElement, + axisVec: Vec3, + probeDistanceCss: number, +): { x: number; y: number } { + const probe = wrapper.ownerDocument!.createElement("div"); + probe.style.position = "absolute"; + probe.style.left = "0"; + probe.style.top = "0"; + probe.style.width = "0"; + probe.style.height = "0"; + probe.style.transform = `translate3d(${axisVec[0] * probeDistanceCss}px, ${axisVec[1] * probeDistanceCss}px, ${axisVec[2] * probeDistanceCss}px)`; + wrapper.appendChild(probe); + const wRect = wrapper.getBoundingClientRect(); + const pRect = probe.getBoundingClientRect(); + wrapper.removeChild(probe); + return { + x: (pRect.left - wRect.left) / probeDistanceCss, + y: (pRect.top - wRect.top) / probeDistanceCss, + }; +} + +export interface AxisDragParams { + cssAxis: 0 | 1 | 2; + sign: 1 | -1; + shaftLengthCss: number; + wrapper: HTMLElement; + startClientX: number; + startClientY: number; + translationSnap: number | null; + onAxisDelta(t: number, axisVec: Vec3): void; + onMouseDown?: () => void; + onMouseUp?: () => void; + onDraggingChanged?: (dragging: boolean) => void; +} + +/** + * Project pointer screen-px deltas onto the screen projection of an axis + * vector via a temporary probe element. + */ +export function startAxisDrag(opts: AxisDragParams): boolean { + const { + cssAxis, + sign, + shaftLengthCss, + wrapper, + startClientX, + startClientY, + translationSnap, + onAxisDelta, + onMouseDown, + onMouseUp, + onDraggingChanged, + } = opts; + + const axisVec: Vec3 = [0, 0, 0]; + axisVec[cssAxis] = sign; + const screen = probeScreenAxis(wrapper, axisVec, shaftLengthCss); + const screenAxisLenSq = screen.x * screen.x + screen.y * screen.y; + if (screenAxisLenSq < SCREEN_AXIS_DEAD_ZONE_SQ) return false; + + onMouseDown?.(); + onDraggingChanged?.(true); + + const handleMove = (ev: PointerEvent): void => { + const dx = ev.clientX - startClientX; + const dy = ev.clientY - startClientY; + const t = snap(solveAxisDragDelta(dx, dy, screen.x, screen.y), translationSnap); + onAxisDelta(t, axisVec); + }; + const handleUp = (): void => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + swallowNextClick(); + onMouseUp?.(); + onDraggingChanged?.(false); + }; + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp); + window.addEventListener("pointercancel", handleUp); + return true; +} + +export interface PlaneDragParams { + axisA: 0 | 1 | 2; + axisB: 0 | 1 | 2; + probeDistanceCss: number; + wrapper: HTMLElement; + startClientX: number; + startClientY: number; + translationSnap: number | null; + onPlaneDelta(tA: number, tB: number, axisAVec: Vec3, axisBVec: Vec3): void; + onMouseDown?: () => void; + onMouseUp?: () => void; + onDraggingChanged?: (dragging: boolean) => void; +} + +/** + * Project pointer screen-px deltas onto a 2D basis (screen projections of two + * axes) and solve the 2x2 system for planar motion. + */ +export function startPlaneDrag(opts: PlaneDragParams): boolean { + const { + axisA, + axisB, + probeDistanceCss, + wrapper, + startClientX, + startClientY, + translationSnap, + onPlaneDelta, + onMouseDown, + onMouseUp, + onDraggingChanged, + } = opts; + + const axisAVec: Vec3 = [0, 0, 0]; + axisAVec[axisA] = 1; + const axisBVec: Vec3 = [0, 0, 0]; + axisBVec[axisB] = 1; + const pA = probeScreenAxis(wrapper, axisAVec, probeDistanceCss); + const pB = probeScreenAxis(wrapper, axisBVec, probeDistanceCss); + const det = screenPlaneDet(pA, pB); + if (Math.abs(det) < SCREEN_AXIS_DEAD_ZONE_SQ) return false; + + onMouseDown?.(); + onDraggingChanged?.(true); + + const handleMove = (ev: PointerEvent): void => { + const dx = ev.clientX - startClientX; + const dy = ev.clientY - startClientY; + const solved = solvePlaneDragDeltas(dx, dy, pA, pB, det); + const tA = snap(solved.tA, translationSnap); + const tB = snap(solved.tB, translationSnap); + onPlaneDelta(tA, tB, axisAVec, axisBVec); + }; + const handleUp = (): void => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + swallowNextClick(); + onMouseUp?.(); + onDraggingChanged?.(false); + }; + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp); + window.addEventListener("pointercancel", handleUp); + return true; +} + +export interface RingDragParams { + wrapper: HTMLElement; + startClientX: number; + startClientY: number; + rotationSnap: number | null; + onAngleDelta(degrees: number): void; + onMouseDown?: () => void; + onMouseUp?: () => void; + onDraggingChanged?: (dragging: boolean) => void; + onComplete?: () => void; +} + +/** + * Track pointer angle around the gizmo center, accumulate unwrapped radians, + * and report degrees of rotation. + */ +export function startRingDrag(opts: RingDragParams): void { + const { + wrapper, + startClientX, + startClientY, + rotationSnap, + onAngleDelta, + onMouseDown, + onMouseUp, + onDraggingChanged, + onComplete, + } = opts; + + const wRect = wrapper.getBoundingClientRect(); + const centerX = wRect.left; + const centerY = wRect.top; + + let lastAngle = Math.atan2(startClientY - centerY, startClientX - centerX); + let cumulative = 0; + + onMouseDown?.(); + onDraggingChanged?.(true); + + const handleMove = (ev: PointerEvent): void => { + const a = Math.atan2(ev.clientY - centerY, ev.clientX - centerX); + cumulative += unwrapAngleDelta(a, lastAngle); + lastAngle = a; + const degrees = snap((cumulative * 180) / Math.PI, rotationSnap); + onAngleDelta(degrees); + }; + const handleUp = (): void => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + swallowNextClick(); + onMouseUp?.(); + onDraggingChanged?.(false); + onComplete?.(); + }; + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp); + window.addEventListener("pointercancel", handleUp); +} + +// ── Shared geometry builders ────────────────────────────────────────────── + +export function gizmoAlphaForKey( + key: string, + hoveredKey: string | null, + draggingKey: string | null, +): number { + if (draggingKey === key) return ALPHA_DRAGGING; + if (hoveredKey === key) return ALPHA_HOVER; + return ALPHA_IDLE; +} + +export function buildArrowGizmoPolygons( + spec: { cssAxis: 0 | 1 | 2; sign: 1 | -1; color: string }, + lengthWorld: number, + alpha: number, + rotX: number, + rotY: number, +): Polygon[] { + const backFacing = isAxisBackFacing(spec.cssAxis, spec.sign, rotX, rotY); + return arrowPolygons({ + axis: WORLD_AXIS_FOR_CSS[spec.cssAxis], + sign: spec.sign, + shaftLength: lengthWorld, + shaftHalfThickness: lengthWorld * SHAFT_HALF_THICKNESS_RATIO, + headLength: lengthWorld * HEAD_LENGTH_RATIO, + headHalfThickness: lengthWorld * HEAD_HALF_THICKNESS_RATIO, + color: withAlpha(spec.color, alpha), + shaft: !backFacing, + }); +} + +export function buildPlaneGizmoPolygons( + spec: { perpAxis: 0 | 1 | 2; color: string }, + lengthWorld: number, + alpha: number, + rotX: number, + rotY: number, +): Polygon[] { + const worldPerp = WORLD_AXIS_FOR_CSS[spec.perpAxis]; + const worldA = ((worldPerp + 1) % 3) as 0 | 1 | 2; + const worldB = ((worldPerp + 2) % 3) as 0 | 1 | 2; + const cssAForOffset = WORLD_AXIS_FOR_CSS[worldA]; + const cssBForOffset = WORLD_AXIS_FOR_CSS[worldB]; + const signA = isAxisBackFacing(cssAForOffset, 1, rotX, rotY) ? -1 : 1; + const signB = isAxisBackFacing(cssBForOffset, 1, rotX, rotY) ? -1 : 1; + const mag = lengthWorld * PLANE_OFFSET_RATIO; + return planePolygons({ + axis: worldPerp, + size: lengthWorld * PLANE_HALF_SIZE_RATIO, + offset: [signA * mag, signB * mag], + color: withAlpha(spec.color, alpha), + }); +} + +export function buildRingGizmoPolygons( + spec: { cssAxis: 0 | 1 | 2; color: string }, + shaftLengthCss: number, + alpha: number, +): Polygon[] { + const radiusWorld = (shaftLengthCss * RING_RADIUS_RATIO) / SCENE_TILE_SIZE; + const outerWorld = radiusWorld * RING_QUAD_OUTER_RATIO; + return ringQuadPolygons({ + axis: WORLD_AXIS_FOR_CSS[spec.cssAxis], + outerRadius: outerWorld, + color: withAlpha(spec.color, alpha), + }); +} + +export function isArrowSpecVisible( + spec: GizmoArrowSpec, + vis: GizmoVisibility, +): boolean { + const show = { + x: vis.showX !== false, + y: vis.showY !== false, + z: vis.showZ !== false, + }; + return show[userAxisLetterOf(spec.key)]; +} + +export function isPlaneSpecVisible( + spec: GizmoPlaneSpec, + vis: GizmoVisibility, +): boolean { + const show = { + x: vis.showX !== false, + y: vis.showY !== false, + z: vis.showZ !== false, + }; + const axes = ["x", "y", "z"] as const; + return show[axes[spec.axisA]] && show[axes[spec.axisB]]; +} + +export function isRingSpecVisible( + spec: GizmoRingSpec, + vis: GizmoVisibility, +): boolean { + const show = { + x: vis.showX !== false, + y: vis.showY !== false, + z: vis.showZ !== false, + }; + return show[spec.key as "x" | "y" | "z"]; +} + +export interface BuildTransformGizmoEntriesOptions extends GizmoVisibility { + mode: GizmoMode; + polygons: Polygon[]; + size: number; + rotX: number; + rotY: number; + hoveredKey: string | null; + draggingKey: string | null; +} + +export function buildTransformGizmoEntries( + opts: BuildTransformGizmoEntriesOptions, +): TransformGizmoEntries { + const shaftLengthCss = gizmoLengthForMesh(opts.polygons) * opts.size; + const lengthWorld = shaftLengthCss / SCENE_TILE_SIZE; + + if (opts.mode === "translate") { + const arrows = ARROW_SPECS.filter((spec) => isArrowSpecVisible(spec, opts)).map( + (spec) => ({ + spec, + polygons: buildArrowGizmoPolygons( + spec, + lengthWorld, + gizmoAlphaForKey(spec.key, opts.hoveredKey, opts.draggingKey), + opts.rotX, + opts.rotY, + ), + }), + ); + const planes = PLANE_SPECS.filter((spec) => isPlaneSpecVisible(spec, opts)).map( + (spec) => ({ + spec, + polygons: buildPlaneGizmoPolygons( + spec, + lengthWorld, + gizmoAlphaForKey(spec.key, opts.hoveredKey, opts.draggingKey), + opts.rotX, + opts.rotY, + ), + }), + ); + return { shaftLengthCss, arrows, planes, rings: [] }; + } + + const rings = RING_SPECS.filter((spec) => isRingSpecVisible(spec, opts)).map( + (spec) => ({ + spec, + polygons: buildRingGizmoPolygons( + spec, + shaftLengthCss, + gizmoAlphaForKey(spec.key, opts.hoveredKey, opts.draggingKey), + ), + }), + ); + return { shaftLengthCss, arrows: [], planes: [], rings }; +} + +/** + * Compute the gizmo wrapper's CSS-pixel `translate3d` position from a target's + * world-unit `position` and mesh polygons (applying the world→CSS axis swap + + * `SCENE_TILE_SIZE` scale + mesh bbox center). + */ +export function computeGizmoWrapperPositionCss( + position: Vec3 | undefined, + polygons: Polygon[], +): Vec3 { + const pos = position ?? ([0, 0, 0] as Vec3); + const bboxCenter = gizmoCenterForMesh(polygons); + return [ + pos[1] * SCENE_TILE_SIZE + bboxCenter[0], + pos[0] * SCENE_TILE_SIZE + bboxCenter[1], + pos[2] * SCENE_TILE_SIZE + bboxCenter[2], + ]; +} + +// ── Declarative React/Vue gizmo drag & fallback controller ──────────────── + +export interface DeclarativeGizmoTarget { + getPosition(): Vec3 | undefined; + getRotation(): Vec3 | undefined; + rebakeAtlas(): void; +} + +export interface DeclarativeGizmoObjectChangeEvent< + TTarget extends DeclarativeGizmoTarget, +> { + object: TTarget; + position?: Vec3; + rotation?: Vec3; +} + +export interface DeclarativeGizmoCallbacks< + TTarget extends DeclarativeGizmoTarget, +> { + onChange?: () => void; + onObjectChange?: (event: DeclarativeGizmoObjectChangeEvent) => void; + onMouseDown?: () => void; + onMouseUp?: () => void; + onDraggingChanged?: (dragging: boolean) => void; +} + +export interface DeclarativeGizmoDragState< + TTarget extends DeclarativeGizmoTarget, +> extends DeclarativeGizmoCallbacks, + GizmoVisibility { + target: TTarget | null; + mode: GizmoMode; + shaftLengthCss: number; + enabled: boolean; + translationSnap: number | null; + rotationSnap: number | null; + onDraggingKeyChange?: (key: string | null) => void; +} + +export function startDeclarativeArrowDrag< + TTarget extends DeclarativeGizmoTarget, +>( + spec: GizmoArrowSpec, + wrapper: HTMLElement, + startClientX: number, + startClientY: number, + state: DeclarativeGizmoDragState, +): boolean { + const target = state.target; + if (!target || !state.enabled) return false; + const startPos = (target.getPosition() ?? [0, 0, 0]) as Vec3; + const started = startAxisDrag({ + cssAxis: spec.cssAxis, + sign: spec.sign, + shaftLengthCss: state.shaftLengthCss, + wrapper, + startClientX, + startClientY, + translationSnap: state.translationSnap, + onAxisDelta: (t, axisVec) => { + const next: Vec3 = [ + startPos[0] + t * axisVec[0], + startPos[1] + t * axisVec[1], + startPos[2] + t * axisVec[2], + ]; + state.onObjectChange?.({ object: target, position: next }); + state.onChange?.(); + }, + onMouseDown: state.onMouseDown, + onMouseUp: state.onMouseUp, + onDraggingChanged: (d) => { + state.onDraggingKeyChange?.(d ? spec.key : null); + state.onDraggingChanged?.(d); + }, + }); + return started; +} + +export function startDeclarativePlaneDrag< + TTarget extends DeclarativeGizmoTarget, +>( + spec: GizmoPlaneSpec, + wrapper: HTMLElement, + startClientX: number, + startClientY: number, + state: DeclarativeGizmoDragState, +): boolean { + const target = state.target; + if (!target || !state.enabled) return false; + const startPos = (target.getPosition() ?? [0, 0, 0]) as Vec3; + return startPlaneDrag({ + axisA: spec.axisA, + axisB: spec.axisB, + probeDistanceCss: state.shaftLengthCss, + wrapper, + startClientX, + startClientY, + translationSnap: state.translationSnap, + onPlaneDelta: (tA, tB, axisAVec, axisBVec) => { + const next: Vec3 = [ + startPos[0] + tA * axisAVec[0] + tB * axisBVec[0], + startPos[1] + tA * axisAVec[1] + tB * axisBVec[1], + startPos[2] + tA * axisAVec[2] + tB * axisBVec[2], + ]; + state.onObjectChange?.({ object: target, position: next }); + state.onChange?.(); + }, + onMouseDown: state.onMouseDown, + onMouseUp: state.onMouseUp, + onDraggingChanged: (d) => { + state.onDraggingKeyChange?.(d ? spec.key : null); + state.onDraggingChanged?.(d); + }, + }); +} + +export function startDeclarativeRingDrag< + TTarget extends DeclarativeGizmoTarget, +>( + spec: GizmoRingSpec, + wrapper: HTMLElement, + startClientX: number, + startClientY: number, + state: DeclarativeGizmoDragState, +): void { + const target = state.target; + if (!target || !state.enabled) return; + const startRotation = (target.getRotation() ?? [0, 0, 0]) as Vec3; + const qStart = quatFromEulerXYZ(startRotation); + const axisVec: Vec3 = [0, 0, 0]; + axisVec[spec.cssAxis] = 1; + startRingDrag({ + wrapper, + startClientX, + startClientY, + rotationSnap: state.rotationSnap, + onAngleDelta: (degrees) => { + const qDelta = quatFromAxisAngle(axisVec, (degrees * Math.PI) / 180); + const nextRotation = eulerXYZFromQuat(quatMultiply(qDelta, qStart)); + state.onObjectChange?.({ object: target, rotation: nextRotation }); + state.onChange?.(); + }, + onMouseDown: state.onMouseDown, + onMouseUp: state.onMouseUp, + onDraggingChanged: (d) => { + state.onDraggingKeyChange?.(d ? spec.key : null); + state.onDraggingChanged?.(d); + }, + onComplete: () => { + target.rebakeAtlas(); + }, + }); +} + +/** + * Attach a camera-level `pointerdown` JS bounding-rect fallback listener for + * declarative `` wrappers (React & Vue). Handles clicks + * that fall through native polygon hit-testing (e.g. `border-shape` clipping + * or upstream `pointer-events: none`), while skipping clicks that already hit + * a `.polycss-transform-gizmo` element. + */ +export function attachDeclarativeGizmoFallback< + TTarget extends DeclarativeGizmoTarget, +>( + cameraEl: HTMLElement, + getState: () => DeclarativeGizmoDragState, +): () => void { + const onPointerDown = (event: PointerEvent): void => { + const state = getState(); + if (!state.target || !state.enabled) return; + const targetEl = event.target as Element | null; + if (targetEl?.closest(".polycss-transform-gizmo")) return; + const doc = cameraEl.ownerDocument ?? document; + + if (state.mode === "translate") { + // Plane handles are hit-tested first so they win at overlapping corners. + for (const spec of PLANE_SPECS) { + if (!isPlaneSpecVisible(spec, state)) continue; + const planeEl = doc.querySelector( + `.polycss-transform-plane--${spec.key}`, + ) as HTMLElement | null; + if (!planeEl) continue; + if (!pointInMeshElement(planeEl, event.clientX, event.clientY)) continue; + const wrapper = planeEl.closest( + "[data-poly-transform-controls]", + ) as HTMLElement | null; + if (!wrapper) return; + event.preventDefault(); + event.stopPropagation(); + startDeclarativePlaneDrag(spec, wrapper, event.clientX, event.clientY, state); + return; + } + for (const spec of ARROW_SPECS) { + if (!isArrowSpecVisible(spec, state)) continue; + const arrowEl = doc.querySelector( + `.polycss-transform-arrow--${spec.key}`, + ) as HTMLElement | null; + if (!arrowEl) continue; + if (!pointInMeshElement(arrowEl, event.clientX, event.clientY)) continue; + const wrapper = arrowEl.closest( + "[data-poly-transform-controls]", + ) as HTMLElement | null; + if (!wrapper) return; + event.preventDefault(); + event.stopPropagation(); + startDeclarativeArrowDrag(spec, wrapper, event.clientX, event.clientY, state); + return; + } + return; + } + + for (const spec of RING_SPECS) { + if (!isRingSpecVisible(spec, state)) continue; + const ringEl = doc.querySelector( + `.polycss-transform-ring--${spec.key}`, + ) as HTMLElement | null; + if (!ringEl) continue; + if (!pointInMeshElement(ringEl, event.clientX, event.clientY)) continue; + const wrapper = ringEl.closest( + "[data-poly-transform-controls]", + ) as HTMLElement | null; + if (!wrapper) return; + event.preventDefault(); + event.stopPropagation(); + startDeclarativeRingDrag(spec, wrapper, event.clientX, event.clientY, state); + return; + } + }; + + cameraEl.addEventListener("pointerdown", onPointerDown); + return () => cameraEl.removeEventListener("pointerdown", onPointerDown); +} diff --git a/packages/polycss/src/api/controls/selectionEngine.ts b/packages/polycss/src/api/controls/selectionEngine.ts new file mode 100644 index 000000000..debb9e19a --- /dev/null +++ b/packages/polycss/src/api/controls/selectionEngine.ts @@ -0,0 +1,131 @@ +/** + * Shared mesh selection state and click-delegation controller. + * + * Used by: + * - `createSelect` (`@layoutit/polycss`) + * - `` (`@layoutit/polycss-react`) + * - `` (`@layoutit/polycss-vue`) + */ + +export interface SelectionControllerOptions { + /** Whether multi-selection (shift/meta/ctrl + click, `add`) is enabled. */ + getMultiple: () => boolean; + /** Whether clicking background clears selection. Default true. */ + getClearOnMiss: () => boolean; + /** Optional filter applied to every selection update. */ + getFilter: () => ((meshes: TMesh[]) => TMesh[]) | undefined; + /** Resolve a clicked DOM target or viewport coordinate to a mesh handle. */ + resolveTarget: (target: Element | null, clientX: number, clientY: number) => TMesh | null; + /** Optional predicate to ignore clicks (e.g. transform gizmo elements). */ + shouldIgnoreTarget?: (target: Element | null) => boolean; + /** Called whenever selection is committed. */ + onChange: (meshes: TMesh[]) => void; + /** Called when a click resolves to no mesh. */ + onPointerMissed?: (event: MouseEvent) => void; + /** When true, `clear()` is a no-op if selection is already empty. Default false. */ + skipEmptyClear?: boolean; +} + +export interface SelectionController { + readonly selected: TMesh[]; + set(next: TMesh[]): void; + add(mesh: TMesh): void; + remove(mesh: TMesh): void; + toggle(mesh: TMesh): void; + clear(): void; + has(mesh: TMesh): boolean; + handleClick(event: MouseEvent): void; + attach(el: HTMLElement): () => void; +} + +export function createSelectionController( + options: SelectionControllerOptions, +): SelectionController { + let selected: TMesh[] = []; + + function commit(next: TMesh[]): void { + const filter = options.getFilter(); + const filtered = filter ? filter(next) : next; + selected = filtered; + options.onChange(filtered); + } + + function set(next: TMesh[]): void { + commit(next); + } + + function add(mesh: TMesh): void { + if (options.getMultiple()) { + if (selected.includes(mesh)) { + commit(selected); + return; + } + commit([...selected, mesh]); + } else { + commit([mesh]); + } + } + + function remove(mesh: TMesh): void { + if (!selected.includes(mesh)) return; + commit(selected.filter((item) => item !== mesh)); + } + + function toggle(mesh: TMesh): void { + if (selected.includes(mesh)) { + commit(selected.filter((item) => item !== mesh)); + } else if (options.getMultiple()) { + commit([...selected, mesh]); + } else { + commit([mesh]); + } + } + + function clear(): void { + if (options.skipEmptyClear && selected.length === 0) return; + commit([]); + } + + function has(mesh: TMesh): boolean { + return selected.includes(mesh); + } + + function handleClick(event: MouseEvent): void { + const target = event.target as Element | null; + if (options.shouldIgnoreTarget?.(target)) return; + const handle = options.resolveTarget(target, event.clientX, event.clientY); + if (!handle) { + options.onPointerMissed?.(event); + if (options.getClearOnMiss()) clear(); + return; + } + const additive = + options.getMultiple() && (event.shiftKey || event.metaKey || event.ctrlKey); + if (additive) { + toggle(handle); + } else if (selected.length === 1 && selected[0] === handle) { + clear(); + } else { + set([handle]); + } + } + + function attach(el: HTMLElement): () => void { + el.addEventListener("click", handleClick); + return () => el.removeEventListener("click", handleClick); + } + + return { + get selected() { + return selected; + }, + set, + add, + remove, + toggle, + clear, + has, + handleClick, + attach, + }; +} diff --git a/packages/polycss/src/api/createPolyScene.ts b/packages/polycss/src/api/createPolyScene.ts index 5b4f01da2..84b4bd3f1 100644 --- a/packages/polycss/src/api/createPolyScene.ts +++ b/packages/polycss/src/api/createPolyScene.ts @@ -33,11 +33,10 @@ import { DEFAULT_SEAM_BLEED, computeSceneBbox, computeLightVisibility, - capturePolyCameraSnapshot, inverseRotateVec3, optimizeMeshPolygons, - } from "@layoutit/polycss-core"; +import { writeCameraSnapshotAttrs } from "./cameraSnapshotAttrs"; import { getSolidPaintDefaults, renderPolygonsWithTextureAtlas, @@ -270,16 +269,7 @@ export function createPolyScene( // the wrapper must be the perspective context for .polycss-scene to work // correctly — matching React/Vue's PolyPerspectiveCamera wrapper shape. function applyCameraStyle(el: HTMLElement, _opts: Omit): void { - const snapshot = capturePolyCameraSnapshot(camera); - el.style.perspective = snapshot.appliedPerspectiveStyle; - el.dataset.polycssCameraProjection = snapshot.projection; - el.dataset.polycssCameraPerspective = snapshot.perspectiveStyle; - el.dataset.polycssCameraAppliedPerspective = snapshot.appliedPerspectiveStyle; - el.dataset.polycssCameraZoom = String(snapshot.state.zoom); - el.dataset.polycssCameraDistance = String(snapshot.state.distance); - el.dataset.polycssCameraRotX = String(snapshot.state.rotX); - el.dataset.polycssCameraRotY = String(snapshot.state.rotY); - el.dataset.polycssCameraTarget = snapshot.state.target.join(","); + writeCameraSnapshotAttrs(el, camera, { applyPerspective: true }); } // Dynamic lighting cascade vars: PolyScene writes the directional + ambient diff --git a/packages/polycss/src/api/createSelect.ts b/packages/polycss/src/api/createSelect.ts index 5ea87cde9..ada2a31fb 100644 --- a/packages/polycss/src/api/createSelect.ts +++ b/packages/polycss/src/api/createSelect.ts @@ -1,33 +1,21 @@ /** * createSelect — additive selection layer for vanilla PolyCSS scenes. - * Mirrors the React `. - clear(); - } else { - set([handle]); - } - }; - scene.host.addEventListener("click", onClick); + const detach = controller.attach(scene.host); function destroy(): void { - scene.host.removeEventListener("click", onClick); + detach(); subscribers.clear(); } return { - get selected() { return selected; }, - set, - add, - remove, - toggle, - clear, - has, + get selected() { + return controller.selected; + }, + set: controller.set, + add: controller.add, + remove: controller.remove, + toggle: controller.toggle, + clear: controller.clear, + has: controller.has, destroy, }; } diff --git a/packages/polycss/src/api/createTransformControls.ts b/packages/polycss/src/api/createTransformControls.ts index 92836a777..64ac1795c 100644 --- a/packages/polycss/src/api/createTransformControls.ts +++ b/packages/polycss/src/api/createTransformControls.ts @@ -1,77 +1,49 @@ /** - * createTransformControls — vanilla equivalent of ``. - * Builds the same six-arrow translate gizmo / three-ring rotate gizmo - * around an attached mesh and emits `objectChange` events as the user - * drags. Mirrors the React API surface (mode, size, snap, draggingChanged - * event) and uses the same shared geometry helpers in `@layoutit/polycss-core` - * (`arrowPolygons`, `ringQuadPolygons`). - * - * Usage: - * const tc = createTransformControls(scene, { - * mode: "translate", - * // Events are constructor options — the handle has no `on(...)`. - * onObjectChange: ({ position, rotation }) => { - * // Apply to your own state if you need to keep it in sync; the - * // gizmo already calls target.setTransform internally. - * }, - * }); - * tc.attach(meshHandle); - * tc.setMode("rotate"); - * tc.detach(); - * tc.destroy(); + * createTransformControls — vanilla equivalent of ``. + * Builds the six-arrow + three-plane translate gizmo or three-ring rotate gizmo + * around an attached mesh and emits `objectChange` events as the user drags. + * Shares drag math and geometry builders with React/Vue via `gizmoEngine.ts`. */ import { - ALPHA_DRAGGING, - ALPHA_HOVER, - ALPHA_IDLE, ARROW_SPECS, - HEAD_HALF_THICKNESS_RATIO, - HEAD_LENGTH_RATIO, - PLANE_HALF_SIZE_RATIO, - PLANE_OFFSET_RATIO, PLANE_SPECS, - RING_QUAD_OUTER_RATIO, - RING_HALF_THICKNESS_RATIO, - RING_RADIUS_RATIO, RING_SPECS, SCENE_TILE_SIZE, - SCREEN_AXIS_DEAD_ZONE_SQ, - SHAFT_HALF_THICKNESS_RATIO, WORLD_AXIS_FOR_CSS, - arrowPolygons, eulerXYZFromQuat, gizmoLengthForMesh, - isAxisBackFacing, - planePolygons, quatFromAxisAngle, quatFromEulerXYZ, quatMultiply, - ringQuadPolygons, rotateVec3, - screenPlaneDet, - snap, - solveAxisDragDelta, - solvePlaneDragDeltas, - unwrapAngleDelta, - withAlpha, } from "@layoutit/polycss-core"; import type { Polygon, Vec3 } from "@layoutit/polycss-core"; import type { PolyMeshHandle, PolySceneHandle } from "./createPolyScene"; import { pointInMeshElement } from "./meshHitTest"; +import { + RING_MASK_INNER_RATIO, + RING_MASK_OUTER_RATIO, + buildArrowGizmoPolygons, + buildPlaneGizmoPolygons, + buildRingGizmoPolygons, + gizmoAlphaForKey, + isArrowSpecVisible, + isPlaneSpecVisible, + isRingSpecVisible, + startAxisDrag, + startPlaneDrag, + startRingDrag, + type GizmoMode, +} from "./controls/gizmoEngine"; -type Mode = "translate" | "rotate"; - -/** Compute the bbox center of a mesh's polygons in WORLD units, world-axis - * order (`+X right, +Y forward, +Z up`). Added to `target.transform.position` - * (also world units, world-axis) to place the gizmo at the mesh's visible - * centroid. PolyMesh's buildMeshTransform applies the world→CSS axis swap + - * ×BASE_TILE on the resulting position, so consumers stay in world units. - * Collapses to (0,0,0) when the mesh is already centered (e.g. when - * PolyMesh autoCenter or `loadMesh(..., { center: true })` was used). */ function bboxCenterWorld(polygons: Polygon[]): Vec3 { if (polygons.length === 0) return [0, 0, 0]; - let minX = Infinity, minY = Infinity, minZ = Infinity; - let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; + let minX = Infinity; + let minY = Infinity; + let minZ = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + let maxZ = -Infinity; for (const poly of polygons) { for (const v of poly.vertices) { if (v[0] < minX) minX = v[0]; @@ -83,11 +55,7 @@ function bboxCenterWorld(polygons: Polygon[]): Vec3 { } } if (!Number.isFinite(minX)) return [0, 0, 0]; - return [ - (minX + maxX) / 2, - (minY + maxY) / 2, - (minZ + maxZ) / 2, - ]; + return [(minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2]; } export interface PolyTransformControlsObjectChangeEvent { @@ -98,7 +66,7 @@ export interface PolyTransformControlsObjectChangeEvent { export interface PolyTransformControlsOptions { /** Drag mode. "translate" → axial arrows, "rotate" → axial rings. */ - mode?: Mode; + mode?: GizmoMode; /** Multiplier on gizmo size (shaft length / ring radius). Default 1. */ size?: number; /** Snap step (CSS pixels) for translate-mode. */ @@ -119,9 +87,7 @@ export interface PolyTransformControlsOptions { applyTransform?: boolean; /** Fires for any transform change. Argument-less, mirrors three.js. */ onChange?: () => void; - /** Fires with the new transform during drag. The gizmo also calls - * `target.setTransform` internally; this callback lets parent code - * mirror the change into its own state. */ + /** Fires with the new transform during drag. */ onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; /** Fires once on drag start. */ onMouseDown?: () => void; @@ -132,396 +98,80 @@ export interface PolyTransformControlsOptions { } export interface PolyTransformControlsHandle { - /** Bind to a mesh — gizmo follows the mesh's transform. Pass `null` - * to detach. Calling `attach` again with a new target swaps the - * binding without rebuilding the gizmo geometry. */ + /** Bind to a mesh — gizmo follows the mesh's transform. Pass `null` to detach. */ attach(mesh: PolyMeshHandle | null): void; /** Equivalent to `attach(null)`. */ detach(): void; - /** Switch between translate and rotate. Tears down the old gizmo - * and rebuilds the new one. */ - setMode(mode: Mode): void; - /** Re-read the target's transform and reposition the gizmo. Call - * after mutating `target.setTransform` externally if you want the - * gizmo to follow. */ + /** Switch between translate and rotate. */ + setMode(mode: GizmoMode): void; + /** Re-read the target's transform and reposition the gizmo. */ update(): void; - /** Update options (size, snaps, visibility, callbacks, applyTransform) - * in place without tearing down the controller. Rebuilds gizmo geometry - * only when mode, size, or axis visibility changed. */ + /** Update options in place without tearing down the controller. */ setOptions(partial: Partial): void; /** Remove all listeners + gizmo meshes from the scene. Idempotent. */ destroy(): void; } -interface DragOptions { - cssAxis: 0 | 1 | 2; - sign: 1 | -1; - shaftLengthCss: number; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - translationSnap: number | null; - onAxisDelta(t: number, axisVec: Vec3): void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** Project pointer screen-px deltas onto the screen projection of an - * axis vector via a temporary probe element. Matches React's - * `startAxisDrag`. */ -function startAxisDrag(opts: DragOptions): void { - const { - cssAxis, - sign, - shaftLengthCss, - wrapper, - target: _target, - startClientX, - startClientY, - translationSnap, - onAxisDelta, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - const probeDistance = shaftLengthCss; - const axisVec: Vec3 = [0, 0, 0]; - axisVec[cssAxis] = sign; - const probe = wrapper.ownerDocument!.createElement("div"); - probe.style.position = "absolute"; - probe.style.left = "0"; - probe.style.top = "0"; - probe.style.width = "0"; - probe.style.height = "0"; - probe.style.transform = `translate3d(${axisVec[0] * probeDistance}px, ${axisVec[1] * probeDistance}px, ${axisVec[2] * probeDistance}px)`; - wrapper.appendChild(probe); - const wRect = wrapper.getBoundingClientRect(); - const pRect = probe.getBoundingClientRect(); - wrapper.removeChild(probe); - const screenAxisX = (pRect.left - wRect.left) / probeDistance; - const screenAxisY = (pRect.top - wRect.top) / probeDistance; - const screenAxisLenSq = screenAxisX * screenAxisX + screenAxisY * screenAxisY; - if (screenAxisLenSq < SCREEN_AXIS_DEAD_ZONE_SQ) return; - - onMouseDown?.(); - onDraggingChanged?.(true); - - const handleMove = (ev: PointerEvent): void => { - const dx = ev.clientX - startClientX; - const dy = ev.clientY - startClientY; - let t = solveAxisDragDelta(dx, dy, screenAxisX, screenAxisY); - t = snap(t, translationSnap); - onAxisDelta(t, axisVec); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - // Swallow the click that follows pointerup so a release-over-mesh - // doesn't toggle selection in createSelect. - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - -interface PlaneDragOptions { - axisA: 0 | 1 | 2; - axisB: 0 | 1 | 2; - probeDistanceCss: number; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - translationSnap: number | null; - onPlaneDelta(tA: number, tB: number, axisAVec: Vec3, axisBVec: Vec3): void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** Project pointer screen-px deltas onto a 2D basis (screen projections of - * two world axes) and solve a 2x2 system for the planar motion. Mirror of - * the single-axis projection in `startAxisDrag`, extended to two axes. */ -function startPlaneDrag(opts: PlaneDragOptions): void { - const { - axisA, - axisB, - probeDistanceCss, - wrapper, - startClientX, - startClientY, - translationSnap, - onPlaneDelta, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - // Probe both in-plane axes to measure their screen projections. Same - // technique as startAxisDrag: place a 0×0 element at `axis * dist`, read - // its bounding rect against the wrapper's, divide by `dist` to get the - // unit screen vector for that world axis. - const axisAVec: Vec3 = [0, 0, 0]; axisAVec[axisA] = 1; - const axisBVec: Vec3 = [0, 0, 0]; axisBVec[axisB] = 1; - function probe(axisVec: Vec3): { x: number; y: number } { - const el = wrapper.ownerDocument!.createElement("div"); - el.style.position = "absolute"; - el.style.left = "0"; - el.style.top = "0"; - el.style.width = "0"; - el.style.height = "0"; - el.style.transform = `translate3d(${axisVec[0] * probeDistanceCss}px, ${axisVec[1] * probeDistanceCss}px, ${axisVec[2] * probeDistanceCss}px)`; - wrapper.appendChild(el); - const wR = wrapper.getBoundingClientRect(); - const pR = el.getBoundingClientRect(); - wrapper.removeChild(el); - return { - x: (pR.left - wR.left) / probeDistanceCss, - y: (pR.top - wR.top) / probeDistanceCss, - }; - } - const pA = probe(axisAVec); - const pB = probe(axisBVec); - const det = screenPlaneDet(pA, pB); - if (Math.abs(det) < SCREEN_AXIS_DEAD_ZONE_SQ) return; // plane edge-on to camera - - onMouseDown?.(); - onDraggingChanged?.(true); - - const handleMove = (ev: PointerEvent): void => { - const dx = ev.clientX - startClientX; - const dy = ev.clientY - startClientY; - const solved = solvePlaneDragDeltas(dx, dy, pA, pB, det); - const tA = snap(solved.tA, translationSnap); - const tB = snap(solved.tB, translationSnap); - onPlaneDelta(tA, tB, axisAVec, axisBVec); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - -interface RingDragOptions { - cssAxis: 0 | 1 | 2; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - rotationSnap: number | null; - onAngleDelta(degrees: number): void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** Track pointer angle around the gizmo center, accumulate the - * unwrapped delta, and feed it back as degrees of rotation. Matches - * React's `startRingDrag`. */ -function startRingDrag(opts: RingDragOptions): void { - const { - cssAxis: _cssAxis, - wrapper, - target: _target, - startClientX, - startClientY, - rotationSnap, - onAngleDelta, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - const wRect = wrapper.getBoundingClientRect(); - const centerX = wRect.left; - const centerY = wRect.top; - - let lastAngle = Math.atan2(startClientY - centerY, startClientX - centerX); - let cumulative = 0; - - onMouseDown?.(); - onDraggingChanged?.(true); - - const handleMove = (ev: PointerEvent): void => { - const a = Math.atan2(ev.clientY - centerY, ev.clientX - centerX); - cumulative += unwrapAngleDelta(a, lastAngle); - lastAngle = a; - let degrees = (cumulative * 180) / Math.PI; - degrees = snap(degrees, rotationSnap); - onAngleDelta(degrees); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} +type GizmoSpec = + | { kind: "arrow"; key: string; cssAxis: 0 | 1 | 2; sign: 1 | -1; color: string } + | { kind: "ring"; key: string; cssAxis: 0 | 1 | 2; color: string } + | { kind: "plane"; key: string; perpAxis: 0 | 1 | 2; axisA: 0 | 1 | 2; axisB: 0 | 1 | 2; color: string }; export function createTransformControls( scene: PolySceneHandle, options: PolyTransformControlsOptions = {}, ): PolyTransformControlsHandle { let target: PolyMeshHandle | null = null; - let mode: Mode = options.mode ?? "translate"; + let mode: GizmoMode = options.mode ?? "translate"; let size = options.size ?? 1; const opts: PolyTransformControlsOptions = { ...options }; - // No standalone wrapper element. The earlier draft appended a - // wrapper to `scene.host`, but that lives OUTSIDE the camera- - // transformed scene root (`.polycss-camera` carries the scale + - // rotateX/rotateY), so the gizmo polygons rendered in screen space - // and ignored the camera. Going through `scene.add` for each gizmo - // mesh puts it inside the centerWrapper (camera-space), which is - // exactly the same coordinate frame the user mesh lives in. Each - // gizmo mesh is positioned at `target.transform.position` via - // setTransform — that's the gizmo origin. - - // Per-key tracking. Each gizmo arrow / ring / plane is a polycss - // PolyMeshHandle added to the scene, then re-parented under our wrapper. - type GizmoSpec = - | { kind: "arrow"; key: string; cssAxis: 0 | 1 | 2; sign: 1 | -1; color: string } - | { kind: "ring"; key: string; cssAxis: 0 | 1 | 2; color: string } - | { kind: "plane"; key: string; perpAxis: 0 | 1 | 2; axisA: 0 | 1 | 2; axisB: 0 | 1 | 2; color: string }; type GizmoMesh = { handle: PolyMeshHandle; spec: GizmoSpec }; const gizmos = new Map(); let hoveredKey: string | null = null; let draggingKey: string | null = null; - // Offset added to `target.transform.position` to place the gizmo at - // the mesh's visible center under scene-level autoCenter. Cached on - // attach because it depends only on the target's polygon bbox. let centerOffset: Vec3 = [0, 0, 0]; + let dragStartPosition: Vec3 | null = null; + let dragStartRotation: Vec3 | null = null; function gizmoPosition(): Vec3 { if (!target) return [0, 0, 0]; const t = target.transform.position ?? ([0, 0, 0] as Vec3); const r = target.transform.rotation ?? ([0, 0, 0] as Vec3); - const s = typeof target.transform.scale === "number" - ? target.transform.scale - : (target.transform.scale?.[0] ?? 1); - // Visible mesh center under the post-parity wrapper transform - // `T · R · S · p`: at p = bboxCenter (mesh-local), visible center - // = T + scale * R(rotation) * bboxCenter. Apply current rotation so - // the gizmo follows the mesh while it spins — without this, the - // rotation handler's pivot compensation slides position around to - // keep the visible center fixed and the gizmo (placed at - // position + centerOffset) drifts off-axis. + const s = + typeof target.transform.scale === "number" + ? target.transform.scale + : (target.transform.scale?.[0] ?? 1); const rc = rotateVec3(centerOffset, r[0], r[1], r[2]); return [t[0] + s * rc[0], t[1] + s * rc[1], t[2] + s * rc[2]]; } function alphaFor(key: string): number { - if (draggingKey === key) return ALPHA_DRAGGING; - if (hoveredKey === key) return ALPHA_HOVER; - return ALPHA_IDLE; - } - - function rebuildGizmoColors(): void { - // Re-emit each arrow/ring's polygons with the updated alpha. Cheap - // — geometry hasn't changed, just the per-polygon color string. - for (const [key, gm] of gizmos) { - const polys = buildPolygonsFor(gm.spec, alphaFor(key)); - gm.handle.setPolygons(polys, { recomputeAutoCenter: false }); - } + return gizmoAlphaForKey(key, hoveredKey, draggingKey); } function buildPolygonsFor(spec: GizmoSpec, alpha: number): Polygon[] { - const baseLength = gizmoLengthForMesh(target?.polygons ?? []); - const shaftLengthCss = baseLength * size; + const shaftLengthCss = gizmoLengthForMesh(target?.polygons ?? []) * size; const lengthWorld = shaftLengthCss / SCENE_TILE_SIZE; - const color = withAlpha(spec.color, alpha); + const cameraState = scene.camera.state; + const rotX = cameraState.rotX ?? 65; + const rotY = cameraState.rotY ?? 45; + if (spec.kind === "arrow") { - // Strip the shaft for back-facing arrows so the visible-only-from- - // outside silhouette stays clean. Both halves of a pair otherwise - // share the same shaft volume at the gizmo origin. - const cameraState = scene.camera.state; - const backFacing = isAxisBackFacing( - spec.cssAxis, - spec.sign, - cameraState.rotX ?? 65, - cameraState.rotY ?? 45, - ); - return arrowPolygons({ - axis: WORLD_AXIS_FOR_CSS[spec.cssAxis], - sign: spec.sign, - shaftLength: lengthWorld, - shaftHalfThickness: lengthWorld * SHAFT_HALF_THICKNESS_RATIO, - headLength: lengthWorld * HEAD_LENGTH_RATIO, - headHalfThickness: lengthWorld * HEAD_HALF_THICKNESS_RATIO, - color, - shaft: !backFacing, - }); + return buildArrowGizmoPolygons(spec, lengthWorld, alpha, rotX, rotY); } if (spec.kind === "plane") { - // Place the quad in the camera-facing octant: for each in-plane axis, - // flip the offset sign if the +axis is back-facing. planePolygons - // works in WORLD axes (a = (perp+1)%3, b = (perp+2)%3); since - // WORLD_AXIS_FOR_CSS is involutive, the CSS axis we test for back- - // facing is just WORLD_AXIS_FOR_CSS[worldA / worldB]. - const cameraState = scene.camera.state; - const rotX = cameraState.rotX ?? 65; - const rotY = cameraState.rotY ?? 45; - const worldPerp = WORLD_AXIS_FOR_CSS[spec.perpAxis]; - const worldA = ((worldPerp + 1) % 3) as 0 | 1 | 2; - const worldB = ((worldPerp + 2) % 3) as 0 | 1 | 2; - const cssAForOffset = WORLD_AXIS_FOR_CSS[worldA]; - const cssBForOffset = WORLD_AXIS_FOR_CSS[worldB]; - const signA = isAxisBackFacing(cssAForOffset, 1, rotX, rotY) ? -1 : 1; - const signB = isAxisBackFacing(cssBForOffset, 1, rotX, rotY) ? -1 : 1; - const mag = lengthWorld * PLANE_OFFSET_RATIO; - return planePolygons({ - axis: worldPerp, - size: lengthWorld * PLANE_HALF_SIZE_RATIO, - offset: [signA * mag, signB * mag], - color, + return buildPlaneGizmoPolygons(spec, lengthWorld, alpha, rotX, rotY); + } + return buildRingGizmoPolygons(spec, shaftLengthCss, alpha); + } + + function rebuildGizmoColors(): void { + for (const [key, gm] of gizmos) { + gm.handle.setPolygons(buildPolygonsFor(gm.spec, alphaFor(key)), { + recomputeAutoCenter: false, }); } - // ring — single square quad masked to a donut via CSS (see - // .polycss-transform-ring rule in styles.ts). One DOM node per ring - // instead of N segment quads. Quad outer radius is sized by - // RING_QUAD_OUTER_RATIO so the hit footprint stays generous even when - // the visible band (driven by RING_HALF_THICKNESS_RATIO) is thin. - const radiusWorld = (shaftLengthCss * RING_RADIUS_RATIO) / SCENE_TILE_SIZE; - const outerWorld = radiusWorld * RING_QUAD_OUTER_RATIO; - return ringQuadPolygons({ - axis: WORLD_AXIS_FOR_CSS[spec.cssAxis], - outerRadius: outerWorld, - color, - }); } function classPrefixFor(spec: GizmoSpec): string { @@ -530,63 +180,44 @@ export function createTransformControls( return "polycss-transform-ring"; } - /** Resolve the active spec list for the current mode. Translate mode mixes - * the 6 axis arrows with the 3 planar handles; rotate mode just rings. */ function activeSpecs(): GizmoSpec[] { if (mode === "translate") { - const arrows: GizmoSpec[] = ARROW_SPECS.map((a) => ({ - kind: "arrow", - key: a.key, - cssAxis: a.cssAxis, - sign: a.sign, - color: a.color, - })); - const planes: GizmoSpec[] = PLANE_SPECS.map((p) => ({ - kind: "plane", - key: p.key, - perpAxis: p.perpAxis, - axisA: p.axisA, - axisB: p.axisB, - color: p.color, - })); + const arrows: GizmoSpec[] = ARROW_SPECS.filter((a) => isArrowSpecVisible(a, opts)).map( + (a) => ({ kind: "arrow", key: a.key, cssAxis: a.cssAxis, sign: a.sign, color: a.color }), + ); + const planes: GizmoSpec[] = PLANE_SPECS.filter((p) => isPlaneSpecVisible(p, opts)).map( + (p) => ({ + kind: "plane", + key: p.key, + perpAxis: p.perpAxis, + axisA: p.axisA, + axisB: p.axisB, + color: p.color, + }), + ); return [...arrows, ...planes]; } - if (mode === "rotate") { - return RING_SPECS.map((r) => ({ kind: "ring", key: r.key, cssAxis: r.cssAxis, color: r.color })); - } - return []; + return RING_SPECS.filter((r) => isRingSpecVisible(r, opts)).map((r) => ({ + kind: "ring", + key: r.key, + cssAxis: r.cssAxis, + color: r.color, + })); + } + + function teardownGizmos(): void { + for (const { handle } of gizmos.values()) handle.remove(); + gizmos.clear(); + hoveredKey = null; + draggingKey = null; } function buildGizmos(): void { teardownGizmos(); if (!target) return; - const showByKey = { - x: opts.showX !== false, - y: opts.showY !== false, - z: opts.showZ !== false, - }; - function specVisible(spec: GizmoSpec): boolean { - if (spec.kind === "arrow") { - const userAxis = spec.key.replace("-", "")[0] as "x" | "y" | "z"; - return showByKey[userAxis]; - } - if (spec.kind === "ring") { - return showByKey[spec.key as "x" | "y" | "z"]; - } - // Plane handles need BOTH in-plane axes visible. - const aName = (["x", "y", "z"] as const)[spec.axisA]; - const bName = (["x", "y", "z"] as const)[spec.axisB]; - return showByKey[aName] && showByKey[bName]; - } const targetPos = gizmoPosition(); for (const spec of activeSpecs()) { - if (!specVisible(spec)) continue; const polys = buildPolygonsFor(spec, alphaFor(spec.key)); - // Each gizmo mesh is added directly to the scene at the target's - // position. scene.add appends to centerWrapper (the camera- - // transformed scene root), so the arrow inherits the scene's - // perspective + rotateX/rotateY/scale automatically — no - // separate wrapper needed. const handle = scene.add( { polygons: polys, objectUrls: [], warnings: [], dispose: () => {} }, { @@ -603,28 +234,13 @@ export function createTransformControls( `${classPrefix}--${spec.key}`, ); if (spec.kind === "ring") { - // Two CSS vars consumed by the .polycss-transform-ring mask: where - // the visible band STARTS and ENDS, both as a fraction of the quad - // edge (50%). The quad's outer radius is RING_QUAD_OUTER_RATIO · - // mid-radius, so we normalize the visible inner/outer edges - // (mid ± halfThickness) against the quad outer to get the mask - // positions inside the quad. - const innerRatio = (1 - RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; - const outerRatio = (1 + RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; - handle.element.style.setProperty("--ring-inner-ratio", `${innerRatio}`); - handle.element.style.setProperty("--ring-outer-ratio", `${outerRatio}`); + handle.element.style.setProperty("--ring-inner-ratio", `${RING_MASK_INNER_RATIO}`); + handle.element.style.setProperty("--ring-outer-ratio", `${RING_MASK_OUTER_RATIO}`); } gizmos.set(spec.key, { handle, spec }); } } - function teardownGizmos(): void { - for (const { handle } of gizmos.values()) handle.remove(); - gizmos.clear(); - hoveredKey = null; - draggingKey = null; - } - function syncGizmoPositions(): void { if (!target) return; const pos = gizmoPosition(); @@ -653,7 +269,7 @@ export function createTransformControls( attach(null); } - function setMode(m: Mode): void { + function setMode(m: GizmoMode): void { if (m === mode) return; mode = m; if (target) { @@ -662,92 +278,46 @@ export function createTransformControls( } } - function applyAxisDelta(spec: { cssAxis: 0 | 1 | 2 }, t: number, axisVec: Vec3): void { + function commitTransform(next: { position?: Vec3; rotation?: Vec3 }): void { if (!target) return; - // Snapshot at drag start lives in the closure passed to - // startAxisDrag — but applyAxisDelta is called per move with the - // raw cumulative `t`, so we need to anchor each application to - // the drag-start position, not the live (already-mutated) one. - // The dragStartPosition snapshot is captured in the pointerdown - // handler below. - if (!dragStartPosition) return; - // Translate the drag from CSS-pixel CSS-axis space (where the screen - // probe was measured) to world-unit world-axis space (where - // `transform.position` lives post-parity). t is CSS px along the - // visible arrow direction; divide by SCENE_TILE_SIZE for world units. - // axisVec encodes the ±sign at index cssAxis; the corresponding - // world axis is WORLD_AXIS_FOR_CSS[cssAxis]. - const sign = axisVec[spec.cssAxis]; - const worldAxis = WORLD_AXIS_FOR_CSS[spec.cssAxis]; - const worldStep = (t * sign) / SCENE_TILE_SIZE; - const next = dragStartPosition.slice() as Vec3; - next[worldAxis] = dragStartPosition[worldAxis] + worldStep; if (opts.applyTransform !== false) { - target.setTransform({ position: next }); + target.setTransform(next); syncGizmoPositions(); } - opts.onObjectChange?.({ object: target, position: next }); + opts.onObjectChange?.({ object: target, ...next }); opts.onChange?.(); } - let dragStartPosition: Vec3 | null = null; - - // Track the start-of-drag rotation snapshot so accumulated deltas - // are anchored to the rotation at pointerdown rather than the live - // (already-mutated) rotation each move. - let dragStartRotation: Vec3 | null = null; - // Pointerdown listener on the host. Same JS bbox hit-test the React - // version uses — reliable regardless of CSS pointer-events / border- - // shape clipping issues. const onPointerDown = (event: PointerEvent): void => { if (!target || opts.enabled === false) return; - const showByKey = { - x: opts.showX !== false, - y: opts.showY !== false, - z: opts.showZ !== false, - }; + if (mode === "translate") { - // Plane handles are hit-tested FIRST so they win when overlapping with - // the arrow shafts at the corner. + // Plane handles hit-tested first so they win at overlapping corners. for (const spec of PLANE_SPECS) { - const aName = (["x", "y", "z"] as const)[spec.axisA]; - const bName = (["x", "y", "z"] as const)[spec.axisB]; - if (!showByKey[aName] || !showByKey[bName]) continue; + if (!isPlaneSpecVisible(spec, opts)) continue; const gm = gizmos.get(spec.key); - if (!gm) continue; - if (!pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; + if (!gm || !pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; event.preventDefault(); event.stopPropagation(); draggingKey = spec.key; rebuildGizmoColors(); dragStartPosition = (target.transform.position ?? [0, 0, 0]).slice() as Vec3; - startPlaneDrag({ + const started = startPlaneDrag({ axisA: spec.axisA, axisB: spec.axisB, probeDistanceCss: gizmoLengthForMesh(target.polygons) * size, wrapper: gm.handle.element, - target, startClientX: event.clientX, startClientY: event.clientY, translationSnap: opts.translationSnap ?? null, onPlaneDelta: (tA, tB, aVec, bVec) => { - if (!target || !dragStartPosition) return; - // Same CSS→world translation as applyAxisDelta. aVec/bVec - // encode the ±sign at index axisA/axisB (CSS-axis order); - // the world axes to translate along are WORLD_AXIS_FOR_CSS. - const signA = aVec[spec.axisA]; - const signB = bVec[spec.axisB]; + if (!dragStartPosition) return; const worldAxisA = WORLD_AXIS_FOR_CSS[spec.axisA]; const worldAxisB = WORLD_AXIS_FOR_CSS[spec.axisB]; const next = dragStartPosition.slice() as Vec3; - next[worldAxisA] += (tA * signA) / SCENE_TILE_SIZE; - next[worldAxisB] += (tB * signB) / SCENE_TILE_SIZE; - if (opts.applyTransform !== false) { - target.setTransform({ position: next }); - syncGizmoPositions(); - } - opts.onObjectChange?.({ object: target, position: next }); - opts.onChange?.(); + next[worldAxisA] += (tA * aVec[spec.axisA]) / SCENE_TILE_SIZE; + next[worldAxisB] += (tB * bVec[spec.axisB]) / SCENE_TILE_SIZE; + commitTransform({ position: next }); }, onMouseDown: opts.onMouseDown, onMouseUp: opts.onMouseUp, @@ -760,37 +330,39 @@ export function createTransformControls( opts.onDraggingChanged?.(d); }, }); + if (!started) { + draggingKey = null; + dragStartPosition = null; + rebuildGizmoColors(); + } return; } + for (const spec of ARROW_SPECS) { - const userAxis = spec.key.replace("-", "")[0] as "x" | "y" | "z"; - if (!showByKey[userAxis]) continue; + if (!isArrowSpecVisible(spec, opts)) continue; const gm = gizmos.get(spec.key); - if (!gm) continue; - if (!pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; + if (!gm || !pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; event.preventDefault(); event.stopPropagation(); draggingKey = spec.key; rebuildGizmoColors(); - // Snapshot the position at drag start so each pointermove - // applies its cumulative `t` against the same anchor instead - // of compounding off the live (already-mutated) position. dragStartPosition = (target.transform.position ?? [0, 0, 0]).slice() as Vec3; - startAxisDrag({ + const started = startAxisDrag({ cssAxis: spec.cssAxis, sign: spec.sign, shaftLengthCss: gizmoLengthForMesh(target.polygons) * size, - // Use the arrow's own mesh wrapper as the probe target — - // it's positioned at target.position and lives in the same - // camera-transformed scene root as the polygons we're - // dragging, so probe-vs-wrapper bbox math gives px-per- - // scene-px directly. wrapper: gm.handle.element, - target, startClientX: event.clientX, startClientY: event.clientY, translationSnap: opts.translationSnap ?? null, - onAxisDelta: (t, axisVec) => applyAxisDelta(spec, t, axisVec), + onAxisDelta: (t, axisVec) => { + if (!dragStartPosition) return; + const worldAxis = WORLD_AXIS_FOR_CSS[spec.cssAxis]; + const next = dragStartPosition.slice() as Vec3; + next[worldAxis] = + dragStartPosition[worldAxis] + (t * axisVec[spec.cssAxis]) / SCENE_TILE_SIZE; + commitTransform({ position: next }); + }, onMouseDown: opts.onMouseDown, onMouseUp: opts.onMouseUp, onDraggingChanged: (d) => { @@ -802,115 +374,79 @@ export function createTransformControls( opts.onDraggingChanged?.(d); }, }); + if (!started) { + draggingKey = null; + dragStartPosition = null; + rebuildGizmoColors(); + } return; } - } else if (mode === "rotate") { - for (const spec of RING_SPECS) { - if (!showByKey[spec.key as "x" | "y" | "z"]) continue; - const gm = gizmos.get(spec.key); - if (!gm) continue; - // Plain bbox-containment hit-test. The donut mask is decoration; the - // entire ring quad bbox is clickable so the rings are easy to land on. - if (!pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; - event.preventDefault(); - event.stopPropagation(); - draggingKey = spec.key; - rebuildGizmoColors(); - dragStartRotation = (target.transform.rotation ?? [0, 0, 0]).slice() as Vec3; - // Snapshot the position too so the per-tick pivot compensation - // anchors to the drag-start state (otherwise compounding rounding - // drift across moves slowly slides the mesh off-pivot). - dragStartPosition = (target.transform.position ?? [0, 0, 0]).slice() as Vec3; - startRingDrag({ - cssAxis: spec.cssAxis, - wrapper: gm.handle.element, - target, - startClientX: event.clientX, - startClientY: event.clientY, - rotationSnap: opts.rotationSnap ?? null, - onAngleDelta: (degrees) => { - if (!target || !dragStartRotation || !dragStartPosition) return; - // Each ring rotates the mesh around the WORLD axis the ring - // visually wraps. Ring quads are built with axis = - // WORLD_AXIS_FOR_CSS[cssAxis] (see `buildPolygonsFor`), so the - // rotation axis here must match — otherwise the mesh spins - // around a different axis than the ring the user grabbed. - const worldAxis = WORLD_AXIS_FOR_CSS[spec.cssAxis]; - const axisVec: Vec3 = [0, 0, 0]; - axisVec[worldAxis] = 1; - // Negate the screen-derived angle: `startRingDrag` returns a - // CCW-in-screen-space delta, but the world↔CSS axis swap is a - // reflection (det -1) so the same screen direction maps to a - // CW world rotation around the ring's axis. Flip once globally - // rather than per-axis empirically. - const deltaRad = (-degrees * Math.PI) / 180; - const qStart = quatFromEulerXYZ(dragStartRotation); - const qDelta = quatFromAxisAngle(axisVec, deltaRad); - const nextRot = eulerXYZFromQuat(quatMultiply(qDelta, qStart)); - // Pivot the mesh around its visible bbox center, not its - // local origin. Post-parity `` pivots at - // (0,0,0) by design — for callers that haven't pre-centered - // their geometry (most loaders default to `{ center: "min" }`), - // raw rotation would swing the mesh around its bbox-min corner. - // We compensate by re-translating so the world-space point - // `position + scale * R * bboxCenter` stays put across the drag. - const scaleVal = typeof target.transform.scale === "number" + return; + } + + for (const spec of RING_SPECS) { + if (!isRingSpecVisible(spec, opts)) continue; + const gm = gizmos.get(spec.key); + if (!gm || !pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; + event.preventDefault(); + event.stopPropagation(); + draggingKey = spec.key; + rebuildGizmoColors(); + dragStartRotation = (target.transform.rotation ?? [0, 0, 0]).slice() as Vec3; + dragStartPosition = (target.transform.position ?? [0, 0, 0]).slice() as Vec3; + const worldAxis = WORLD_AXIS_FOR_CSS[spec.cssAxis]; + const axisVec: Vec3 = [0, 0, 0]; + axisVec[worldAxis] = 1; + const qStart = quatFromEulerXYZ(dragStartRotation); + startRingDrag({ + wrapper: gm.handle.element, + startClientX: event.clientX, + startClientY: event.clientY, + rotationSnap: opts.rotationSnap ?? null, + onAngleDelta: (degrees) => { + if (!target || !dragStartRotation || !dragStartPosition) return; + // Negate screen-derived angle: world↔CSS axis swap is a reflection (det -1). + const qDelta = quatFromAxisAngle(axisVec, (-degrees * Math.PI) / 180); + const nextRot = eulerXYZFromQuat(quatMultiply(qDelta, qStart)); + const scaleVal = + typeof target.transform.scale === "number" ? target.transform.scale : (target.transform.scale?.[0] ?? 1); - const startC = rotateVec3( - centerOffset, - dragStartRotation[0], - dragStartRotation[1], - dragStartRotation[2], - ); - const nextC = rotateVec3(centerOffset, nextRot[0], nextRot[1], nextRot[2]); - const nextPos: Vec3 = [ - dragStartPosition[0] + scaleVal * (startC[0] - nextC[0]), - dragStartPosition[1] + scaleVal * (startC[1] - nextC[1]), - dragStartPosition[2] + scaleVal * (startC[2] - nextC[2]), - ]; + const startC = rotateVec3( + centerOffset, + dragStartRotation[0], + dragStartRotation[1], + dragStartRotation[2], + ); + const nextC = rotateVec3(centerOffset, nextRot[0], nextRot[1], nextRot[2]); + const nextPos: Vec3 = [ + dragStartPosition[0] + scaleVal * (startC[0] - nextC[0]), + dragStartPosition[1] + scaleVal * (startC[1] - nextC[1]), + dragStartPosition[2] + scaleVal * (startC[2] - nextC[2]), + ]; + commitTransform({ rotation: nextRot, position: nextPos }); + }, + onMouseDown: opts.onMouseDown, + onMouseUp: opts.onMouseUp, + onDraggingChanged: (d) => { + if (!d) { + draggingKey = null; + dragStartRotation = null; + dragStartPosition = null; + rebuildGizmoColors(); if (opts.applyTransform !== false) { - target.setTransform({ rotation: nextRot, position: nextPos }); - syncGizmoPositions(); + target?.rebakeAtlas(); } - opts.onObjectChange?.({ object: target, rotation: nextRot, position: nextPos }); - opts.onChange?.(); - }, - onMouseDown: opts.onMouseDown, - onMouseUp: opts.onMouseUp, - onDraggingChanged: (d) => { - if (!d) { - draggingKey = null; - dragStartRotation = null; - dragStartPosition = null; - rebuildGizmoColors(); - // Rebake the atlas now that the rotation is committed. The - // mesh wrapper's CSS rotation has already been applied via - // setTransform; rebakeAtlas() inverse-rotates the world light - // into the mesh's new local frame and re-rasterizes the atlas - // so baked Lambert shading is correct for the new orientation. - if (opts.applyTransform !== false) { - target?.rebakeAtlas(); - } - } - opts.onDraggingChanged?.(d); - }, - }); - return; - } + } + opts.onDraggingChanged?.(d); + }, + }); + return; } }; - // Capture-phase so we fire BEFORE createPolyOrbitControls' bubble-phase - // pointerdown listener on the same host element. If the click hits - // a gizmo arrow / ring we call stopPropagation, which prevents - // the orbit/map controls from starting a camera-rotate gesture in parallel. - // If the click misses every gizmo, we don't stop — PolyControls - // gets the event during its bubble phase and rotates as usual. + // Capture-phase so gizmo hits beat bubble-phase orbit/map controls on the host. scene.host.addEventListener("pointerdown", onPointerDown, { capture: true }); - // Hover tracking — listen at the host and figure out which gizmo - // mesh (if any) is under the cursor. Cheaper than per-element - // listeners and works regardless of pointer-events quirks. const onPointerMove = (event: MouseEvent): void => { if (!target || draggingKey || opts.enabled === false) return; let next: string | null = null; diff --git a/packages/polycss/src/api/meshHitTest.ts b/packages/polycss/src/api/meshHitTest.ts index 7656658a6..ac916990b 100644 --- a/packages/polycss/src/api/meshHitTest.ts +++ b/packages/polycss/src/api/meshHitTest.ts @@ -33,3 +33,126 @@ export function findMeshUnderPoint( } return null; } + +export interface MeshElementRegistry { + registerMeshElement(el: HTMLElement, handle: THandle): void; + unregisterMeshElement(el: HTMLElement): void; + findPolyMeshHandle(el: Element | null): THandle | null; + findMeshUnderPoint( + clientX: number, + clientY: number, + filter?: (meshEl: HTMLElement) => boolean, + ): THandle | null; +} + +/** + * Create a WeakMap-backed DOM-element → mesh-handle registry with ancestor + * lookup and JS bounding-rect hit-test fallback. Shared by React and Vue. + */ +export function createMeshElementRegistry(): MeshElementRegistry { + const registry = new WeakMap(); + + function registerMeshElement(el: HTMLElement, handle: THandle): void { + registry.set(el, handle); + } + + function unregisterMeshElement(el: HTMLElement): void { + registry.delete(el); + } + + function findPolyMeshHandle(el: Element | null): THandle | null { + let cur: Element | null = el; + while (cur) { + if (cur instanceof HTMLElement) { + const h = registry.get(cur); + if (h) return h; + } + cur = cur.parentElement; + } + return null; + } + + function findRegisteredMeshUnderPoint( + clientX: number, + clientY: number, + filter?: (meshEl: HTMLElement) => boolean, + ): THandle | null { + if (typeof document === "undefined") return null; + const meshEls = Array.from( + document.querySelectorAll(".polycss-mesh"), + ) as HTMLElement[]; + for (const meshEl of meshEls) { + if (filter && !filter(meshEl)) continue; + const handle = findPolyMeshHandle(meshEl); + if (!handle) continue; + if (pointInMeshElement(meshEl, clientX, clientY)) return handle; + } + return null; + } + + return { + registerMeshElement, + unregisterMeshElement, + findPolyMeshHandle, + findMeshUnderPoint: findRegisteredMeshUnderPoint, + }; +} + +export interface SynthesizedPolyPointerEvent { + object: THandle; + eventObject: THandle; + intersections: Array<{ object: THandle }>; + pointer: { x: number; y: number }; + delta: number; + nativeEvent: E; + stopPropagation(): void; +} + +/** + * Build a r3f-shaped pointer/mouse/wheel event payload from native DOM inputs, + * using `document.elementsFromPoint`, camera viewport NDC, and pointerdown delta. + */ +export function buildPolyPointerEvent(opts: { + handle: THandle; + nativeEvent: E; + clientX: number; + clientY: number; + cameraEl: HTMLElement | null | undefined; + pointerDownAt: { x: number; y: number } | null; + resolveHandle: (el: Element | null) => THandle | null; +}): SynthesizedPolyPointerEvent { + const { handle, nativeEvent, clientX, clientY, cameraEl, pointerDownAt, resolveHandle } = opts; + const intersections: Array<{ object: THandle }> = []; + if (typeof document !== "undefined" && typeof document.elementsFromPoint === "function") { + const stacked = document.elementsFromPoint(clientX, clientY); + const seen = new Set(); + for (const el of stacked) { + const h = resolveHandle(el); + if (h && !seen.has(h)) { + seen.add(h); + intersections.push({ object: h }); + } + } + } + let nx = 0; + let ny = 0; + if (cameraEl) { + const r = cameraEl.getBoundingClientRect(); + if (r.width > 0 && r.height > 0) { + nx = ((clientX - r.left) / r.width) * 2 - 1; + ny = -(((clientY - r.top) / r.height) * 2 - 1); + } + } + const delta = pointerDownAt + ? Math.hypot(clientX - pointerDownAt.x, clientY - pointerDownAt.y) + : 0; + return { + object: intersections[0]?.object ?? handle, + eventObject: handle, + intersections, + pointer: { x: nx, y: ny }, + delta, + nativeEvent, + stopPropagation: () => nativeEvent.stopPropagation(), + }; +} diff --git a/packages/polycss/src/api/runtimeHelpers.test.ts b/packages/polycss/src/api/runtimeHelpers.test.ts new file mode 100644 index 000000000..d6d28d7f9 --- /dev/null +++ b/packages/polycss/src/api/runtimeHelpers.test.ts @@ -0,0 +1,479 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { CameraState, Polygon, Vec3 } from "@layoutit/polycss-core"; +import { + RING_MASK_INNER_RATIO, + RING_MASK_OUTER_RATIO, + attachDeclarativeGizmoFallback, + buildTransformGizmoEntries, + computeGizmoWrapperPositionCss, + startDeclarativeArrowDrag, + startDeclarativePlaneDrag, + startDeclarativeRingDrag, + type DeclarativeGizmoDragState, + type DeclarativeGizmoTarget, +} from "./controls/gizmoEngine"; +import { createSelectionController } from "./controls/selectionEngine"; +import { + applyCameraTransformDirect, + bindCameraStoreSync, + createLiveRuntimeCamera, + writeCameraSnapshotAttrs, +} from "./cameraSnapshotAttrs"; +import { + buildPolyPointerEvent, + createMeshElementRegistry, +} from "./meshHitTest"; +import { + clearOwnedDomNodes, + renderStandaloneMeshIntoWrapper, + restoreVoxelMeshClass, +} from "./standaloneMesh"; +import { + buildDirectMaterialLeafDescriptor, + buildFallbackLeafDescriptor, + buildPolyWrapperTransform, + cssPropToCamel, + isAxisAlignedRectUVs, + readElementDataAttrs, + readElementStyleRecord, + syncLeafBorderShapeStyle, +} from "../render/polyLeafDescriptor"; +import { computeTextureAtlasPlanPublic } from "../render/textureAtlas"; + +const QUAD: Polygon = { + vertices: [ + [0, 0, 0], + [1, 0, 0], + [1, 1, 0], + [0, 1, 0], + ], + color: "#ff0000", + uvs: [ + [0, 0], + [1, 0], + [1, 1], + [0, 1], + ], + data: { face: "top" }, + doubleSided: true, +}; + +afterEach(() => { + document.body.innerHTML = ""; + vi.restoreAllMocks(); +}); + +function withFakeLayout(cameraScale: number, fn: () => void): void { + const TRANSFORM_RE = /translate3d\(\s*(-?[\d.]+)px,\s*(-?[\d.]+)px,\s*(-?[\d.]+)px\s*\)/; + const orig = Element.prototype.getBoundingClientRect; + Element.prototype.getBoundingClientRect = function fakeRect(this: Element): DOMRect { + let x = 0; + let y = 0; + let cur: Element | null = this; + while (cur && cur instanceof HTMLElement) { + const t = cur.style.transform; + if (t) { + const m = TRANSFORM_RE.exec(t); + if (m) { + x += parseFloat(m[1]!) * cameraScale; + y += parseFloat(m[2]!) * cameraScale; + } + } + cur = cur.parentElement; + } + const w = this instanceof HTMLElement ? parseFloat(this.style.width || "0") || 0 : 0; + const h = this instanceof HTMLElement ? parseFloat(this.style.height || "0") || 0 : 0; + return { + left: x, + top: y, + right: x + w, + bottom: y + h, + width: w, + height: h, + x, + y, + toJSON() { + return this; + }, + } as DOMRect; + }; + try { + fn(); + } finally { + Element.prototype.getBoundingClientRect = orig; + } +} + +describe("polyLeafDescriptor", () => { + it("detects axis-aligned rect UVs and rejects non-rect UVs", () => { + expect( + isAxisAlignedRectUVs([ + [0, 0], + [0.5, 0], + [0.5, 1], + [0, 1], + ]), + ).toEqual({ u0: 0, u1: 0.5, v0: 0, v1: 1 }); + expect(isAxisAlignedRectUVs([[0, 0], [1, 0], [0, 1]])).toBeNull(); + expect( + isAxisAlignedRectUVs([ + [0, 0], + [0.5, 0], + [1, 1], + [0, 1], + ]), + ).toBeNull(); + }); + + it("converts CSS property names and reflects inline style & data attributes", () => { + expect(cssPropToCamel("--custom-var")).toBe("--custom-var"); + expect(cssPropToCamel("-webkit-mask-image")).toBe("WebkitMaskImage"); + expect(cssPropToCamel("background-color")).toBe("backgroundColor"); + + const el = document.createElement("i"); + el.style.backgroundColor = "red"; + el.style.setProperty("--shade", "0.5"); + el.setAttribute("data-poly-index", "3"); + el.setAttribute("id", "ignored"); + + expect(readElementStyleRecord(el, { camelCase: true })).toMatchObject({ + backgroundColor: "red", + "--shade": "0.5", + }); + expect(readElementStyleRecord(el)).toMatchObject({ + "background-color": "red", + "--shade": "0.5", + }); + expect(readElementDataAttrs(el)).toEqual({ "data-poly-index": "3" }); + }); + + it("builds direct-material and SSR fallback descriptors plus wrapper transforms", () => { + const plan = computeTextureAtlasPlanPublic(QUAD, 0, { tileSize: 50, layerElevation: 50 })!; + expect(plan).not.toBeNull(); + + const direct = buildDirectMaterialLeafDescriptor({ + plan, + material: { texture: "/sprite.png" }, + uvRect: { u0: 0, u1: 0.5, v0: 0, v1: 0.5 }, + className: " custom ", + pointerEvents: "none", + imageRendering: "pixelated", + }); + expect(direct.className).toBe("custom"); + expect(direct.style.backgroundImage).toBe("url(/sprite.png)"); + expect(direct.style.imageRendering).toBe("pixelated"); + expect(direct.style.pointerEvents).toBe("none"); + expect(direct.dataAttrs["data-face"]).toBe("top"); + expect(direct.dataAttrs["data-polycss-double-sided"]).toBe("true"); + + const solidFallback = buildFallbackLeafDescriptor({ + plan, + polygon: QUAD, + isTextured: false, + className: "ssr-leaf", + pointerEvents: "none", + }); + expect(solidFallback.tag).toBe("b"); + expect(solidFallback.style.backgroundColor).toBe(plan.shadedColor); + expect(solidFallback.style.pointerEvents).toBe("none"); + + const texFallback = buildFallbackLeafDescriptor({ + plan, + polygon: QUAD, + isTextured: true, + }); + expect(texFallback.tag).toBe("s"); + expect(texFallback.style.backgroundColor).toBeUndefined(); + + expect(buildPolyWrapperTransform({})).toBeUndefined(); + expect( + buildPolyWrapperTransform({ + position: [1, 2, 3], + scale: 2, + rotation: [10, 20, 30], + }), + ).toBe("translate3d(1px, 2px, 3px) scale3d(2, 2, 2) rotateX(10deg) rotateY(20deg) rotateZ(30deg)"); + expect(buildPolyWrapperTransform({ scale: [1, 2, 3] })).toBe("scale3d(1, 2, 3)"); + + const leaf = document.createElement("i"); + syncLeafBorderShapeStyle(leaf, "polygon(0 0, 100% 0, 0 100%)", "color: red;", "none", { + opacity: "0.5", + }); + expect(leaf.style.pointerEvents).toBe("none"); + expect(leaf.style.opacity).toBe("0.5"); + }); +}); + +describe("cameraSnapshotAttrs & camera store sync", () => { + it("creates a live runtime camera, writes snapshot attrs, and syncs store bidirectionally", () => { + let projection: "orthographic" | "perspective" = "perspective"; + let perspectiveStyle = "24000px"; + const cam = createLiveRuntimeCamera({ + zoom: 1.5, + rotX: 45, + rotY: 30, + initialProjection: projection, + initialPerspectiveStyle: perspectiveStyle, + getProjection: () => projection, + getPerspectiveStyle: () => perspectiveStyle, + }); + expect(cam.type).toBe("perspective"); + expect(cam.perspectiveStyle).toBe("24000px"); + + const cameraEl = document.createElement("div"); + const sceneEl = document.createElement("div"); + writeCameraSnapshotAttrs(cameraEl, cam, { applyPerspective: true }); + expect(cameraEl.dataset.polycssCameraProjection).toBe("perspective"); + expect(cameraEl.style.perspective).toBe("24000px"); + + const listeners = new Set<() => void>(); + let state: { cameraState: CameraState } = { cameraState: { ...cam.state } }; + const store = { + getState: () => state, + subscribe: (fn: () => void) => { + listeners.add(fn); + return () => listeners.delete(fn); + }, + updateCameraFromRef: vi.fn((c: { state: CameraState }) => { + state = { cameraState: { ...c.state } }; + }), + }; + const applyCamera = vi.fn(); + const unbind = bindCameraStoreSync(cam, store, () => ({ applyCamera }) as never); + + cam.update({ zoom: 2 }); + expect(store.updateCameraFromRef).toHaveBeenCalledTimes(1); + + state = { cameraState: { ...cam.state, rotY: 90 } }; + for (const fn of listeners) fn(); + expect(cam.state.rotY).toBe(90); + expect(applyCamera).toHaveBeenCalledTimes(1); + + applyCameraTransformDirect({ + runtimeScene: null, + sceneEl, + cameraEl, + handle: cam, + autoCenterOffset: [0, 0, 0], + projection, + perspectiveStyle, + }); + expect(sceneEl.style.transform).toContain("rotate(90deg)"); + + applyCameraTransformDirect({ + runtimeScene: { applyCamera } as never, + sceneEl, + cameraEl, + handle: cam, + autoCenterOffset: [0, 0, 0], + projection, + perspectiveStyle, + }); + expect(applyCamera).toHaveBeenCalledTimes(2); + unbind(); + }); +}); + +describe("meshHitTest registry, pointer events, and standaloneMesh", () => { + it("registers meshes, resolves hit-test fallback, and builds pointer events", () => { + type FakeHandle = { id: string; element: HTMLElement }; + const reg = createMeshElementRegistry(); + const meshEl = document.createElement("div"); + meshEl.className = "polycss-mesh"; + const leaf = document.createElement("b"); + leaf.getBoundingClientRect = () => + ({ left: 10, top: 10, right: 60, bottom: 60, width: 50, height: 50, x: 10, y: 10, toJSON() { return this; } }) as DOMRect; + meshEl.appendChild(leaf); + document.body.appendChild(meshEl); + + const handle: FakeHandle = { id: "m1", element: meshEl }; + reg.registerMeshElement(meshEl, handle); + expect(reg.findPolyMeshHandle(leaf)).toBe(handle); + expect(reg.findMeshUnderPoint(25, 25)).toBe(handle); + expect(reg.findMeshUnderPoint(25, 25, () => false)).toBeNull(); + + const camEl = document.createElement("div"); + camEl.getBoundingClientRect = () => + ({ left: 0, top: 0, right: 200, bottom: 100, width: 200, height: 100, x: 0, y: 0, toJSON() { return this; } }) as DOMRect; + const nativeEv = new MouseEvent("click"); + const spyStop = vi.spyOn(nativeEv, "stopPropagation"); + const polyEv = buildPolyPointerEvent({ + handle, + nativeEvent: nativeEv, + clientX: 100, + clientY: 50, + cameraEl: camEl, + pointerDownAt: { x: 97, y: 46 }, + resolveHandle: reg.findPolyMeshHandle, + }); + expect(polyEv.pointer.x).toBeCloseTo(0); + expect(polyEv.pointer.y).toBeCloseTo(0); + expect(polyEv.delta).toBe(5); + polyEv.stopPropagation(); + expect(spyStop).toHaveBeenCalledOnce(); + + reg.unregisterMeshElement(meshEl); + expect(reg.findPolyMeshHandle(leaf)).toBeNull(); + }); + + it("mounts standalone mesh leaves preserving static children and restores voxel class", () => { + const wrapper = document.createElement("div"); + const staticChild = document.createElement("span"); + wrapper.appendChild(staticChild); + const owned = new Set(); + + const mounted = renderStandaloneMeshIntoWrapper(wrapper, owned, [QUAD], { + doc: document, + textureLighting: "baked", + }); + expect(owned.size).toBe(1); + expect(wrapper.lastChild).toBe(staticChild); + mounted.dispose(); + expect(owned.size).toBe(0); + expect(wrapper.children.length).toBe(1); + + const empty = renderStandaloneMeshIntoWrapper(wrapper, owned, [], { + doc: document, + textureLighting: "baked", + }); + empty.dispose(); + clearOwnedDomNodes(owned); + + const voxelFace = document.createElement("div"); + voxelFace.className = "polycss-voxel-face"; + wrapper.appendChild(voxelFace); + restoreVoxelMeshClass(wrapper); + expect(wrapper.classList.contains("polycss-voxel-mesh")).toBe(true); + }); +}); + +describe("gizmoEngine declarative helpers & selectionEngine", () => { + it("builds translate/rotate entries, runs declarative drags, and handles camera fallback", () => { + expect(RING_MASK_INNER_RATIO).toBeLessThan(RING_MASK_OUTER_RATIO); + const tEntries = buildTransformGizmoEntries({ + mode: "translate", + polygons: [QUAD], + size: 1, + showX: true, + showY: true, + showZ: false, + rotX: 60, + rotY: 45, + hoveredKey: "x", + draggingKey: null, + }); + expect(tEntries.arrows.length).toBe(4); + expect(tEntries.planes.length).toBe(1); + + const rEntries = buildTransformGizmoEntries({ + mode: "rotate", + polygons: [QUAD], + size: 1, + showX: true, + showY: false, + showZ: true, + rotX: 60, + rotY: 45, + hoveredKey: null, + draggingKey: "x", + }); + expect(rEntries.rings.length).toBe(2); + expect(computeGizmoWrapperPositionCss([1, 2, 3], [QUAD])).toEqual([125, 75, 150]); + + const onObjectChange = vi.fn(); + const rebakeAtlas = vi.fn(); + const target: DeclarativeGizmoTarget = { + getPosition: () => [10, 20, 30] as Vec3, + getRotation: () => [0, 0, 0] as Vec3, + rebakeAtlas, + }; + const wrapper = document.createElement("div"); + wrapper.setAttribute("data-poly-transform-controls", ""); + const cameraEl = document.createElement("div"); + const planeEl = document.createElement("div"); + planeEl.className = "polycss-transform-gizmo polycss-transform-plane polycss-transform-plane--xy"; + const planeLeaf = document.createElement("b"); + planeLeaf.getBoundingClientRect = () => + ({ left: 0, top: 0, right: 50, bottom: 50, width: 50, height: 50, x: 0, y: 0, toJSON() { return this; } }) as DOMRect; + planeEl.appendChild(planeLeaf); + wrapper.appendChild(planeEl); + cameraEl.appendChild(wrapper); + document.body.appendChild(cameraEl); + + const state: DeclarativeGizmoDragState = { + target, + mode: "translate", + shaftLengthCss: 100, + enabled: true, + showX: true, + showY: true, + showZ: true, + translationSnap: null, + rotationSnap: null, + onObjectChange, + }; + + withFakeLayout(2, () => { + startDeclarativeArrowDrag(tEntries.arrows[0]!.spec, wrapper, 0, 0, state); + window.dispatchEvent(new PointerEvent("pointermove", { clientX: 10, clientY: 0 })); + window.dispatchEvent(new PointerEvent("pointerup")); + expect(onObjectChange).toHaveBeenCalledWith({ object: target, position: [15, 20, 30] }); + + startDeclarativePlaneDrag(tEntries.planes[0]!.spec, wrapper, 0, 0, state); + window.dispatchEvent(new PointerEvent("pointermove", { clientX: 8, clientY: 6 })); + window.dispatchEvent(new PointerEvent("pointerup")); + expect(onObjectChange).toHaveBeenLastCalledWith({ object: target, position: [14, 23, 30] }); + + startDeclarativeRingDrag(rEntries.rings[0]!.spec, wrapper, 100, 0, { + ...state, + mode: "rotate", + }); + window.dispatchEvent(new PointerEvent("pointermove", { clientX: 0, clientY: 100 })); + window.dispatchEvent(new PointerEvent("pointerup")); + expect(rebakeAtlas).toHaveBeenCalledOnce(); + }); + + const detach = attachDeclarativeGizmoFallback(cameraEl, () => state); + withFakeLayout(2, () => { + cameraEl.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, clientX: 25, clientY: 25 })); + window.dispatchEvent(new PointerEvent("pointerup")); + }); + detach(); + }); + + it("manages selection add/remove/toggle/clear and click delegation", () => { + const onChange = vi.fn(); + const onMiss = vi.fn(); + const ctrl = createSelectionController({ + getMultiple: () => true, + getClearOnMiss: () => true, + getFilter: () => undefined, + resolveTarget: (el) => el?.getAttribute("data-id") ?? null, + onChange, + onPointerMissed: onMiss, + }); + ctrl.add("a"); + ctrl.add("a"); + ctrl.add("b"); + expect(ctrl.has("a")).toBe(true); + ctrl.remove("missing"); + ctrl.remove("a"); + ctrl.toggle("b"); + ctrl.toggle("c"); + ctrl.clear(); + expect(ctrl.selected).toEqual([]); + + const host = document.createElement("div"); + const item = document.createElement("div"); + item.setAttribute("data-id", "x"); + host.appendChild(item); + const detach = ctrl.attach(host); + item.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(ctrl.selected).toEqual(["x"]); + item.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(ctrl.selected).toEqual([]); + host.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(onMiss).toHaveBeenCalledOnce(); + detach(); + }); +}); diff --git a/packages/polycss/src/api/standaloneMesh.ts b/packages/polycss/src/api/standaloneMesh.ts new file mode 100644 index 000000000..6abbec000 --- /dev/null +++ b/packages/polycss/src/api/standaloneMesh.ts @@ -0,0 +1,68 @@ +/** + * Shared standalone `` DOM helpers for React and Vue adapters. + */ +import type { Polygon } from "@layoutit/polycss-core"; +import { + renderPolygonsWithTextureAtlas, + type RenderTextureAtlasOptions, +} from "../render/textureAtlas"; + +const RESOLVED_PROMISE = Promise.resolve(); + +/** + * Re-apply `.polycss-voxel-mesh` on an adopted direct-voxel wrapper after + * React/Vue reconciles its `className`/`class` attribute. + */ +export function restoreVoxelMeshClass(el: HTMLElement | null): void { + if (!el) return; + for (let i = 0; i < el.children.length; i += 1) { + if (el.children[i]?.classList.contains("polycss-voxel-face")) { + el.classList.add("polycss-voxel-mesh"); + break; + } + } +} + +export function clearOwnedDomNodes(owned: Set): void { + for (const node of owned) { + node.parentNode?.removeChild(node); + } + owned.clear(); +} + +export interface StandaloneMeshMountResult { + dispose: () => void; + ready: Promise; +} + +/** + * Render polygons directly into a standalone `` wrapper element + * (when mounted outside a ``), preserving any non-owned static + * framework children at the end of the wrapper. + */ +export function renderStandaloneMeshIntoWrapper( + el: HTMLElement, + owned: Set, + polygons: Polygon[], + options: RenderTextureAtlasOptions, +): StandaloneMeshMountResult { + clearOwnedDomNodes(owned); + if (polygons.length === 0) { + return { dispose: () => {}, ready: RESOLVED_PROMISE }; + } + const result = renderPolygonsWithTextureAtlas(polygons, options); + const firstStatic = Array.from(el.childNodes).find((n) => !owned.has(n)) ?? null; + const frag = (el.ownerDocument ?? document).createDocumentFragment(); + for (const item of result.rendered) { + owned.add(item.element); + frag.appendChild(item.element); + } + el.insertBefore(frag, firstStatic); + return { + dispose: () => { + result.dispose(); + clearOwnedDomNodes(owned); + }, + ready: result.pagesReady ?? RESOLVED_PROMISE, + }; +} diff --git a/packages/polycss/src/render/polyLeafDescriptor.ts b/packages/polycss/src/render/polyLeafDescriptor.ts new file mode 100644 index 000000000..afda0b4a6 --- /dev/null +++ b/packages/polycss/src/render/polyLeafDescriptor.ts @@ -0,0 +1,212 @@ +/** + * Shared standalone `` leaf-descriptor helpers. + * + * Used by `@layoutit/polycss-react` (`Poly.tsx`) and `@layoutit/polycss-vue` + * (`Poly.ts`) so direct-texture UV positioning, SSR fallback style assembly, + * wrapper transforms, and DOM leaf style/data-attr reflection live in one place. + */ +import type { + PolyMaterial, + PolyTextureImageRendering, + Polygon, + Vec2, + Vec3, +} from "@layoutit/polycss-core"; +import { formatCssLength } from "@layoutit/polycss-core"; +import type { TextureAtlasPlan } from "./textureAtlas"; + +const DIRECT_TEXTURE_CSS_DECIMALS = 4; + +export interface PolyUvRect { + u0: number; + u1: number; + v0: number; + v1: number; +} + +export function isAxisAlignedRectUVs(uvs: Vec2[]): PolyUvRect | null { + if (uvs.length !== 4) return null; + const us = [...new Set(uvs.map((uv) => uv[0]))].sort((a, b) => a - b); + const vs = [...new Set(uvs.map((uv) => uv[1]))].sort((a, b) => a - b); + if (us.length !== 2 || vs.length !== 2) return null; + const corners = new Set([ + `${us[0]},${vs[0]}`, + `${us[0]},${vs[1]}`, + `${us[1]},${vs[0]}`, + `${us[1]},${vs[1]}`, + ]); + for (const uv of uvs) { + if (!corners.has(`${uv[0]},${uv[1]}`)) return null; + } + return { u0: us[0]!, u1: us[1]!, v0: vs[0]!, v1: vs[1]! }; +} + +export function cssPropToCamel(prop: string): string { + if (prop.startsWith("--")) return prop; + if (prop.startsWith("-webkit-")) { + return "Webkit" + prop.slice(7).replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()); + } + return prop.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()); +} + +export function readElementStyleRecord( + el: HTMLElement, + options?: { camelCase?: boolean }, +): Record { + const camelCase = options?.camelCase ?? false; + const out: Record = {}; + const style = el.style; + for (let i = 0; i < style.length; i += 1) { + const prop = style[i]!; + const val = style.getPropertyValue(prop); + if (val) out[camelCase ? cssPropToCamel(prop) : prop] = val; + } + return out; +} + +export function readElementDataAttrs(el: HTMLElement): Record { + const out: Record = {}; + for (const attr of Array.from(el.attributes)) { + if (attr.name.startsWith("data-")) { + out[attr.name] = attr.value; + } + } + return out; +} + +export interface DirectMaterialLeafDescriptor { + className: string | undefined; + style: Record; + dataAttrs: Record; +} + +export function buildDirectMaterialLeafDescriptor(opts: { + plan: TextureAtlasPlan; + material: PolyMaterial; + uvRect: PolyUvRect; + className?: string; + pointerEvents?: "auto" | "none"; + imageRendering?: PolyTextureImageRendering; +}): DirectMaterialLeafDescriptor { + const { plan, material, uvRect, className, pointerEvents = "auto", imageRendering } = opts; + const { u0, u1, v0, v1 } = uvRect; + const du = u1 - u0; + const dv = v1 - v0; + const sourceW = 1 / du; + const sourceH = 1 / dv; + const vMax = Math.max(v0, v1); + const offsetX = u0 / du; + const offsetY = (1 - vMax) / dv; + + const style: Record = { + transform: `matrix3d(${plan.canonicalMatrix})`, + backgroundImage: `url(${material.texture})`, + backgroundSize: `${formatCssLength(sourceW, DIRECT_TEXTURE_CSS_DECIMALS)} ${formatCssLength(sourceH, DIRECT_TEXTURE_CSS_DECIMALS)}`, + backgroundPosition: `${formatCssLength(-offsetX, DIRECT_TEXTURE_CSS_DECIMALS)} ${formatCssLength(-offsetY, DIRECT_TEXTURE_CSS_DECIMALS)}`, + backgroundRepeat: "no-repeat", + imageRendering: imageRendering === "pixelated" ? "pixelated" : undefined, + pointerEvents: pointerEvents === "none" ? "none" : undefined, + }; + + const polygonDataAttrs = plan.polygon.data + ? Object.fromEntries( + Object.entries(plan.polygon.data).map(([k, v]) => [`data-${k}`, String(v)]), + ) + : {}; + + const dataAttrs: Record = { + "data-poly-index": String(plan.index), + "data-polycss-leaf": "polygon", + "data-polycss-texture-backend": "image", + "data-polycss-texture-ready": "true", + "data-polycss-texture-image-rendering": imageRendering ?? "auto", + "data-polycss-texture-projection": "affine", + "data-polycss-texture-lighting": "source", + "data-polycss-double-sided": plan.polygon.doubleSided ? "true" : undefined, + ...polygonDataAttrs, + }; + + return { + className: className?.trim() || undefined, + style, + dataAttrs, + }; +} + +export interface FallbackLeafDescriptor { + tag: "b" | "s"; + className: string | undefined; + style: Record; + dataAttrs: Record; +} + +export function buildFallbackLeafDescriptor(opts: { + plan: TextureAtlasPlan; + polygon: Polygon; + isTextured: boolean; + className?: string; + pointerEvents?: "auto" | "none"; +}): FallbackLeafDescriptor { + const { plan, polygon, isTextured, className, pointerEvents } = opts; + const tag = !isTextured && polygon.vertices.length === 4 ? "b" : "s"; + const style: Record = { + transform: `matrix3d(${plan.canonicalMatrix})`, + ...(!isTextured ? { backgroundColor: plan.shadedColor } : {}), + pointerEvents: pointerEvents === "none" ? "none" : undefined, + }; + const dataAttrs: Record = { + "data-poly-index": "0", + "data-polycss-leaf": "polygon", + "data-polycss-double-sided": polygon.doubleSided ? "true" : undefined, + }; + return { + tag, + className: className?.trim() || undefined, + style, + dataAttrs, + }; +} + +export function buildPolyWrapperTransform(opts: { + position?: Vec3; + scale?: number | Vec3; + rotation?: Vec3; +}): string | undefined { + const { position, scale, rotation } = opts; + const parts: string[] = []; + if (position) { + parts.push(`translate3d(${position[0]}px, ${position[1]}px, ${position[2]}px)`); + } + if (scale !== undefined) { + if (typeof scale === "number") { + if (scale !== 1) parts.push(`scale3d(${scale}, ${scale}, ${scale})`); + } else { + parts.push(`scale3d(${scale[0]}, ${scale[1]}, ${scale[2]})`); + } + } + if (rotation) { + if (rotation[0]) parts.push(`rotateX(${rotation[0]}deg)`); + if (rotation[1]) parts.push(`rotateY(${rotation[1]}deg)`); + if (rotation[2]) parts.push(`rotateZ(${rotation[2]}deg)`); + } + return parts.length > 0 ? parts.join(" ") : undefined; +} + +/** + * Re-apply raw engine cssText when a leaf uses CSS `border-shape`, which + * frameworks and happy-dom can strip during style object syncing. + */ +export function syncLeafBorderShapeStyle( + el: HTMLElement | null, + rawBorderShape: string, + rawLeafCssText: string, + pointerEvents?: "auto" | "none", + userStyle?: Record, +): void { + if (!el || !rawBorderShape) return; + el.setAttribute("style", rawLeafCssText); + if (pointerEvents === "none") el.style.pointerEvents = "none"; + if (userStyle && typeof userStyle === "object") { + Object.assign(el.style, userStyle); + } +} diff --git a/packages/polycss/src/runtime.ts b/packages/polycss/src/runtime.ts index 929c3653f..76f25f679 100644 --- a/packages/polycss/src/runtime.ts +++ b/packages/polycss/src/runtime.ts @@ -68,6 +68,12 @@ export type { export { createSelect } from "./api/createSelect"; export type { PolySelectOptions, PolySelectionHandle } from "./api/createSelect"; +export { createSelectionController } from "./api/controls/selectionEngine"; +export type { + SelectionController, + SelectionControllerOptions, +} from "./api/controls/selectionEngine"; + export { createTransformControls } from "./api/createTransformControls"; export type { PolyTransformControlsHandle, @@ -75,6 +81,90 @@ export type { PolyTransformControlsOptions, } from "./api/createTransformControls"; +export { + RING_MASK_INNER_RATIO, + RING_MASK_OUTER_RATIO, + attachDeclarativeGizmoFallback, + buildArrowGizmoPolygons, + buildPlaneGizmoPolygons, + buildRingGizmoPolygons, + buildTransformGizmoEntries, + computeGizmoWrapperPositionCss, + gizmoAlphaForKey, + isArrowSpecVisible, + isPlaneSpecVisible, + isRingSpecVisible, + startAxisDrag, + startDeclarativeArrowDrag, + startDeclarativePlaneDrag, + startDeclarativeRingDrag, + startPlaneDrag, + startRingDrag, + swallowNextClick, +} from "./api/controls/gizmoEngine"; +export type { + AxisDragParams, + BuildTransformGizmoEntriesOptions, + DeclarativeGizmoCallbacks, + DeclarativeGizmoDragState, + DeclarativeGizmoObjectChangeEvent, + DeclarativeGizmoTarget, + GizmoArrowSpec, + GizmoMode, + GizmoPlaneSpec, + GizmoPolygonEntry, + GizmoRingSpec, + GizmoVisibility, + PlaneDragParams, + RingDragParams, + TransformGizmoEntries, +} from "./api/controls/gizmoEngine"; + +export { + buildPolyPointerEvent, + createMeshElementRegistry, + pointInMeshElement, +} from "./api/meshHitTest"; +export type { + MeshElementRegistry, + SynthesizedPolyPointerEvent, +} from "./api/meshHitTest"; + +export { + applyCameraTransformDirect, + bindCameraStoreSync, + createLiveRuntimeCamera, + writeCameraSnapshotAttrs, +} from "./api/cameraSnapshotAttrs"; +export type { + CameraSyncStoreLike, + LiveRuntimeCameraOptions, + WriteCameraSnapshotAttrsOptions, +} from "./api/cameraSnapshotAttrs"; + +export { + clearOwnedDomNodes, + renderStandaloneMeshIntoWrapper, + restoreVoxelMeshClass, +} from "./api/standaloneMesh"; +export type { StandaloneMeshMountResult } from "./api/standaloneMesh"; + +export { + buildDirectMaterialLeafDescriptor, + buildFallbackLeafDescriptor, + buildPolyWrapperTransform, + cssPropToCamel, + isAxisAlignedRectUVs, + readElementDataAttrs, + readElementStyleRecord, + syncLeafBorderShapeStyle, +} from "./render/polyLeafDescriptor"; +export type { + DirectMaterialLeafDescriptor, + FallbackLeafDescriptor, + PolyUvRect, +} from "./render/polyLeafDescriptor"; + // ── Low-level atlas & voxel renderers ───────────────────────────── export { buildAtlasPages, diff --git a/packages/polycss/src/three.ts b/packages/polycss/src/three.ts index bf098f501..57bf3ad7d 100644 --- a/packages/polycss/src/three.ts +++ b/packages/polycss/src/three.ts @@ -13,13 +13,13 @@ import type { import { createPolyOrthographicCamera, createPolyPerspectiveCamera, - createPolyScene, -} from "./index"; +} from "./api/createPolyCamera"; +import { createPolyScene } from "./api/createPolyScene"; import type { PolyMeshTransform, PolySceneHandle, PolySceneOptions, -} from "./index"; +} from "./api/createPolyScene"; export { AmbientLight, diff --git a/packages/polycss/tsup.config.ts b/packages/polycss/tsup.config.ts index 9a0ba1a91..ac58f6466 100644 --- a/packages/polycss/tsup.config.ts +++ b/packages/polycss/tsup.config.ts @@ -7,9 +7,7 @@ export default createLibraryConfig({ elements: "src/elements/index.ts", three: "src/three.ts", }, - // esbuild drops `export * from "@layoutit/polycss-core"` when splitting: true - // with an external package, stripping all core re-exports from dist/index.js. - splitting: false, + splitting: true, tsconfig: "tsconfig.build.json", external: ["@layoutit/polycss-core", "@layoutit/polycss-core/three"], }); diff --git a/packages/react/src/camera/useCamera.ts b/packages/react/src/camera/useCamera.ts index d06e66172..044f2d558 100644 --- a/packages/react/src/camera/useCamera.ts +++ b/packages/react/src/camera/useCamera.ts @@ -1,12 +1,10 @@ import { useRef, useCallback, useEffect, useMemo } from "react"; -import { - buildPolyCameraSceneTransform, - capturePolyCameraSnapshot, -} from "@layoutit/polycss-core"; import type { CameraState, CameraHandle, PolyCameraProjection, Vec3 } from "@layoutit/polycss-core"; import { - createPolyOrthographicCamera, - createPolyPerspectiveCamera, + applyCameraTransformDirect, + bindCameraStoreSync, + createLiveRuntimeCamera, + writeCameraSnapshotAttrs, type PolyOrthographicCameraHandle, type PolyPerspectiveCameraHandle, type PolySceneHandle, @@ -35,24 +33,6 @@ export interface UseCameraResult { applyTransformDirect: () => void; } -function writeCameraSnapshotAttrs( - el: HTMLElement | null, - camera: CameraHandle, - projection: PolyCameraProjection | undefined, - perspectiveStyle: string | undefined, -): void { - if (!el) return; - const snapshot = capturePolyCameraSnapshot(camera, { projection, perspectiveStyle }); - el.dataset.polycssCameraProjection = snapshot.projection; - el.dataset.polycssCameraPerspective = snapshot.perspectiveStyle; - el.dataset.polycssCameraAppliedPerspective = snapshot.appliedPerspectiveStyle; - el.dataset.polycssCameraZoom = String(snapshot.state.zoom); - el.dataset.polycssCameraDistance = String(snapshot.state.distance); - el.dataset.polycssCameraRotX = String(snapshot.state.rotX); - el.dataset.polycssCameraRotY = String(snapshot.state.rotY); - el.dataset.polycssCameraTarget = snapshot.state.target.join(","); -} - export function usePolyCamera(options: UseCameraOptions): UseCameraResult { const projectionRef = useRef(options.projection ?? "orthographic"); projectionRef.current = options.projection ?? "orthographic"; @@ -64,116 +44,42 @@ export function usePolyCamera(options: UseCameraOptions): UseCameraResult { const handleRef = useRef(null); if (!handleRef.current) { - const baseOpts = { + handleRef.current = createLiveRuntimeCamera({ zoom: options.zoom, target: options.target, rotX: options.rotX, rotY: options.rotY, distance: options.distance, - }; - const inner = - options.projection === "perspective" - ? createPolyPerspectiveCamera({ - ...baseOpts, - perspective: parseFloat(perspectiveStyleRef.current) || 32000, - }) - : createPolyOrthographicCamera(baseOpts); - // Wrap with live projection/perspectiveStyle getters so prop updates to - // `perspective` flow into createPolyScene's `applyCamera()`. - handleRef.current = { - get state() { return inner.state; }, - update(next: Partial) { inner.update(next); }, - getStyle(input) { return inner.getStyle(input); }, - subscribe(listener) { return inner.subscribe(listener); }, - get type() { return projectionRef.current as "perspective" & "orthographic"; }, - get perspectiveStyle() { return perspectiveStyleRef.current as string & "none"; }, - } as PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle; + initialProjection: options.projection, + initialPerspectiveStyle: perspectiveStyleRef.current, + getProjection: () => projectionRef.current, + getPerspectiveStyle: () => perspectiveStyleRef.current, + }); } const sceneElRef = useRef(null); const cameraElRef = useRef(null); const runtimeSceneRef = useRef(null); - const store = useMemo( - () => createSceneStore(handleRef.current!.state), - [], - ); + const store = useMemo(() => createSceneStore(handleRef.current!.state), []); - // Sync camera handle mutations (from runtime controls or direct handle.update) - // back into the reactive store, AND sync direct store.setState({ cameraState }) - // mutations back into the camera handle + runtime scene (for receiver shadow - // camera-boundary crossings and external store drivers). - useEffect(() => { - const handle = handleRef.current!; - let syncing = false; - const unsubHandle = handle.subscribe(() => { - if (syncing) return; - syncing = true; - try { - store.updateCameraFromRef(handle); - } finally { - syncing = false; - } - }); - const unsubStore = store.subscribe(() => { - if (syncing) return; - const next = store.getState().cameraState; - const cur = handle.state; - const changed = - next.rotX !== cur.rotX || - next.rotY !== cur.rotY || - next.zoom !== cur.zoom || - next.distance !== cur.distance || - next.target[0] !== cur.target[0] || - next.target[1] !== cur.target[1] || - next.target[2] !== cur.target[2]; - if (!changed) return; - syncing = true; - try { - handle.update(next); - runtimeSceneRef.current?.applyCamera(); - } finally { - syncing = false; - } - }); - return () => { - unsubHandle(); - unsubStore(); - }; - }, [store]); + useEffect( + () => bindCameraStoreSync(handleRef.current!, store, () => runtimeSceneRef.current), + [store], + ); - // Apply camera transform directly to scene element (bypasses React). - // Delegates to the mounted runtime scene when present so voxel culling and - // receiver-shadow camera crossings stay in sync; falls back to direct DOM - // transform for standalone camera tests without a . const applyTransformDirect = useCallback(() => { - const handle = handleRef.current!; - const runtimeScene = runtimeSceneRef.current; - if (runtimeScene) { - runtimeScene.applyCamera(); - writeCameraSnapshotAttrs( - cameraElRef.current, - handle, - projectionRef.current, - perspectiveStyleRef.current, - ); - return; - } - const el = sceneElRef.current; - if (el) { - el.style.transform = buildPolyCameraSceneTransform(handle.state, { - autoCenterOffset: store.getState().autoCenterOffset, - }); - } - writeCameraSnapshotAttrs( - cameraElRef.current, - handle, - projectionRef.current, - perspectiveStyleRef.current, - ); + applyCameraTransformDirect({ + runtimeScene: runtimeSceneRef.current, + sceneEl: sceneElRef.current, + cameraEl: cameraElRef.current, + handle: handleRef.current!, + autoCenterOffset: store.getState().autoCenterOffset, + projection: projectionRef.current, + perspectiveStyle: perspectiveStyleRef.current, + }); }, [store]); - // Sync prop changes to camera handle useEffect(() => { const handle = handleRef.current!; const next: Partial = {}; @@ -188,12 +94,10 @@ export function usePolyCamera(options: UseCameraOptions): UseCameraResult { store.updateCameraFromRef(handle); store.notifyAll(); } else { - writeCameraSnapshotAttrs( - cameraElRef.current, - handle, - projectionRef.current, - perspectiveStyleRef.current, - ); + writeCameraSnapshotAttrs(cameraElRef.current, handle, { + projection: projectionRef.current, + perspectiveStyle: perspectiveStyleRef.current, + }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [ diff --git a/packages/react/src/controls/TransformControls.tsx b/packages/react/src/controls/TransformControls.tsx index dffe26832..a9b160016 100644 --- a/packages/react/src/controls/TransformControls.tsx +++ b/packages/react/src/controls/TransformControls.tsx @@ -1,31 +1,8 @@ /** - * — drag gizmo for translating a `` along - * the six world-axis directions (±X, ±Y, ±Z). Mirrors three.js's - * TransformControls API (`mode`, `space`, `size`, `showX/Y/Z`, - * `translationSnap`, events `onChange` / `onObjectChange` / `onMouseDown` - * / `onMouseUp` / `onDraggingChanged`). - * - * Geometry: each arrow is a polycss `` whose vertices come - * from `arrowPolygons` (a thin axis-aligned cuboid shaft + a 4-sided - * pyramid head). This matches how `` is built — same - * 3D primitives, so the gizmo's lit appearance composes naturally with - * the rest of the scene. - * - * Drag math: project pointer screen-pixel delta onto the screen - * projection of the world axis. Screen-axis is snapshotted at - * pointerdown via a probe element placed `axis × beamLength` from the - * gizmo origin, then normalized — `getBoundingClientRect()` deltas give - * px-per-scene-px automatically (handles camera tilt + zoom). - * - * `position` / drag deltas live in scene-CSS pixels, matching `` (which is `translate3d(x px, y px, z px)`). Polygon - * vertices live in WORLD units; we convert via `SCENE_TILE_SIZE` (the - * default `tileSize` PolyScene applies to atlas geometry). - * - * `space="local"` is accepted in the type but only "world" is implemented. + * — thin React wrapper over `@layoutit/polycss/runtime`'s + * shared gizmo drag, geometry, and fallback hit-test engine. */ import { - useCallback, useContext, useEffect, useMemo, @@ -34,53 +11,28 @@ import { type CSSProperties, type RefObject, } from "react"; +import { DEFAULT_CAMERA_STATE, type Vec3 } from "@layoutit/polycss-core"; import { - ALPHA_DRAGGING, - ALPHA_HOVER, - ALPHA_IDLE, - ARROW_SPECS, - HEAD_HALF_THICKNESS_RATIO, - HEAD_LENGTH_RATIO, - PLANE_HALF_SIZE_RATIO, - PLANE_OFFSET_RATIO, - PLANE_SPECS, - RING_HALF_THICKNESS_RATIO, - RING_QUAD_OUTER_RATIO, - RING_RADIUS_RATIO, - RING_SPECS, - SCENE_TILE_SIZE, - SCREEN_AXIS_DEAD_ZONE_SQ, - SHAFT_HALF_THICKNESS_RATIO, - WORLD_AXIS_FOR_CSS, - arrowPolygons, - DEFAULT_CAMERA_STATE, - eulerXYZFromQuat, - gizmoCenterForMesh, - gizmoLengthForMesh, - isAxisBackFacing, - planePolygons, - quatFromAxisAngle, - quatFromEulerXYZ, - quatMultiply, - ringQuadPolygons, - screenPlaneDet, - snap, - solveAxisDragDelta, - solvePlaneDragDeltas, - unwrapAngleDelta, - userAxisLetterOf, - withAlpha, - type Polygon, - type Vec3, -} from "@layoutit/polycss-core"; + RING_MASK_INNER_RATIO, + RING_MASK_OUTER_RATIO, + attachDeclarativeGizmoFallback, + buildTransformGizmoEntries, + computeGizmoWrapperPositionCss, + startDeclarativeArrowDrag, + startDeclarativePlaneDrag, + startDeclarativeRingDrag, + type DeclarativeGizmoDragState, + type GizmoArrowSpec, + type GizmoMode, + type GizmoPlaneSpec, + type GizmoRingSpec, +} from "@layoutit/polycss/runtime"; import { PolyMesh } from "../scene/PolyMesh"; -import { pointInMeshElement, type PolyMeshHandle, type PolyPointerEvent } from "../scene/events"; +import type { PolyMeshHandle, PolyPointerEvent } from "../scene/events"; import { PolyCameraContext } from "../camera/context"; import { createSceneStore, useStoreSelector } from "../store/sceneStore"; -// Stable no-op store used as a hook-rule-compliant fallback when -// PolyTransformControls is rendered outside a PolyCamera. We always pass a -// store to useStoreSelector; this one never changes, so it never re-renders. +// Stable no-op store used as a hook-rule-compliant fallback outside . const FALLBACK_CAMERA_STORE = createSceneStore(DEFAULT_CAMERA_STATE); /** Optional ref-or-direct binding to a target mesh. */ @@ -94,24 +46,20 @@ export interface PolyTransformControlsObjectChangeEvent { object: PolyMeshHandle; /** The new position. Only emitted when `mode` is "translate". */ position?: Vec3; - /** The new Euler rotation (degrees, X/Y/Z). Only emitted when - * `mode` is "rotate". */ + /** The new Euler rotation (degrees, X/Y/Z). Only emitted when `mode` is "rotate". */ rotation?: Vec3; } export interface PolyTransformControlsProps { - /** Mesh to attach to. Pass a ref returned from `useRef()` - * or a handle directly. `null` hides the gizmo. */ + /** Mesh to attach to. Pass a ref or handle directly. `null` hides the gizmo. */ object: PolyTransformControlsObject; - /** Drag mode. "translate" → axial arrows, "rotate" → axial rings. */ - mode?: "translate" | "rotate"; + /** Drag mode. "translate" → axial arrows + planes, "rotate" → axial rings. */ + mode?: GizmoMode; /** Axis basis. Only "world" is implemented in v1. */ space?: "world" | "local"; /** Multiplier on gizmo size (shaft length / ring radius). Default 1. */ size?: number; - /** Show / hide axis gizmo PAIRS. Default true. In translate mode this - * hides both the +/- arrows for that axis; in rotate mode this hides - * the corresponding ring. */ + /** Show / hide axis gizmo PAIRS. Default true. */ showX?: boolean; showY?: boolean; showZ?: boolean; @@ -123,16 +71,13 @@ export interface PolyTransformControlsProps { enabled?: boolean; /** Fires for any transform change. Argument-less, mirrors three.js. */ onChange?: () => void; - /** Fires with the new transform during drag. Use this to update - * position state — controlled flow, parent owns state. */ + /** Fires with the new transform during drag. */ onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; /** Fires once on drag start. */ onMouseDown?: () => void; /** Fires once on drag end. */ onMouseUp?: () => void; - /** Fires with `true` on drag start, `false` on drag end. Mirrors - * three.js's `'dragging-changed'` event (kebab-case preserved here - * via the boolean payload, since react prop naming is camelCase). */ + /** Fires with `true` on drag start, `false` on drag end. */ onDraggingChanged?: (dragging: boolean) => void; } @@ -142,312 +87,6 @@ function resolveObject(o: PolyTransformControlsObject): PolyMeshHandle | null { return o as PolyMeshHandle; } -interface DragOptions { - /** CSS axis index this arrow drives (0=x, 1=y, 2=z). The probe is - * placed along this CSS direction; pointer-px deltas project onto - * it; the resulting `t` updates `position[cssAxis]`. */ - cssAxis: 0 | 1 | 2; - sign: 1 | -1; - shaftLengthCss: number; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - translationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** Project the screen-space delta of a CSS-axis vector via a probe - * placed `axis × shaftLengthCss` from the gizmo wrapper origin, then - * run a pointermove/up loop translating pointer-px deltas into - * scene-px along the axis. Shared by the per-arrow - * PolyMesh.onPointerDown handler AND the cameraEl JS hit-test - * fallback so both paths produce identical drag behavior. */ -function startAxisDrag(opts: DragOptions): void { - const { - cssAxis, - sign, - shaftLengthCss, - wrapper, - target, - startClientX, - startClientY, - translationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - const probeDistance = shaftLengthCss; - const axisVec: Vec3 = [0, 0, 0]; - axisVec[cssAxis] = sign; - const probe = document.createElement("div"); - probe.style.position = "absolute"; - probe.style.left = "0"; - probe.style.top = "0"; - probe.style.width = "0"; - probe.style.height = "0"; - probe.style.transform = `translate3d(${axisVec[0] * probeDistance}px, ${axisVec[1] * probeDistance}px, ${axisVec[2] * probeDistance}px)`; - wrapper.appendChild(probe); - const wRect = wrapper.getBoundingClientRect(); - const pRect = probe.getBoundingClientRect(); - wrapper.removeChild(probe); - const screenAxisX = (pRect.left - wRect.left) / probeDistance; - const screenAxisY = (pRect.top - wRect.top) / probeDistance; - const screenAxisLenSq = screenAxisX * screenAxisX + screenAxisY * screenAxisY; - if (screenAxisLenSq < SCREEN_AXIS_DEAD_ZONE_SQ) return; - - const startPos = target.getPosition() ?? ([0, 0, 0] as Vec3); - - onMouseDown?.(); - onDraggingChanged?.(true); - - const handleMove = (ev: PointerEvent): void => { - const dx = ev.clientX - startClientX; - const dy = ev.clientY - startClientY; - let t = solveAxisDragDelta(dx, dy, screenAxisX, screenAxisY); - t = snap(t, translationSnap); - const newPos: Vec3 = [ - startPos[0] + t * axisVec[0], - startPos[1] + t * axisVec[1], - startPos[2] + t * axisVec[2], - ]; - onObjectChange?.({ object: target, position: newPos }); - onChange?.(); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - // Defang the synthesized `click` that follows pointerup. Without - // this, releasing a gizmo drag over the chicken's polygons fires - // Select's click listener and (since the chicken is already - // selected) immediately toggles it off. Capture-phase one-shot - // listener stops the click before it bubbles to cameraEl. The - // setTimeout(0) cleanup handles the case where the browser - // didn't synthesize a click (large pointer movement) — the - // listener would otherwise stay armed and eat the next real click. - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - -interface PlaneDragOptions { - axisA: 0 | 1 | 2; - axisB: 0 | 1 | 2; - /** Distance (CSS px) the probe is offset along each in-plane axis. Uses - * the same scale as the arrow's shaftLengthCss so screen projection is - * proportional to one axis-unit of mesh translation. */ - probeDistanceCss: number; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - translationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** Project pointer screen-px deltas onto the screen projections of TWO - * world axes (the plane's basis), solve a 2x2 system, and update the - * mesh position along both axes. Same probe trick as `startAxisDrag`, - * extended to two basis vectors. */ -function startPlaneDrag(opts: PlaneDragOptions): void { - const { - axisA, - axisB, - probeDistanceCss, - wrapper, - target, - startClientX, - startClientY, - translationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - const axisAVec: Vec3 = [0, 0, 0]; axisAVec[axisA] = 1; - const axisBVec: Vec3 = [0, 0, 0]; axisBVec[axisB] = 1; - function probe(axisVec: Vec3): { x: number; y: number } { - const el = wrapper.ownerDocument!.createElement("div"); - el.style.position = "absolute"; - el.style.left = "0"; - el.style.top = "0"; - el.style.width = "0"; - el.style.height = "0"; - el.style.transform = `translate3d(${axisVec[0] * probeDistanceCss}px, ${axisVec[1] * probeDistanceCss}px, ${axisVec[2] * probeDistanceCss}px)`; - wrapper.appendChild(el); - const wR = wrapper.getBoundingClientRect(); - const pR = el.getBoundingClientRect(); - wrapper.removeChild(el); - return { - x: (pR.left - wR.left) / probeDistanceCss, - y: (pR.top - wR.top) / probeDistanceCss, - }; - } - const pA = probe(axisAVec); - const pB = probe(axisBVec); - const det = screenPlaneDet(pA, pB); - if (Math.abs(det) < SCREEN_AXIS_DEAD_ZONE_SQ) return; - - const startPos = target.getPosition() ?? ([0, 0, 0] as Vec3); - onMouseDown?.(); - onDraggingChanged?.(true); - - const handleMove = (ev: PointerEvent): void => { - const dx = ev.clientX - startClientX; - const dy = ev.clientY - startClientY; - let { tA, tB } = solvePlaneDragDeltas(dx, dy, pA, pB, det); - if (translationSnap !== null) { - tA = Math.round(tA / translationSnap) * translationSnap; - tB = Math.round(tB / translationSnap) * translationSnap; - } - const next: Vec3 = [ - startPos[0] + tA * axisAVec[0] + tB * axisBVec[0], - startPos[1] + tA * axisAVec[1] + tB * axisBVec[1], - startPos[2] + tA * axisAVec[2] + tB * axisBVec[2], - ]; - onObjectChange?.({ object: target, position: next }); - onChange?.(); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - -interface RingDragOptions { - /** CSS axis the ring rotates around (0=x, 1=y, 2=z). Maps directly - * to PolyMesh's `rotation[cssAxis]` slot (rotateX/rotateY/rotateZ). */ - cssAxis: 0 | 1 | 2; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - rotationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** Rotation drag: track the pointer's screen-space angle around the - * gizmo wrapper's screen center, accumulate the unwrapped delta - * across moves, and apply it as degrees-of-rotation around the ring's - * CSS axis. Coarser than three.js's true ray-onto-rotation-plane - * projection (which would reproject through the camera per move) but - * reads naturally for the intuitive case of dragging a ring face-on, - * and degenerates predictably when the ring is edge-on (rotation - * speed scales with the apparent ring size). */ -function startRingDrag(opts: RingDragOptions): void { - const { - cssAxis, - wrapper, - target, - startClientX, - startClientY, - rotationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - const wRect = wrapper.getBoundingClientRect(); - // Wrapper is a 0×0 anchor at the gizmo origin — its bounding rect - // collapses to a single point in screen space, which is exactly the - // ring's center (we want angle relative to the rotation pivot). - const centerX = wRect.left; - const centerY = wRect.top; - - let lastAngle = Math.atan2(startClientY - centerY, startClientX - centerX); - let cumulative = 0; // accumulated radians since drag start - const startRotation = (target.getRotation() ?? [0, 0, 0]) as Vec3; - - onMouseDown?.(); - onDraggingChanged?.(true); - - // World-frame quaternion compose. The gizmo's rings stay at fixed world - // axes (the wrapper isn't rotated with the mesh), so the user clicks a - // ring expecting rotation around the WORLD axis they see. We pre-multiply: - // Qnew = Qdelta · Qstart - // → rotation applies in the WORLD frame, then the prior orientation. Each - // ring drag composes cumulatively on top of the mesh's current orientation - // without resetting it — which Euler-add couldn't do for repeated axes. - const qStart = quatFromEulerXYZ(startRotation); - const handleMove = (ev: PointerEvent): void => { - const a = Math.atan2(ev.clientY - centerY, ev.clientX - centerX); - // Unwrap so a drag that crosses the ±π boundary doesn't jump by 2π. - cumulative += unwrapAngleDelta(a, lastAngle); - lastAngle = a; - let degrees = (cumulative * 180) / Math.PI; - degrees = snap(degrees, rotationSnap); - const axisVec: Vec3 = [0, 0, 0]; - axisVec[cssAxis] = 1; - const qDelta = quatFromAxisAngle(axisVec, (degrees * Math.PI) / 180); - const newRotation = eulerXYZFromQuat(quatMultiply(qDelta, qStart)); - onObjectChange?.({ object: target, rotation: newRotation }); - onChange?.(); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - // Same click-swallow trick as the translate drag — release-over- - // chicken would otherwise toggle selection off mid-rotation. - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - // Rebake the atlas with the new rotation baked in. Must come after the - // callbacks above so consumers have already committed the final rotation - // to state before the atlas snapshot runs. - target.rebakeAtlas(); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - export function PolyTransformControls({ object, mode = "translate", @@ -465,241 +104,74 @@ export function PolyTransformControls({ onMouseUp, onDraggingChanged, }: PolyTransformControlsProps) { - // Refs don't trigger React re-renders. When `object` is a RefObject - // whose `.current` lands AFTER first render (the common case — the - // target mounts in the same pass and only sets the ref - // after our first render), we need a single follow-up render to - // pick it up. useEffect with `object` in the deps array handles - // both first-mount and ref-identity changes cleanly. + // Refs don't trigger React re-renders; pick up `.current` after mount commit. const [, forceRender] = useState(0); useEffect(() => { forceRender((n) => n + 1); }, [object]); - // Camera rotation, reactively. Used to compute which translate arrows are - // pointing AWAY from the viewer so we can render them as head-only. The - // store subscription means the gizmo geometry re-evaluates whenever the - // user orbits the camera — no stale back/front state. - const cameraCtxForRot = useContext(PolyCameraContext); - // Two primitive selectors — returning an object literal each call would - // make useSyncExternalStore see a "changed" snapshot every render and - // trigger an infinite re-render loop. + const cameraCtx = useContext(PolyCameraContext); + const cameraElRef = cameraCtx?.cameraElRef; const rotX = useStoreSelector( - cameraCtxForRot?.store ?? FALLBACK_CAMERA_STORE, + cameraCtx?.store ?? FALLBACK_CAMERA_STORE, (s) => s.cameraState.rotX, ); const rotY = useStoreSelector( - cameraCtxForRot?.store ?? FALLBACK_CAMERA_STORE, + cameraCtx?.store ?? FALLBACK_CAMERA_STORE, (s) => s.cameraState.rotY, ); - // Per-arrow hover + dragging state. Lifted here so both the React - // PolyMesh.onPointerDown handler and the cameraEl JS hit-test - // fallback can keep them in sync. Each render re-evaluates which - // arrow is hot, and TranslateArrow paints its polygons at the - // matching alpha (idle / hover / drag). const [hoveredKey, setHoveredKey] = useState(null); const [draggingKey, setDraggingKey] = useState(null); - // Pin everything the cameraEl fallback listener needs. The listener - // is attached once per cameraEl identity and reads through the refs, - // so prop changes don't re-bind window listeners during a drag. - const cameraCtx = useContext(PolyCameraContext); - const cameraElRef = cameraCtx?.cameraElRef; - const dragRef = useRef<{ - target: PolyMeshHandle | null; - mode: "translate" | "rotate"; - shaftLengthCss: number; - enabled: boolean; - show: { x: boolean; y: boolean; z: boolean }; - translationSnap: number | null; - rotationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; - }>({ + const dragStateRef = useRef>({ target: null, - mode: "translate", + mode, shaftLengthCss: 0, - enabled: true, - show: { x: true, y: true, z: true }, - translationSnap: null, - rotationSnap: null, + enabled, + showX, + showY, + showZ, + translationSnap, + rotationSnap, }); - // cameraEl JS hit-test fallback. Native polygon hit-testing handles - // the common case (PolyMesh.onPointerDown fires when an arrow's - // `` is clicked), but if something upstream forces - // `pointer-events: none` on polycss elements, OR `border-shape` - // clipping suppresses the click on the visible-but-transparent - // corners of an arrow rect, the click falls through to cameraEl. - // This bubble-phase listener catches those misses, walks the six - // arrow elements testing each polygon's bounding rect against the - // click point, and dispatches the same `startAxisDrag`. - // - // Skips events whose target is already inside an arrow PolyMesh — - // those will trigger the per-arrow handler shortly via React - // synthetic dispatch; falling through here would double-fire. useEffect(() => { const cameraEl = cameraElRef?.current; if (!cameraEl) return; - const onPointerDown = (event: PointerEvent): void => { - const state = dragRef.current; - if (!state.target || !state.enabled) return; - const targetEl = event.target as Element | null; - // Don't double-fire when the click already hit one of our gizmo - // PolyMeshes — React's per-arrow/per-ring synthetic handler will - // pick it up. The shared `polycss-transform-gizmo` class is set - // on both translate arrows and rotate rings. - if (targetEl?.closest(".polycss-transform-gizmo")) return; - if (state.mode === "translate") { - // Plane handles hit-tested FIRST so they win over arrow shafts at - // overlapping corners. - for (const spec of PLANE_SPECS) { - const aL = (["x", "y", "z"] as const)[spec.axisA]; - const bL = (["x", "y", "z"] as const)[spec.axisB]; - if (!state.show[aL] || !state.show[bL]) continue; - const planeEl = document.querySelector( - `.polycss-transform-plane--${spec.key}`, - ) as HTMLElement | null; - if (!planeEl) continue; - if (!pointInMeshElement(planeEl, event.clientX, event.clientY)) continue; - event.preventDefault(); - event.stopPropagation(); - const wrapper = planeEl.closest( - "[data-poly-transform-controls]", - ) as HTMLElement | null; - if (!wrapper) return; - setDraggingKey(spec.key); - startPlaneDrag({ - axisA: spec.axisA, - axisB: spec.axisB, - probeDistanceCss: state.shaftLengthCss, - wrapper, - target: state.target, - startClientX: event.clientX, - startClientY: event.clientY, - translationSnap: state.translationSnap, - onChange: state.onChange, - onObjectChange: state.onObjectChange, - onMouseDown: state.onMouseDown, - onMouseUp: state.onMouseUp, - onDraggingChanged: (d) => { - if (!d) setDraggingKey(null); - state.onDraggingChanged?.(d); - }, - }); - return; - } - for (const spec of ARROW_SPECS) { - if (!state.show[userAxisLetterOf(spec.key)]) continue; - const arrowEl = document.querySelector( - `.polycss-transform-arrow--${spec.key}`, - ) as HTMLElement | null; - if (!arrowEl) continue; - if (!pointInMeshElement(arrowEl, event.clientX, event.clientY)) continue; - event.preventDefault(); - event.stopPropagation(); - const wrapper = arrowEl.closest( - "[data-poly-transform-controls]", - ) as HTMLElement | null; - if (!wrapper) return; - setDraggingKey(spec.key); - startAxisDrag({ - cssAxis: spec.cssAxis, - sign: spec.sign, - shaftLengthCss: state.shaftLengthCss, - wrapper, - target: state.target, - startClientX: event.clientX, - startClientY: event.clientY, - translationSnap: state.translationSnap, - onChange: state.onChange, - onObjectChange: state.onObjectChange, - onMouseDown: state.onMouseDown, - onMouseUp: state.onMouseUp, - onDraggingChanged: (d) => { - if (!d) setDraggingKey(null); - state.onDraggingChanged?.(d); - }, - }); - return; - } - } else if (state.mode === "rotate") { - for (const spec of RING_SPECS) { - if (!state.show[spec.key as "x" | "y" | "z"]) continue; - const ringEl = document.querySelector( - `.polycss-transform-ring--${spec.key}`, - ) as HTMLElement | null; - if (!ringEl) continue; - // Regular bbox-containment hit. The visible donut mask is only - // decoration — the WHOLE ring quad bbox is clickable so the rings - // are easy to land on. Clicks inside the inner hole also trigger - // rotation; selecting the wrapped mesh is done via clicks outside - // any ring's bbox (or via the Scene panel). - if (!pointInMeshElement(ringEl, event.clientX, event.clientY)) continue; - event.preventDefault(); - event.stopPropagation(); - const wrapper = ringEl.closest( - "[data-poly-transform-controls]", - ) as HTMLElement | null; - if (!wrapper) return; - setDraggingKey(spec.key); - startRingDrag({ - cssAxis: spec.cssAxis, - wrapper, - target: state.target, - startClientX: event.clientX, - startClientY: event.clientY, - rotationSnap: state.rotationSnap, - onChange: state.onChange, - onObjectChange: state.onObjectChange, - onMouseDown: state.onMouseDown, - onMouseUp: state.onMouseUp, - onDraggingChanged: (d) => { - if (!d) setDraggingKey(null); - state.onDraggingChanged?.(d); - }, - }); - return; - } - } - }; - cameraEl.addEventListener("pointerdown", onPointerDown); - return () => cameraEl.removeEventListener("pointerdown", onPointerDown); + return attachDeclarativeGizmoFallback(cameraEl, () => dragStateRef.current); }, [cameraElRef]); const target = resolveObject(object); - if (!target) return null; - - const position = target.getPosition() ?? ([0, 0, 0] as Vec3); - const polygons = target.getPolygons(); - const bboxCenter = gizmoCenterForMesh(polygons); - // Post-parity: `position` is world units in world-axis order. The gizmo - // wrapper lives in scene-CSS pixel space, so apply the world→CSS axis - // swap + ×BASE_TILE before adding the (already CSS-pixel) bbox center. - // bboxCenter accounts for meshes whose vertices aren't centered at 0; - // when PolyMesh autoCenter is set, bboxCenter is (0,0,0) and this is a - // pure axis-swap. - const cssPosX = position[1] * SCENE_TILE_SIZE; - const cssPosY = position[0] * SCENE_TILE_SIZE; - const cssPosZ = position[2] * SCENE_TILE_SIZE; - const wrapperPos: Vec3 = [ - cssPosX + bboxCenter[0], - cssPosY + bboxCenter[1], - cssPosZ + bboxCenter[2], - ]; - const baseLength = gizmoLengthForMesh(polygons); - const shaftLengthCss = baseLength * size; + const polygons = target ? target.getPolygons() : []; + + const entries = useMemo( + () => + target + ? buildTransformGizmoEntries({ + mode, + polygons, + size, + showX, + showY, + showZ, + rotX, + rotY, + hoveredKey, + draggingKey, + }) + : null, + [target, mode, polygons, size, showX, showY, showZ, rotX, rotY, hoveredKey, draggingKey], + ); - dragRef.current = { + dragStateRef.current = { target, mode, - shaftLengthCss, + shaftLengthCss: entries?.shaftLengthCss ?? 0, enabled, - show: { x: showX, y: showY, z: showZ }, + showX, + showY, + showZ, translationSnap, rotationSnap, onChange, @@ -707,521 +179,114 @@ export function PolyTransformControls({ onMouseDown, onMouseUp, onDraggingChanged, + onDraggingKeyChange: setDraggingKey, }; - // Gizmo stays at world-axis orientation (NOT rotated with the mesh). This - // keeps the arrows in fixed screen positions so panning + repeated drags - // stay predictable. The MATH still composes rotations correctly — see - // `startRingDrag` for the world-frame quaternion compose. + if (!target || !entries) return null; + + const wrapperPos = computeGizmoWrapperPositionCss(target.getPosition(), polygons); const wrapperStyle: CSSProperties = { transform: `translate3d(${wrapperPos[0]}px, ${wrapperPos[1]}px, ${wrapperPos[2]}px)`, position: "absolute", transformStyle: "preserve-3d", - // No `pointer-events: none` here — that property is inherited, so - // setting it on the wrapper would cascade to every arrow polygon - // and disable native hit-testing on the gizmo entirely. The - // wrapper is a 0×0 anchor so it has no surface to be hit on its - // own; descendants opt in via the default `auto`. zIndex: 1000, }; - return ( -
- {mode === "translate" && ARROW_SPECS.map((spec) => { - const show = { x: showX, y: showY, z: showZ }[userAxisLetterOf(spec.key)]; - if (!show) return null; - const hovered = hoveredKey === spec.key; - const dragging = draggingKey === spec.key; - const alpha = dragging ? ALPHA_DRAGGING : hovered ? ALPHA_HOVER : ALPHA_IDLE; - const backFacing = isAxisBackFacing(spec.cssAxis, spec.sign, rotX, rotY); - return ( - setHoveredKey(h ? spec.key : (cur) => (cur === spec.key ? null : cur))} - onDraggingStart={() => setDraggingKey(spec.key)} - onDraggingStop={() => setDraggingKey((cur) => (cur === spec.key ? null : cur))} - /> - ); - })} - {mode === "translate" && PLANE_SPECS.map((spec) => { - const aLetter = (["x", "y", "z"] as const)[spec.axisA]; - const bLetter = (["x", "y", "z"] as const)[spec.axisB]; - const show = ({ x: showX, y: showY, z: showZ }[aLetter]) - && ({ x: showX, y: showY, z: showZ }[bLetter]); - if (!show) return null; - const hovered = hoveredKey === spec.key; - const dragging = draggingKey === spec.key; - const alpha = dragging ? ALPHA_DRAGGING : hovered ? ALPHA_HOVER : ALPHA_IDLE; - return ( - setHoveredKey(h ? spec.key : (cur) => (cur === spec.key ? null : cur))} - onDraggingStart={() => setDraggingKey(spec.key)} - onDraggingStop={() => setDraggingKey((cur) => (cur === spec.key ? null : cur))} - /> - ); - })} - {mode === "rotate" && RING_SPECS.map((spec) => { - const show = { x: showX, y: showY, z: showZ }[spec.key as "x" | "y" | "z"]; - if (!show) return null; - const hovered = hoveredKey === spec.key; - const dragging = draggingKey === spec.key; - const alpha = dragging ? ALPHA_DRAGGING : hovered ? ALPHA_HOVER : ALPHA_IDLE; - return ( - setHoveredKey(h ? spec.key : (cur) => (cur === spec.key ? null : cur))} - onDraggingStart={() => setDraggingKey(spec.key)} - onDraggingStop={() => setDraggingKey((cur) => (cur === spec.key ? null : cur))} - /> - ); - })} -
- ); -} - -interface TranslateArrowProps { - cssAxis: 0 | 1 | 2; - sign: 1 | -1; - axisKey: string; - color: string; - shaftLengthCss: number; - /** Emit the shaft cuboid. Caller sets false when this arrow is on the - * camera-facing-away side of an axis pair, leaving just the head. */ - includeShaft: boolean; - target: PolyMeshHandle; - enabled: boolean; - translationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; - /** Local hover-state notifications, lifted to the parent so it can - * mark the right arrow as hovered without per-arrow render plumbing. */ - onHoverChange?: (hovered: boolean) => void; - onDraggingStart?: () => void; - onDraggingStop?: () => void; -} + const ringStyle: CSSProperties = { + ["--ring-inner-ratio" as string]: RING_MASK_INNER_RATIO, + ["--ring-outer-ratio" as string]: RING_MASK_OUTER_RATIO, + }; -function TranslateArrow({ - cssAxis, - sign, - axisKey, - color, - shaftLengthCss, - includeShaft, - target, - enabled, - translationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onHoverChange, - onDraggingStart, - onDraggingStop, -}: TranslateArrowProps) { - // Pin callback refs so the pointerdown handler always reads fresh - // closures without re-binding window listeners. - const cbRef = useRef({ - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onDraggingStart, - onDraggingStop, - enabled, - translationSnap, - }); - cbRef.current = { - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onDraggingStart, - onDraggingStop, - enabled, - translationSnap, + const startFromMeshEvent = ( + e: PolyPointerEvent, + run: (wrapper: HTMLElement) => void, + ): void => { + if (!dragStateRef.current.enabled) return; + e.stopPropagation(); + const wrapper = e.eventObject.element?.closest( + "[data-poly-transform-controls]", + ) as HTMLElement | null; + if (!wrapper) return; + run(wrapper); }; - // Build the polygon geometry. Vertex coords are in WORLD units; the - // scene multiplies by tileSize when rendering, so the arrow ends up - // `shaftLengthCss` scene-CSS pixels long. Convert from CSS axis to - // world axis here — the rest of the component (probe, drag math) - // operates in CSS coords. - const polygons = useMemo(() => { - const lengthWorld = shaftLengthCss / SCENE_TILE_SIZE; - return arrowPolygons({ - axis: WORLD_AXIS_FOR_CSS[cssAxis], - sign, - shaftLength: lengthWorld, - shaftHalfThickness: lengthWorld * SHAFT_HALF_THICKNESS_RATIO, - headLength: lengthWorld * HEAD_LENGTH_RATIO, - headHalfThickness: lengthWorld * HEAD_HALF_THICKNESS_RATIO, - color, - shaft: includeShaft, + const handleArrowDown = (spec: GizmoArrowSpec) => (e: PolyPointerEvent) => + startFromMeshEvent(e, (wrapper) => { + startDeclarativeArrowDrag( + spec, + wrapper, + e.nativeEvent.clientX, + e.nativeEvent.clientY, + dragStateRef.current, + ); }); - }, [cssAxis, sign, color, shaftLengthCss, includeShaft]); - const onPointerDown = useCallback( - (e: PolyPointerEvent): void => { - if (!cbRef.current.enabled) return; - // Stop propagation BOTH on the polycss event (React tree) AND on - // the underlying native event — the latter prevents PolyControls' - // camera-drag bubble listener on .polycss-camera from starting a - // rotation in parallel with our axis drag, and also signals the - // gizmo's own cameraEl fallback listener (in TransformControls) - // not to redundantly start a second drag. - e.stopPropagation(); - const meshEl = e.eventObject.element; - const wrapper = meshEl?.closest("[data-poly-transform-controls]") as HTMLElement | null; - if (!wrapper) return; - cbRef.current.onDraggingStart?.(); - startAxisDrag({ - cssAxis, - sign, - shaftLengthCss, + const handlePlaneDown = (spec: GizmoPlaneSpec) => (e: PolyPointerEvent) => + startFromMeshEvent(e, (wrapper) => { + startDeclarativePlaneDrag( + spec, wrapper, - target, - startClientX: e.nativeEvent.clientX, - startClientY: e.nativeEvent.clientY, - translationSnap: cbRef.current.translationSnap, - onChange: cbRef.current.onChange, - onObjectChange: cbRef.current.onObjectChange, - onMouseDown: cbRef.current.onMouseDown, - onMouseUp: cbRef.current.onMouseUp, - onDraggingChanged: (d) => { - if (!d) cbRef.current.onDraggingStop?.(); - cbRef.current.onDraggingChanged?.(d); - }, - }); - }, - [cssAxis, sign, target, shaftLengthCss], - ); - - // Render the arrow as a directly under - // .polycss-transform-controls — no intermediate wrapper. An extra - //
between PolyScene and PolyMesh flattens the 3D context (the - // intermediate generates its own group and composites its children - // as a flat bitmap before drawing into the scene's 3D space), so the - // cuboid shaft + pyramid head end up as a single 2D strip even - // though every polygon has a real matrix3d transform. Hanging axis - // identification on the PolyMesh wrapper via className keeps the - // 3D chain unbroken while still giving us a queryable marker. - return ( - onHoverChange?.(true)} - onPointerOut={() => onHoverChange?.(false)} - className={`polycss-transform-gizmo polycss-transform-arrow polycss-transform-arrow--${axisKey}`} - // Force baked rendering: in dynamic mode every color change - // (hover / drag) re-builds the texture atlas asynchronously, - // and the polygon ``'s background-image briefly resolves to - // null mid-rebuild — visually the arrow disappears for a frame. - // Baked mode renders solid polygons via inline `color` / currentColor - // (TextureBorderShapePoly path) which updates synchronously - // with no atlas hop, giving instant hover/drag feedback. - textureLighting="baked" - /> - ); -} - -interface TranslatePlaneProps { - axisA: 0 | 1 | 2; - axisB: 0 | 1 | 2; - perpAxis: 0 | 1 | 2; - planeKey: "xy" | "xz" | "yz"; - color: string; - shaftLengthCss: number; - /** Scene rotation (degrees) used to pick the camera-facing octant for - * the plane handle. */ - rotX: number; - rotY: number; - target: PolyMeshHandle; - enabled: boolean; - translationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; - onHoverChange?: (hovered: boolean) => void; - onDraggingStart?: () => void; - onDraggingStop?: () => void; -} - -function TranslatePlane({ - axisA, - axisB, - perpAxis, - planeKey, - color, - shaftLengthCss, - rotX, - rotY, - target, - enabled, - translationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onHoverChange, - onDraggingStart, - onDraggingStop, -}: TranslatePlaneProps) { - const cbRef = useRef({ - onChange, onObjectChange, onMouseDown, onMouseUp, - onDraggingChanged, onDraggingStart, onDraggingStop, enabled, translationSnap, - }); - cbRef.current = { - onChange, onObjectChange, onMouseDown, onMouseUp, - onDraggingChanged, onDraggingStart, onDraggingStop, enabled, translationSnap, - }; - - const polygons = useMemo(() => { - const lengthWorld = shaftLengthCss / SCENE_TILE_SIZE; - // Place the quad in the camera-facing octant: for each in-plane axis, - // flip the offset if its CSS +direction is back-facing the viewer. - // planePolygons uses WORLD axes (a/b derived from perp); WORLD_AXIS_FOR_CSS - // is involutive so the CSS axis we test is WORLD_AXIS_FOR_CSS[worldA]. - const worldPerp = WORLD_AXIS_FOR_CSS[perpAxis]; - const worldA = ((worldPerp + 1) % 3) as 0 | 1 | 2; - const worldB = ((worldPerp + 2) % 3) as 0 | 1 | 2; - const cssAForOffset = WORLD_AXIS_FOR_CSS[worldA]; - const cssBForOffset = WORLD_AXIS_FOR_CSS[worldB]; - const signA = isAxisBackFacing(cssAForOffset, 1, rotX, rotY) ? -1 : 1; - const signB = isAxisBackFacing(cssBForOffset, 1, rotX, rotY) ? -1 : 1; - const mag = lengthWorld * PLANE_OFFSET_RATIO; - return planePolygons({ - axis: worldPerp, - size: lengthWorld * PLANE_HALF_SIZE_RATIO, - offset: [signA * mag, signB * mag], - color, + e.nativeEvent.clientX, + e.nativeEvent.clientY, + dragStateRef.current, + ); }); - }, [perpAxis, color, shaftLengthCss, rotX, rotY]); - const onPointerDown = useCallback( - (e: PolyPointerEvent): void => { - if (!cbRef.current.enabled) return; - e.stopPropagation(); - const meshEl = e.eventObject.element; - const wrapper = meshEl?.closest("[data-poly-transform-controls]") as HTMLElement | null; - if (!wrapper) return; - cbRef.current.onDraggingStart?.(); - startPlaneDrag({ - axisA, - axisB, - probeDistanceCss: shaftLengthCss, + const handleRingDown = (spec: GizmoRingSpec) => (e: PolyPointerEvent) => + startFromMeshEvent(e, (wrapper) => { + startDeclarativeRingDrag( + spec, wrapper, - target, - startClientX: e.nativeEvent.clientX, - startClientY: e.nativeEvent.clientY, - translationSnap: cbRef.current.translationSnap, - onChange: cbRef.current.onChange, - onObjectChange: cbRef.current.onObjectChange, - onMouseDown: cbRef.current.onMouseDown, - onMouseUp: cbRef.current.onMouseUp, - onDraggingChanged: (d) => { - if (!d) cbRef.current.onDraggingStop?.(); - cbRef.current.onDraggingChanged?.(d); - }, - }); - }, - [axisA, axisB, target, shaftLengthCss], - ); - - return ( - onHoverChange?.(true)} - onPointerOut={() => onHoverChange?.(false)} - className={`polycss-transform-gizmo polycss-transform-plane polycss-transform-plane--${planeKey}`} - textureLighting="baked" - /> - ); -} - -interface RotateRingProps { - cssAxis: 0 | 1 | 2; - axisKey: string; - color: string; - radiusCss: number; - target: PolyMeshHandle; - enabled: boolean; - rotationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; - onHoverChange?: (hovered: boolean) => void; - onDraggingStart?: () => void; - onDraggingStop?: () => void; -} - -function RotateRing({ - cssAxis, - axisKey, - color, - radiusCss, - target, - enabled, - rotationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onHoverChange, - onDraggingStart, - onDraggingStop, -}: RotateRingProps) { - const cbRef = useRef({ - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onDraggingStart, - onDraggingStop, - enabled, - rotationSnap, - }); - cbRef.current = { - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onDraggingStart, - onDraggingStop, - enabled, - rotationSnap, - }; - - // Single square quad covering the ring's outer bounding box; CSS mask - // (`mask: radial-gradient(...)`) clips it to the donut shape. The mask - // reads `--ring-inner-ratio` so the donut's inner cutout scales with our - // chosen RING_HALF_THICKNESS_RATIO without hardcoding it in CSS. One DOM - // node per ring instead of `segments` segment quads. - const polygons = useMemo(() => { - const radiusWorld = radiusCss / SCENE_TILE_SIZE; - const outerWorld = radiusWorld * RING_QUAD_OUTER_RATIO; - return ringQuadPolygons({ - axis: WORLD_AXIS_FOR_CSS[cssAxis], - outerRadius: outerWorld, - color, + e.nativeEvent.clientX, + e.nativeEvent.clientY, + dragStateRef.current, + ); }); - }, [cssAxis, color, radiusCss]); - // Visible band start/end as fractions of the quad edge. The quad covers - // ±RING_QUAD_OUTER_RATIO · mid-radius; the visible ring is mid ± - // halfThickness. Normalize against the quad outer to get mask positions. - const ringInnerRatio = (1 - RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; - const ringOuterRatio = (1 + RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; - const onPointerDown = useCallback( - (e: PolyPointerEvent): void => { - if (!cbRef.current.enabled) return; - // No donut hit-test — let any click on the ring's quad bbox start - // the drag. The whole bbox is the click target so the rings are - // easy to land on; the visible donut mask is decoration only. - e.stopPropagation(); - const meshEl = e.eventObject.element; - const wrapper = meshEl?.closest("[data-poly-transform-controls]") as HTMLElement | null; - if (!wrapper) return; - cbRef.current.onDraggingStart?.(); - startRingDrag({ - cssAxis, - wrapper, - target, - startClientX: e.nativeEvent.clientX, - startClientY: e.nativeEvent.clientY, - rotationSnap: cbRef.current.rotationSnap, - onChange: cbRef.current.onChange, - onObjectChange: cbRef.current.onObjectChange, - onMouseDown: cbRef.current.onMouseDown, - onMouseUp: cbRef.current.onMouseUp, - onDraggingChanged: (d) => { - if (!d) cbRef.current.onDraggingStop?.(); - cbRef.current.onDraggingChanged?.(d); - }, - }); - }, - [cssAxis, target], - ); + const hoverHandlers = (key: string) => ({ + onPointerOver: () => setHoveredKey(key), + onPointerOut: () => setHoveredKey((cur) => (cur === key ? null : cur)), + }); return ( - onHoverChange?.(true)} - onPointerOut={() => onHoverChange?.(false)} - className={`polycss-transform-gizmo polycss-transform-ring polycss-transform-ring--${axisKey}`} - // CSS variable consumed by the .polycss-transform-ring radial-gradient - // mask in styles.ts. Carries the donut's inner/outer radius ratio. - style={{ - ["--ring-inner-ratio" as string]: ringInnerRatio, - ["--ring-outer-ratio" as string]: ringOuterRatio, - }} - // Same baked-mode reasoning as the translate arrows: avoid the - // dynamic-mode atlas-rebuild flash on hover/drag color changes. - textureLighting="baked" - /> +
+ {entries.arrows.map(({ spec, polygons: arrowPolys }) => ( + + ))} + {entries.planes.map(({ spec, polygons: planePolys }) => ( + + ))} + {entries.rings.map(({ spec, polygons: ringPolys }) => ( + + ))} +
); } diff --git a/packages/react/src/scene/PolyMesh.tsx b/packages/react/src/scene/PolyMesh.tsx index 394606c97..b6ef90115 100644 --- a/packages/react/src/scene/PolyMesh.tsx +++ b/packages/react/src/scene/PolyMesh.tsx @@ -29,7 +29,9 @@ import type { } from "@layoutit/polycss-core"; import { buildPolyMeshTransform } from "@layoutit/polycss-core"; import { - renderPolygonsWithTextureAtlas, + clearOwnedDomNodes, + renderStandaloneMeshIntoWrapper, + restoreVoxelMeshClass, type PolyMeshHandle as RuntimeMeshHandle, type PolySceneHandle, type TextureQuality, @@ -433,14 +435,7 @@ export const PolyMesh = forwardRef(function PolyM // Re-apply `.polycss-voxel-mesh` when React updates `className` on an adopted // direct-voxel wrapper (voxelRenderer attaches that class imperatively). useLayoutEffect(() => { - const el = wrapperRef.current; - if (!el) return; - for (let i = 0; i < el.children.length; i += 1) { - if (el.children[i]?.classList.contains("polycss-voxel-face")) { - el.classList.add("polycss-voxel-mesh"); - break; - } - } + restoreVoxelMeshClass(wrapperRef.current); }, [className, isLoadingSlot, isErrorSlot]); // Sync polygon array updates without tearing down the mesh entry. @@ -559,42 +554,24 @@ export const PolyMesh = forwardRef(function PolyM ]); // Standalone fallback when `` is rendered outside `` - // (e.g. isolated unit tests). Uses the same `@layoutit/polycss/runtime` - // `renderPolygonsWithTextureAtlas` so zero atlas code is duplicated. + // (e.g. isolated unit tests). useLayoutEffect(() => { const el = wrapperRef.current; if (sceneCtx || runtimeScene || !el || renderPolygon || isLoadingSlot || isErrorSlot) { - for (const node of standaloneOwnedRef.current) { - if (node.parentNode === el) el?.removeChild(node); - } - standaloneOwnedRef.current.clear(); + clearOwnedDomNodes(standaloneOwnedRef.current); return; } - const effectiveLighting = textureLighting ?? "baked"; - const result = renderPolygonsWithTextureAtlas(polygons, { + const mounted = renderStandaloneMeshIntoWrapper(el, standaloneOwnedRef.current, polygons, { doc: el.ownerDocument ?? document, - textureLighting: effectiveLighting, + textureLighting: textureLighting ?? "baked", textureQuality, textureLeafSizing, textureImageRendering, textureBackend, textureProjection, }); - standaloneReadyRef.current = result.pagesReady ?? RESOLVED_PROMISE; - const firstStatic = Array.from(el.childNodes).find((n) => !standaloneOwnedRef.current.has(n)) ?? null; - const frag = (el.ownerDocument ?? document).createDocumentFragment(); - for (const item of result.rendered) { - standaloneOwnedRef.current.add(item.element); - frag.appendChild(item.element); - } - el.insertBefore(frag, firstStatic); - return () => { - for (const node of standaloneOwnedRef.current) { - if (node.parentNode === el) el.removeChild(node); - } - standaloneOwnedRef.current.clear(); - result.dispose(); - }; + standaloneReadyRef.current = mounted.ready; + return () => mounted.dispose(); }, [ runtimeScene, renderPolygon, diff --git a/packages/react/src/scene/events.ts b/packages/react/src/scene/events.ts index 1a3dbd3c5..b5320c1eb 100644 --- a/packages/react/src/scene/events.ts +++ b/packages/react/src/scene/events.ts @@ -1,28 +1,13 @@ /** - * Pointer event API for . Mirrors @react-three/fiber's mesh - * event surface (handler names + payload shape) so devs migrating from - * three.js use the same mental model. PolyCSS is DOM-native so we get - * native pointer events for free — no raycaster, no canvas event - * synthesis. - * - * Diverges from r3f in two intentional ways: - * 1. Bubbling matches DOM (pointer hits the front element only). r3f - * replays events to occluded objects behind the front hit; doing - * that here would require running our own raycaster, which defeats - * the point of being DOM-native. - * 2. `face`, `uv`, `uv1`, `instanceId` are omitted — they're three.js - * BufferGeometry / InstancedMesh concepts with no polycss analogue. - * The polycss-native equivalent of `face` is the hit polygon's - * index, exposed via `polygon` (set when the underlying DOM target - * is an `` polygon element). + * Pointer event API for . Delegates DOM element registry and + * bounding-rect hit-testing to `@layoutit/polycss/runtime`. */ import type { Polygon, Vec3 } from "@layoutit/polycss-core"; +import { createMeshElementRegistry, pointInMeshElement } from "@layoutit/polycss/runtime"; /** * Imperative handle exposed by ``. Read-only view of the - * mesh's element + current transform + polygons. Mutation flows through - * controlled props (parent owns transform state) — matches three.js - * editor's pattern of keeping `selected` external to the object. + * mesh's element + current transform + polygons. */ export interface PolyMeshHandle { /** The `.polycss-mesh` wrapper div (null until mounted). */ @@ -37,73 +22,24 @@ export interface PolyMeshHandle { getScale(): number | Vec3 | undefined; /** Polygons currently being rendered (post-autoCenter). */ getPolygons(): Polygon[]; - /** - * Replace the mesh polygons imperatively. Animated solid-triangle meshes use - * a stable DOM update path that mutates mounted leaves directly; unsupported - * topology falls back to the normal framework render path. - */ + /** Replace the mesh polygons imperatively. */ setPolygons(polygons: Polygon[]): void; - /** - * Snapshot the current `rotation` prop as the new "baked rotation" and - * trigger an atlas re-rasterization with the directional light - * inverse-rotated into the mesh's local frame. - * - * Call this after a rotate-mode drag ends (i.e. on pointer release) — - * **not** on every pointermove during the drag. The visual wrapper already - * follows the live `rotation` prop smoothly; the atlas only needs to - * update once per committed rotation so it doesn't re-bake every frame. - * - * Math rationale: baked atlas tiles encode `baseColor × Lambert(worldNormal, - * worldLight)`. When the mesh wrapper rotates via CSS the world-space normal - * changes but the baked color does not, causing stale shading. Calling - * `rebakeAtlas()` inverse-rotates the world light into the mesh-local frame - * before re-running the atlas baker, so `dot(localNormal, localLight) === - * dot(worldNormal, worldLight)` and the shading is correct again. - * - * In dynamic (`textureLighting="dynamic"`) mode this call is a no-op for - * shading purposes (dynamic mode re-evaluates per frame), but it is still - * safe to call. - */ + /** Snapshot current `rotation` and re-rasterize baked atlas lighting. */ rebakeAtlas(): void; /** Resolves when this mesh's current texture generation has usable backgrounds. */ whenTexturesReady(): Promise; - /** - * Mutate a single polygon in place and re-render the mesh. `target` is - * either a polygon reference (as returned by `getPolygons()`) or its index. - * `partial` fields are merged onto the polygon via `Object.assign`. Skips - * the merge pass — cheaper than a full prop change for targeted edits like - * color picker updates from an inspector UI. Silently no-ops when `target` - * is not found or the index is out of range. - */ + /** Mutate a single polygon in place and re-render the mesh. */ updatePolygon(target: Polygon | number, partial: Partial): void; } -/** - * Pointer event payload delivered to handlers. Mirrors r3f's - * shape, minus raycaster-specific fields. See module docstring for the - * intentional divergences. - */ +/** Pointer event payload delivered to `` handlers. */ export interface PolyPointerEvent { - /** The mesh originally under the pointer (deepest hit). */ object: PolyMeshHandle; - /** The mesh whose handler is being invoked. Equal to `object` until - * ancestor bubbling is added (out of scope for v1). */ eventObject: PolyMeshHandle; - /** All meshes stacked under the pointer this moment, front-to-back. - * Computed via `document.elementsFromPoint` then filtered to - * registered `.polycss-mesh` ancestors. */ intersections: Array<{ object: PolyMeshHandle }>; - /** Pointer position in normalized device coords [-1, 1] relative to - * the camera viewport. (0,0) = viewport center. Falls back to (0,0) - * when the mesh is rendered outside a ``. */ pointer: { x: number; y: number }; - /** Pixel distance from the most recent `pointerdown` to this event. - * 0 on pointerdown itself. Use to discriminate click-vs-drag. */ delta: number; - /** The underlying DOM event. */ nativeEvent: E; - /** Stops native bubbling. (Equivalent to `nativeEvent.stopPropagation()` - * today; reserved for future r3f-style bubbling above the wrapper.) */ stopPropagation(): void; } @@ -114,11 +50,7 @@ export type PolyEventHandler = ( event: PolyPointerEvent, ) => void; -/** - * Pointer / mouse / wheel handlers accepted by ``. Names mirror - * r3f exactly. Provide any handler to opt the mesh into receiving events; - * absent handlers add zero overhead. - */ +/** Pointer / mouse / wheel handlers accepted by ``. */ export interface InteractionProps { onClick?: PolyEventHandler; onContextMenu?: PolyEventHandler; @@ -134,95 +66,10 @@ export interface InteractionProps { onPointerCancel?: PolyEventHandler; } -// ── Mesh element registry ──────────────────────────────────────────────── -// Maps `.polycss-mesh` DOM elements to their PolyMeshHandle so consumers -// (intersections list, (to resolve a click target back to the chosen -// mesh) and (to know which axis arrow was hit -// when the click fell through). DRY: one place defines the rules. - -/** Test whether `(clientX, clientY)` falls inside any polygon leaf - * child of `meshEl`'s post-3D bounding rect. Skips zero-area rects - * (happy-dom and pre-layout SSR return those). */ -export function pointInMeshElement( - meshEl: HTMLElement, - clientX: number, - clientY: number, -): boolean { - const polys = Array.from(meshEl.querySelectorAll("i,b,s,u")) as HTMLElement[]; - for (const p of polys) { - const r = p.getBoundingClientRect(); - if (r.width <= 0 || r.height <= 0) continue; - if ( - clientX >= r.left && - clientX <= r.right && - clientY >= r.top && - clientY <= r.bottom - ) { - return true; - } - } - return false; -} - -/** Walk every registered `.polycss-mesh` in the document and return - * the first whose polygon bounding-rects contain `(clientX, clientY)`. - * An optional `filter` skips matched mesh elements (e.g. gizmos). */ -export function findMeshUnderPoint( - clientX: number, - clientY: number, - filter?: (meshEl: HTMLElement) => boolean, -): PolyMeshHandle | null { - if (typeof document === "undefined") return null; - const meshEls = Array.from( - document.querySelectorAll(".polycss-mesh"), - ) as HTMLElement[]; - for (const meshEl of meshEls) { - if (filter && !filter(meshEl)) continue; - const handle = findPolyMeshHandle(meshEl); - if (!handle) continue; - if (pointInMeshElement(meshEl, clientX, clientY)) return handle; - } - return null; -} +export const registerMeshElement = meshRegistry.registerMeshElement; +export const unregisterMeshElement = meshRegistry.unregisterMeshElement; +export const findPolyMeshHandle = meshRegistry.findPolyMeshHandle; +export const findMeshUnderPoint = meshRegistry.findMeshUnderPoint; +export { pointInMeshElement }; diff --git a/packages/react/src/scene/mesh/useMeshEvents.ts b/packages/react/src/scene/mesh/useMeshEvents.ts index c94aee73e..e2a1e0aea 100644 --- a/packages/react/src/scene/mesh/useMeshEvents.ts +++ b/packages/react/src/scene/mesh/useMeshEvents.ts @@ -1,10 +1,14 @@ /** - * useMeshEvents — pointer-event synthesis (polycss-shaped payloads from - * React synthetic events) and the union of wrapper DOM handlers. Extracted - * verbatim from PolyMesh.tsx. + * useMeshEvents — pointer-event synthesis over `@layoutit/polycss/runtime`'s + * `buildPolyPointerEvent` and wrapper DOM handler wiring for React ``. */ import { useCallback, useMemo, useRef } from "react"; -import type { PointerEvent as ReactPointerEvent, MouseEvent as ReactMouseEvent, WheelEvent as ReactWheelEvent } from "react"; +import type { + PointerEvent as ReactPointerEvent, + MouseEvent as ReactMouseEvent, + WheelEvent as ReactWheelEvent, +} from "react"; +import { buildPolyPointerEvent } from "@layoutit/polycss/runtime"; import type { PolyCameraContextValue } from "../../camera/context"; import { findPolyMeshHandle, @@ -35,12 +39,6 @@ export function useMeshEvents({ onPointerLeave, onPointerCancel, }: UseMeshEventsOptions) { - // ── Pointer event synthesis ─────────────────────────────────────────── - // Build the polycss-shaped payload from a native React synthetic event. - // intersections come from elementsFromPoint, walked up to nearest mesh - // ancestor — front-to-back order matches DOM stacking. NDC pointer is - // computed against the camera viewport bounds (falls back to (0,0) when - // PolyMesh is rendered outside a ). const cameraElRef = cameraCtx?.cameraElRef ?? null; const pointerDownAtRef = useRef<{ x: number; y: number } | null>(null); @@ -50,53 +48,20 @@ export function useMeshEvents({ clientX: number, clientY: number, ): PolyPointerEvent { - const intersections: Array<{ object: PolyMeshHandle }> = []; - if (typeof document !== "undefined" && typeof document.elementsFromPoint === "function") { - const stacked = document.elementsFromPoint(clientX, clientY); - const seen = new Set(); - for (const el of stacked) { - const h = findPolyMeshHandle(el); - if (h && !seen.has(h)) { - seen.add(h); - intersections.push({ object: h }); - } - } - } - let nx = 0; - let ny = 0; - const camEl = cameraElRef?.current; - if (camEl) { - const r = camEl.getBoundingClientRect(); - if (r.width > 0 && r.height > 0) { - nx = ((clientX - r.left) / r.width) * 2 - 1; - ny = -(((clientY - r.top) / r.height) * 2 - 1); - } - } - let delta = 0; - const pd = pointerDownAtRef.current; - if (pd) delta = Math.hypot(clientX - pd.x, clientY - pd.y); - return { - object: intersections[0]?.object ?? handle, - eventObject: handle, - intersections, - pointer: { x: nx, y: ny }, - delta, + return buildPolyPointerEvent({ + handle, nativeEvent, - stopPropagation: () => nativeEvent.stopPropagation(), - }; + clientX, + clientY, + cameraEl: cameraElRef?.current, + pointerDownAt: pointerDownAtRef.current, + resolveHandle: findPolyMeshHandle, + }); }, [cameraElRef, handle], ); - // Build the union of DOM handlers we need to attach. Wiring stays inert - // when the user provides no handlers — `wrapperHandlers` ends up empty. const wrapperHandlers = useMemo(() => { - // Wrap the polycss event's stopPropagation to ALSO stop React's - // synthetic event propagation (which is the relevant tree-bubbling - // for ancestor handlers in JSX). Without this, calling - // event.stopPropagation() from a polycss handler would only stop - // native DOM bubbling — React's tree bubbling would still hit - // ancestor onClick handlers, surprising consumers. const dispatch = ( polyHandler: PolyEventHandler | undefined, reactEvent: R, @@ -125,44 +90,25 @@ export function useMeshEvents({ onPointerLeave?: (e: ReactPointerEvent) => void; onPointerCancel?: (e: ReactPointerEvent) => void; } = {}; - if (onClick) { - out.onClick = (e) => dispatch(onClick, e, e.nativeEvent, e.clientX, e.clientY); - } + if (onClick) out.onClick = (e) => dispatch(onClick, e, e.nativeEvent, e.clientX, e.clientY); if (onContextMenu) { out.onContextMenu = (e) => dispatch(onContextMenu, e, e.nativeEvent, e.clientX, e.clientY); } if (onDoubleClick) { out.onDoubleClick = (e) => dispatch(onDoubleClick, e, e.nativeEvent, e.clientX, e.clientY); } - if (onWheel) { - out.onWheel = (e) => dispatch(onWheel, e, e.nativeEvent, e.clientX, e.clientY); - } - if (onPointerDown) { - out.onPointerDown = (e) => { - pointerDownAtRef.current = { x: e.clientX, y: e.clientY }; - dispatch(onPointerDown, e, e.nativeEvent, e.clientX, e.clientY); - }; - } else { - // Still need to track pointerdown for delta computation when other - // handlers (move/up/click) want it. - out.onPointerDown = (e) => { - pointerDownAtRef.current = { x: e.clientX, y: e.clientY }; - }; - } - if (onPointerUp) { - out.onPointerUp = (e) => { - dispatch(onPointerUp, e, e.nativeEvent, e.clientX, e.clientY); - pointerDownAtRef.current = null; - }; - } else { - out.onPointerUp = () => { pointerDownAtRef.current = null; }; - } + if (onWheel) out.onWheel = (e) => dispatch(onWheel, e, e.nativeEvent, e.clientX, e.clientY); + out.onPointerDown = (e) => { + pointerDownAtRef.current = { x: e.clientX, y: e.clientY }; + if (onPointerDown) dispatch(onPointerDown, e, e.nativeEvent, e.clientX, e.clientY); + }; + out.onPointerUp = (e) => { + if (onPointerUp) dispatch(onPointerUp, e, e.nativeEvent, e.clientX, e.clientY); + pointerDownAtRef.current = null; + }; if (onPointerMove) { out.onPointerMove = (e) => dispatch(onPointerMove, e, e.nativeEvent, e.clientX, e.clientY); } - // r3f: onPointerOver and onPointerEnter both fire on entering the - // mesh; onPointerOut and onPointerLeave on leaving. DOM enter/leave - // (no bubble for child→child transitions) is the right primitive. if (onPointerOver || onPointerEnter) { out.onPointerEnter = (e) => { if (onPointerOver) dispatch(onPointerOver, e, e.nativeEvent, e.clientX, e.clientY); diff --git a/packages/react/src/select/Select.tsx b/packages/react/src/select/Select.tsx index eadb9cc87..36bf3a24f 100644 --- a/packages/react/src/select/Select.tsx +++ b/packages/react/src/select/Select.tsx @@ -1,39 +1,9 @@ /** - * — selection wrapper that auto-tracks descendant `` - * clicks and exposes the current selection via `usePolySelect()`. - * - * API mirrors @react-three/drei's ` still works - // outside a camera context. const handleClick = (e: ReactMouseEvent) => { if (cameraCtx) return; - const handle = - findPolyMeshHandle(e.target as Element) ?? - findMeshUnderPoint(e.clientX, e.clientY); - if (!handle) { - if (onPointerMissed) onPointerMissed(e); - if (clearOnMiss) apply([]); - return; - } - if (multiple && (e.shiftKey || e.metaKey || e.ctrlKey)) { - api.toggle(handle); - } else if (selected.length === 1 && selected[0] === handle) { - apply([]); - } else { - apply([handle]); - } + controller.handleClick(e.nativeEvent); }; - // display:contents keeps the wrapper invisible to CSS layout AND CSS - // 3D context — important because polycss-camera relies on an - // unbroken `transform-style: preserve-3d` chain from camera → scene → - // mesh → polygon for 3D rendering. A plain block-level wrapper, even - // with preserve-3d via the `.polycss-camera *` rule, flattens the - // scene (the chicken renders as a pancake). Event delivery to a - // display:contents element is unreliable in some browsers, but we - // don't depend on it — the native click listener attaches to - // the parent scene element instead (see useEffect above). + // display:contents keeps the wrapper invisible to CSS 3D preserve-3d nesting. const wrapperStyle: CSSProperties = { display: "contents", ...style }; return (
`. - * Returns an empty array when used outside a `` (matches drei). - */ +/** Read the current selection from the nearest enclosing ``. */ export function usePolySelect(): PolyMeshHandle[] { return useContext(SelectContext)?.selected ?? []; } -/** - * Read the imperative selection API. Throws when used outside `` - * — fail loudly because callers expect to mutate. - */ +/** Read the imperative selection API. Throws when used outside ``. */ export function usePolySelectionApi(): PolySelectionApi { const ctx = useContext(SelectContext); if (!ctx) { diff --git a/packages/react/src/shapes/Poly.tsx b/packages/react/src/shapes/Poly.tsx index d3ba2ce13..09ce04869 100644 --- a/packages/react/src/shapes/Poly.tsx +++ b/packages/react/src/shapes/Poly.tsx @@ -1,145 +1,24 @@ import { createElement, memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import type React from "react"; import type { CSSProperties } from "react"; -import type { - PolyMaterial, - PolyTextureImageRendering, - Polygon, - Vec2, -} from "@layoutit/polycss-core"; +import type { Polygon } from "@layoutit/polycss-core"; import { worldDirectionalLightToCss } from "@layoutit/polycss-core"; import { + buildDirectMaterialLeafDescriptor, + buildFallbackLeafDescriptor, + buildPolyWrapperTransform, computeTextureAtlasPlanPublic, + isAxisAlignedRectUVs, + readElementDataAttrs, + readElementStyleRecord, renderPolygonsWithTextureAtlas, + syncLeafBorderShapeStyle, type RenderTextureAtlasResult, - type TextureAtlasPlan, } from "@layoutit/polycss/runtime"; import type { PolyProps } from "./types"; const useIsomorphicLayoutEffect = typeof document !== "undefined" ? useLayoutEffect : useEffect; -const DIRECT_TEXTURE_CSS_DECIMALS = 4; - -function formatCssLength(value: number, decimals = DIRECT_TEXTURE_CSS_DECIMALS): string { - const next = value.toFixed(decimals).replace(/\.?0+$/, ""); - return Number(next) === 0 || Object.is(Number(next), -0) ? "0" : `${next}px`; -} - -function isAxisAlignedRectUVs( - uvs: Vec2[], -): { u0: number; u1: number; v0: number; v1: number } | null { - if (uvs.length !== 4) return null; - const us = [...new Set(uvs.map((uv) => uv[0]))].sort((a, b) => a - b); - const vs = [...new Set(uvs.map((uv) => uv[1]))].sort((a, b) => a - b); - if (us.length !== 2 || vs.length !== 2) return null; - const corners = new Set([ - `${us[0]},${vs[0]}`, - `${us[0]},${vs[1]}`, - `${us[1]},${vs[0]}`, - `${us[1]},${vs[1]}`, - ]); - for (const uv of uvs) { - if (!corners.has(`${uv[0]},${uv[1]}`)) return null; - } - return { u0: us[0]!, u1: us[1]!, v0: vs[0]!, v1: vs[1]! }; -} - -function cssPropToCamel(prop: string): string { - if (prop.startsWith("--")) return prop; - if (prop.startsWith("-webkit-")) { - return "Webkit" + prop.slice(8).replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()); - } - return prop.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()); -} - -function readElementStyle(el: HTMLElement): CSSProperties { - const out: Record = {}; - const style = el.style; - for (let i = 0; i < style.length; i += 1) { - const prop = style[i]!; - const val = style.getPropertyValue(prop); - if (val) out[cssPropToCamel(prop)] = val; - } - return out as CSSProperties; -} - -function readElementDataAttrs(el: HTMLElement): Record { - const out: Record = {}; - for (const attr of Array.from(el.attributes)) { - if (attr.name.startsWith("data-")) { - out[attr.name] = attr.value; - } - } - return out; -} - -function MaterialDirectPoly({ - plan, - material, - uvRect, - className, - style: styleProp, - domAttrs, - domEventHandlers, - pointerEvents = "auto", - imageRendering, -}: { - plan: TextureAtlasPlan; - material: PolyMaterial; - uvRect: { u0: number; u1: number; v0: number; v1: number }; - className?: string; - style?: CSSProperties; - domAttrs?: Record; - domEventHandlers?: React.DOMAttributes; - pointerEvents?: "auto" | "none"; - imageRendering?: PolyTextureImageRendering; -}) { - const { u0, u1, v0, v1 } = uvRect; - const du = u1 - u0; - const dv = v1 - v0; - const sourceW = 1 / du; - const sourceH = 1 / dv; - const vMax = Math.max(v0, v1); - const offsetX = u0 / du; - const offsetY = (1 - vMax) / dv; - - const style: CSSProperties = { - transform: `matrix3d(${plan.canonicalMatrix})`, - backgroundImage: `url(${material.texture})`, - backgroundSize: `${formatCssLength(sourceW)} ${formatCssLength(sourceH)}`, - backgroundPosition: `${formatCssLength(-offsetX)} ${formatCssLength(-offsetY)}`, - backgroundRepeat: "no-repeat", - imageRendering: imageRendering === "pixelated" ? "pixelated" : undefined, - pointerEvents: pointerEvents === "none" ? "none" : undefined, - ...styleProp, - }; - - const dataAttrs = plan.polygon.data - ? Object.fromEntries( - Object.entries(plan.polygon.data).map(([k, v]) => [`data-${k}`, String(v)]), - ) - : {}; - const elementClassName = className?.trim() || undefined; - - return ( - - ); -} - /** * Poly — renders one polygon as a render-strategy DOM leaf via * `@layoutit/polycss/runtime`. @@ -243,9 +122,8 @@ function PolyInner({ const isTextured = Boolean(effectiveTexture || textureImageSource); const hasDom = typeof document !== "undefined"; - // Solid polygons are 100% synchronous with zero blob URLs; textured polygons - // manage their async canvas/blob atlas inside an effect so React StrictMode - // double-invocation cleanly cancels and recreates without revoking live URLs. + // Solid polygons are synchronous with zero blob URLs; textured polygons + // manage async canvas/blob atlases in a layout effect for StrictMode safety. const solidRenderedResult = useMemo(() => { if (materialUvRect || isTextured || !hasDom) return null; return renderPolygonsWithTextureAtlas([polygon], { @@ -305,7 +183,6 @@ function PolyInner({ }); setTexturedState({ result: next, tick: 0 }); const leaf = next.rendered[0]?.element; - // Only atlas leaves mutate their background asynchronously after pagesReady. if (leaf && leaf.tagName.toLowerCase() === "s") { next.pagesReady?.then(() => { if (alive) { @@ -336,8 +213,7 @@ function PolyInner({ const renderedResult = isTextured ? texturedState?.result ?? null : solidRenderedResult; - // Pure-JS fallback plan for Node SSR (no `document`) and the initial pre-effect - // frame of textured polygons so `` always emits valid deterministic markup. + // Pure-JS fallback plan for Node SSR and pre-effect textured initial frame. const fallbackPlan = useMemo( () => !materialUvRect && !renderedResult?.rendered[0] @@ -392,53 +268,40 @@ function PolyInner({ : {}), }; - const transformParts: string[] = []; - if (position) { - transformParts.push( - `translate3d(${position[0]}px, ${position[1]}px, ${position[2]}px)`, - ); - } - if (scale !== undefined) { - if (typeof scale === "number") { - if (scale !== 1) transformParts.push(`scale3d(${scale}, ${scale}, ${scale})`); - } else { - transformParts.push(`scale3d(${scale[0]}, ${scale[1]}, ${scale[2]})`); - } - } - if (rotation) { - if (rotation[0]) transformParts.push(`rotateX(${rotation[0]}deg)`); - if (rotation[1]) transformParts.push(`rotateY(${rotation[1]}deg)`); - if (rotation[2]) transformParts.push(`rotateZ(${rotation[2]}deg)`); - } - const wrapperTransform = transformParts.length > 0 ? transformParts.join(" ") : undefined; + const wrapperTransform = buildPolyWrapperTransform({ position, scale, rotation }); const leafDomRef = useRef(null); - const rawBorderShape = renderedResult?.rendered[0]?.element.style.getPropertyValue("border-shape") || ""; + const rawBorderShape = + renderedResult?.rendered[0]?.element.style.getPropertyValue("border-shape") || ""; const rawLeafCssText = renderedResult?.rendered[0]?.element.getAttribute("style") || ""; useIsomorphicLayoutEffect(() => { - const el = leafDomRef.current; - if (!el || !rawBorderShape) return; - // Preserve exact engine cssText order (transform; border-shape; color) - // and ensure non-standard `border-shape` survives React/happy-dom style syncing. - el.setAttribute("style", rawLeafCssText); - if (pointerEventsProp === "none") el.style.pointerEvents = "none"; - if (styleProp) Object.assign(el.style, styleProp); + syncLeafBorderShapeStyle( + leafDomRef.current, + rawBorderShape, + rawLeafCssText, + pointerEventsProp, + styleProp as Record | undefined, + ); }, [rawBorderShape, rawLeafCssText, pointerEventsProp, styleProp]); let front: React.ReactNode = null; if (materialUvRect && material && materialPlan) { + const desc = buildDirectMaterialLeafDescriptor({ + plan: materialPlan, + material, + uvRect: materialUvRect, + className, + pointerEvents: pointerEventsProp ?? "auto", + imageRendering: textureImageRendering, + }); front = ( - ); } else if (renderedResult?.rendered[0]) { @@ -446,7 +309,7 @@ function PolyInner({ const tag = leafEl.tagName.toLowerCase(); const leafClass = leafEl.className.trim(); const combinedClassName = [leafClass, className?.trim()].filter(Boolean).join(" ") || undefined; - const leafStyle = readElementStyle(leafEl); + const leafStyle = readElementStyleRecord(leafEl, { camelCase: true }) as CSSProperties; const mergedStyle: CSSProperties = { ...leafStyle, pointerEvents: pointerEventsProp === "none" ? "none" : leafStyle.pointerEvents, @@ -462,20 +325,18 @@ function PolyInner({ ...domAttrs, }); } else if (fallbackPlan) { - const tag = !isTextured && polygon.vertices.length === 4 ? "b" : "s"; - const mergedStyle: CSSProperties = { - transform: `matrix3d(${fallbackPlan.canonicalMatrix})`, - ...(!isTextured ? { backgroundColor: fallbackPlan.shadedColor } : {}), - pointerEvents: pointerEventsProp === "none" ? "none" : undefined, - ...styleProp, - }; - front = createElement(tag, { + const desc = buildFallbackLeafDescriptor({ + plan: fallbackPlan, + polygon, + isTextured, + className, + pointerEvents: pointerEventsProp, + }); + front = createElement(desc.tag, { ref: leafDomRef, - className: className?.trim() || undefined, - style: mergedStyle, - "data-poly-index": "0", - "data-polycss-leaf": "polygon", - "data-polycss-double-sided": polygon.doubleSided ? "true" : undefined, + className: desc.className, + style: { ...(desc.style as CSSProperties), ...styleProp }, + ...desc.dataAttrs, ...domEventHandlers, ...domAttrs, }); diff --git a/packages/vue/src/camera/useCamera.ts b/packages/vue/src/camera/useCamera.ts index e6b479f31..6f75c2ee3 100644 --- a/packages/vue/src/camera/useCamera.ts +++ b/packages/vue/src/camera/useCamera.ts @@ -1,13 +1,11 @@ import { onScopeDispose, ref, shallowRef, watch } from "vue"; import type { Ref, ShallowRef } from "vue"; -import { - buildPolyCameraSceneTransform, - capturePolyCameraSnapshot, -} from "@layoutit/polycss-core"; import type { CameraState, CameraHandle, PolyCameraProjection, Vec3 } from "@layoutit/polycss-core"; import { - createPolyOrthographicCamera, - createPolyPerspectiveCamera, + applyCameraTransformDirect, + bindCameraStoreSync, + createLiveRuntimeCamera, + writeCameraSnapshotAttrs, type PolyOrthographicCameraHandle, type PolyPerspectiveCameraHandle, type PolySceneHandle, @@ -37,55 +35,20 @@ export interface UseCameraResult { applyTransformDirect: () => void; } -function writeCameraSnapshotAttrs( - el: HTMLElement | null, - camera: CameraHandle, - projection: PolyCameraProjection | undefined, - perspectiveStyle: string | undefined, -): void { - if (!el) return; - const snapshot = capturePolyCameraSnapshot(camera, { projection, perspectiveStyle }); - el.dataset.polycssCameraProjection = snapshot.projection; - el.dataset.polycssCameraPerspective = snapshot.perspectiveStyle; - el.dataset.polycssCameraAppliedPerspective = snapshot.appliedPerspectiveStyle; - el.dataset.polycssCameraZoom = String(snapshot.state.zoom); - el.dataset.polycssCameraDistance = String(snapshot.state.distance); - el.dataset.polycssCameraRotX = String(snapshot.state.rotX); - el.dataset.polycssCameraRotY = String(snapshot.state.rotY); - el.dataset.polycssCameraTarget = snapshot.state.target.join(","); -} - export function usePolyCamera(options: Ref): UseCameraResult { - const baseOpts = { + const handle = createLiveRuntimeCamera({ zoom: options.value.zoom, target: options.value.target, rotX: options.value.rotX, rotY: options.value.rotY, distance: options.value.distance, - }; - const inner = - options.value.projection === "perspective" - ? createPolyPerspectiveCamera({ - ...baseOpts, - perspective: parseFloat(options.value.perspectiveStyle ?? "32000px") || 32000, - }) - : createPolyOrthographicCamera(baseOpts); - - const handle: PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle = { - get state() { return inner.state; }, - update(next: Partial) { inner.update(next); }, - getStyle(input) { return inner.getStyle(input); }, - subscribe(listener) { return inner.subscribe(listener); }, - get type() { - return (options.value.projection ?? "orthographic") as "perspective" & "orthographic"; - }, - get perspectiveStyle() { - return ( - options.value.perspectiveStyle ?? - (options.value.projection === "perspective" ? "32000px" : "none") - ) as string & "none"; - }, - } as PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle; + initialProjection: options.value.projection, + initialPerspectiveStyle: options.value.perspectiveStyle, + getProjection: () => options.value.projection ?? "orthographic", + getPerspectiveStyle: () => + options.value.perspectiveStyle ?? + (options.value.projection === "perspective" ? "32000px" : "none"), + }); const cameraRef = shallowRef(handle); const runtimeCameraRef = shallowRef< @@ -97,66 +60,19 @@ export function usePolyCamera(options: Ref): UseCameraResult { const autoCenterOffset = ref([0, 0, 0]); const store = createSceneStore(handle.state); - let syncing = false; - const unsubHandle = handle.subscribe(() => { - if (syncing) return; - syncing = true; - try { - store.updateCameraFromRef(handle); - } finally { - syncing = false; - } - }); - const unsubStore = store.subscribe(() => { - if (syncing) return; - const next = store.getState().cameraState; - const cur = handle.state; - const changed = - next.rotX !== cur.rotX || - next.rotY !== cur.rotY || - next.zoom !== cur.zoom || - next.distance !== cur.distance || - next.target[0] !== cur.target[0] || - next.target[1] !== cur.target[1] || - next.target[2] !== cur.target[2]; - if (!changed) return; - syncing = true; - try { - handle.update(next); - runtimeSceneRef.value?.applyCamera(); - } finally { - syncing = false; - } - }); - onScopeDispose(() => { - unsubHandle(); - unsubStore(); - }); + const unbindSync = bindCameraStoreSync(handle, store, () => runtimeSceneRef.value); + onScopeDispose(unbindSync); function applyTransformDirect(): void { - const runtimeScene = runtimeSceneRef.value; - if (runtimeScene) { - runtimeScene.applyCamera(); - writeCameraSnapshotAttrs( - cameraElRef.value, - handle, - options.value.projection, - options.value.perspectiveStyle, - ); - return; - } - const el = sceneElRef.value; - if (el) { - el.style.transform = buildPolyCameraSceneTransform(handle.state, { - autoCenterOffset: autoCenterOffset.value, - }); - } - writeCameraSnapshotAttrs( - cameraElRef.value, + applyCameraTransformDirect({ + runtimeScene: runtimeSceneRef.value, + sceneEl: sceneElRef.value, + cameraEl: cameraElRef.value, handle, - options.value.projection, - options.value.perspectiveStyle, - ); + autoCenterOffset: autoCenterOffset.value, + projection: options.value.projection, + perspectiveStyle: options.value.perspectiveStyle, + }); } watch( @@ -182,24 +98,20 @@ export function usePolyCamera(options: Ref): UseCameraResult { store.updateCameraFromRef(handle); store.notifyAll(); } - writeCameraSnapshotAttrs( - cameraElRef.value, - handle, - options.value.projection, - options.value.perspectiveStyle, - ); + writeCameraSnapshotAttrs(cameraElRef.value, handle, { + projection: options.value.projection, + perspectiveStyle: options.value.perspectiveStyle, + }); }, ); watch( cameraElRef, (el) => - writeCameraSnapshotAttrs( - el, - handle, - options.value.projection, - options.value.perspectiveStyle, - ), + writeCameraSnapshotAttrs(el, handle, { + projection: options.value.projection, + perspectiveStyle: options.value.perspectiveStyle, + }), { flush: "post" }, ); diff --git a/packages/vue/src/controls/PolyTransformControls.ts b/packages/vue/src/controls/PolyTransformControls.ts index 86a5295f4..4809961f3 100644 --- a/packages/vue/src/controls/PolyTransformControls.ts +++ b/packages/vue/src/controls/PolyTransformControls.ts @@ -1,18 +1,7 @@ /** - * `` (Vue) — drag gizmo for translating / rotating - * a `` along the six axis arrows or three axis rings. - * Mirrors the React PolyTransformControls API and the vanilla - * createTransformControls behavior. - * - * Geometry: arrows use `arrowPolygons`, rings use `ringQuadPolygons` - * (both from @layoutit/polycss-core). Each is rendered through a regular - * `` so it composes with the scene's lighting / atlas - * pipeline. baked mode is forced on the gizmo PolyMeshes so hover/ - * drag color updates are instant (no atlas rebuild flash). - * - * Drag math: probe-based screen-axis projection for translate; pointer- - * angle accumulation for rotate. Same algorithms as the React/vanilla - * versions. + * `` (Vue) — thin Vue wrapper over + * `@layoutit/polycss/runtime`'s shared gizmo drag, geometry, and fallback + * hit-test engine. */ import { defineComponent, @@ -22,55 +11,28 @@ import { onMounted, ref, computed, - watch, type ComputedRef, type PropType, type Ref, } from "vue"; +import type { Vec3 } from "@layoutit/polycss-core"; import { - ALPHA_DRAGGING, - ALPHA_HOVER, - ALPHA_IDLE, - ARROW_SPECS, - HEAD_HALF_THICKNESS_RATIO, - HEAD_LENGTH_RATIO, - PLANE_HALF_SIZE_RATIO, - PLANE_OFFSET_RATIO, - PLANE_SPECS, - RING_HALF_THICKNESS_RATIO, - RING_QUAD_OUTER_RATIO, - RING_RADIUS_RATIO, - RING_SPECS, - SCENE_TILE_SIZE, - SCREEN_AXIS_DEAD_ZONE_SQ, - SHAFT_HALF_THICKNESS_RATIO, - WORLD_AXIS_FOR_CSS, - arrowPolygons, - eulerXYZFromQuat, - gizmoCenterForMesh, - gizmoLengthForMesh, - isAxisBackFacing, - planePolygons, - quatFromAxisAngle, - quatFromEulerXYZ, - quatMultiply, - ringQuadPolygons, - screenPlaneDet, - snap, - solveAxisDragDelta, - solvePlaneDragDeltas, - unwrapAngleDelta, - userAxisLetterOf, - withAlpha, - type Polygon, - type Vec3, -} from "@layoutit/polycss-core"; + RING_MASK_INNER_RATIO, + RING_MASK_OUTER_RATIO, + attachDeclarativeGizmoFallback, + buildTransformGizmoEntries, + computeGizmoWrapperPositionCss, + startDeclarativeArrowDrag, + startDeclarativePlaneDrag, + startDeclarativeRingDrag, + type DeclarativeGizmoDragState, + type GizmoArrowSpec, + type GizmoMode, + type GizmoPlaneSpec, + type GizmoRingSpec, +} from "@layoutit/polycss/runtime"; import { PolyMesh } from "../scene/PolyMesh"; -import { - pointInMeshElement, - type PolyMeshHandle, - type PolyPointerEvent, -} from "../scene/events"; +import type { PolyMeshHandle, PolyPointerEvent } from "../scene/events"; import { PolyCameraContextKey } from "../camera"; export interface PolyTransformControlsObjectChangeEvent { @@ -81,7 +43,7 @@ export interface PolyTransformControlsObjectChangeEvent { export interface PolyTransformControlsProps { object: PolyTransformControlsObject; - mode?: "translate" | "rotate"; + mode?: GizmoMode; space?: "world" | "local"; size?: number; showX?: boolean; @@ -97,216 +59,7 @@ export interface PolyTransformControlsProps { onDraggingChanged?: (dragging: boolean) => void; } -interface AxisDragOptions { - cssAxis: 0 | 1 | 2; - sign: 1 | -1; - shaftLengthCss: number; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - translationSnap: number | null; - onChange?: () => void; - onObjectChange?: (e: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (d: boolean) => void; -} - -function startAxisDrag(opts: AxisDragOptions): void { - const probeDistance = opts.shaftLengthCss; - const axisVec: Vec3 = [0, 0, 0]; - axisVec[opts.cssAxis] = opts.sign; - const probe = opts.wrapper.ownerDocument!.createElement("div"); - probe.style.position = "absolute"; - probe.style.left = "0"; - probe.style.top = "0"; - probe.style.width = "0"; - probe.style.height = "0"; - probe.style.transform = `translate3d(${axisVec[0] * probeDistance}px, ${axisVec[1] * probeDistance}px, ${axisVec[2] * probeDistance}px)`; - opts.wrapper.appendChild(probe); - const wRect = opts.wrapper.getBoundingClientRect(); - const pRect = probe.getBoundingClientRect(); - opts.wrapper.removeChild(probe); - const screenAxisX = (pRect.left - wRect.left) / probeDistance; - const screenAxisY = (pRect.top - wRect.top) / probeDistance; - const screenAxisLenSq = screenAxisX * screenAxisX + screenAxisY * screenAxisY; - if (screenAxisLenSq < SCREEN_AXIS_DEAD_ZONE_SQ) return; - - const startPos = (opts.target.getPosition() ?? [0, 0, 0]) as Vec3; - opts.onMouseDown?.(); - opts.onDraggingChanged?.(true); - - const handleMove = (ev: PointerEvent): void => { - const dx = ev.clientX - opts.startClientX; - const dy = ev.clientY - opts.startClientY; - let t = solveAxisDragDelta(dx, dy, screenAxisX, screenAxisY); - t = snap(t, opts.translationSnap); - const newPos: Vec3 = [ - startPos[0] + t * axisVec[0], - startPos[1] + t * axisVec[1], - startPos[2] + t * axisVec[2], - ]; - opts.onObjectChange?.({ object: opts.target, position: newPos }); - opts.onChange?.(); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - opts.onMouseUp?.(); - opts.onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - -interface PlaneDragOptions { - axisA: 0 | 1 | 2; - axisB: 0 | 1 | 2; - probeDistanceCss: number; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - translationSnap: number | null; - onChange?: () => void; - onObjectChange?: (e: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (d: boolean) => void; -} - -/** Planar drag: probe both in-plane axes for their screen projections, - * then solve a 2x2 system per move and apply position deltas along both - * axes simultaneously. Mirror of vanilla `startPlaneDrag`. */ -function startPlaneDrag(opts: PlaneDragOptions): void { - const axisAVec: Vec3 = [0, 0, 0]; axisAVec[opts.axisA] = 1; - const axisBVec: Vec3 = [0, 0, 0]; axisBVec[opts.axisB] = 1; - const probeDistance = opts.probeDistanceCss; - function probe(axisVec: Vec3): { x: number; y: number } { - const el = opts.wrapper.ownerDocument!.createElement("div"); - el.style.position = "absolute"; - el.style.left = "0"; - el.style.top = "0"; - el.style.width = "0"; - el.style.height = "0"; - el.style.transform = `translate3d(${axisVec[0] * probeDistance}px, ${axisVec[1] * probeDistance}px, ${axisVec[2] * probeDistance}px)`; - opts.wrapper.appendChild(el); - const wR = opts.wrapper.getBoundingClientRect(); - const pR = el.getBoundingClientRect(); - opts.wrapper.removeChild(el); - return { - x: (pR.left - wR.left) / probeDistance, - y: (pR.top - wR.top) / probeDistance, - }; - } - const pA = probe(axisAVec); - const pB = probe(axisBVec); - const det = screenPlaneDet(pA, pB); - if (Math.abs(det) < SCREEN_AXIS_DEAD_ZONE_SQ) return; - - const startPos = (opts.target.getPosition() ?? [0, 0, 0]) as Vec3; - opts.onMouseDown?.(); - opts.onDraggingChanged?.(true); - - const handleMove = (ev: PointerEvent): void => { - const dx = ev.clientX - opts.startClientX; - const dy = ev.clientY - opts.startClientY; - const solved = solvePlaneDragDeltas(dx, dy, pA, pB, det); - const tA = snap(solved.tA, opts.translationSnap); - const tB = snap(solved.tB, opts.translationSnap); - const next: Vec3 = [ - startPos[0] + tA * axisAVec[0] + tB * axisBVec[0], - startPos[1] + tA * axisAVec[1] + tB * axisBVec[1], - startPos[2] + tA * axisAVec[2] + tB * axisBVec[2], - ]; - opts.onObjectChange?.({ object: opts.target, position: next }); - opts.onChange?.(); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - opts.onMouseUp?.(); - opts.onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - -interface RingDragOptions { - cssAxis: 0 | 1 | 2; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - rotationSnap: number | null; - onChange?: () => void; - onObjectChange?: (e: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (d: boolean) => void; -} - -function startRingDrag(opts: RingDragOptions): void { - const wRect = opts.wrapper.getBoundingClientRect(); - const centerX = wRect.left; - const centerY = wRect.top; - let lastAngle = Math.atan2(opts.startClientY - centerY, opts.startClientX - centerX); - let cumulative = 0; - const startRot = (opts.target.getRotation() ?? [0, 0, 0]) as Vec3; - // See React's RingDrag: snapshot Qstart, right-multiply Qdelta around - // the ring's CSS axis to compose in the mesh's LOCAL frame. Plain - // Euler-add breaks for repeated / non-XYZ-order ring drags. - const qStart = quatFromEulerXYZ(startRot); - opts.onMouseDown?.(); - opts.onDraggingChanged?.(true); - const handleMove = (ev: PointerEvent): void => { - const a = Math.atan2(ev.clientY - centerY, ev.clientX - centerX); - cumulative += unwrapAngleDelta(a, lastAngle); - lastAngle = a; - let degrees = (cumulative * 180) / Math.PI; - degrees = snap(degrees, opts.rotationSnap); - const axisVec: Vec3 = [0, 0, 0]; - axisVec[opts.cssAxis] = 1; - const qDelta = quatFromAxisAngle(axisVec, (degrees * Math.PI) / 180); - // World-frame compose (pre-mult): rings stay at world axes visually, - // so each ring drag rotates around the world axis the ring points to, - // cumulatively on top of the mesh's current orientation. - const next = eulerXYZFromQuat(quatMultiply(qDelta, qStart)); - opts.onObjectChange?.({ object: opts.target, rotation: next }); - opts.onChange?.(); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - opts.onMouseUp?.(); - opts.onDraggingChanged?.(false); - opts.target.rebakeAtlas(); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - -/** `object` prop: either a PolyMeshHandle directly or a Vue ref to one - * (e.g. a template ref via `:object="meshRef"`). */ +/** `object` prop: either a PolyMeshHandle directly or a Vue ref to one. */ export type PolyTransformControlsObject = | PolyMeshHandle | Ref @@ -327,7 +80,7 @@ export const PolyTransformControls = defineComponent({ name: "PolyTransformControls", props: { object: { type: null as unknown as PropType, default: null }, - mode: { type: String as PropType<"translate" | "rotate">, default: "translate" }, + mode: { type: String as PropType, default: "translate" }, space: { type: String as PropType<"world" | "local">, default: "world" }, size: { type: Number, default: 1 }, showX: { type: Boolean, default: true }, @@ -347,421 +100,191 @@ export const PolyTransformControls = defineComponent({ setup(props, { emit }) { const hoveredKey = ref(null); const draggingKey = ref(null); - const arrowRefs = ref(new Map()); - const target = computed(() => resolveObject(props.object)); - // Force one re-render after mount so a ref-based `object` prop - // (whose `.value` lands AFTER first render) gets picked up. + // Re-evaluate once after mount so ref-based `object` props resolve. const tick = ref(0); - onMounted(() => { tick.value++; }); - - // Subscribe to camera state so back-facing arrow geometry re-evaluates - // when the user orbits the camera. cameraTick is read inside arrowEntries - // so the computed re-runs on every camera change. const cameraTick = ref(0); - const cameraCtxForRot = inject(PolyCameraContextKey, undefined); + const cameraCtx = inject(PolyCameraContextKey, undefined); + let unsubscribeCamera: (() => void) | null = null; - onMounted(() => { - const store = cameraCtxForRot?.store; - if (!store) return; - unsubscribeCamera = store.subscribe(() => { cameraTick.value++; }); - }); - onBeforeUnmount(() => { unsubscribeCamera?.(); }); - function currentRot(): { rotX: number; rotY: number } { - void cameraTick.value; - const s = cameraCtxForRot?.store.getState().cameraState; - return { rotX: s?.rotX ?? 65, rotY: s?.rotY ?? 45 }; - } + let detachFallback: (() => void) | null = null; - const baseLength = computed(() => { - void tick.value; // re-evaluate after first render so target.polygons resolves - return gizmoLengthForMesh(target.value?.getPolygons() ?? []); + const entries = computed(() => { + void tick.value; + void cameraTick.value; + const t = target.value; + if (!t) return null; + const s = cameraCtx?.store.getState().cameraState; + return buildTransformGizmoEntries({ + mode: props.mode, + polygons: t.getPolygons(), + size: props.size, + showX: props.showX, + showY: props.showY, + showZ: props.showZ, + rotX: s?.rotX ?? 65, + rotY: s?.rotY ?? 45, + hoveredKey: hoveredKey.value, + draggingKey: draggingKey.value, + }); }); - const shaftLengthCss = computed(() => baseLength.value * props.size); - function alphaFor(key: string): number { - if (draggingKey.value === key) return ALPHA_DRAGGING; - if (hoveredKey.value === key) return ALPHA_HOVER; - return ALPHA_IDLE; + function getDragState(): DeclarativeGizmoDragState { + return { + target: target.value, + mode: props.mode, + shaftLengthCss: entries.value?.shaftLengthCss ?? 0, + enabled: props.enabled, + showX: props.showX, + showY: props.showY, + showZ: props.showZ, + translationSnap: props.translationSnap, + rotationSnap: props.rotationSnap, + onChange: () => emit("change"), + onObjectChange: (e) => emit("objectChange", e), + onMouseDown: () => emit("mouseDown"), + onMouseUp: () => emit("mouseUp"), + onDraggingChanged: (d) => emit("draggingChanged", d), + onDraggingKeyChange: (key) => { + draggingKey.value = key; + }, + }; } - function emitChange(): void { emit("change"); } - function emitObjectChange(e: PolyTransformControlsObjectChangeEvent): void { emit("objectChange", e); } - function emitDragging(d: boolean): void { emit("draggingChanged", d); } - function emitMouseDown(): void { emit("mouseDown"); } - function emitMouseUp(): void { emit("mouseUp"); } - - // cameraEl JS hit-test fallback for clicks that fall through the - // gizmo polygons (border-shape clipping or external pointer-events - // overrides). Same pattern as React/vanilla. - const cameraCtx = inject(PolyCameraContextKey, undefined); - let detach: (() => void) | null = null; onMounted(() => { + tick.value++; + const store = cameraCtx?.store; + if (store) { + unsubscribeCamera = store.subscribe(() => { + cameraTick.value++; + }); + } const cameraEl = cameraCtx?.cameraElRef.value; - if (!cameraEl) return; - const onPointerDown = (event: PointerEvent): void => { - const t = target.value; - if (!t || !props.enabled) return; - const targetEl = event.target as Element | null; - if (targetEl?.closest(".polycss-transform-gizmo")) return; - const showByKey = { x: props.showX, y: props.showY, z: props.showZ }; - if (props.mode === "translate") { - // Plane handles hit-tested first so they win at corner overlaps. - for (const spec of PLANE_SPECS) { - const aL = (["x", "y", "z"] as const)[spec.axisA]; - const bL = (["x", "y", "z"] as const)[spec.axisB]; - if (!showByKey[aL] || !showByKey[bL]) continue; - const planeEl = document.querySelector( - `.polycss-transform-plane--${spec.key}`, - ) as HTMLElement | null; - if (!planeEl) continue; - if (!pointInMeshElement(planeEl, event.clientX, event.clientY)) continue; - event.preventDefault(); - event.stopPropagation(); - const wrapper = planeEl.closest("[data-poly-transform-controls]") as HTMLElement | null; - if (!wrapper) return; - draggingKey.value = spec.key; - startPlaneDrag({ - axisA: spec.axisA, - axisB: spec.axisB, - probeDistanceCss: shaftLengthCss.value, - wrapper, - target: t, - startClientX: event.clientX, - startClientY: event.clientY, - translationSnap: props.translationSnap, - onChange: emitChange, - onObjectChange: emitObjectChange, - onMouseDown: emitMouseDown, - onMouseUp: emitMouseUp, - onDraggingChanged: (d) => { - if (!d) draggingKey.value = null; - emitDragging(d); - }, - }); - return; - } - } - const specs = props.mode === "translate" ? ARROW_SPECS : RING_SPECS; - for (const spec of specs) { - const userAxis = spec.key.replace("-", "")[0] as "x" | "y" | "z"; - if (!showByKey[userAxis]) continue; - const arrowEl = document.querySelector( - `.polycss-transform-${props.mode === "translate" ? "arrow" : "ring"}--${spec.key}`, - ) as HTMLElement | null; - if (!arrowEl) continue; - // Rings use donut-shaped hit-testing (CSS mask doesn't block - // pointer events, so we have to gate clicks here). - const hit = props.mode === "rotate" - ? pointInMeshElement(arrowEl, event.clientX, event.clientY) - : pointInMeshElement(arrowEl, event.clientX, event.clientY); - if (!hit) continue; - event.preventDefault(); - event.stopPropagation(); - const wrapper = arrowEl.closest("[data-poly-transform-controls]") as HTMLElement | null; - if (!wrapper) return; - draggingKey.value = spec.key; - if (props.mode === "translate") { - const arrowSpec = spec as typeof ARROW_SPECS[number]; - startAxisDrag({ - cssAxis: arrowSpec.cssAxis, - sign: arrowSpec.sign, - shaftLengthCss: shaftLengthCss.value, - wrapper, - target: t, - startClientX: event.clientX, - startClientY: event.clientY, - translationSnap: props.translationSnap, - onChange: emitChange, - onObjectChange: emitObjectChange, - onMouseDown: emitMouseDown, - onMouseUp: emitMouseUp, - onDraggingChanged: (d) => { - if (!d) draggingKey.value = null; - emitDragging(d); - }, - }); - } else { - startRingDrag({ - cssAxis: spec.cssAxis, - wrapper, - target: t, - startClientX: event.clientX, - startClientY: event.clientY, - rotationSnap: props.rotationSnap, - onChange: emitChange, - onObjectChange: emitObjectChange, - onMouseDown: emitMouseDown, - onMouseUp: emitMouseUp, - onDraggingChanged: (d) => { - if (!d) draggingKey.value = null; - emitDragging(d); - }, - }); - } - return; - } - }; - cameraEl.addEventListener("pointerdown", onPointerDown); - detach = () => cameraEl.removeEventListener("pointerdown", onPointerDown); + if (cameraEl) { + detachFallback = attachDeclarativeGizmoFallback(cameraEl, getDragState); + } }); + onBeforeUnmount(() => { - detach?.(); + unsubscribeCamera?.(); + detachFallback?.(); }); - // Rebuild geometry caches whenever the visible specs / size / - // hover / drag change. Computeds keep these reactive without - // explicit watchers. - const arrowEntries = computed(() => { - if (props.mode !== "translate") return []; - void tick.value; - const length = shaftLengthCss.value; - const lengthWorld = length / SCENE_TILE_SIZE; - const { rotX, rotY } = currentRot(); - return ARROW_SPECS - .filter((spec) => ({ x: props.showX, y: props.showY, z: props.showZ }[userAxisLetterOf(spec.key)])) - .map((spec) => { - const alpha = alphaFor(spec.key); - const backFacing = isAxisBackFacing(spec.cssAxis, spec.sign, rotX, rotY); - return { - spec, - polygons: arrowPolygons({ - axis: WORLD_AXIS_FOR_CSS[spec.cssAxis], - sign: spec.sign, - shaftLength: lengthWorld, - shaftHalfThickness: lengthWorld * SHAFT_HALF_THICKNESS_RATIO, - headLength: lengthWorld * HEAD_LENGTH_RATIO, - headHalfThickness: lengthWorld * HEAD_HALF_THICKNESS_RATIO, - color: withAlpha(spec.color, alpha), - shaft: !backFacing, - }), - }; - }); - }); - const planeEntries = computed(() => { - if (props.mode !== "translate") return []; - void tick.value; - const length = shaftLengthCss.value; - const lengthWorld = length / SCENE_TILE_SIZE; - const show = { x: props.showX, y: props.showY, z: props.showZ }; - const ax = (["x", "y", "z"] as const); - const { rotX, rotY } = currentRot(); - const mag = lengthWorld * PLANE_OFFSET_RATIO; - return PLANE_SPECS - .filter((spec) => show[ax[spec.axisA]] && show[ax[spec.axisB]]) - .map((spec) => { - const alpha = alphaFor(spec.key); - // Place the quad in the camera-facing octant — see vanilla/React. - const worldPerp = WORLD_AXIS_FOR_CSS[spec.perpAxis]; - const worldA = ((worldPerp + 1) % 3) as 0 | 1 | 2; - const worldB = ((worldPerp + 2) % 3) as 0 | 1 | 2; - const cssAForOffset = WORLD_AXIS_FOR_CSS[worldA]; - const cssBForOffset = WORLD_AXIS_FOR_CSS[worldB]; - const signA = isAxisBackFacing(cssAForOffset, 1, rotX, rotY) ? -1 : 1; - const signB = isAxisBackFacing(cssBForOffset, 1, rotX, rotY) ? -1 : 1; - return { - spec, - polygons: planePolygons({ - axis: worldPerp, - size: lengthWorld * PLANE_HALF_SIZE_RATIO, - offset: [signA * mag, signB * mag], - color: withAlpha(spec.color, alpha), - }), - }; - }); - }); - const ringEntries = computed(() => { - if (props.mode !== "rotate") return []; - void tick.value; - const length = shaftLengthCss.value; - const radiusWorld = (length * RING_RADIUS_RATIO) / SCENE_TILE_SIZE; - const outerWorld = radiusWorld * RING_QUAD_OUTER_RATIO; - return RING_SPECS - .filter((spec) => ({ x: props.showX, y: props.showY, z: props.showZ }[spec.key as "x" | "y" | "z"])) - .map((spec) => { - const alpha = alphaFor(spec.key); - // Single square quad masked to a donut via CSS (see - // .polycss-transform-ring rule in styles.ts). - return { - spec, - polygons: ringQuadPolygons({ - axis: WORLD_AXIS_FOR_CSS[spec.cssAxis], - outerRadius: outerWorld, - color: withAlpha(spec.color, alpha), - }), - }; - }); - }); - // Visible band start/end as fractions of the quad edge. The quad covers - // ±RING_QUAD_OUTER_RATIO · mid-radius; the visible ring is mid ± - // halfThickness. Normalize against the quad outer to get mask positions. - const ringInnerRatio = (1 - RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; - const ringOuterRatio = (1 + RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; + function startFromMeshEvent( + e: PolyPointerEvent, + run: (wrapper: HTMLElement) => void, + ): void { + if (!props.enabled || !target.value) return; + e.stopPropagation(); + const wrapper = e.eventObject.element?.closest( + "[data-poly-transform-controls]", + ) as HTMLElement | null; + if (!wrapper) return; + run(wrapper); + } - function makeArrowPointerDown(spec: typeof ARROW_SPECS[number]) { - return (e: PolyPointerEvent): void => { - if (!props.enabled) return; - const t = target.value; - if (!t) return; - e.stopPropagation(); - const meshEl = e.eventObject.element; - const wrapper = meshEl?.closest("[data-poly-transform-controls]") as HTMLElement | null; - if (!wrapper) return; - draggingKey.value = spec.key; - startAxisDrag({ - cssAxis: spec.cssAxis, - sign: spec.sign, - shaftLengthCss: shaftLengthCss.value, - wrapper, - target: t, - startClientX: e.nativeEvent.clientX, - startClientY: e.nativeEvent.clientY, - translationSnap: props.translationSnap, - onChange: emitChange, - onObjectChange: emitObjectChange, - onMouseDown: emitMouseDown, - onMouseUp: emitMouseUp, - onDraggingChanged: (d) => { - if (!d) draggingKey.value = null; - emitDragging(d); - }, + function makeArrowPointerDown(spec: GizmoArrowSpec) { + return (e: PolyPointerEvent) => + startFromMeshEvent(e, (wrapper) => { + startDeclarativeArrowDrag( + spec, + wrapper, + e.nativeEvent.clientX, + e.nativeEvent.clientY, + getDragState(), + ); }); - }; } - function makePlanePointerDown(spec: typeof PLANE_SPECS[number]) { - return (e: PolyPointerEvent): void => { - if (!props.enabled) return; - const t = target.value; - if (!t) return; - e.stopPropagation(); - const meshEl = e.eventObject.element; - const wrapper = meshEl?.closest("[data-poly-transform-controls]") as HTMLElement | null; - if (!wrapper) return; - draggingKey.value = spec.key; - startPlaneDrag({ - axisA: spec.axisA, - axisB: spec.axisB, - probeDistanceCss: shaftLengthCss.value, - wrapper, - target: t, - startClientX: e.nativeEvent.clientX, - startClientY: e.nativeEvent.clientY, - translationSnap: props.translationSnap, - onChange: emitChange, - onObjectChange: emitObjectChange, - onMouseDown: emitMouseDown, - onMouseUp: emitMouseUp, - onDraggingChanged: (d) => { - if (!d) draggingKey.value = null; - emitDragging(d); - }, + function makePlanePointerDown(spec: GizmoPlaneSpec) { + return (e: PolyPointerEvent) => + startFromMeshEvent(e, (wrapper) => { + startDeclarativePlaneDrag( + spec, + wrapper, + e.nativeEvent.clientX, + e.nativeEvent.clientY, + getDragState(), + ); }); - }; } - function makeRingPointerDown(spec: typeof RING_SPECS[number]) { - return (e: PolyPointerEvent): void => { - if (!props.enabled) return; - const t = target.value; - if (!t) return; - // No donut hit-test — the whole ring quad bbox is the click target - // so the rings are easy to land on. The donut mask is decoration. - const meshEl = e.eventObject.element; - e.stopPropagation(); - const wrapper = meshEl?.closest("[data-poly-transform-controls]") as HTMLElement | null; - if (!wrapper) return; - draggingKey.value = spec.key; - startRingDrag({ - cssAxis: spec.cssAxis, - wrapper, - target: t, - startClientX: e.nativeEvent.clientX, - startClientY: e.nativeEvent.clientY, - rotationSnap: props.rotationSnap, - onChange: emitChange, - onObjectChange: emitObjectChange, - onMouseDown: emitMouseDown, - onMouseUp: emitMouseUp, - onDraggingChanged: (d) => { - if (!d) draggingKey.value = null; - emitDragging(d); - }, + function makeRingPointerDown(spec: GizmoRingSpec) { + return (e: PolyPointerEvent) => + startFromMeshEvent(e, (wrapper) => { + startDeclarativeRingDrag( + spec, + wrapper, + e.nativeEvent.clientX, + e.nativeEvent.clientY, + getDragState(), + ); }); - }; } function makeHoverHandlers(key: string) { return { - onPointerOver: () => { hoveredKey.value = key; }, - onPointerOut: () => { if (hoveredKey.value === key) hoveredKey.value = null; }, + onPointerOver: () => { + hoveredKey.value = key; + }, + onPointerOut: () => { + if (hoveredKey.value === key) hoveredKey.value = null; + }, }; } - // Suppress unused variable warning — arrowRefs is used by the component - void arrowRefs; + const ringStyle = { + ["--ring-inner-ratio" as string]: RING_MASK_INNER_RATIO, + ["--ring-outer-ratio" as string]: RING_MASK_OUTER_RATIO, + }; return () => { const t = target.value; - if (!t) return null; - const position = t.getPosition() ?? ([0, 0, 0] as Vec3); - // Post-parity: `position` is world units in world-axis order. The gizmo - // wrapper lives in scene-CSS pixel space, so apply the world→CSS axis - // swap + ×SCENE_TILE_SIZE before adding the (already CSS-pixel) bbox - // center. bboxCenter accounts for meshes whose vertices aren't centered - // at 0; when PolyMesh autoCenter is set, bboxCenter is (0,0,0) and this - // is a pure axis-swap. - const bboxCenter = gizmoCenterForMesh(t.getPolygons()); - const wx = position[1] * SCENE_TILE_SIZE + bboxCenter[0]; - const wy = position[0] * SCENE_TILE_SIZE + bboxCenter[1]; - const wz = position[2] * SCENE_TILE_SIZE + bboxCenter[2]; + const current = entries.value; + if (!t || !current) return null; + + const wrapperPos = computeGizmoWrapperPositionCss(t.getPosition(), t.getPolygons()); const wrapperStyle: Record = { - transform: `translate3d(${wx}px, ${wy}px, ${wz}px)`, + transform: `translate3d(${wrapperPos[0]}px, ${wrapperPos[1]}px, ${wrapperPos[2]}px)`, position: "absolute", transformStyle: "preserve-3d", zIndex: 1000, }; - const children = props.mode === "translate" - ? [ - ...arrowEntries.value.map(({ spec, polygons }) => - h(PolyMesh, { - key: `arrow-${spec.key}`, - polygons, - class: `polycss-transform-gizmo polycss-transform-arrow polycss-transform-arrow--${spec.key}`, - textureLighting: "baked", - onPointerDown: makeArrowPointerDown(spec), - ...makeHoverHandlers(spec.key), - }), - ), - ...planeEntries.value.map(({ spec, polygons }) => - h(PolyMesh, { - key: `plane-${spec.key}`, - polygons, - class: `polycss-transform-gizmo polycss-transform-plane polycss-transform-plane--${spec.key}`, - textureLighting: "baked", - onPointerDown: makePlanePointerDown(spec), - ...makeHoverHandlers(spec.key), - }), - ), - ] - : ringEntries.value.map(({ spec, polygons }) => - h(PolyMesh, { - key: spec.key, - polygons, - class: `polycss-transform-gizmo polycss-transform-ring polycss-transform-ring--${spec.key}`, - // CSS var read by the .polycss-transform-ring radial-gradient - // mask to size the donut cutout. - style: { - ["--ring-inner-ratio" as string]: ringInnerRatio, - ["--ring-outer-ratio" as string]: ringOuterRatio, - }, - textureLighting: "baked", - onPointerDown: makeRingPointerDown(spec), - ...makeHoverHandlers(spec.key), - }), - ); + const children = [ + ...current.arrows.map(({ spec, polygons }) => + h(PolyMesh, { + key: `arrow-${spec.key}`, + polygons, + class: `polycss-transform-gizmo polycss-transform-arrow polycss-transform-arrow--${spec.key}`, + textureLighting: "baked", + onPointerDown: makeArrowPointerDown(spec), + ...makeHoverHandlers(spec.key), + }), + ), + ...current.planes.map(({ spec, polygons }) => + h(PolyMesh, { + key: `plane-${spec.key}`, + polygons, + class: `polycss-transform-gizmo polycss-transform-plane polycss-transform-plane--${spec.key}`, + textureLighting: "baked", + onPointerDown: makePlanePointerDown(spec), + ...makeHoverHandlers(spec.key), + }), + ), + ...current.rings.map(({ spec, polygons }) => + h(PolyMesh, { + key: spec.key, + polygons, + class: `polycss-transform-gizmo polycss-transform-ring polycss-transform-ring--${spec.key}`, + style: ringStyle, + textureLighting: "baked", + onPointerDown: makeRingPointerDown(spec), + ...makeHoverHandlers(spec.key), + }), + ), + ]; return h( "div", diff --git a/packages/vue/src/scene/PolyMesh.ts b/packages/vue/src/scene/PolyMesh.ts index 37732c3e4..22dde3b47 100644 --- a/packages/vue/src/scene/PolyMesh.ts +++ b/packages/vue/src/scene/PolyMesh.ts @@ -26,7 +26,9 @@ import type { } from "@layoutit/polycss-core"; import { buildPolyMeshTransform } from "@layoutit/polycss-core"; import { - renderPolygonsWithTextureAtlas, + clearOwnedDomNodes, + renderStandaloneMeshIntoWrapper, + restoreVoxelMeshClass, type PolyMeshHandle as RuntimeMeshHandle, type TextureQuality, } from "@layoutit/polycss/runtime"; @@ -198,14 +200,11 @@ export const PolyMesh = defineComponent({ ); function clearStandalone(): void { - const el = wrapperRef.value; - for (const node of standaloneOwned) { - if (node.parentNode === el) el?.removeChild(node); - } - standaloneOwned.clear(); if (standaloneDispose) { standaloneDispose(); standaloneDispose = null; + } else { + clearOwnedDomNodes(standaloneOwned); } } @@ -279,26 +278,17 @@ export const PolyMesh = defineComponent({ // Standalone fallback when mounted outside . teardownRuntimeMesh(); clearStandalone(); - const effectiveLighting = props.textureLighting ?? "baked"; - const result = renderPolygonsWithTextureAtlas(polygons.value, { + const mounted = renderStandaloneMeshIntoWrapper(el, standaloneOwned, polygons.value, { doc: el.ownerDocument ?? document, - textureLighting: effectiveLighting, + textureLighting: props.textureLighting ?? "baked", textureQuality: props.textureQuality, textureLeafSizing: props.textureLeafSizing, textureImageRendering: props.textureImageRendering, textureBackend: props.textureBackend, textureProjection: props.textureProjection, }); - standaloneDispose = result.dispose; - standaloneReady = result.pagesReady ?? RESOLVED_PROMISE; - const firstStatic = - Array.from(el.childNodes).find((n) => !standaloneOwned.has(n)) ?? null; - const frag = (el.ownerDocument ?? document).createDocumentFragment(); - for (const item of result.rendered) { - standaloneOwned.add(item.element); - frag.appendChild(item.element); - } - el.insertBefore(frag, firstStatic); + standaloneDispose = mounted.dispose; + standaloneReady = mounted.ready; } onMounted(() => { @@ -337,16 +327,7 @@ export const PolyMesh = defineComponent({ // on an adopted direct-voxel wrapper (voxelRenderer attaches it imperatively). watch( [() => props.class, () => attrs.class], - () => { - const el = wrapperRef.value; - if (!el) return; - for (let i = 0; i < el.children.length; i += 1) { - if (el.children[i]?.classList.contains("polycss-voxel-face")) { - el.classList.add("polycss-voxel-mesh"); - break; - } - } - }, + () => restoreVoxelMeshClass(wrapperRef.value), { flush: "post" }, ); diff --git a/packages/vue/src/scene/events.ts b/packages/vue/src/scene/events.ts index c8dd76558..e6db808df 100644 --- a/packages/vue/src/scene/events.ts +++ b/packages/vue/src/scene/events.ts @@ -1,22 +1,11 @@ /** - * Pointer event API for `` (Vue). Mirrors @react-three/fiber's - * mesh event surface (handler names + payload shape) so devs migrating - * from three.js use the same mental model. PolyCSS is DOM-native so - * we get native pointer events for free — no raycaster, no canvas - * event synthesis. - * - * Diverges from r3f in two intentional ways: - * 1. Bubbling matches DOM (pointer hits the front element only). - * 2. `face`, `uv`, `uv1`, `instanceId` are omitted — three.js - * BufferGeometry / InstancedMesh concepts with no polycss - * analogue. + * Pointer event API for `` (Vue). Delegates DOM element registry and + * bounding-rect hit-testing to `@layoutit/polycss/runtime`. */ import type { Polygon, Vec3 } from "@layoutit/polycss-core"; +import { createMeshElementRegistry, pointInMeshElement } from "@layoutit/polycss/runtime"; -/** Imperative handle exposed by `` via Vue's defineExpose. - * Read-only view of the mesh's element + current transform + - * polygons. Mutation flows through controlled props (parent owns - * transform state). */ +/** Imperative handle exposed by `` via Vue's `defineExpose`. */ export interface PolyMeshHandle { readonly element: HTMLDivElement | null; readonly id?: string; @@ -24,41 +13,9 @@ export interface PolyMeshHandle { getRotation(): Vec3 | undefined; getScale(): number | Vec3 | undefined; getPolygons(): Polygon[]; - /** - * Replace the mesh polygons imperatively. Animated solid-triangle meshes use - * a stable DOM update path that mutates mounted leaves directly; unsupported - * topology falls back to the normal framework render path. - */ setPolygons(polygons: Polygon[]): void; - /** - * Update a single polygon in place. `target` is either a polygon - * reference (as returned by `getPolygons()`) or its index. `partial` - * fields are merged onto the polygon; the mesh is then re-rendered. - * Skips the merge pass, so this is cheaper than replacing the - * `polygons` prop for targeted edits like color picker updates from - * an inspector UI. Silently no-ops if `target` isn't found. - */ updatePolygon(target: Polygon | number, partial: Partial): void; - /** - * Re-rasterize the baked texture atlas using the mesh's current rotation. - * - * Call this after a rotation gesture completes (e.g. on rotate-ring pointer - * release) to correct stale lighting. Baked atlas tiles encode - * `baseColor × Lambert(worldNormal, worldLight)` at bake time. When the - * mesh wrapper rotates via CSS, the polygon normals change in world space - * but the pre-multiplied colors don't — faces stay lit/unlit incorrectly. - * - * `rebakeAtlas()` advances the internal `bakedRotation` snapshot to the - * current `rotation` prop and re-runs the atlas pipeline, this time - * inverse-rotating the world light into the mesh-local frame so that - * `dot(localNormal, localLight) === dot(worldNormal, worldLight)` holds. - * - * In `textureLighting === "dynamic"` mode this is a no-op: dynamic - * shading is computed per-frame from live surface-normal CSS vars, so it - * is always correct and never needs rebaking. - */ rebakeAtlas(): void; - /** Resolves when this mesh's current texture generation has usable backgrounds. */ whenTexturesReady(): Promise; } @@ -79,8 +36,7 @@ export type PolyEventHandler = ( event: PolyPointerEvent, ) => void; -/** Pointer / mouse / wheel handlers accepted by ``. Same - * names as r3f. Provide any handler to opt in to events. */ +/** Pointer / mouse / wheel handlers accepted by ``. */ export interface InteractionProps { onClick?: PolyEventHandler; onContextMenu?: PolyEventHandler; @@ -96,74 +52,10 @@ export interface InteractionProps { onPointerCancel?: PolyEventHandler; } -// ── Mesh element registry ──────────────────────────────────────────────── -const MESH_REGISTRY = new WeakMap(); +const meshRegistry = createMeshElementRegistry(); -export function registerMeshElement( - el: HTMLElement, - handle: PolyMeshHandle, -): void { - MESH_REGISTRY.set(el, handle); -} - -export function unregisterMeshElement(el: HTMLElement): void { - MESH_REGISTRY.delete(el); -} - -export function findPolyMeshHandle(el: Element | null): PolyMeshHandle | null { - let cur: Element | null = el; - while (cur) { - if (cur instanceof HTMLElement) { - const h = MESH_REGISTRY.get(cur); - if (h) return h; - } - cur = cur.parentElement; - } - return null; -} - -// ── JS bounding-rect hit-testing ──────────────────────────────────────── -// polycss polygons render via the CSS `border-shape` property, which -// (in current Chromium) clips both paint AND native hit-testing to the -// visible polygon shape — so a click on a transparent corner of an -// `` rectangle frequently falls through to whichever element is -// behind it. The JS bbox hit-test bypasses the clip. - -export function pointInMeshElement( - meshEl: HTMLElement, - clientX: number, - clientY: number, -): boolean { - const polys = Array.from(meshEl.querySelectorAll("i,b,s,u")) as HTMLElement[]; - for (const p of polys) { - const r = p.getBoundingClientRect(); - if (r.width <= 0 || r.height <= 0) continue; - if ( - clientX >= r.left && - clientX <= r.right && - clientY >= r.top && - clientY <= r.bottom - ) { - return true; - } - } - return false; -} - -export function findMeshUnderPoint( - clientX: number, - clientY: number, - filter?: (meshEl: HTMLElement) => boolean, -): PolyMeshHandle | null { - if (typeof document === "undefined") return null; - const meshEls = Array.from( - document.querySelectorAll(".polycss-mesh"), - ) as HTMLElement[]; - for (const meshEl of meshEls) { - if (filter && !filter(meshEl)) continue; - const handle = findPolyMeshHandle(meshEl); - if (!handle) continue; - if (pointInMeshElement(meshEl, clientX, clientY)) return handle; - } - return null; -} +export const registerMeshElement = meshRegistry.registerMeshElement; +export const unregisterMeshElement = meshRegistry.unregisterMeshElement; +export const findPolyMeshHandle = meshRegistry.findPolyMeshHandle; +export const findMeshUnderPoint = meshRegistry.findMeshUnderPoint; +export { pointInMeshElement }; diff --git a/packages/vue/src/scene/mesh/useMeshEvents.ts b/packages/vue/src/scene/mesh/useMeshEvents.ts index 5eacdcb2a..69da723e3 100644 --- a/packages/vue/src/scene/mesh/useMeshEvents.ts +++ b/packages/vue/src/scene/mesh/useMeshEvents.ts @@ -1,14 +1,13 @@ /** - * useMeshEvents — pointer-event synthesis (polycss-shaped payloads from - * native DOM events) and the union of wrapper DOM handlers built per - * render. Extracted verbatim from PolyMesh.ts. + * useMeshEvents — pointer-event synthesis over `@layoutit/polycss/runtime`'s + * `buildPolyPointerEvent` and wrapper DOM handler wiring for Vue ``. */ +import { buildPolyPointerEvent } from "@layoutit/polycss/runtime"; import type { PolyCameraContextValue } from "../../camera/context"; import { findPolyMeshHandle, type PolyEventHandler, type PolyMeshHandle, - type PolyPointerEvent, } from "../events"; export interface MeshEventsProps { @@ -37,48 +36,6 @@ export function useMeshEvents({ }) { let pointerDownAt: { x: number; y: number } | null = null; - function makeEvent( - nativeEvent: E, - clientX: number, - clientY: number, - ): PolyPointerEvent { - const intersections: Array<{ object: PolyMeshHandle }> = []; - if (typeof document !== "undefined" && typeof document.elementsFromPoint === "function") { - const stacked = document.elementsFromPoint(clientX, clientY); - const seen = new Set(); - for (const el of stacked) { - const h = findPolyMeshHandle(el); - if (h && !seen.has(h)) { - seen.add(h); - intersections.push({ object: h }); - } - } - } - let nx = 0; - let ny = 0; - const camEl = cameraCtx?.cameraElRef.value; - if (camEl) { - const r = camEl.getBoundingClientRect(); - if (r.width > 0 && r.height > 0) { - nx = ((clientX - r.left) / r.width) * 2 - 1; - ny = -(((clientY - r.top) / r.height) * 2 - 1); - } - } - let delta = 0; - if (pointerDownAt) { - delta = Math.hypot(clientX - pointerDownAt.x, clientY - pointerDownAt.y); - } - return { - object: intersections[0]?.object ?? handle, - eventObject: handle, - intersections, - pointer: { x: nx, y: ny }, - delta, - nativeEvent, - stopPropagation: () => nativeEvent.stopPropagation(), - }; - } - function dispatch( handler: PolyEventHandler | undefined, nativeEvent: E, @@ -86,14 +43,19 @@ export function useMeshEvents({ clientY: number, ): void { if (!handler) return; - handler(makeEvent(nativeEvent, clientX, clientY)); + handler( + buildPolyPointerEvent({ + handle, + nativeEvent, + clientX, + clientY, + cameraEl: cameraCtx?.cameraElRef.value, + pointerDownAt, + resolveHandle: findPolyMeshHandle, + }), + ); } - // Build the union of DOM handlers we need to attach. Each - // registered prop becomes a `onXxx` attr on the wrapper div; - // omitted props add zero overhead. pointerOver/pointerOut are - // mapped to enter/leave so they fire once per mesh boundary - // crossing (not per internal polygon transition). const buildHandlers = (): Record void> => { const handlers: Record void> = {}; if (props.onClick) { @@ -120,8 +82,6 @@ export function useMeshEvents({ dispatch(props.onWheel, m, m.clientX, m.clientY); }; } - // pointerdown is always wired (even without user handler) so we - // can track delta for click-vs-drag discrimination. handlers.onPointerdown = (e) => { const p = e as PointerEvent; pointerDownAt = { x: p.clientX, y: p.clientY }; diff --git a/packages/vue/src/select/PolySelect.ts b/packages/vue/src/select/PolySelect.ts index 6715d8616..68182680e 100644 --- a/packages/vue/src/select/PolySelect.ts +++ b/packages/vue/src/select/PolySelect.ts @@ -1,18 +1,6 @@ /** - * `` — selection wrapper that auto-tracks descendant - * `` clicks and exposes the current selection via the - * `usePolySelect()` composable. Mirrors the React API and the vanilla - * `createSelect` so users get the same UX across all three packages. - * - * Usage: - * - * - * - * - * - * // anywhere inside the tree: - * const selected = usePolySelect(); // ComputedRef - * const api = usePolySelectionApi(); // imperative add/remove/toggle + * `` (Vue) — thin Vue wrapper over `@layoutit/polycss/runtime`'s + * shared `createSelectionController`. */ import { defineComponent, @@ -21,14 +9,19 @@ import { onBeforeUnmount, onMounted, provide, - reactive, ref, + shallowRef, computed, type ComputedRef, type InjectionKey, type PropType, } from "vue"; -import { findPolyMeshHandle, findMeshUnderPoint as findMeshUnderPointShared, type PolyMeshHandle } from "../scene/events"; +import { createSelectionController } from "@layoutit/polycss/runtime"; +import { + findPolyMeshHandle, + findMeshUnderPoint as findMeshUnderPointShared, + type PolyMeshHandle, +} from "../scene/events"; import { PolyCameraContextKey } from "../camera"; export interface PolySelectProps { @@ -69,78 +62,48 @@ export const PolySelect = defineComponent({ pointerMissed: (_event: MouseEvent) => true, }, setup(props, { emit, slots }) { - const state = reactive<{ selected: PolyMeshHandle[] }>({ selected: [] }); - const selected = computed(() => state.selected); + const selectedRef = shallowRef([]); + const selected = computed(() => selectedRef.value); - function apply(next: PolyMeshHandle[]): void { - const filtered = props.filter ? props.filter(next) : next; - state.selected = filtered; - emit("change", filtered); - } + const controller = createSelectionController({ + getMultiple: () => props.multiple, + getClearOnMiss: () => props.clearOnMiss, + getFilter: () => props.filter, + shouldIgnoreTarget: (target) => Boolean(target?.closest("[data-poly-transform-controls]")), + resolveTarget: (target, clientX, clientY) => + findPolyMeshHandle(target) ?? + findMeshUnderPointShared( + clientX, + clientY, + (meshEl) => !meshEl.closest("[data-poly-transform-controls]"), + ), + onChange: (next) => { + selectedRef.value = next; + emit("change", next); + }, + onPointerMissed: (event) => emit("pointerMissed", event), + }); const api: PolySelectionApi = { - get selected() { return state.selected; }, - set: (next) => apply(next), - add: (h) => { - if (props.multiple) { - if (!state.selected.includes(h)) apply([...state.selected, h]); - } else { - apply([h]); - } - }, - remove: (h) => { - if (!state.selected.includes(h)) return; - apply(state.selected.filter((x) => x !== h)); + get selected() { + return selectedRef.value; }, - toggle: (h) => { - if (state.selected.includes(h)) { - apply(state.selected.filter((x) => x !== h)); - } else if (props.multiple) { - apply([...state.selected, h]); - } else { - apply([h]); - } - }, - clear: () => apply([]), - has: (h) => state.selected.includes(h), + set: controller.set, + add: controller.add, + remove: controller.remove, + toggle: controller.toggle, + clear: controller.clear, + has: controller.has, }; provide(PolySelectionContextKey, { selected, api }); const cameraCtx = inject(PolyCameraContextKey, undefined); - const findUnderPoint = (clientX: number, clientY: number): PolyMeshHandle | null => - findMeshUnderPointShared( - clientX, - clientY, - (meshEl) => !meshEl.closest("[data-poly-transform-controls]"), - ); - let detach: (() => void) | null = null; onMounted(() => { const cameraEl = cameraCtx?.cameraElRef.value; if (!cameraEl) return; - const onClick = (event: MouseEvent): void => { - const target = event.target as Element | null; - if (target?.closest("[data-poly-transform-controls]")) return; - const handle = - findPolyMeshHandle(event.target as Element) ?? - findUnderPoint(event.clientX, event.clientY); - if (!handle) { - emit("pointerMissed", event); - if (props.clearOnMiss) apply([]); - return; - } - const additive = props.multiple && (event.shiftKey || event.metaKey || event.ctrlKey); - if (additive) { - api.toggle(handle); - } else if (state.selected.length === 1 && state.selected[0] === handle) { - apply([]); - } else { - apply([handle]); - } - }; - cameraEl.addEventListener("click", onClick); - detach = () => cameraEl.removeEventListener("click", onClick); + detach = controller.attach(cameraEl); }); onBeforeUnmount(() => { detach?.(); @@ -158,15 +121,14 @@ export const PolySelect = defineComponent({ }, }); -/** Read the current selection from the nearest enclosing ``. - * Returns an empty array when called outside one. */ +/** Read the current selection from the nearest enclosing ``. */ export function usePolySelect(): ComputedRef { const ctx = inject(PolySelectionContextKey, undefined); if (!ctx) return ref([]) as unknown as ComputedRef; return ctx.selected; } -/** Read the imperative selection API. Throws when called outside a ``. */ +/** Read the imperative selection API. Throws when used outside ``. */ export function usePolySelectionApi(): PolySelectionApi { const ctx = inject(PolySelectionContextKey, undefined); if (!ctx) { diff --git a/packages/vue/src/select/Select.test.ts b/packages/vue/src/select/Select.test.ts index ba8e0fe84..06630d0bb 100644 --- a/packages/vue/src/select/Select.test.ts +++ b/packages/vue/src/select/Select.test.ts @@ -89,7 +89,7 @@ describe(" + usePolySelect (Vue)", () => { expect(onChange.mock.calls[1][0][0].id).toBe("b"); }); - it("re-clicking the only-selected mesh replaces selection with itself (single mode click path)", async () => { + it("clicking the currently-selected mesh toggles it off (single mode)", async () => { const onChange = vi.fn(); const { container } = mountSelect( { onChange }, @@ -104,8 +104,7 @@ describe(" + usePolySelect (Vue)", () => { clickMesh(container, "a"); await nextTick(); expect(onChange).toHaveBeenCalledTimes(2); - expect(onChange.mock.calls[1][0]).toHaveLength(1); - expect(onChange.mock.calls[1][0][0].id).toBe("a"); + expect(onChange.mock.calls[1][0]).toEqual([]); }); it("multiple=true + shift-click adds to selection", async () => { diff --git a/packages/vue/src/shapes/Poly.ts b/packages/vue/src/shapes/Poly.ts index c36d71748..ed8706348 100644 --- a/packages/vue/src/shapes/Poly.ts +++ b/packages/vue/src/shapes/Poly.ts @@ -28,122 +28,20 @@ import type { } from "@layoutit/polycss-core"; import { worldDirectionalLightToCss } from "@layoutit/polycss-core"; import { + buildDirectMaterialLeafDescriptor, + buildFallbackLeafDescriptor, + buildPolyWrapperTransform, computeTextureAtlasPlanPublic, + isAxisAlignedRectUVs, + readElementDataAttrs, + readElementStyleRecord, renderPolygonsWithTextureAtlas, + syncLeafBorderShapeStyle, type RenderTextureAtlasResult, type TextureAtlasPlan, type TextureQuality, } from "@layoutit/polycss/runtime"; -const DIRECT_TEXTURE_CSS_DECIMALS = 4; - -function formatCssLength(value: number, decimals = DIRECT_TEXTURE_CSS_DECIMALS): string { - const next = value.toFixed(decimals).replace(/\.?0+$/, ""); - return Number(next) === 0 || Object.is(Number(next), -0) ? "0" : `${next}px`; -} - -function isAxisAlignedRectUVs( - uvs: Vec2[], -): { u0: number; u1: number; v0: number; v1: number } | null { - if (uvs.length !== 4) return null; - const us = [...new Set(uvs.map((uv) => uv[0]))].sort((a, b) => a - b); - const vs = [...new Set(uvs.map((uv) => uv[1]))].sort((a, b) => a - b); - if (us.length !== 2 || vs.length !== 2) return null; - const corners = new Set([ - `${us[0]},${vs[0]}`, - `${us[0]},${vs[1]}`, - `${us[1]},${vs[0]}`, - `${us[1]},${vs[1]}`, - ]); - for (const uv of uvs) { - if (!corners.has(`${uv[0]},${uv[1]}`)) return null; - } - return { u0: us[0]!, u1: us[1]!, v0: vs[0]!, v1: vs[1]! }; -} - -function readElementStyleRecord(el: HTMLElement): Record { - const out: Record = {}; - const style = el.style; - for (let i = 0; i < style.length; i += 1) { - const prop = style[i]!; - const val = style.getPropertyValue(prop); - if (val) out[prop] = val; - } - return out; -} - -function readElementDataAttrs(el: HTMLElement): Record { - const out: Record = {}; - for (const attr of Array.from(el.attributes)) { - if (attr.name.startsWith("data-")) { - out[attr.name] = attr.value; - } - } - return out; -} - -function renderMaterialDirectPoly({ - plan, - material, - uvRect, - className, - style: styleProp, - domAttrs, - pointerEvents = "auto", - imageRendering, -}: { - plan: TextureAtlasPlan; - material: PolyMaterial; - uvRect: { u0: number; u1: number; v0: number; v1: number }; - className?: string; - style?: CSSProperties; - domAttrs?: Record; - pointerEvents?: "auto" | "none"; - imageRendering?: PolyTextureImageRendering; -}) { - const { u0, u1, v0, v1 } = uvRect; - const du = u1 - u0; - const dv = v1 - v0; - const sourceW = 1 / du; - const sourceH = 1 / dv; - const vMax = Math.max(v0, v1); - const offsetX = u0 / du; - const offsetY = (1 - vMax) / dv; - - const style: CSSProperties = { - transform: `matrix3d(${plan.canonicalMatrix})`, - backgroundImage: `url(${material.texture})`, - backgroundSize: `${formatCssLength(sourceW)} ${formatCssLength(sourceH)}`, - backgroundPosition: `${formatCssLength(-offsetX)} ${formatCssLength(-offsetY)}`, - backgroundRepeat: "no-repeat", - imageRendering: imageRendering === "pixelated" ? "pixelated" : undefined, - pointerEvents: pointerEvents === "none" ? "none" : undefined, - ...styleProp, - }; - - const dataAttrs = plan.polygon.data - ? Object.fromEntries( - Object.entries(plan.polygon.data).map(([k, v]) => [`data-${k}`, String(v)]), - ) - : {}; - const elementClassName = className?.trim() || undefined; - - return h("i", { - class: elementClassName, - style, - "data-poly-index": String(plan.index), - "data-polycss-leaf": "polygon", - "data-polycss-texture-backend": "image", - "data-polycss-texture-ready": "true", - "data-polycss-texture-image-rendering": imageRendering ?? "auto", - "data-polycss-texture-projection": "affine", - "data-polycss-texture-lighting": "source", - "data-polycss-double-sided": plan.polygon.doubleSided ? "true" : undefined, - ...dataAttrs, - ...domAttrs, - }); -} - export interface PolyContext { tileSize?: number; layerElevation?: number; @@ -283,16 +181,15 @@ export const Poly = defineComponent({ ); function syncBorderShape(): void { - const el = leafDomRef.value; const leafEl = renderedResult.value?.rendered[0]?.element; - if (!el || !leafEl) return; - const rawBorderShape = leafEl.style.getPropertyValue("border-shape"); - if (!rawBorderShape) return; - const rawCssText = leafEl.getAttribute("style") || ""; - el.setAttribute("style", rawCssText); - if (props.pointerEvents === "none") el.style.pointerEvents = "none"; - const userStyle = attrs.style as CSSProperties | undefined; - if (userStyle && typeof userStyle === "object") Object.assign(el.style, userStyle); + if (!leafEl) return; + syncLeafBorderShapeStyle( + leafDomRef.value, + leafEl.style.getPropertyValue("border-shape"), + leafEl.getAttribute("style") || "", + props.pointerEvents, + attrs.style as Record | undefined, + ); } onMounted(syncBorderShape); @@ -303,7 +200,6 @@ export const Poly = defineComponent({ }); return () => { - // Touch reactive tick so async atlas page URLs re-render. void atlasTick.value; const userClass = typeof attrs.class === "string" ? attrs.class : undefined; @@ -319,42 +215,28 @@ export const Poly = defineComponent({ } } - const transformParts: string[] = []; - if (props.position) { - transformParts.push( - `translate3d(${props.position[0]}px, ${props.position[1]}px, ${props.position[2]}px)`, - ); - } - if (props.scale !== undefined) { - if (typeof props.scale === "number") { - if (props.scale !== 1) { - transformParts.push(`scale3d(${props.scale}, ${props.scale}, ${props.scale})`); - } - } else { - transformParts.push( - `scale3d(${props.scale[0]}, ${props.scale[1]}, ${props.scale[2]})`, - ); - } - } - if (props.rotation) { - if (props.rotation[0]) transformParts.push(`rotateX(${props.rotation[0]}deg)`); - if (props.rotation[1]) transformParts.push(`rotateY(${props.rotation[1]}deg)`); - if (props.rotation[2]) transformParts.push(`rotateZ(${props.rotation[2]}deg)`); - } - const wrapperTransform = transformParts.length > 0 ? transformParts.join(" ") : undefined; + const wrapperTransform = buildPolyWrapperTransform({ + position: props.position, + scale: props.scale, + rotation: props.rotation, + }); let front = null; if (materialUvRect.value && props.material && materialPlan.value) { - front = renderMaterialDirectPoly({ + const desc = buildDirectMaterialLeafDescriptor({ plan: materialPlan.value, material: props.material, uvRect: materialUvRect.value, className: userClass, - style: userStyle, - domAttrs, pointerEvents: props.pointerEvents, imageRendering: atlasTextureImageRendering.value, }); + front = h("i", { + class: desc.className, + style: { ...(desc.style as CSSProperties), ...userStyle }, + ...desc.dataAttrs, + ...domAttrs, + }); } else if (renderedResult.value?.rendered[0]) { const leafEl = renderedResult.value.rendered[0].element; const tag = leafEl.tagName.toLowerCase(); @@ -362,9 +244,8 @@ export const Poly = defineComponent({ const combinedClass = [leafClass, userClass?.trim()].filter(Boolean).join(" ") || undefined; const leafStyle = readElementStyleRecord(leafEl); if (props.pointerEvents === "none") leafStyle["pointer-events"] = "none"; - const mergedStyle = userStyle && typeof userStyle === "object" - ? { ...leafStyle, ...userStyle } - : leafStyle; + const mergedStyle = + userStyle && typeof userStyle === "object" ? { ...leafStyle, ...userStyle } : leafStyle; const leafDataAttrs = readElementDataAttrs(leafEl); front = h(tag, { ref: leafDomRef, @@ -374,7 +255,6 @@ export const Poly = defineComponent({ ...domAttrs, }); } else if (!materialUvRect.value) { - // Pure-JS fallback for Node SSR (when `document` is unavailable). const tileSize = props.context?.tileSize ?? 50; const fallbackPlan = computeTextureAtlasPlanPublic(polygon.value, 0, { tileSize, @@ -386,22 +266,22 @@ export const Poly = defineComponent({ }); if (fallbackPlan) { const isTextured = Boolean(effectiveTexture.value || props.textureImageSource); - const tag = !isTextured && polygon.value.vertices.length === 4 ? "b" : "s"; - const fallbackStyle: Record = { - transform: `matrix3d(${fallbackPlan.canonicalMatrix})`, - }; - if (!isTextured) fallbackStyle["background-color"] = fallbackPlan.shadedColor; - if (props.pointerEvents === "none") fallbackStyle["pointer-events"] = "none"; - const mergedStyle = userStyle && typeof userStyle === "object" - ? { ...fallbackStyle, ...userStyle } - : fallbackStyle; - front = h(tag, { + const desc = buildFallbackLeafDescriptor({ + plan: fallbackPlan, + polygon: polygon.value, + isTextured, + className: userClass, + pointerEvents: props.pointerEvents, + }); + const mergedStyle = + userStyle && typeof userStyle === "object" + ? { ...(desc.style as CSSProperties), ...userStyle } + : (desc.style as CSSProperties); + front = h(desc.tag, { ref: leafDomRef, - class: userClass?.trim() || undefined, + class: desc.className, style: mergedStyle, - "data-poly-index": "0", - "data-polycss-leaf": "polygon", - "data-polycss-double-sided": polygon.value.doubleSided ? "true" : undefined, + ...desc.dataAttrs, ...domAttrs, }); } From 60e6a05998da63153af3e1e12d53cc98058b82a4 Mon Sep 17 00:00:00 2001 From: alowpoly Date: Thu, 3 Dec 2026 18:49:16 -0300 Subject: [PATCH 2/5] refactor: deduplicate BVH, pointer controls, core helpers, and example/website clones --- .github/architecture/repo-map.md | 28 +- examples/react/vite.config.ts | 12 +- examples/shared-inputs.mjs | 13 + examples/vanilla/vite.config.ts | 12 +- examples/vue/vite.config.ts | 12 +- packages/core/src/atlas/plan.ts | 10 +- packages/core/src/color/color.ts | 43 ++ packages/core/src/cull/bvh.ts | 416 ++++++++++++++++++ .../core/src/cull/cullInteriorPolygons.ts | 324 +------------- packages/core/src/cull/lightVisibility.ts | 266 +---------- packages/core/src/index.ts | 3 +- packages/core/src/math/vec3.ts | 12 + .../core/src/merge/coverPlanarPolygons.ts | 6 +- .../src/merge/dedupeOverlappingPolygons.ts | 6 +- packages/core/src/merge/mergePolygons.ts | 33 +- packages/core/src/merge/optimizePolygons.ts | 36 +- packages/core/src/merge/seamRepair.ts | 30 +- .../core/src/merge/simplifyTriangleMesh.ts | 8 +- packages/core/src/merge/textureTriangles.ts | 27 ++ .../src/parser/optimizeMeshParseResult.ts | 47 +- packages/core/src/parser/parseStl.ts | 8 +- packages/core/src/parser/parseVox.ts | 35 +- packages/core/src/scene/context.ts | 26 ++ packages/core/src/scene/normalize.ts | 6 +- packages/core/src/three/index.ts | 56 +++ packages/core/src/transform/meshTransform.ts | 33 ++ packages/morph/src/prepare/compile.ts | 8 +- .../src/api/controls/pointerControlsCore.ts | 306 +++++++++++++ .../polycss/src/api/createPolyMapControls.ts | 271 +----------- .../src/api/createPolyOrbitControls.ts | 286 +----------- .../PolyDirectionalLightHelperElement.ts | 10 +- .../polycss/src/elements/PolyIframeElement.ts | 58 +-- .../src/elements/PolyMapControlsElement.ts | 140 +----- .../polycss/src/elements/PolyMeshElement.ts | 36 +- .../src/elements/PolyOrbitControlsElement.ts | 148 +------ .../elements/PolyPointerControlsElement.ts | 128 ++++++ .../src/elements/PolyPolygonElement.ts | 10 +- .../polycss/src/elements/PolySceneElement.ts | 16 +- .../polycss/src/elements/PolyShapeElements.ts | 20 +- packages/react/src/scene/PolyIframe.tsx | 39 +- .../react/src/scene/mesh/useMeshGeometry.ts | 26 +- .../src/three/PolyThreeOrthographicCamera.tsx | 22 +- .../src/three/PolyThreePerspectiveCamera.tsx | 20 +- packages/vue/src/scene/PolyIframe.ts | 38 +- .../vue/src/scene/mesh/useMeshGeometry.ts | 26 +- .../src/three/PolyThreeOrthographicCamera.ts | 22 +- .../src/three/PolyThreePerspectiveCamera.ts | 20 +- .../BuilderWorkbench/BuilderWorkbench.tsx | 11 +- .../components/BuilderScene.tsx | 10 +- .../GalleryWorkbench/hooks/useDroppedFiles.ts | 2 +- .../src/components/helpers/interiorShell.ts | 12 +- 51 files changed, 1190 insertions(+), 2003 deletions(-) create mode 100644 examples/shared-inputs.mjs create mode 100644 packages/core/src/cull/bvh.ts create mode 100644 packages/core/src/math/vec3.ts create mode 100644 packages/core/src/merge/textureTriangles.ts create mode 100644 packages/polycss/src/api/controls/pointerControlsCore.ts create mode 100644 packages/polycss/src/elements/PolyPointerControlsElement.ts diff --git a/.github/architecture/repo-map.md b/.github/architecture/repo-map.md index 30402f5e1..226c6c0d7 100644 --- a/.github/architecture/repo-map.md +++ b/.github/architecture/repo-map.md @@ -1,20 +1,20 @@ # PolyCSS Repository Map -Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **426 files**, **100,105 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. +Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **431 files**, **99,303 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. ## 1. Packages & Entry Points | Package | Visibility | Exports | Workspace deps | Src files | Src lines | Test files | |---|---|---|---|---:|---:|---:| -| `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 75 | 27,024 | 58 | +| `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 78 | 26,889 | 58 | | `packages/domformat` (`@layoutit/polycss-domformat`) | private | `., ./browser` | — | 36 | 13,165 | 0 | | `packages/fonts` (`@layoutit/polycss-fonts`) | npm | `.` | `@layoutit/polycss-core` | 7 | 1,661 | 4 | -| `packages/morph` (`@layoutit/polycss-morph`) | npm | `., ./prepare` | `@layoutit/polycss`, `@layoutit/polycss-core` | 49 | 7,633 | 14 | -| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./elements, ./three` | `@layoutit/polycss-core` | 67 | 17,562 | 41 | -| `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 4,835 | 31 | +| `packages/morph` (`@layoutit/polycss-morph`) | npm | `., ./prepare` | `@layoutit/polycss`, `@layoutit/polycss-core` | 49 | 7,627 | 14 | +| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./elements, ./three` | `@layoutit/polycss-core` | 69 | 17,085 | 41 | +| `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 4,754 | 31 | | `packages/skills` (`@layoutit/polycss-skills`) | npm | `.` | — | 1 | 415 | 1 | -| `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 4,670 | 29 | +| `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 4,590 | 29 | ## 2. Canonical Workspace Source Aliases @@ -44,29 +44,29 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | Fan-in | Lines | File | |---:|---:|---| -| 112 | 642 | `packages/core/src/index.ts` | -| 65 | 248 | `packages/core/src/types.ts` | -| 32 | 237 | `packages/polycss/src/runtime.ts` | +| 111 | 643 | `packages/core/src/index.ts` | +| 67 | 248 | `packages/core/src/types.ts` | +| 33 | 237 | `packages/polycss/src/runtime.ts` | | 32 | 301 | `packages/react/src/index.ts` | | 31 | 119 | `website/src/components/types.ts` | | 18 | 88 | `website/src/components/GalleryWorkbench/types.ts` | +| 17 | 1,386 | `packages/polycss/src/api/createPolyScene.ts` | | 17 | 218 | `packages/polycss/src/index.ts` | | 15 | 45 | `packages/polycss/src/render/textureAtlas.ts` | -| 14 | 1,386 | `packages/polycss/src/api/createPolyScene.ts` | -| 13 | 283 | `packages/polycss/src/elements/PolySceneElement.ts` | | 13 | 41 | `packages/react/src/camera/context.ts` | -| 11 | 101 | `packages/core/src/atlas/constants.ts` | +| 12 | 476 | `packages/polycss/src/api/scene/types.ts` | +| 12 | 269 | `packages/polycss/src/elements/PolySceneElement.ts` | ### Largest production source files | Lines | File | |---:|---| | 3,578 | `packages/domformat/src/schema.ts` | -| 2,746 | `packages/core/src/merge/optimizePolygons.ts` | +| 2,714 | `packages/core/src/merge/optimizePolygons.ts` | | 2,185 | `packages/core/src/shadow/computeReceiverShadows.ts` | | 2,017 | `packages/core/src/parser/parseGltf.ts` | | 1,935 | `packages/domformat/src/state/polycss.ts` | -| 1,592 | `packages/core/src/merge/seamRepair.ts` | +| 1,566 | `packages/core/src/merge/seamRepair.ts` | | 1,527 | `website/src/components/GalleryWorkbench/GalleryWorkbench.tsx` | | 1,386 | `packages/polycss/src/api/createPolyScene.ts` | | 1,283 | `website/src/components/VanillaScene/VanillaScene.tsx` | diff --git a/examples/react/vite.config.ts b/examples/react/vite.config.ts index 1d968b65f..6d0fb7acb 100644 --- a/examples/react/vite.config.ts +++ b/examples/react/vite.config.ts @@ -1,20 +1,12 @@ import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; -import { resolve } from "path"; +import { createExampleRollupInputs } from "../shared-inputs.mjs"; export default defineConfig({ plugins: [react()], build: { rollupOptions: { - input: { - main: resolve(__dirname, "index.html"), - "baked-shapes": resolve(__dirname, "baked-shapes/index.html"), - "multi-mesh": resolve(__dirname, "multi-mesh/index.html"), - "solid-glb": resolve(__dirname, "solid-glb/index.html"), - "textured-glb": resolve(__dirname, "textured-glb/index.html"), - animated: resolve(__dirname, "animated/index.html"), - voxel: resolve(__dirname, "voxel/index.html"), - }, + input: createExampleRollupInputs(__dirname), }, }, }); diff --git a/examples/shared-inputs.mjs b/examples/shared-inputs.mjs new file mode 100644 index 000000000..54ec560a1 --- /dev/null +++ b/examples/shared-inputs.mjs @@ -0,0 +1,13 @@ +import { resolve } from "node:path"; + +export function createExampleRollupInputs(dir) { + return { + main: resolve(dir, "index.html"), + "baked-shapes": resolve(dir, "baked-shapes/index.html"), + "multi-mesh": resolve(dir, "multi-mesh/index.html"), + "solid-glb": resolve(dir, "solid-glb/index.html"), + "textured-glb": resolve(dir, "textured-glb/index.html"), + animated: resolve(dir, "animated/index.html"), + voxel: resolve(dir, "voxel/index.html"), + }; +} diff --git a/examples/vanilla/vite.config.ts b/examples/vanilla/vite.config.ts index c8362326f..4b8b62a5d 100644 --- a/examples/vanilla/vite.config.ts +++ b/examples/vanilla/vite.config.ts @@ -1,18 +1,10 @@ import { defineConfig } from "vite"; -import { resolve } from "path"; +import { createExampleRollupInputs } from "../shared-inputs.mjs"; export default defineConfig({ build: { rollupOptions: { - input: { - main: resolve(__dirname, "index.html"), - "baked-shapes": resolve(__dirname, "baked-shapes/index.html"), - "multi-mesh": resolve(__dirname, "multi-mesh/index.html"), - "solid-glb": resolve(__dirname, "solid-glb/index.html"), - "textured-glb": resolve(__dirname, "textured-glb/index.html"), - animated: resolve(__dirname, "animated/index.html"), - voxel: resolve(__dirname, "voxel/index.html"), - }, + input: createExampleRollupInputs(__dirname), }, }, }); diff --git a/examples/vue/vite.config.ts b/examples/vue/vite.config.ts index 7fa998f3e..a8ed15b84 100644 --- a/examples/vue/vite.config.ts +++ b/examples/vue/vite.config.ts @@ -1,20 +1,12 @@ import { defineConfig } from "vite"; import vue from "@vitejs/plugin-vue"; -import { resolve } from "path"; +import { createExampleRollupInputs } from "../shared-inputs.mjs"; export default defineConfig({ plugins: [vue()], build: { rollupOptions: { - input: { - main: resolve(__dirname, "index.html"), - "baked-shapes": resolve(__dirname, "baked-shapes/index.html"), - "multi-mesh": resolve(__dirname, "multi-mesh/index.html"), - "solid-glb": resolve(__dirname, "solid-glb/index.html"), - "textured-glb": resolve(__dirname, "textured-glb/index.html"), - animated: resolve(__dirname, "animated/index.html"), - voxel: resolve(__dirname, "voxel/index.html"), - }, + input: createExampleRollupInputs(__dirname), }, }, }); diff --git a/packages/core/src/atlas/plan.ts b/packages/core/src/atlas/plan.ts index 17d8516d1..12a29c298 100644 --- a/packages/core/src/atlas/plan.ts +++ b/packages/core/src/atlas/plan.ts @@ -5,6 +5,8 @@ import type { Vec2, Vec3, } from "../types"; +import { crossVec } from "../math/vec3"; +export { crossVec }; import { DEFAULT_TILE, DEFAULT_LIGHT_DIR, @@ -188,14 +190,6 @@ export function dotVec(a: Vec3, b: Vec3): number { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } -export function crossVec(a: Vec3, b: Vec3): Vec3 { - return [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ]; -} - export function isBasisOptimizable(polygon: Polygon): boolean { return !polygon.texture; } diff --git a/packages/core/src/color/color.ts b/packages/core/src/color/color.ts index cf1c13987..0dcbc911a 100644 --- a/packages/core/src/color/color.ts +++ b/packages/core/src/color/color.ts @@ -58,3 +58,46 @@ export function formatColor(color: ParsedColor): string { ? `rgba(${r}, ${g}, ${b}, ${color.alpha})` : `rgb(${r}, ${g}, ${b})`; } + +export interface HsvColor { + hue: number; + saturation: number; + value: number; +} + +export function colorDistance( + a: { rgb: readonly [number, number, number] }, + b: { rgb: readonly [number, number, number] }, +): number { + return Math.hypot( + a.rgb[0] - b.rgb[0], + a.rgb[1] - b.rgb[1], + a.rgb[2] - b.rgb[2], + ); +} + +export function hsvFromColor(color: { rgb: readonly [number, number, number] }): HsvColor { + const r = color.rgb[0] / 255; + const g = color.rgb[1] / 255; + const b = color.rgb[2] / 255; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const delta = max - min; + let hue = 0; + if (delta !== 0) { + if (max === r) hue = 60 * (((g - b) / delta) % 6); + else if (max === g) hue = 60 * ((b - r) / delta + 2); + else hue = 60 * ((r - g) / delta + 4); + } + if (hue < 0) hue += 360; + return { + hue, + saturation: max === 0 ? 0 : delta / max, + value: max, + }; +} + +export function hueDistance(a: number, b: number): number { + const delta = Math.abs(a - b) % 360; + return delta > 180 ? 360 - delta : delta; +} diff --git a/packages/core/src/cull/bvh.ts b/packages/core/src/cull/bvh.ts new file mode 100644 index 000000000..6402cf787 --- /dev/null +++ b/packages/core/src/cull/bvh.ts @@ -0,0 +1,416 @@ +/** + * Shared flat-array SAH BVH and Möller–Trumbore ray-triangle intersection. + * + * Used by `cullInteriorPolygons` and `computeLightVisibility` for fast any-hit + * ray occlusion queries. + */ + +export const BVH_PARALLEL_EPS = 1e-9; +export const BVH_MIN_HIT_T = 1e-3; + +const BVH_STRIDE = 9; +const BVH_LEAF_SIZE = 6; +const DEFAULT_SAH_BUCKETS = 8; + +export interface BvhPolyMeta { + /** Flat triangle data: [ax,ay,az, bx,by,bz, cx,cy,cz, ...] per triangle */ + triFlat: Float64Array; + /** Bounding sphere center + radius² */ + bcx: number; + bcy: number; + bcz: number; + br2: number; + /** Axis-aligned bounding box */ + minX: number; + minY: number; + minZ: number; + maxX: number; + maxY: number; + maxZ: number; +} + +export interface BVH { + data: Float64Array; + nodeCount: number; + polyIndices: Int32Array; + meta: Array; +} + +/** + * Möller–Trumbore ray-triangle intersection (flat array variant). + * Returns true if the ray hits the triangle at t > BVH_MIN_HIT_T. + */ +export function rayTriFlat( + ox: number, + oy: number, + oz: number, + dx: number, + dy: number, + dz: number, + tf: Float64Array, + base: number, +): boolean { + const ax = tf[base]!; + const ay = tf[base + 1]!; + const az = tf[base + 2]!; + const e1x = tf[base + 3]! - ax; + const e1y = tf[base + 4]! - ay; + const e1z = tf[base + 5]! - az; + const e2x = tf[base + 6]! - ax; + const e2y = tf[base + 7]! - ay; + const e2z = tf[base + 8]! - az; + const hx = dy * e2z - dz * e2y; + const hy = dz * e2x - dx * e2z; + const hz = dx * e2y - dy * e2x; + const det = e1x * hx + e1y * hy + e1z * hz; + if (det > -BVH_PARALLEL_EPS && det < BVH_PARALLEL_EPS) return false; + const invDet = 1 / det; + const sx = ox - ax; + const sy = oy - ay; + const sz = oz - az; + const u = invDet * (sx * hx + sy * hy + sz * hz); + if (u < 0 || u > 1) return false; + const qx = sy * e1z - sz * e1y; + const qy = sz * e1x - sx * e1z; + const qz = sx * e1y - sy * e1x; + const v = invDet * (dx * qx + dy * qy + dz * qz); + if (v < 0 || u + v > 1) return false; + return invDet * (e2x * qx + e2y * qy + e2z * qz) > BVH_MIN_HIT_T; +} + +/** + * Test if ray hits any triangle in polygon `q`, using a bounding-sphere + * pre-reject before triangle testing. + */ +export function rayHitsPolygon( + ox: number, + oy: number, + oz: number, + dx: number, + dy: number, + dz: number, + q: BvhPolyMeta, +): boolean { + const vx = q.bcx - ox; + const vy = q.bcy - oy; + const vz = q.bcz - oz; + const proj = vx * dx + vy * dy + vz * dz; + const perpX = vx - proj * dx; + const perpY = vy - proj * dy; + const perpZ = vz - proj * dz; + if (perpX * perpX + perpY * perpY + perpZ * perpZ > q.br2) return false; + const tf = q.triFlat; + const n = tf.length; + for (let b = 0; b < n; b += 9) { + if (rayTriFlat(ox, oy, oz, dx, dy, dz, tf, b)) return true; + } + return false; +} + +/** Half-surface-area of an AABB (factor 2 cancels in SAH ratios). */ +function aabbSA( + minX: number, + minY: number, + minZ: number, + maxX: number, + maxY: number, + maxZ: number, +): number { + const dx = maxX - minX; + const dy = maxY - minY; + const dz = maxZ - minZ; + return dx * dy + dy * dz + dz * dx; +} + +/** + * Build a flat-array SAH-bucketed binary BVH over polygon metadata. + * Node layout (9 Float64 values per node): + * [0..5] AABB: minX minY minZ maxX maxY maxZ + * [6] isLeaf: 1 = leaf, 0 = internal + * [7,8] internal: leftIdx, rightIdx; leaf: start, end into polyIndices + */ +export function buildBVH( + meta: Array, + sahBuckets = DEFAULT_SAH_BUCKETS, +): BVH { + const valid: number[] = []; + for (let i = 0; i < meta.length; i++) { + if (meta[i]) valid.push(i); + } + const n = valid.length; + const polyIndices = new Int32Array(n); + for (let i = 0; i < n; i++) polyIndices[i] = valid[i]!; + + const centX = new Float64Array(n); + const centY = new Float64Array(n); + const centZ = new Float64Array(n); + for (let i = 0; i < n; i++) { + const m = meta[polyIndices[i]!]!; + centX[i] = (m.minX + m.maxX) * 0.5; + centY[i] = (m.minY + m.maxY) * 0.5; + centZ[i] = (m.minZ + m.maxZ) * 0.5; + } + + const maxNodes = 2 * Math.max(1, n) + 1; + const data = new Float64Array(maxNodes * BVH_STRIDE); + let nodeCount = 0; + + const bMinX = new Float64Array(sahBuckets); + const bMinY = new Float64Array(sahBuckets); + const bMinZ = new Float64Array(sahBuckets); + const bMaxX = new Float64Array(sahBuckets); + const bMaxY = new Float64Array(sahBuckets); + const bMaxZ = new Float64Array(sahBuckets); + const bCnt = new Int32Array(sahBuckets); + const lSA = new Float64Array(sahBuckets - 1); + const lCnt = new Int32Array(sahBuckets - 1); + const rSA = new Float64Array(sahBuckets - 1); + const rCnt = new Int32Array(sahBuckets - 1); + + function buildNode(start: number, end: number): number { + const ni = nodeCount++; + const base = ni * BVH_STRIDE; + const count = end - start; + + let minX = Infinity; + let minY = Infinity; + let minZ = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + let maxZ = -Infinity; + for (let i = start; i < end; i++) { + const m = meta[polyIndices[i]!]!; + if (m.minX < minX) minX = m.minX; + if (m.maxX > maxX) maxX = m.maxX; + if (m.minY < minY) minY = m.minY; + if (m.maxY > maxY) maxY = m.maxY; + if (m.minZ < minZ) minZ = m.minZ; + if (m.maxZ > maxZ) maxZ = m.maxZ; + } + data[base] = minX; + data[base + 1] = minY; + data[base + 2] = minZ; + data[base + 3] = maxX; + data[base + 4] = maxY; + data[base + 5] = maxZ; + + if (count <= BVH_LEAF_SIZE) { + data[base + 6] = 1; + data[base + 7] = start; + data[base + 8] = end; + return ni; + } + + let cxMin = Infinity; + let cyMin = Infinity; + let czMin = Infinity; + let cxMax = -Infinity; + let cyMax = -Infinity; + let czMax = -Infinity; + for (let i = start; i < end; i++) { + if (centX[i]! < cxMin) cxMin = centX[i]!; + if (centX[i]! > cxMax) cxMax = centX[i]!; + if (centY[i]! < cyMin) cyMin = centY[i]!; + if (centY[i]! > cyMax) cyMax = centY[i]!; + if (centZ[i]! < czMin) czMin = centZ[i]!; + if (centZ[i]! > czMax) czMax = centZ[i]!; + } + const extX = cxMax - cxMin; + const extY = cyMax - cyMin; + const extZ = czMax - czMin; + + if (extX === 0 && extY === 0 && extZ === 0) { + data[base + 6] = 1; + data[base + 7] = start; + data[base + 8] = end; + return ni; + } + + const nodeSA = aabbSA(minX, minY, minZ, maxX, maxY, maxZ); + const invSA = nodeSA > 0 ? 1 / nodeSA : 0; + let bestCost = count + 1; + let bestAxis = 0; + let bestSplitVal = 0; + + for (let axis = 0; axis < 3; axis++) { + const cMin = axis === 0 ? cxMin : axis === 1 ? cyMin : czMin; + const ext = axis === 0 ? extX : axis === 1 ? extY : extZ; + if (ext === 0) continue; + const centArr = axis === 0 ? centX : axis === 1 ? centY : centZ; + const scale = sahBuckets / ext; + + bMinX.fill(Infinity); + bMinY.fill(Infinity); + bMinZ.fill(Infinity); + bMaxX.fill(-Infinity); + bMaxY.fill(-Infinity); + bMaxZ.fill(-Infinity); + bCnt.fill(0); + + for (let i = start; i < end; i++) { + let b = ((centArr[i]! - cMin) * scale) | 0; + if (b >= sahBuckets) b = sahBuckets - 1; + const m = meta[polyIndices[i]!]!; + if (m.minX < bMinX[b]!) bMinX[b] = m.minX; + if (m.maxX > bMaxX[b]!) bMaxX[b] = m.maxX; + if (m.minY < bMinY[b]!) bMinY[b] = m.minY; + if (m.maxY > bMaxY[b]!) bMaxY[b] = m.maxY; + if (m.minZ < bMinZ[b]!) bMinZ[b] = m.minZ; + if (m.maxZ > bMaxZ[b]!) bMaxZ[b] = m.maxZ; + bCnt[b]!++; + } + + let lx0 = Infinity; + let ly0 = Infinity; + let lz0 = Infinity; + let lx1 = -Infinity; + let ly1 = -Infinity; + let lz1 = -Infinity; + let lc = 0; + for (let k = 0; k < sahBuckets - 1; k++) { + if (bMinX[k]! < lx0) lx0 = bMinX[k]!; + if (bMaxX[k]! > lx1) lx1 = bMaxX[k]!; + if (bMinY[k]! < ly0) ly0 = bMinY[k]!; + if (bMaxY[k]! > ly1) ly1 = bMaxY[k]!; + if (bMinZ[k]! < lz0) lz0 = bMinZ[k]!; + if (bMaxZ[k]! > lz1) lz1 = bMaxZ[k]!; + lc += bCnt[k]!; + lSA[k] = aabbSA(lx0, ly0, lz0, lx1, ly1, lz1); + lCnt[k] = lc; + } + + let rx0 = Infinity; + let ry0 = Infinity; + let rz0 = Infinity; + let rx1 = -Infinity; + let ry1 = -Infinity; + let rz1 = -Infinity; + let rc = 0; + for (let k = sahBuckets - 2; k >= 0; k--) { + const kb = k + 1; + if (bMinX[kb]! < rx0) rx0 = bMinX[kb]!; + if (bMaxX[kb]! > rx1) rx1 = bMaxX[kb]!; + if (bMinY[kb]! < ry0) ry0 = bMinY[kb]!; + if (bMaxY[kb]! > ry1) ry1 = bMaxY[kb]!; + if (bMinZ[kb]! < rz0) rz0 = bMinZ[kb]!; + if (bMaxZ[kb]! > rz1) rz1 = bMaxZ[kb]!; + rc += bCnt[kb]!; + rSA[k] = aabbSA(rx0, ry0, rz0, rx1, ry1, rz1); + rCnt[k] = rc; + } + + for (let k = 0; k < sahBuckets - 1; k++) { + if (lCnt[k] === 0 || rCnt[k] === 0) continue; + const cost = 0.125 + (lSA[k]! * lCnt[k]! + rSA[k]! * rCnt[k]!) * invSA; + if (cost < bestCost) { + bestCost = cost; + bestAxis = axis; + bestSplitVal = cMin + (k + 1) / scale; + } + } + } + + const centArr2 = bestAxis === 0 ? centX : bestAxis === 1 ? centY : centZ; + let lo = start; + let hi = end - 1; + while (lo <= hi) { + if (centArr2[lo]! < bestSplitVal) { + lo++; + } else { + const tmp = polyIndices[lo]!; + polyIndices[lo] = polyIndices[hi]!; + polyIndices[hi] = tmp; + const t0 = centX[lo]!; + centX[lo] = centX[hi]!; + centX[hi] = t0; + const t1 = centY[lo]!; + centY[lo] = centY[hi]!; + centY[hi] = t1; + const t2 = centZ[lo]!; + centZ[lo] = centZ[hi]!; + centZ[hi] = t2; + hi--; + } + } + let mid = lo; + if (mid === start || mid === end) mid = (start + end) >> 1; + + data[base + 6] = 0; + const left = buildNode(start, mid); + const right = buildNode(mid, end); + data[ni * BVH_STRIDE + 7] = left; + data[ni * BVH_STRIDE + 8] = right; + + return ni; + } + + if (n > 0) buildNode(0, n); + return { data, nodeCount, polyIndices, meta }; +} + +/** + * Any-hit ray traversal over the BVH. Returns true immediately on first hit. + */ +export function rayHitsAnyInBVH( + ox: number, + oy: number, + oz: number, + dx: number, + dy: number, + dz: number, + selfIdx: number, + bvh: BVH, + stack: Int32Array, +): boolean { + if (bvh.nodeCount === 0) return false; + const { data, polyIndices, meta } = bvh; + + const invDx = dx !== 0 ? 1 / dx : dx >= 0 ? Infinity : -Infinity; + const invDy = dy !== 0 ? 1 / dy : dy >= 0 ? Infinity : -Infinity; + const invDz = dz !== 0 ? 1 / dz : dz >= 0 ? Infinity : -Infinity; + + let top = 0; + stack[top++] = 0; + + while (top > 0) { + const ni = stack[--top]!; + const base = ni * BVH_STRIDE; + + const tx1 = (data[base]! - ox) * invDx; + const tx2 = (data[base + 3]! - ox) * invDx; + let tMin = tx1 < tx2 ? tx1 : tx2; + let tMax = tx1 < tx2 ? tx2 : tx1; + + const ty1 = (data[base + 1]! - oy) * invDy; + const ty2 = (data[base + 4]! - oy) * invDy; + const tyMin = ty1 < ty2 ? ty1 : ty2; + const tyMax = ty1 < ty2 ? ty2 : ty1; + if (tMin > tyMax || tyMin > tMax) continue; + if (tyMin > tMin) tMin = tyMin; + if (tyMax < tMax) tMax = tyMax; + + const tz1 = (data[base + 2]! - oz) * invDz; + const tz2 = (data[base + 5]! - oz) * invDz; + const tzMin = tz1 < tz2 ? tz1 : tz2; + const tzMax = tz1 < tz2 ? tz2 : tz1; + if (tMin > tzMax || tzMin > tMax) continue; + if (tzMax < tMax) tMax = tzMax; + + if (tMax < BVH_MIN_HIT_T) continue; + + if (data[base + 6] === 1) { + const start = data[base + 7]! | 0; + const end = data[base + 8]! | 0; + for (let k = start; k < end; k++) { + const j = polyIndices[k]!; + if (j === selfIdx) continue; + const q = meta[j]; + if (q && rayHitsPolygon(ox, oy, oz, dx, dy, dz, q)) return true; + } + } else { + stack[top++] = data[base + 7]! | 0; + stack[top++] = data[base + 8]! | 0; + } + } + return false; +} diff --git a/packages/core/src/cull/cullInteriorPolygons.ts b/packages/core/src/cull/cullInteriorPolygons.ts index 9267e3392..f34523320 100644 --- a/packages/core/src/cull/cullInteriorPolygons.ts +++ b/packages/core/src/cull/cullInteriorPolygons.ts @@ -19,11 +19,15 @@ * a truly hidden poly) are safe; false positives would be a visual bug. */ import type { Polygon, Vec3 } from "../types"; +import { + BVH_PARALLEL_EPS as PARALLEL_EPS, + buildBVH, + rayHitsAnyInBVH, + rayHitsPolygon, +} from "./bvh"; const DEFAULT_HEMISPHERE_SAMPLES = 8; const RAY_ORIGIN_OFFSET = 1e-3; -const MIN_HIT_T = 1e-3; -const PARALLEL_EPS = 1e-9; const OPEN_TOPOLOGY_MIN_POLYGONS = 100; const OPEN_TOPOLOGY_MIN_BOUNDARY_EDGES = 128; const OPEN_TOPOLOGY_BOUNDARY_RATIO = 0.2; @@ -146,322 +150,6 @@ function precompute(p: Polygon): PolyMeta | null { }; } -/** - * Möller–Trumbore ray-triangle intersection (flat array variant). - * Returns true if the ray hits the triangle at t > MIN_HIT_T. - */ -function rayTriFlat( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - tf: Float64Array, base: number, -): boolean { - const ax = tf[base], ay = tf[base + 1], az = tf[base + 2]; - const e1x = tf[base + 3] - ax, e1y = tf[base + 4] - ay, e1z = tf[base + 5] - az; - const e2x = tf[base + 6] - ax, e2y = tf[base + 7] - ay, e2z = tf[base + 8] - az; - const hx = dy * e2z - dz * e2y; - const hy = dz * e2x - dx * e2z; - const hz = dx * e2y - dy * e2x; - const det = e1x * hx + e1y * hy + e1z * hz; - if (det > -PARALLEL_EPS && det < PARALLEL_EPS) return false; - const invDet = 1 / det; - const sx = ox - ax, sy = oy - ay, sz = oz - az; - const u = invDet * (sx * hx + sy * hy + sz * hz); - if (u < 0 || u > 1) return false; - const qx = sy * e1z - sz * e1y; - const qy = sz * e1x - sx * e1z; - const qz = sx * e1y - sy * e1x; - const v = invDet * (dx * qx + dy * qy + dz * qz); - if (v < 0 || u + v > 1) return false; - return invDet * (e2x * qx + e2y * qy + e2z * qz) > MIN_HIT_T; -} - -/** - * Test if ray hits any triangle in polygon q. - * Bounding-sphere pre-reject for non-BVH callers; BVH has already done AABB culling. - */ -function rayHitsPolygon( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - q: PolyMeta, -): boolean { - // Bounding-sphere reject (keeps leaf testing fast for non-hitting rays). - const vx = q.bcx - ox, vy = q.bcy - oy, vz = q.bcz - oz; - const proj = vx * dx + vy * dy + vz * dz; - const perpX = vx - proj * dx; - const perpY = vy - proj * dy; - const perpZ = vz - proj * dz; - if (perpX * perpX + perpY * perpY + perpZ * perpZ > q.br2) return false; - const tf = q.triFlat; - const n = tf.length; - for (let b = 0; b < n; b += 9) { - if (rayTriFlat(ox, oy, oz, dx, dy, dz, tf, b)) return true; - } - return false; -} - -// ─── Flat-array SAH BVH ────────────────────────────────────────────────────── -// Node layout (BVH_STRIDE Float64 values per node): -// [0..5] AABB: minX minY minZ maxX maxY maxZ -// [6] isLeaf: 1 = leaf, 0 = internal -// Internal: [7] leftIdx [8] rightIdx -// Leaf: [7] start [8] end (into polyIndices) - -const BVH_STRIDE = 9; -const BVH_LEAF_SIZE = 6; -const SAH_BUCKETS = 8; - -interface BVH { - data: Float64Array; - nodeCount: number; - polyIndices: Int32Array; - meta: Array; -} - -/** Half-surface-area of an AABB (factor 2 cancels in SAH ratios). */ -function aabbSA(minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number): number { - const dx = maxX - minX, dy = maxY - minY, dz = maxZ - minZ; - return dx * dy + dy * dz + dz * dx; -} - -function buildBVH(meta: Array): BVH { - const valid: number[] = []; - for (let i = 0; i < meta.length; i++) { if (meta[i]) valid.push(i); } - const n = valid.length; - const polyIndices = new Int32Array(n); - for (let i = 0; i < n; i++) polyIndices[i] = valid[i]; - - // Precompute centroid per reordered index slot. - const centX = new Float64Array(n); - const centY = new Float64Array(n); - const centZ = new Float64Array(n); - for (let i = 0; i < n; i++) { - const m = meta[polyIndices[i]]!; - centX[i] = (m.minX + m.maxX) * 0.5; - centY[i] = (m.minY + m.maxY) * 0.5; - centZ[i] = (m.minZ + m.maxZ) * 0.5; - } - - // Worst case: 2*N nodes for a balanced tree; +1 for safety. - const maxNodes = 2 * Math.max(1, n) + 1; - const data = new Float64Array(maxNodes * BVH_STRIDE); - let nodeCount = 0; - - // Reusable bucket arrays to avoid alloc in the hot build loop. - const bMinX = new Float64Array(SAH_BUCKETS); - const bMinY = new Float64Array(SAH_BUCKETS); - const bMinZ = new Float64Array(SAH_BUCKETS); - const bMaxX = new Float64Array(SAH_BUCKETS); - const bMaxY = new Float64Array(SAH_BUCKETS); - const bMaxZ = new Float64Array(SAH_BUCKETS); - const bCnt = new Int32Array(SAH_BUCKETS); - const lSA = new Float64Array(SAH_BUCKETS - 1); - const lCnt = new Int32Array(SAH_BUCKETS - 1); - const rSA = new Float64Array(SAH_BUCKETS - 1); - const rCnt = new Int32Array(SAH_BUCKETS - 1); - - function buildNode(start: number, end: number): number { - const ni = nodeCount++; - const base = ni * BVH_STRIDE; - const count = end - start; - - // Compute AABB for this range and write to node. - let minX = Infinity, minY = Infinity, minZ = Infinity; - let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; - for (let i = start; i < end; i++) { - const m = meta[polyIndices[i]]!; - if (m.minX < minX) minX = m.minX; if (m.maxX > maxX) maxX = m.maxX; - if (m.minY < minY) minY = m.minY; if (m.maxY > maxY) maxY = m.maxY; - if (m.minZ < minZ) minZ = m.minZ; if (m.maxZ > maxZ) maxZ = m.maxZ; - } - data[base] = minX; data[base + 1] = minY; data[base + 2] = minZ; - data[base + 3] = maxX; data[base + 4] = maxY; data[base + 5] = maxZ; - - if (count <= BVH_LEAF_SIZE) { - data[base + 6] = 1; data[base + 7] = start; data[base + 8] = end; - return ni; - } - - // Centroid AABB for SAH axis selection. - let cxMin = Infinity, cyMin = Infinity, czMin = Infinity; - let cxMax = -Infinity, cyMax = -Infinity, czMax = -Infinity; - for (let i = start; i < end; i++) { - if (centX[i] < cxMin) cxMin = centX[i]; if (centX[i] > cxMax) cxMax = centX[i]; - if (centY[i] < cyMin) cyMin = centY[i]; if (centY[i] > cyMax) cyMax = centY[i]; - if (centZ[i] < czMin) czMin = centZ[i]; if (centZ[i] > czMax) czMax = centZ[i]; - } - const extX = cxMax - cxMin, extY = cyMax - cyMin, extZ = czMax - czMin; - - if (extX === 0 && extY === 0 && extZ === 0) { - data[base + 6] = 1; data[base + 7] = start; data[base + 8] = end; - return ni; - } - - const nodeSA = aabbSA(minX, minY, minZ, maxX, maxY, maxZ); - const invSA = nodeSA > 0 ? 1 / nodeSA : 0; - let bestCost = count + 1; - let bestAxis = 0, bestSplitVal = 0; - - // Evaluate SAH on all three axes. - for (let axis = 0; axis < 3; axis++) { - const cMin = axis === 0 ? cxMin : (axis === 1 ? cyMin : czMin); - const ext = axis === 0 ? extX : (axis === 1 ? extY : extZ); - if (ext === 0) continue; - const centArr = axis === 0 ? centX : (axis === 1 ? centY : centZ); - const scale = SAH_BUCKETS / ext; - - bMinX.fill(Infinity); bMinY.fill(Infinity); bMinZ.fill(Infinity); - bMaxX.fill(-Infinity); bMaxY.fill(-Infinity); bMaxZ.fill(-Infinity); - bCnt.fill(0); - - for (let i = start; i < end; i++) { - let b = (centArr[i] - cMin) * scale | 0; - if (b >= SAH_BUCKETS) b = SAH_BUCKETS - 1; - const m = meta[polyIndices[i]]!; - if (m.minX < bMinX[b]) bMinX[b] = m.minX; if (m.maxX > bMaxX[b]) bMaxX[b] = m.maxX; - if (m.minY < bMinY[b]) bMinY[b] = m.minY; if (m.maxY > bMaxY[b]) bMaxY[b] = m.maxY; - if (m.minZ < bMinZ[b]) bMinZ[b] = m.minZ; if (m.maxZ > bMaxZ[b]) bMaxZ[b] = m.maxZ; - bCnt[b]++; - } - - // Left sweep. - let lx0 = Infinity, ly0 = Infinity, lz0 = Infinity; - let lx1 = -Infinity, ly1 = -Infinity, lz1 = -Infinity; - let lc = 0; - for (let k = 0; k < SAH_BUCKETS - 1; k++) { - if (bMinX[k] < lx0) lx0 = bMinX[k]; if (bMaxX[k] > lx1) lx1 = bMaxX[k]; - if (bMinY[k] < ly0) ly0 = bMinY[k]; if (bMaxY[k] > ly1) ly1 = bMaxY[k]; - if (bMinZ[k] < lz0) lz0 = bMinZ[k]; if (bMaxZ[k] > lz1) lz1 = bMaxZ[k]; - lc += bCnt[k]; - lSA[k] = aabbSA(lx0, ly0, lz0, lx1, ly1, lz1); - lCnt[k] = lc; - } - // Right sweep. - let rx0 = Infinity, ry0 = Infinity, rz0 = Infinity; - let rx1 = -Infinity, ry1 = -Infinity, rz1 = -Infinity; - let rc = 0; - for (let k = SAH_BUCKETS - 2; k >= 0; k--) { - const kb = k + 1; - if (bMinX[kb] < rx0) rx0 = bMinX[kb]; if (bMaxX[kb] > rx1) rx1 = bMaxX[kb]; - if (bMinY[kb] < ry0) ry0 = bMinY[kb]; if (bMaxY[kb] > ry1) ry1 = bMaxY[kb]; - if (bMinZ[kb] < rz0) rz0 = bMinZ[kb]; if (bMaxZ[kb] > rz1) rz1 = bMaxZ[kb]; - rc += bCnt[kb]; - rSA[k] = aabbSA(rx0, ry0, rz0, rx1, ry1, rz1); - rCnt[k] = rc; - } - - for (let k = 0; k < SAH_BUCKETS - 1; k++) { - if (lCnt[k] === 0 || rCnt[k] === 0) continue; - const cost = 0.125 + (lSA[k] * lCnt[k] + rSA[k] * rCnt[k]) * invSA; - if (cost < bestCost) { - bestCost = cost; - bestAxis = axis; - bestSplitVal = cMin + (k + 1) / scale; - } - } - } - - // Partition around bestSplitVal on bestAxis. - const centArr2 = bestAxis === 0 ? centX : (bestAxis === 1 ? centY : centZ); - let lo = start, hi = end - 1; - while (lo <= hi) { - if (centArr2[lo] < bestSplitVal) { - lo++; - } else { - // Swap polyIndices and centroids. - const tmp = polyIndices[lo]; polyIndices[lo] = polyIndices[hi]; polyIndices[hi] = tmp; - const t0 = centX[lo]; centX[lo] = centX[hi]; centX[hi] = t0; - const t1 = centY[lo]; centY[lo] = centY[hi]; centY[hi] = t1; - const t2 = centZ[lo]; centZ[lo] = centZ[hi]; centZ[hi] = t2; - hi--; - } - } - let mid = lo; - if (mid === start || mid === end) mid = (start + end) >> 1; - - // Internal node: recurse. Must write children after recursion since - // nodeCount advances during recursion. - data[base + 6] = 0; - const left = buildNode(start, mid); - const right = buildNode(mid, end); - // Re-compute base since nodeCount changed (data buffer is fixed-size). - data[ni * BVH_STRIDE + 7] = left; - data[ni * BVH_STRIDE + 8] = right; - - return ni; - } - - if (n > 0) buildNode(0, n); - - return { data, nodeCount, polyIndices, meta }; -} - -/** - * Any-hit ray traversal over the BVH. Returns true immediately on first hit - * (perfect for occlusion queries). Uses an explicit stack for speed. - */ -function rayHitsAnyInBVH( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - selfIdx: number, - bvh: BVH, - stack: Int32Array, -): boolean { - if (bvh.nodeCount === 0) return false; - const { data, polyIndices, meta } = bvh; - - const invDx = dx !== 0 ? 1 / dx : (dx >= 0 ? Infinity : -Infinity); - const invDy = dy !== 0 ? 1 / dy : (dy >= 0 ? Infinity : -Infinity); - const invDz = dz !== 0 ? 1 / dz : (dz >= 0 ? Infinity : -Infinity); - - let top = 0; - stack[top++] = 0; - - while (top > 0) { - const ni = stack[--top]; - const base = ni * BVH_STRIDE; - - // AABB slab test. - const tx1 = (data[base] - ox) * invDx; - const tx2 = (data[base + 3] - ox) * invDx; - let tMin = tx1 < tx2 ? tx1 : tx2; - let tMax = tx1 < tx2 ? tx2 : tx1; - - const ty1 = (data[base + 1] - oy) * invDy; - const ty2 = (data[base + 4] - oy) * invDy; - const tyMin = ty1 < ty2 ? ty1 : ty2; - const tyMax = ty1 < ty2 ? ty2 : ty1; - if (tMin > tyMax || tyMin > tMax) continue; - if (tyMin > tMin) tMin = tyMin; - if (tyMax < tMax) tMax = tyMax; - - const tz1 = (data[base + 2] - oz) * invDz; - const tz2 = (data[base + 5] - oz) * invDz; - const tzMin = tz1 < tz2 ? tz1 : tz2; - const tzMax = tz1 < tz2 ? tz2 : tz1; - if (tMin > tzMax || tzMin > tMax) continue; - if (tzMax < tMax) tMax = tzMax; - - if (tMax < MIN_HIT_T) continue; // AABB entirely behind origin - - if (data[base + 6] === 1) { - // Leaf node. - const start = data[base + 7] | 0; - const end = data[base + 8] | 0; - for (let k = start; k < end; k++) { - const j = polyIndices[k]; - if (j === selfIdx) continue; - const q = meta[j]; - if (q && rayHitsPolygon(ox, oy, oz, dx, dy, dz, q)) return true; - } - } else { - // Push both children; order doesn't matter for any-hit. - stack[top++] = data[base + 7] | 0; - stack[top++] = data[base + 8] | 0; - } - } - return false; -} - /** * Precompute K Fibonacci-spiral hemisphere samples as a flat Float64Array. * Layout: [lx0, ly0, lz0, lx1, ly1, lz1, ...] diff --git a/packages/core/src/cull/lightVisibility.ts b/packages/core/src/cull/lightVisibility.ts index fcd82c83a..958a38f42 100644 --- a/packages/core/src/cull/lightVisibility.ts +++ b/packages/core/src/cull/lightVisibility.ts @@ -14,10 +14,14 @@ * (mesh geometry version, lightDir hash) and only recompute on change. */ import type { Polygon, Vec3 } from "../types"; +import { + BVH_PARALLEL_EPS as PARALLEL_EPS, + buildBVH, + rayHitsAnyInBVH, +} from "./bvh"; -const PARALLEL_EPS = 1e-9; -const MIN_HIT_T = 1e-3; const RAY_ORIGIN_OFFSET = 1e-3; +const LIGHT_VISIBILITY_SAH_BUCKETS = 12; interface PolyMeta { triFlat: Float64Array; @@ -71,262 +75,6 @@ function precompute(p: Polygon): PolyMeta | null { }; } -function rayTriFlat( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - tf: Float64Array, base: number, -): boolean { - const ax = tf[base], ay = tf[base + 1], az = tf[base + 2]; - const e1x = tf[base + 3] - ax, e1y = tf[base + 4] - ay, e1z = tf[base + 5] - az; - const e2x = tf[base + 6] - ax, e2y = tf[base + 7] - ay, e2z = tf[base + 8] - az; - const hx = dy * e2z - dz * e2y; - const hy = dz * e2x - dx * e2z; - const hz = dx * e2y - dy * e2x; - const det = e1x * hx + e1y * hy + e1z * hz; - if (det > -PARALLEL_EPS && det < PARALLEL_EPS) return false; - const invDet = 1 / det; - const sx = ox - ax, sy = oy - ay, sz = oz - az; - const u = invDet * (sx * hx + sy * hy + sz * hz); - if (u < 0 || u > 1) return false; - const qx = sy * e1z - sz * e1y; - const qy = sz * e1x - sx * e1z; - const qz = sx * e1y - sy * e1x; - const v = invDet * (dx * qx + dy * qy + dz * qz); - if (v < 0 || u + v > 1) return false; - return invDet * (e2x * qx + e2y * qy + e2z * qz) > MIN_HIT_T; -} - -function rayHitsPolygon( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - q: PolyMeta, -): boolean { - const vx = q.bcx - ox, vy = q.bcy - oy, vz = q.bcz - oz; - const proj = vx * dx + vy * dy + vz * dz; - const perpX = vx - proj * dx; - const perpY = vy - proj * dy; - const perpZ = vz - proj * dz; - if (perpX * perpX + perpY * perpY + perpZ * perpZ > q.br2) return false; - const tf = q.triFlat; - const n = tf.length; - for (let b = 0; b < n; b += 9) { - if (rayTriFlat(ox, oy, oz, dx, dy, dz, tf, b)) return true; - } - return false; -} - -// Flat-array SAH BVH (mirrors cullInteriorPolygons). Node layout: -// [0..5] AABB minX minY minZ maxX maxY maxZ -// [6] isLeaf (1/0) -// [7,8] leaf: start,end into polyIndices; internal: left,right -const BVH_STRIDE = 9; -const BVH_LEAF_SIZE = 6; -const SAH_BUCKETS = 12; - -interface BVH { - data: Float64Array; - nodeCount: number; - polyIndices: Int32Array; - meta: Array; -} - -function aabbSA(minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number): number { - const dx = maxX - minX, dy = maxY - minY, dz = maxZ - minZ; - return dx * dy + dy * dz + dz * dx; -} - -function buildBVH(meta: Array): BVH { - const valid: number[] = []; - for (let i = 0; i < meta.length; i++) { if (meta[i]) valid.push(i); } - const n = valid.length; - const polyIndices = new Int32Array(n); - for (let i = 0; i < n; i++) polyIndices[i] = valid[i]; - const centX = new Float64Array(n); - const centY = new Float64Array(n); - const centZ = new Float64Array(n); - for (let i = 0; i < n; i++) { - const m = meta[polyIndices[i]]!; - centX[i] = (m.minX + m.maxX) * 0.5; - centY[i] = (m.minY + m.maxY) * 0.5; - centZ[i] = (m.minZ + m.maxZ) * 0.5; - } - const maxNodes = 2 * Math.max(1, n) + 1; - const data = new Float64Array(maxNodes * BVH_STRIDE); - let nodeCount = 0; - const bMinX = new Float64Array(SAH_BUCKETS); - const bMinY = new Float64Array(SAH_BUCKETS); - const bMinZ = new Float64Array(SAH_BUCKETS); - const bMaxX = new Float64Array(SAH_BUCKETS); - const bMaxY = new Float64Array(SAH_BUCKETS); - const bMaxZ = new Float64Array(SAH_BUCKETS); - const bCnt = new Int32Array(SAH_BUCKETS); - const lSA = new Float64Array(SAH_BUCKETS - 1); - const lCnt = new Int32Array(SAH_BUCKETS - 1); - const rSA = new Float64Array(SAH_BUCKETS - 1); - const rCnt = new Int32Array(SAH_BUCKETS - 1); - function buildNode(start: number, end: number): number { - const ni = nodeCount++; - const base = ni * BVH_STRIDE; - const count = end - start; - let minX = Infinity, minY = Infinity, minZ = Infinity; - let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; - for (let i = start; i < end; i++) { - const m = meta[polyIndices[i]]!; - if (m.minX < minX) minX = m.minX; if (m.maxX > maxX) maxX = m.maxX; - if (m.minY < minY) minY = m.minY; if (m.maxY > maxY) maxY = m.maxY; - if (m.minZ < minZ) minZ = m.minZ; if (m.maxZ > maxZ) maxZ = m.maxZ; - } - data[base] = minX; data[base + 1] = minY; data[base + 2] = minZ; - data[base + 3] = maxX; data[base + 4] = maxY; data[base + 5] = maxZ; - if (count <= BVH_LEAF_SIZE) { - data[base + 6] = 1; data[base + 7] = start; data[base + 8] = end; - return ni; - } - let cxMin = Infinity, cyMin = Infinity, czMin = Infinity; - let cxMax = -Infinity, cyMax = -Infinity, czMax = -Infinity; - for (let i = start; i < end; i++) { - if (centX[i] < cxMin) cxMin = centX[i]; if (centX[i] > cxMax) cxMax = centX[i]; - if (centY[i] < cyMin) cyMin = centY[i]; if (centY[i] > cyMax) cyMax = centY[i]; - if (centZ[i] < czMin) czMin = centZ[i]; if (centZ[i] > czMax) czMax = centZ[i]; - } - const extX = cxMax - cxMin, extY = cyMax - cyMin, extZ = czMax - czMin; - if (extX === 0 && extY === 0 && extZ === 0) { - data[base + 6] = 1; data[base + 7] = start; data[base + 8] = end; - return ni; - } - const nodeSA = aabbSA(minX, minY, minZ, maxX, maxY, maxZ); - const invSA = nodeSA > 0 ? 1 / nodeSA : 0; - let bestCost = count + 1; - let bestAxis = 0, bestSplitVal = 0; - for (let axis = 0; axis < 3; axis++) { - const cMin = axis === 0 ? cxMin : (axis === 1 ? cyMin : czMin); - const ext = axis === 0 ? extX : (axis === 1 ? extY : extZ); - if (ext === 0) continue; - const centArr = axis === 0 ? centX : (axis === 1 ? centY : centZ); - const scale = SAH_BUCKETS / ext; - bMinX.fill(Infinity); bMinY.fill(Infinity); bMinZ.fill(Infinity); - bMaxX.fill(-Infinity); bMaxY.fill(-Infinity); bMaxZ.fill(-Infinity); - bCnt.fill(0); - for (let i = start; i < end; i++) { - let b = (centArr[i] - cMin) * scale | 0; - if (b >= SAH_BUCKETS) b = SAH_BUCKETS - 1; - const m = meta[polyIndices[i]]!; - if (m.minX < bMinX[b]) bMinX[b] = m.minX; if (m.maxX > bMaxX[b]) bMaxX[b] = m.maxX; - if (m.minY < bMinY[b]) bMinY[b] = m.minY; if (m.maxY > bMaxY[b]) bMaxY[b] = m.maxY; - if (m.minZ < bMinZ[b]) bMinZ[b] = m.minZ; if (m.maxZ > bMaxZ[b]) bMaxZ[b] = m.maxZ; - bCnt[b]++; - } - let lx0 = Infinity, ly0 = Infinity, lz0 = Infinity; - let lx1 = -Infinity, ly1 = -Infinity, lz1 = -Infinity; - let lc = 0; - for (let k = 0; k < SAH_BUCKETS - 1; k++) { - if (bMinX[k] < lx0) lx0 = bMinX[k]; if (bMaxX[k] > lx1) lx1 = bMaxX[k]; - if (bMinY[k] < ly0) ly0 = bMinY[k]; if (bMaxY[k] > ly1) ly1 = bMaxY[k]; - if (bMinZ[k] < lz0) lz0 = bMinZ[k]; if (bMaxZ[k] > lz1) lz1 = bMaxZ[k]; - lc += bCnt[k]; - lSA[k] = aabbSA(lx0, ly0, lz0, lx1, ly1, lz1); - lCnt[k] = lc; - } - let rx0 = Infinity, ry0 = Infinity, rz0 = Infinity; - let rx1 = -Infinity, ry1 = -Infinity, rz1 = -Infinity; - let rc = 0; - for (let k = SAH_BUCKETS - 2; k >= 0; k--) { - const kb = k + 1; - if (bMinX[kb] < rx0) rx0 = bMinX[kb]; if (bMaxX[kb] > rx1) rx1 = bMaxX[kb]; - if (bMinY[kb] < ry0) ry0 = bMinY[kb]; if (bMaxY[kb] > ry1) ry1 = bMaxY[kb]; - if (bMinZ[kb] < rz0) rz0 = bMinZ[kb]; if (bMaxZ[kb] > rz1) rz1 = bMaxZ[kb]; - rc += bCnt[kb]; - rSA[k] = aabbSA(rx0, ry0, rz0, rx1, ry1, rz1); - rCnt[k] = rc; - } - for (let k = 0; k < SAH_BUCKETS - 1; k++) { - if (lCnt[k] === 0 || rCnt[k] === 0) continue; - const cost = 0.125 + (lSA[k] * lCnt[k] + rSA[k] * rCnt[k]) * invSA; - if (cost < bestCost) { - bestCost = cost; - bestAxis = axis; - bestSplitVal = cMin + (k + 1) / scale; - } - } - } - const centArr2 = bestAxis === 0 ? centX : (bestAxis === 1 ? centY : centZ); - let lo = start, hi = end - 1; - while (lo <= hi) { - if (centArr2[lo] < bestSplitVal) { - lo++; - } else { - const tmp = polyIndices[lo]; polyIndices[lo] = polyIndices[hi]; polyIndices[hi] = tmp; - const t0 = centX[lo]; centX[lo] = centX[hi]; centX[hi] = t0; - const t1 = centY[lo]; centY[lo] = centY[hi]; centY[hi] = t1; - const t2 = centZ[lo]; centZ[lo] = centZ[hi]; centZ[hi] = t2; - hi--; - } - } - let mid = lo; - if (mid === start || mid === end) mid = (start + end) >> 1; - data[base + 6] = 0; - const left = buildNode(start, mid); - const right = buildNode(mid, end); - data[ni * BVH_STRIDE + 7] = left; - data[ni * BVH_STRIDE + 8] = right; - return ni; - } - if (n > 0) buildNode(0, n); - return { data, nodeCount, polyIndices, meta }; -} - -function rayHitsAnyInBVH( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - selfIdx: number, - bvh: BVH, - stack: Int32Array, -): boolean { - if (bvh.nodeCount === 0) return false; - const { data, polyIndices, meta } = bvh; - const invDx = dx !== 0 ? 1 / dx : (dx >= 0 ? Infinity : -Infinity); - const invDy = dy !== 0 ? 1 / dy : (dy >= 0 ? Infinity : -Infinity); - const invDz = dz !== 0 ? 1 / dz : (dz >= 0 ? Infinity : -Infinity); - let top = 0; - stack[top++] = 0; - while (top > 0) { - const ni = stack[--top]; - const base = ni * BVH_STRIDE; - const tx1 = (data[base] - ox) * invDx; - const tx2 = (data[base + 3] - ox) * invDx; - let tMin = tx1 < tx2 ? tx1 : tx2; - let tMax = tx1 < tx2 ? tx2 : tx1; - const ty1 = (data[base + 1] - oy) * invDy; - const ty2 = (data[base + 4] - oy) * invDy; - const tyMin = ty1 < ty2 ? ty1 : ty2; - const tyMax = ty1 < ty2 ? ty2 : ty1; - if (tMin > tyMax || tyMin > tMax) continue; - if (tyMin > tMin) tMin = tyMin; - if (tyMax < tMax) tMax = tyMax; - const tz1 = (data[base + 2] - oz) * invDz; - const tz2 = (data[base + 5] - oz) * invDz; - const tzMin = tz1 < tz2 ? tz1 : tz2; - const tzMax = tz1 < tz2 ? tz2 : tz1; - if (tMin > tzMax || tzMin > tMax) continue; - if (tzMax < tMax) tMax = tzMax; - if (tMax < MIN_HIT_T) continue; - if (data[base + 6] === 1) { - const start = data[base + 7] | 0; - const end = data[base + 8] | 0; - for (let k = start; k < end; k++) { - const j = polyIndices[k]; - if (j === selfIdx) continue; - const q = meta[j]; - if (q && rayHitsPolygon(ox, oy, oz, dx, dy, dz, q)) return true; - } - } else { - stack[top++] = data[base + 7] | 0; - stack[top++] = data[base + 8] | 0; - } - } - return false; -} - /** * Returns a Set of polygon indices that are OCCLUDED from the light * (a ray from the polygon's centroid in the +lightDir direction hits @@ -358,7 +106,7 @@ export function computeLightVisibility( if (skipIndices && skipIndices.size > 0) { for (const i of skipIndices) meta[i] = null; } - const bvh = buildBVH(meta); + const bvh = buildBVH(meta, LIGHT_VISIBILITY_SAH_BUCKETS); const stack = new Int32Array(Math.max(64, bvh.nodeCount)); for (let i = 0; i < polygons.length; i++) { const p = meta[i]; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5122a4991..970d0efc2 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -33,6 +33,7 @@ export { buildSceneContext, computeSceneBbox, normalizePolygons, + recenterPolygons, } from "./scene/context"; export type { SceneContext, @@ -293,7 +294,7 @@ export { worldPositionToPolyCss, } from "./shadow/receiverFaceGroups"; export type { ReceiverPlaneGroup } from "./shadow/receiverFaceGroups"; -export { buildPolyMeshTransform } from "./transform/meshTransform"; +export { buildPolyIframeTransform, buildPolyMeshTransform } from "./transform/meshTransform"; export type { PolyMeshTransformInput } from "./transform/meshTransform"; export { buildPolySceneTransform } from "./transform/sceneTransform"; export type { PolySceneTransformInput } from "./transform/sceneTransform"; diff --git a/packages/core/src/math/vec3.ts b/packages/core/src/math/vec3.ts new file mode 100644 index 000000000..66e570aa0 --- /dev/null +++ b/packages/core/src/math/vec3.ts @@ -0,0 +1,12 @@ +import type { Vec3 } from "../types"; + +export function crossVec( + a: readonly [number, number, number], + b: readonly [number, number, number], +): Vec3 { + return [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], + ]; +} diff --git a/packages/core/src/merge/coverPlanarPolygons.ts b/packages/core/src/merge/coverPlanarPolygons.ts index 358a7311d..228c529e7 100644 --- a/packages/core/src/merge/coverPlanarPolygons.ts +++ b/packages/core/src/merge/coverPlanarPolygons.ts @@ -1,3 +1,4 @@ +import { crossVec as cross } from "../math/vec3"; import type { Polygon, Vec2, Vec3 } from "../types"; import { mergePolygons } from "./mergePolygons"; @@ -65,11 +66,6 @@ const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; const scale = (v: Vec3, n: number): Vec3 => [v[0] * n, v[1] * n, v[2] * n]; const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; -const cross = (a: Vec3, b: Vec3): Vec3 => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], -]; const length = (v: Vec3): number => Math.hypot(v[0], v[1], v[2]); function normalize(v: Vec3): Vec3 | null { diff --git a/packages/core/src/merge/dedupeOverlappingPolygons.ts b/packages/core/src/merge/dedupeOverlappingPolygons.ts index 10ef773d5..a914cdae8 100644 --- a/packages/core/src/merge/dedupeOverlappingPolygons.ts +++ b/packages/core/src/merge/dedupeOverlappingPolygons.ts @@ -36,6 +36,7 @@ * dedup logic never executes again. */ +import { crossVec as cross } from "../math/vec3"; import type { Polygon, Vec2, Vec3 } from "../types"; /** Tunable thresholds. Default values are conservative — only catch @@ -94,11 +95,6 @@ interface PolyMeta { } const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; -const cross = (a: Vec3, b: Vec3): Vec3 => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], -]; const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; const norm = (a: Vec3): number => Math.hypot(a[0], a[1], a[2]); diff --git a/packages/core/src/merge/mergePolygons.ts b/packages/core/src/merge/mergePolygons.ts index 7796ec856..f64be0780 100644 --- a/packages/core/src/merge/mergePolygons.ts +++ b/packages/core/src/merge/mergePolygons.ts @@ -25,6 +25,8 @@ */ import type { Polygon, PolyTextureAlphaMode, PolyTextureWrap, TextureTriangle, Vec2, Vec3 } from "../types"; +import { crossVec as cross } from "../math/vec3"; +import { cloneTextureTriangles, fanTextureTriangles } from "./textureTriangles"; const EPS_NORMAL = 1e-3; // dot product tolerance for "same plane" const EPS_DISTANCE = 0.05; // signed-distance tolerance (in scene-space units) @@ -70,11 +72,6 @@ interface EdgeOwners { } const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; -const cross = (a: Vec3, b: Vec3): Vec3 => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], -]; const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; const norm = (a: Vec3): number => Math.hypot(a[0], a[1], a[2]); const eqVec = (a: Vec3, b: Vec3): boolean => @@ -253,13 +250,6 @@ function mergeIsPlanar(vertices: Vec3[], epsilon: number): boolean { return true; } -function cloneTextureTriangles(triangles: TextureTriangle[]): TextureTriangle[] { - return triangles.map((triangle) => ({ - vertices: triangle.vertices.map((vertex) => [...vertex] as Vec3) as [Vec3, Vec3, Vec3], - uvs: triangle.uvs.map((uv) => [...uv] as Vec2) as [Vec2, Vec2, Vec2], - })); -} - function cloneImageSource(source: Polygon["textureImageSource"]): Polygon["textureImageSource"] { if (!source) return undefined; return { @@ -292,25 +282,6 @@ function sameTextureAlphaMode( return (a ?? "") === (b ?? ""); } -function fanTextureTriangles(vertices: Vec3[], uvs: Vec2[]): TextureTriangle[] { - const triangles: TextureTriangle[] = []; - for (let i = 1; i < vertices.length - 1; i++) { - triangles.push({ - vertices: [ - [...vertices[0]] as Vec3, - [...vertices[i]] as Vec3, - [...vertices[i + 1]] as Vec3, - ], - uvs: [ - [...uvs[0]] as Vec2, - [...uvs[i]] as Vec2, - [...uvs[i + 1]] as Vec2, - ], - }); - } - return triangles; -} - function rotateToNonCollinearStart(vertices: Vec3[], uvs?: Vec2[]): { vertices: Vec3[]; uvs?: Vec2[] } { for (let i = 0; i < vertices.length; i++) { const a = vertices[i]; diff --git a/packages/core/src/merge/optimizePolygons.ts b/packages/core/src/merge/optimizePolygons.ts index c5cf0637e..ac8eae67a 100644 --- a/packages/core/src/merge/optimizePolygons.ts +++ b/packages/core/src/merge/optimizePolygons.ts @@ -1,4 +1,5 @@ import { cullInteriorPolygons } from "../cull/cullInteriorPolygons"; +import { crossVec } from "../math/vec3"; import { findOverlappingPolygonDuplicates } from "./dedupeOverlappingPolygons"; import type { MeshResolution, Polygon, TextureTriangle, Vec2, Vec3 } from "../types"; import { coverPlanarPolygons, type CoverPlanarPolygonsOptions } from "./coverPlanarPolygons"; @@ -8,6 +9,7 @@ import { simplifyTriangleMeshPolygons, type SimplifyTriangleMeshPolygonsOptions, } from "./simplifyTriangleMesh"; +import { cloneTextureTriangles, fanTextureTriangles } from "./textureTriangles"; const NORMALIZE_MAX_ANGLE_DEG = 3; const NORMALIZE_MAX_PLANE_DISPLACEMENT = 0.03; @@ -2157,32 +2159,6 @@ function textureTrianglesForPolygons(polygons: Polygon[]): TextureTriangle[] | u return triangles.length > 0 ? triangles : undefined; } -function fanTextureTriangles(vertices: Vec3[], uvs: Vec2[]): TextureTriangle[] { - const triangles: TextureTriangle[] = []; - for (let i = 1; i < vertices.length - 1; i++) { - triangles.push({ - vertices: [ - [...vertices[0]] as Vec3, - [...vertices[i]] as Vec3, - [...vertices[i + 1]] as Vec3, - ], - uvs: [ - [...uvs[0]] as Vec2, - [...uvs[i]] as Vec2, - [...uvs[i + 1]] as Vec2, - ], - }); - } - return triangles; -} - -function cloneTextureTriangles(triangles: TextureTriangle[]): TextureTriangle[] { - return triangles.map((triangle) => ({ - vertices: triangle.vertices.map((vertex) => [...vertex] as Vec3) as [Vec3, Vec3, Vec3], - uvs: triangle.uvs.map((uv) => [...uv] as Vec2) as [Vec2, Vec2, Vec2], - })); -} - function mapTextureTriangleVertices( triangles: TextureTriangle[] | undefined, mapVertex: (vertex: Vec3) => Vec3, @@ -2710,14 +2686,6 @@ function subVec(a: Vec3, b: Vec3): Vec3 { return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; } -function crossVec(a: Vec3, b: Vec3): Vec3 { - return [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ]; -} - function dotVec(a: Vec3, b: Vec3): number { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } diff --git a/packages/core/src/merge/seamRepair.ts b/packages/core/src/merge/seamRepair.ts index a552df7c1..7107239d9 100644 --- a/packages/core/src/merge/seamRepair.ts +++ b/packages/core/src/merge/seamRepair.ts @@ -1,3 +1,5 @@ +import { rotateVec3 as rotateCssVec3 } from "../math/rotation"; +import { crossVec as cross } from "../math/vec3"; import type { Polygon, Vec3 } from "../types"; import type { SeamFacetSplitCandidateReason as SplitReason, SeamFacetSplitOptions as SplitOptions, SeamFacetSplitReport as SplitReport, SeamOverlapCandidate as OverlapCandidate, SeamOverlapCandidateKind as OverlapKind, SeamOverlapDiagnostics as OverlapDiagnostics, SeamOverlapOptions as OverlapOptions } from "./seamRepairTypes"; export type * from "./seamRepairTypes"; @@ -120,34 +122,6 @@ function dot(a: Vec3, b: Vec3) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } -function rotateCssVec3(v: Vec3, rxDeg: number, ryDeg: number, rzDeg: number): Vec3 { - const dx = (rxDeg * Math.PI) / 180; - const dy = (ryDeg * Math.PI) / 180; - const dz = (rzDeg * Math.PI) / 180; - let [x, y, z] = v; - if (dz !== 0) { - const c = Math.cos(dz), s = Math.sin(dz); - [x, y] = [x * c - y * s, x * s + y * c]; - } - if (dy !== 0) { - const c = Math.cos(dy), s = Math.sin(dy); - [x, z] = [x * c + z * s, -x * s + z * c]; - } - if (dx !== 0) { - const c = Math.cos(dx), s = Math.sin(dx); - [y, z] = [y * c - z * s, y * s + z * c]; - } - return [x, y, z]; -} - -function cross(a: Vec3, b: Vec3): Vec3 { - return [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ]; -} - function surfaceNormal(points: Vec3[]): Vec3 | null { if (points.length < 3) return null; const origin = points[0]; diff --git a/packages/core/src/merge/simplifyTriangleMesh.ts b/packages/core/src/merge/simplifyTriangleMesh.ts index ae4ab3111..3df56952f 100644 --- a/packages/core/src/merge/simplifyTriangleMesh.ts +++ b/packages/core/src/merge/simplifyTriangleMesh.ts @@ -1,3 +1,4 @@ +import { crossVec } from "../math/vec3"; import type { Polygon, Vec3 } from "../types"; export interface SimplifyTriangleMeshPolygonsOptions { @@ -160,13 +161,6 @@ function dotVec(a: Vec3, b: Vec3): number { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } -function crossVec(a: Vec3, b: Vec3): Vec3 { - return [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ]; -} function lengthVec(a: Vec3): number { return Math.hypot(a[0], a[1], a[2]); diff --git a/packages/core/src/merge/textureTriangles.ts b/packages/core/src/merge/textureTriangles.ts new file mode 100644 index 000000000..1d6a102d9 --- /dev/null +++ b/packages/core/src/merge/textureTriangles.ts @@ -0,0 +1,27 @@ +import type { TextureTriangle, Vec2, Vec3 } from "../types"; + +export function cloneTextureTriangles(triangles: TextureTriangle[]): TextureTriangle[] { + return triangles.map((triangle) => ({ + vertices: triangle.vertices.map((vertex) => [...vertex] as Vec3) as [Vec3, Vec3, Vec3], + uvs: triangle.uvs.map((uv) => [...uv] as Vec2) as [Vec2, Vec2, Vec2], + })); +} + +export function fanTextureTriangles(vertices: Vec3[], uvs: Vec2[]): TextureTriangle[] { + const triangles: TextureTriangle[] = []; + for (let i = 1; i < vertices.length - 1; i++) { + triangles.push({ + vertices: [ + [...vertices[0]!] as Vec3, + [...vertices[i]!] as Vec3, + [...vertices[i + 1]!] as Vec3, + ], + uvs: [ + [...uvs[0]!] as Vec2, + [...uvs[i]!] as Vec2, + [...uvs[i + 1]!] as Vec2, + ], + }); + } + return triangles; +} diff --git a/packages/core/src/parser/optimizeMeshParseResult.ts b/packages/core/src/parser/optimizeMeshParseResult.ts index 91c0832a1..ca0f643f2 100644 --- a/packages/core/src/parser/optimizeMeshParseResult.ts +++ b/packages/core/src/parser/optimizeMeshParseResult.ts @@ -1,4 +1,9 @@ -import { parsePureColor } from "../color/color"; +import { + colorDistance, + hsvFromColor, + hueDistance, + parsePureColor, +} from "../color/color"; import { optimizeParseMeshPolygons } from "../merge/optimizePolygons"; import type { SimplifyTriangleMeshPolygonsOptions } from "../merge/simplifyTriangleMesh"; import type { MeshResolution, Polygon } from "../types"; @@ -9,12 +14,6 @@ interface RgbColor { alpha: number; } -interface HsvColor { - hue: number; - saturation: number; - value: number; -} - export interface OptimizeMeshParseResultOptions { /** Render-cost optimization intent. Defaults to "lossy". */ meshResolution?: MeshResolution; @@ -67,40 +66,6 @@ function parseRgbColor(color: string): RgbColor | null { }; } -function colorDistance(a: RgbColor, b: RgbColor): number { - return Math.hypot( - a.rgb[0] - b.rgb[0], - a.rgb[1] - b.rgb[1], - a.rgb[2] - b.rgb[2], - ); -} - -function hsvFromColor(color: RgbColor): HsvColor { - const r = color.rgb[0] / 255; - const g = color.rgb[1] / 255; - const b = color.rgb[2] / 255; - const max = Math.max(r, g, b); - const min = Math.min(r, g, b); - const delta = max - min; - let hue = 0; - if (delta !== 0) { - if (max === r) hue = 60 * (((g - b) / delta) % 6); - else if (max === g) hue = 60 * ((b - r) / delta + 2); - else hue = 60 * ((r - g) / delta + 4); - } - if (hue < 0) hue += 360; - return { - hue, - saturation: max === 0 ? 0 : delta / max, - value: max, - }; -} - -function hueDistance(a: number, b: number): number { - const delta = Math.abs(a - b) % 360; - return delta > 180 ? 360 - delta : delta; -} - function compatibleColors(a: RgbColor, b: RgbColor): boolean { if (a.alpha < 1 || b.alpha < 1) return false; const ah = hsvFromColor(a); diff --git a/packages/core/src/parser/parseStl.ts b/packages/core/src/parser/parseStl.ts index 68b69171a..898376e90 100644 --- a/packages/core/src/parser/parseStl.ts +++ b/packages/core/src/parser/parseStl.ts @@ -11,6 +11,7 @@ * consistent supplied-normal signal are oriented to those normals before * polygons are emitted. */ +import { crossVec as cross } from "../math/vec3"; import type { Polygon, Vec3 } from "../types"; import type { ParseResult, ParseStlColor, ParseStlSolid } from "./types"; @@ -380,13 +381,6 @@ function sub(a: Vec3, b: Vec3): Vec3 { return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; } -function cross(a: Vec3, b: Vec3): Vec3 { - return [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ]; -} function dot(a: Vec3, b: Vec3): number { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; diff --git a/packages/core/src/parser/parseVox.ts b/packages/core/src/parser/parseVox.ts index c2a782881..a50fd46f5 100644 --- a/packages/core/src/parser/parseVox.ts +++ b/packages/core/src/parser/parseVox.ts @@ -30,6 +30,7 @@ */ import type { Polygon, Vec3 } from "../types"; import { BASE_TILE } from "../camera/camera"; +import { colorDistance, hsvFromColor, hueDistance } from "../color/color"; import type { ParseResult, PolyVoxelSource } from "./types"; export interface VoxParseOptions { @@ -159,40 +160,6 @@ function parseResolvedVoxColor(color: string): ResolvedVoxColor | null { }; } -function colorDistance(a: ResolvedVoxColor, b: ResolvedVoxColor): number { - return Math.hypot( - a.rgb[0] - b.rgb[0], - a.rgb[1] - b.rgb[1], - a.rgb[2] - b.rgb[2], - ); -} - -function hsvFromColor(color: ResolvedVoxColor): HsvColor { - const r = color.rgb[0] / 255; - const g = color.rgb[1] / 255; - const b = color.rgb[2] / 255; - const max = Math.max(r, g, b); - const min = Math.min(r, g, b); - const delta = max - min; - let hue = 0; - if (delta !== 0) { - if (max === r) hue = 60 * (((g - b) / delta) % 6); - else if (max === g) hue = 60 * ((b - r) / delta + 2); - else hue = 60 * ((r - g) / delta + 4); - } - if (hue < 0) hue += 360; - return { - hue, - saturation: max === 0 ? 0 : delta / max, - value: max, - }; -} - -function hueDistance(a: number, b: number): number { - const delta = Math.abs(a - b) % 360; - return delta > 180 ? 360 - delta : delta; -} - function canMergeVoxColors(a: ResolvedVoxColor, b: ResolvedVoxColor): boolean { if (a.alpha < 1 || b.alpha < 1) return false; const ah = hsvFromColor(a); diff --git a/packages/core/src/scene/context.ts b/packages/core/src/scene/context.ts index 6655a2ffb..29a75eed7 100644 --- a/packages/core/src/scene/context.ts +++ b/packages/core/src/scene/context.ts @@ -111,6 +111,32 @@ export function buildSceneContext(args: SceneContextBuildArgs): SceneContextBuil }; } +/** + * Re-center polygons around their bounding-box midpoint in mesh-local space, + * shifting both polygon vertices and any `textureTriangles` vertices. + */ +export function recenterPolygons(polygons: Polygon[]): Polygon[] { + if (polygons.length === 0) return polygons; + const bbox = computeSceneBbox(polygons); + const cx = (bbox.min[0] + bbox.max[0]) / 2; + const cy = (bbox.min[1] + bbox.max[1]) / 2; + const cz = (bbox.min[2] + bbox.max[2]) / 2; + if (cx === 0 && cy === 0 && cz === 0) return polygons; + const shift = (v: Vec3): Vec3 => [v[0] - cx, v[1] - cy, v[2] - cz]; + return polygons.map((p) => ({ + ...p, + vertices: p.vertices.map(shift), + ...(p.textureTriangles?.length + ? { + textureTriangles: p.textureTriangles.map((triangle) => ({ + ...triangle, + vertices: triangle.vertices.map(shift) as [Vec3, Vec3, Vec3], + })), + } + : null), + })); +} + /** * Re-export `normalizePolygons` for callers that import scene/context as * the canonical scene-pipeline entry point. diff --git a/packages/core/src/scene/normalize.ts b/packages/core/src/scene/normalize.ts index a67be0182..bc17f0163 100644 --- a/packages/core/src/scene/normalize.ts +++ b/packages/core/src/scene/normalize.ts @@ -8,6 +8,7 @@ * Pure: no DOM, no I/O, deterministic. Bbox is NOT computed here — that's * derived on demand by `buildSceneContext` / consumers. */ +import { crossVec as cross } from "../math/vec3"; import type { Polygon, Vec2, Vec3 } from "../types"; import { parseColor } from "../color/lighting"; @@ -19,11 +20,6 @@ export interface NormalizeResult { const DEFAULT_COLOR = "#cccccc"; const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; -const cross = (a: Vec3, b: Vec3): Vec3 => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], -]; const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; const len = (a: Vec3): number => Math.hypot(a[0], a[1], a[2]); diff --git a/packages/core/src/three/index.ts b/packages/core/src/three/index.ts index 99cedcf3c..01de884c9 100644 --- a/packages/core/src/three/index.ts +++ b/packages/core/src/three/index.ts @@ -382,6 +382,62 @@ function perspectiveFromFov(fov: number, viewportHeight: number, zoom = 1): numb return (viewportHeight * zoom) / (2 * Math.tan((fov * DEG) / 2)); } +export interface ThreeOrthographicCameraPropPatch { + left?: number; + right?: number; + top?: number; + bottom?: number; + near?: number; + far?: number; + zoom?: number; + position?: Vector3Tuple; + lookAt?: Vector3Tuple; + up?: Vector3Tuple; +} + +export function applyThreeOrthographicCameraProps( + camera: OrthographicCamera, + props: ThreeOrthographicCameraPropPatch, +): OrthographicCamera { + if (props.left !== undefined) camera.left = props.left; + if (props.right !== undefined) camera.right = props.right; + if (props.top !== undefined) camera.top = props.top; + if (props.bottom !== undefined) camera.bottom = props.bottom; + if (props.near !== undefined) camera.near = props.near; + if (props.far !== undefined) camera.far = props.far; + if (props.zoom !== undefined) camera.zoom = props.zoom; + if (props.position !== undefined) camera.position.set(props.position[0], props.position[1], props.position[2]); + if (props.up !== undefined) camera.up.set(props.up[0], props.up[1], props.up[2]); + if (props.lookAt !== undefined) camera.lookAt(props.lookAt[0], props.lookAt[1], props.lookAt[2]); + return camera; +} + +export interface ThreePerspectiveCameraPropPatch { + fov?: number; + aspect?: number; + near?: number; + far?: number; + zoom?: number; + position?: Vector3Tuple; + lookAt?: Vector3Tuple; + up?: Vector3Tuple; +} + +export function applyThreePerspectiveCameraProps( + camera: PerspectiveCamera, + props: ThreePerspectiveCameraPropPatch, +): PerspectiveCamera { + if (props.fov !== undefined) camera.fov = props.fov; + if (props.aspect !== undefined) camera.aspect = props.aspect; + if (props.near !== undefined) camera.near = props.near; + if (props.far !== undefined) camera.far = props.far; + if (props.zoom !== undefined) camera.zoom = props.zoom; + if (props.position !== undefined) camera.position.set(props.position[0], props.position[1], props.position[2]); + if (props.up !== undefined) camera.up.set(props.up[0], props.up[1], props.up[2]); + if (props.lookAt !== undefined) camera.lookAt(props.lookAt[0], props.lookAt[1], props.lookAt[2]); + return camera; +} + function asVector3(v: Vector3 | Vector3Tuple): Vector3 { return v instanceof Vector3 ? v.clone() : new Vector3(v[0], v[1], v[2]); } diff --git a/packages/core/src/transform/meshTransform.ts b/packages/core/src/transform/meshTransform.ts index 584bd1afa..bbf66550c 100644 --- a/packages/core/src/transform/meshTransform.ts +++ b/packages/core/src/transform/meshTransform.ts @@ -35,3 +35,36 @@ export function buildPolyMeshTransform( } return parts.length > 0 ? parts.join(" ") : undefined; } + +/** + * Build the wrapper transform string for `` / ``. + * Applies world→CSS position swap, conjugated rotation, scale, and a trailing + * `translate(-cssWidth/2, -cssHeight/2)` so transforms pivot at the iframe center. + */ +export function buildPolyIframeTransform( + position: Vec3 | undefined, + rotation: Vec3 | undefined, + scale: number | Vec3 | undefined, + cssWidth: number, + cssHeight: number, +): string { + const sx = typeof scale === "number" ? scale : (scale?.[0] ?? 1); + const sy = typeof scale === "number" ? scale : (scale?.[1] ?? 1); + const sz = typeof scale === "number" ? scale : (scale?.[2] ?? 1); + const hasScale = sx !== 1 || sy !== 1 || sz !== 1; + const hasRotation = !!rotation && (!!rotation[0] || !!rotation[1] || !!rotation[2]); + const cssPos = position ? worldPositionToCss(position) : ([0, 0, 0] as Vec3); + + const parts: string[] = []; + parts.push(`translate3d(${cssPos[0]}px, ${cssPos[1]}px, ${cssPos[2]}px)`); + if (hasRotation) { + if (rotation![0]) parts.push(`rotateY(${-rotation![0]}deg)`); + if (rotation![1]) parts.push(`rotateX(${-rotation![1]}deg)`); + if (rotation![2]) parts.push(`rotateZ(${-rotation![2]}deg)`); + } + if (hasScale) { + parts.push(`scale3d(${sx}, ${sy}, ${sz})`); + } + parts.push(`translate(${-cssWidth / 2}px, ${-cssHeight / 2}px)`); + return parts.join(" "); +} diff --git a/packages/morph/src/prepare/compile.ts b/packages/morph/src/prepare/compile.ts index c27aec302..7eb2ecf63 100644 --- a/packages/morph/src/prepare/compile.ts +++ b/packages/morph/src/prepare/compile.ts @@ -1,5 +1,6 @@ import { computeSolidTrianglePlanFromCssPoints, + crossVec as cross, SOLID_TRIANGLE_CANONICAL_SIZE, type Polygon, } from "@layoutit/polycss-core"; @@ -132,13 +133,6 @@ function subtract(left: PolyMorphVec3, right: PolyMorphVec3): PolyMorphVec3 { ]; } -function cross(left: PolyMorphVec3, right: PolyMorphVec3): PolyMorphVec3 { - return [ - left[1] * right[2] - left[2] * right[1], - left[2] * right[0] - left[0] * right[2], - left[0] * right[1] - left[1] * right[0], - ]; -} function normalise(value: readonly number[], path: string): PolyMorphVec3 { const length = Math.hypot(...value); diff --git a/packages/polycss/src/api/controls/pointerControlsCore.ts b/packages/polycss/src/api/controls/pointerControlsCore.ts new file mode 100644 index 000000000..b4c315e11 --- /dev/null +++ b/packages/polycss/src/api/controls/pointerControlsCore.ts @@ -0,0 +1,306 @@ +/** + * Shared pointer/wheel camera controls engine powering both + * `createPolyOrbitControls` and `createPolyMapControls`. + */ +import { applyOrbit, applyPan } from "@layoutit/polycss-core"; +import type { PolyCameraControlTarget } from "../scene/types"; +import { + BASE_DEFAULTS, + resolveOptions, + makeListenerRegistry, + makeCameraSnapshot, + makeWheelHandler, + makeAnimLoop, + type PolyControlsBaseOptions, + type PolyControlsEvent, + type PolyControlsHandle, + type PolyControlsListener, + type ResolvedOptions, +} from "./common"; + +export type PointerControlsMode = "orbit" | "map"; + +export function createPointerControls( + scene: PolyCameraControlTarget, + mode: PointerControlsMode, + options: PolyControlsBaseOptions = {}, +): PolyControlsHandle { + let opts: ResolvedOptions = resolveOptions(BASE_DEFAULTS, options); + const host = scene.host; + const win = host.ownerDocument?.defaultView ?? globalThis; + + let activePointerId: number | null = null; + let pointer = { x: 0, y: 0 }; + let rightDragActive = false; + let rightPointer = { x: 0, y: 0 }; + let dragStylesApplied = false; + let animPaused = false; + let stopped = false; + + const registry = makeListenerRegistry(); + const snapshot = makeCameraSnapshot(scene); + const { + changeListeners, + startListeners, + endListeners, + listenerArray, + emitChange, + emitInteraction, + } = registry; + + const animLoop = makeAnimLoop( + win as typeof globalThis, + scene, + () => opts, + () => stopped, + () => animPaused, + snapshot, + emitChange, + ); + + function syncDragStyles(): void { + if (!stopped && opts.drag) { + host.style.cursor = activePointerId !== null ? "grabbing" : "grab"; + host.style.touchAction = "none"; + host.style.userSelect = "none"; + dragStylesApplied = true; + } else if (dragStylesApplied) { + host.style.cursor = ""; + host.style.touchAction = ""; + host.style.userSelect = ""; + dragStylesApplied = false; + } + } + + function applyPanDelta(dx: number, dy: number): void { + const cameraState = scene.camera.state; + const { targetD0, targetD1 } = applyPan( + dx, + dy, + cameraState.zoom ?? 1, + cameraState.rotX ?? 65, + cameraState.rotY ?? 45, + ); + const t = cameraState.target ?? [0, 0, 0]; + scene.camera.update({ target: [t[0] + targetD0, t[1] + targetD1, t[2]] }); + } + + function applyOrbitDelta(dx: number, dy: number, clampGroundTilt: boolean): void { + const cameraState = scene.camera.state; + const next = applyOrbit( + dx, + dy, + cameraState.rotX ?? 65, + cameraState.rotY ?? 45, + opts.invert, + ); + // In orbit mode clamp rotX to [0, 89] so the floor's +Z normal never flips + // away from the camera and vanishes with its cast shadows. + const rotX = clampGroundTilt ? Math.max(0, Math.min(89, next.rotX)) : next.rotX; + scene.camera.update({ rotX, rotY: next.rotY }); + } + + const onPointerDown = (e: PointerEvent): void => { + if (!opts.drag || stopped) return; + if (e.button === 2) return; + if (activePointerId !== null) return; + if (e.isPrimary === false) return; + e.preventDefault(); + activePointerId = e.pointerId; + pointer = { x: e.clientX, y: e.clientY }; + host.style.cursor = "grabbing"; + dragStylesApplied = true; + try { + (e.target as Element).setPointerCapture(e.pointerId); + } catch { + /* ignore */ + } + if (opts.animate && opts.animate.pauseOnInteraction) { + animPaused = true; + } + emitInteraction("start", snapshot); + }; + + const onPointerMove = (e: PointerEvent): void => { + if (activePointerId === null || e.pointerId !== activePointerId) return; + if (!opts.drag || stopped) return; + e.preventDefault(); + const dx = e.clientX - pointer.x; + const dy = e.clientY - pointer.y; + pointer = { x: e.clientX, y: e.clientY }; + + const shouldPan = mode === "orbit" ? e.shiftKey : !e.shiftKey; + if (shouldPan) { + applyPanDelta(dx, dy); + } else { + applyOrbitDelta(dx, dy, mode === "orbit"); + } + scene.applyCamera(); + emitChange(snapshot); + }; + + const onPointerUp = (e: PointerEvent): void => { + if (activePointerId !== e.pointerId) return; + activePointerId = null; + syncDragStyles(); + try { + (e.target as Element).releasePointerCapture(e.pointerId); + } catch { + /* ignore */ + } + if (opts.animate && opts.animate.pauseOnInteraction) { + animPaused = false; + } + emitInteraction("end", snapshot); + }; + + const onContextMenu = (e: Event): void => { + if (!opts.drag || stopped) return; + e.preventDefault(); + }; + + const onMouseDown = (e: MouseEvent): void => { + if (!opts.drag || stopped) return; + if (e.button !== 2) return; + rightDragActive = true; + rightPointer = { x: e.clientX, y: e.clientY }; + if (opts.animate && opts.animate.pauseOnInteraction) { + animPaused = true; + } + emitInteraction("start", snapshot); + }; + + const onMouseMove = (e: MouseEvent): void => { + if (!rightDragActive || !opts.drag || stopped) return; + const dx = e.clientX - rightPointer.x; + const dy = e.clientY - rightPointer.y; + rightPointer = { x: e.clientX, y: e.clientY }; + if (mode === "orbit") { + applyPanDelta(dx, dy); + } else { + applyOrbitDelta(dx, dy, false); + } + scene.applyCamera(); + emitChange(snapshot); + }; + + const onMouseUp = (e: MouseEvent): void => { + if (e.button !== 2) return; + if (rightDragActive) { + rightDragActive = false; + if (opts.animate && opts.animate.pauseOnInteraction) { + animPaused = false; + } + emitInteraction("end", snapshot); + } + }; + + const wheelHandler = makeWheelHandler( + scene, + () => opts, + () => stopped, + snapshot, + emitChange, + emitInteraction, + ); + + function attach(): void { + host.addEventListener("pointerdown", onPointerDown); + host.addEventListener("pointermove", onPointerMove); + host.addEventListener("pointerup", onPointerUp); + host.addEventListener("pointercancel", onPointerUp); + host.addEventListener("wheel", wheelHandler.onWheel, { passive: false }); + host.addEventListener("contextmenu", onContextMenu); + host.addEventListener("mousedown", onMouseDown); + host.addEventListener("mousemove", onMouseMove); + host.addEventListener("mouseup", onMouseUp); + syncDragStyles(); + } + + function detach(): void { + host.removeEventListener("pointerdown", onPointerDown); + host.removeEventListener("pointermove", onPointerMove); + host.removeEventListener("pointerup", onPointerUp); + host.removeEventListener("pointercancel", onPointerUp); + host.removeEventListener("wheel", wheelHandler.onWheel); + host.removeEventListener("contextmenu", onContextMenu); + host.removeEventListener("mousedown", onMouseDown); + host.removeEventListener("mousemove", onMouseMove); + host.removeEventListener("mouseup", onMouseUp); + if (dragStylesApplied) { + host.style.cursor = ""; + host.style.touchAction = ""; + host.style.userSelect = ""; + dragStylesApplied = false; + } + wheelHandler.teardown(); + } + + attach(); + animLoop.start(); + + function update(partial: PolyControlsBaseOptions): void { + const wasAnimating = !!opts.animate; + opts = resolveOptions(opts, partial); + if (!stopped && activePointerId === null) { + syncDragStyles(); + } + const isAnimating = !!opts.animate; + if (wasAnimating && !isAnimating) { + animLoop.stop(); + } else if (!wasAnimating && isAnimating) { + animLoop.start(); + } + } + + function resume(): void { + if (!stopped) return; + stopped = false; + attach(); + animLoop.start(); + } + + function pause(): void { + if (stopped) return; + stopped = true; + detach(); + animLoop.stop(); + activePointerId = null; + rightDragActive = false; + animPaused = false; + wheelHandler.teardown(); + } + + function destroy(): void { + pause(); + changeListeners.length = 0; + startListeners.length = 0; + endListeners.length = 0; + } + + function addEventListener( + type: T, + listener: PolyControlsListener>, + ): void { + const arr = listenerArray(type); + if (!arr.includes(listener as PolyControlsListener)) arr.push(listener as PolyControlsListener); + } + + function removeEventListener( + type: T, + listener: PolyControlsListener>, + ): void { + const arr = listenerArray(type); + const idx = arr.indexOf(listener as PolyControlsListener); + if (idx >= 0) arr.splice(idx, 1); + } + + function hasEventListener( + type: T, + listener: PolyControlsListener>, + ): boolean { + return listenerArray(type).includes(listener as PolyControlsListener); + } + + return { update, resume, pause, destroy, addEventListener, removeEventListener, hasEventListener }; +} diff --git a/packages/polycss/src/api/createPolyMapControls.ts b/packages/polycss/src/api/createPolyMapControls.ts index 34ff984ec..b51a70ab5 100644 --- a/packages/polycss/src/api/createPolyMapControls.ts +++ b/packages/polycss/src/api/createPolyMapControls.ts @@ -1,29 +1,12 @@ /** * createPolyMapControls — map/pan-mode camera input for a PolyScene. * - * Left-drag pans the target (slippy-map semantics — terrain follows pointer). - * Right-drag or Shift+left-drag orbits. Wheel zooms or dollies. - * Mirrors Three.js MapControls semantics. - * - * For orbit-only semantics (left-drag orbits) use `createPolyOrbitControls` - * instead. + * Left-drag pans (slippy-map semantics), Shift+left-drag or right-drag orbits, + * wheel zooms or dollies. Mirrors Three.js MapControls semantics. */ - -import { applyOrbit, applyPan } from "@layoutit/polycss-core"; import type { PolyCameraControlTarget } from "./scene/types"; -import { - BASE_DEFAULTS, - resolveOptions, - makeListenerRegistry, - makeCameraSnapshot, - makeWheelHandler, - makeAnimLoop, - type PolyControlsBaseOptions, - type PolyControlsHandle, - type PolyControlsEvent, - type PolyControlsListener, - type ResolvedOptions, -} from "./controls/common"; +import type { PolyControlsBaseOptions, PolyControlsHandle } from "./controls/common"; +import { createPointerControls } from "./controls/pointerControlsCore"; export type { PolyControlsAnimateOptions, @@ -42,249 +25,5 @@ export function createPolyMapControls( scene: PolyCameraControlTarget, options: PolyMapControlsOptions = {}, ): PolyMapControlsHandle { - let opts: ResolvedOptions = resolveOptions(BASE_DEFAULTS, options); - const host = scene.host; - const win = host.ownerDocument?.defaultView ?? globalThis; - - let activePointerId: number | null = null; - let pointer = { x: 0, y: 0 }; - let dragStylesApplied = false; - let animPaused = false; - let stopped = false; - - // Right-drag state for orbit via right button - let rightDragActive = false; - let rightPointer = { x: 0, y: 0 }; - - const registry = makeListenerRegistry(); - const snapshot = makeCameraSnapshot(scene); - const { changeListeners, startListeners, endListeners, listenerArray, emitChange, emitInteraction } = registry; - - const animLoop = makeAnimLoop( - win as typeof globalThis, - scene, - () => opts, - () => stopped, - () => animPaused, - snapshot, - emitChange, - ); - - function syncDragStyles(): void { - if (!stopped && opts.drag) { - host.style.cursor = activePointerId !== null ? "grabbing" : "grab"; - host.style.touchAction = "none"; - host.style.userSelect = "none"; - dragStylesApplied = true; - } else if (dragStylesApplied) { - host.style.cursor = ""; - host.style.touchAction = ""; - host.style.userSelect = ""; - dragStylesApplied = false; - } - } - - // ── Left-drag: pan ──────────────────────────────────────────────────────── - const onPointerDown = (e: PointerEvent): void => { - if (!opts.drag || stopped) return; - if (e.button === 2) return; - if (activePointerId !== null) return; - if (e.isPrimary === false) return; - e.preventDefault(); - activePointerId = e.pointerId; - pointer = { x: e.clientX, y: e.clientY }; - host.style.cursor = "grabbing"; - dragStylesApplied = true; - try { (e.target as Element).setPointerCapture(e.pointerId); } catch { /* ignore */ } - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = true; - } - emitInteraction("start", snapshot); - }; - - const onPointerMove = (e: PointerEvent): void => { - if (activePointerId === null || e.pointerId !== activePointerId) return; - if (!opts.drag || stopped) return; - e.preventDefault(); - const dx = e.clientX - pointer.x; - const dy = e.clientY - pointer.y; - pointer = { x: e.clientX, y: e.clientY }; - const cameraState = scene.camera.state; - - if (e.shiftKey) { - // Shift+left-drag orbits - const next = applyOrbit(dx, dy, cameraState.rotX ?? 65, cameraState.rotY ?? 45, opts.invert); - scene.camera.update({ rotX: next.rotX, rotY: next.rotY }); - } else { - // Left-drag pans (slippy-map semantics) - const { targetD0, targetD1 } = applyPan( - dx, - dy, - cameraState.zoom ?? 1, - cameraState.rotX ?? 65, - cameraState.rotY ?? 45, - ); - const t = cameraState.target ?? [0, 0, 0]; - scene.camera.update({ target: [t[0] + targetD0, t[1] + targetD1, t[2]] }); - } - scene.applyCamera(); - emitChange(snapshot); - }; - - const onPointerUp = (e: PointerEvent): void => { - if (activePointerId !== e.pointerId) return; - activePointerId = null; - syncDragStyles(); - try { (e.target as Element).releasePointerCapture(e.pointerId); } catch { /* ignore */ } - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = false; - } - emitInteraction("end", snapshot); - }; - - // ── Right-drag: orbit ──────────────────────────────────────────────────── - const onContextMenu = (e: Event): void => { - if (!opts.drag || stopped) return; - e.preventDefault(); - }; - - const onMouseDown = (e: MouseEvent): void => { - if (!opts.drag || stopped) return; - if (e.button !== 2) return; - rightDragActive = true; - rightPointer = { x: e.clientX, y: e.clientY }; - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = true; - } - emitInteraction("start", snapshot); - }; - - const onMouseMove = (e: MouseEvent): void => { - if (!rightDragActive || !opts.drag) return; - const dx = e.clientX - rightPointer.x; - const dy = e.clientY - rightPointer.y; - rightPointer = { x: e.clientX, y: e.clientY }; - const cameraState = scene.camera.state; - const next = applyOrbit(dx, dy, cameraState.rotX ?? 65, cameraState.rotY ?? 45, opts.invert); - scene.camera.update({ rotX: next.rotX, rotY: next.rotY }); - scene.applyCamera(); - emitChange(snapshot); - }; - - const onMouseUp = (e: MouseEvent): void => { - if (e.button !== 2) return; - if (rightDragActive) { - rightDragActive = false; - emitInteraction("end", snapshot); - } - }; - - const wheelHandler = makeWheelHandler( - scene, - () => opts, - () => stopped, - snapshot, - emitChange, - emitInteraction, - ); - - function attach(): void { - host.addEventListener("pointerdown", onPointerDown); - host.addEventListener("pointermove", onPointerMove); - host.addEventListener("pointerup", onPointerUp); - host.addEventListener("pointercancel", onPointerUp); - host.addEventListener("wheel", wheelHandler.onWheel, { passive: false }); - host.addEventListener("contextmenu", onContextMenu); - host.addEventListener("mousedown", onMouseDown); - host.addEventListener("mousemove", onMouseMove); - host.addEventListener("mouseup", onMouseUp); - syncDragStyles(); - } - - function detach(): void { - host.removeEventListener("pointerdown", onPointerDown); - host.removeEventListener("pointermove", onPointerMove); - host.removeEventListener("pointerup", onPointerUp); - host.removeEventListener("pointercancel", onPointerUp); - host.removeEventListener("wheel", wheelHandler.onWheel); - host.removeEventListener("contextmenu", onContextMenu); - host.removeEventListener("mousedown", onMouseDown); - host.removeEventListener("mousemove", onMouseMove); - host.removeEventListener("mouseup", onMouseUp); - if (dragStylesApplied) { - host.style.cursor = ""; - host.style.touchAction = ""; - host.style.userSelect = ""; - dragStylesApplied = false; - } - wheelHandler.teardown(); - } - - attach(); - animLoop.start(); - - function update(partial: PolyMapControlsOptions): void { - const wasAnimating = !!opts.animate; - opts = resolveOptions(opts, partial); - if (!stopped && activePointerId === null) { - syncDragStyles(); - } - const isAnimating = !!opts.animate; - if (wasAnimating && !isAnimating) { - animLoop.stop(); - } else if (!wasAnimating && isAnimating) { - animLoop.start(); - } - } - - function resume(): void { - if (!stopped) return; - stopped = false; - attach(); - animLoop.start(); - } - - function pause(): void { - if (stopped) return; - stopped = true; - detach(); - animLoop.stop(); - activePointerId = null; - animPaused = false; - rightDragActive = false; - wheelHandler.teardown(); - } - - function destroy(): void { - pause(); - changeListeners.length = 0; - startListeners.length = 0; - endListeners.length = 0; - } - - function addEventListener( - type: T, - listener: PolyControlsListener>, - ): void { - const arr = listenerArray(type); - if (!arr.includes(listener as PolyControlsListener)) arr.push(listener as PolyControlsListener); - } - - function removeEventListener( - type: T, - listener: PolyControlsListener>, - ): void { - const arr = listenerArray(type); - const idx = arr.indexOf(listener as PolyControlsListener); - if (idx >= 0) arr.splice(idx, 1); - } - - function hasEventListener( - type: T, - listener: PolyControlsListener>, - ): boolean { - return listenerArray(type).includes(listener as PolyControlsListener); - } - - return { update, resume, pause, destroy, addEventListener, removeEventListener, hasEventListener }; + return createPointerControls(scene, "map", options); } diff --git a/packages/polycss/src/api/createPolyOrbitControls.ts b/packages/polycss/src/api/createPolyOrbitControls.ts index 1a1b49f73..d959d155c 100644 --- a/packages/polycss/src/api/createPolyOrbitControls.ts +++ b/packages/polycss/src/api/createPolyOrbitControls.ts @@ -1,28 +1,12 @@ /** * createPolyOrbitControls — orbit-mode camera input for a PolyScene. * - * Left-drag rotates rotX / rotY around the target (orbit). Wheel zooms or - * dollies. Mirrors Three.js OrbitControls semantics. - * - * For map/pan semantics (left-drag pans, right-drag orbits) use - * `createPolyMapControls` instead. + * Left-drag orbits, Shift+left-drag or right-drag pans, wheel zooms or dollies. + * Mirrors Three.js OrbitControls semantics. */ - -import { applyOrbit, applyPan } from "@layoutit/polycss-core"; import type { PolyCameraControlTarget } from "./scene/types"; -import { - BASE_DEFAULTS, - resolveOptions, - makeListenerRegistry, - makeCameraSnapshot, - makeWheelHandler, - makeAnimLoop, - type PolyControlsBaseOptions, - type PolyControlsHandle, - type PolyControlsEvent, - type PolyControlsListener, - type ResolvedOptions, -} from "./controls/common"; +import type { PolyControlsBaseOptions, PolyControlsHandle } from "./controls/common"; +import { createPointerControls } from "./controls/pointerControlsCore"; export type { PolyControlsAnimateOptions, @@ -41,265 +25,5 @@ export function createPolyOrbitControls( scene: PolyCameraControlTarget, options: PolyOrbitControlsOptions = {}, ): PolyOrbitControlsHandle { - let opts: ResolvedOptions = resolveOptions(BASE_DEFAULTS, options); - const host = scene.host; - const win = host.ownerDocument?.defaultView ?? globalThis; - - let activePointerId: number | null = null; - let pointer = { x: 0, y: 0 }; - let rightDragActive = false; - let rightPointer = { x: 0, y: 0 }; - let dragStylesApplied = false; - let animPaused = false; - let stopped = false; - - const registry = makeListenerRegistry(); - const snapshot = makeCameraSnapshot(scene); - const { changeListeners, startListeners, endListeners, listenerArray, emitChange, emitInteraction } = registry; - - const animLoop = makeAnimLoop( - win as typeof globalThis, - scene, - () => opts, - () => stopped, - () => animPaused, - snapshot, - emitChange, - ); - - function syncDragStyles(): void { - if (!stopped && opts.drag) { - host.style.cursor = activePointerId !== null ? "grabbing" : "grab"; - host.style.touchAction = "none"; - host.style.userSelect = "none"; - dragStylesApplied = true; - } else if (dragStylesApplied) { - host.style.cursor = ""; - host.style.touchAction = ""; - host.style.userSelect = ""; - dragStylesApplied = false; - } - } - - // ── Pointer drag (orbit) ───────────────────────────────────────────────── - const onPointerDown = (e: PointerEvent): void => { - if (!opts.drag || stopped) return; - if (e.button === 2) return; - if (activePointerId !== null) return; - if (e.isPrimary === false) return; - e.preventDefault(); - activePointerId = e.pointerId; - pointer = { x: e.clientX, y: e.clientY }; - host.style.cursor = "grabbing"; - dragStylesApplied = true; - try { (e.target as Element).setPointerCapture(e.pointerId); } catch { /* ignore */ } - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = true; - } - emitInteraction("start", snapshot); - }; - - const onPointerMove = (e: PointerEvent): void => { - if (activePointerId === null || e.pointerId !== activePointerId) return; - if (!opts.drag || stopped) return; - e.preventDefault(); - const dx = e.clientX - pointer.x; - const dy = e.clientY - pointer.y; - pointer = { x: e.clientX, y: e.clientY }; - const cameraState = scene.camera.state; - if (e.shiftKey) { - // Shift+left-drag pans (slippy-map semantics) - const { targetD0, targetD1 } = applyPan( - dx, - dy, - cameraState.zoom ?? 1, - cameraState.rotX ?? 65, - cameraState.rotY ?? 45, - ); - const t = cameraState.target ?? [0, 0, 0]; - scene.camera.update({ target: [t[0] + targetD0, t[1] + targetD1, t[2]] }); - } else { - // Left-drag orbits. - // rotX is clamped to [0, 89]: at 0 the camera is looking straight - // down at the scene (floor's +Z normal faces the camera); rotating - // PAST 90 flips the floor's normal away from camera, so its - // `backface-visibility: hidden` leaf vanishes and any cast shadow - // ON the floor vanishes with it. The old upper bound of 100 let a - // user drag the camera into that back-facing region (visible in the - // gallery as "the ground disappears when I rotate up"); stop at 89 - // so the floor stays visible at the steepest practical tilt. - const next = applyOrbit(dx, dy, cameraState.rotX ?? 65, cameraState.rotY ?? 45, opts.invert); - scene.camera.update({ rotX: Math.max(0, Math.min(89, next.rotX)), rotY: next.rotY }); - } - scene.applyCamera(); - emitChange(snapshot); - }; - - const onPointerUp = (e: PointerEvent): void => { - if (activePointerId !== e.pointerId) return; - activePointerId = null; - syncDragStyles(); - try { (e.target as Element).releasePointerCapture(e.pointerId); } catch { /* ignore */ } - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = false; - // Reset lastTime to avoid a catch-up jump equal to drag duration. - } - emitInteraction("end", snapshot); - }; - - // ── Right-drag: pan ────────────────────────────────────────────────────── - const onContextMenu = (e: Event): void => { - if (!opts.drag || stopped) return; - e.preventDefault(); - }; - - const onMouseDown = (e: MouseEvent): void => { - if (!opts.drag || stopped) return; - if (e.button !== 2) return; - rightDragActive = true; - rightPointer = { x: e.clientX, y: e.clientY }; - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = true; - } - emitInteraction("start", snapshot); - }; - - const onMouseMove = (e: MouseEvent): void => { - if (!rightDragActive || !opts.drag || stopped) return; - const dx = e.clientX - rightPointer.x; - const dy = e.clientY - rightPointer.y; - rightPointer = { x: e.clientX, y: e.clientY }; - const cameraState = scene.camera.state; - const { targetD0, targetD1 } = applyPan( - dx, - dy, - cameraState.zoom ?? 1, - cameraState.rotX ?? 65, - cameraState.rotY ?? 45, - ); - const t = cameraState.target ?? [0, 0, 0]; - scene.camera.update({ target: [t[0] + targetD0, t[1] + targetD1, t[2]] }); - scene.applyCamera(); - emitChange(snapshot); - }; - - const onMouseUp = (e: MouseEvent): void => { - if (e.button !== 2) return; - if (rightDragActive) { - rightDragActive = false; - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = false; - } - emitInteraction("end", snapshot); - } - }; - - const wheelHandler = makeWheelHandler( - scene, - () => opts, - () => stopped, - snapshot, - emitChange, - emitInteraction, - ); - - function attach(): void { - host.addEventListener("pointerdown", onPointerDown); - host.addEventListener("pointermove", onPointerMove); - host.addEventListener("pointerup", onPointerUp); - host.addEventListener("pointercancel", onPointerUp); - host.addEventListener("wheel", wheelHandler.onWheel, { passive: false }); - host.addEventListener("contextmenu", onContextMenu); - host.addEventListener("mousedown", onMouseDown); - host.addEventListener("mousemove", onMouseMove); - host.addEventListener("mouseup", onMouseUp); - syncDragStyles(); - } - - function detach(): void { - host.removeEventListener("pointerdown", onPointerDown); - host.removeEventListener("pointermove", onPointerMove); - host.removeEventListener("pointerup", onPointerUp); - host.removeEventListener("pointercancel", onPointerUp); - host.removeEventListener("wheel", wheelHandler.onWheel); - host.removeEventListener("contextmenu", onContextMenu); - host.removeEventListener("mousedown", onMouseDown); - host.removeEventListener("mousemove", onMouseMove); - host.removeEventListener("mouseup", onMouseUp); - if (dragStylesApplied) { - host.style.cursor = ""; - host.style.touchAction = ""; - host.style.userSelect = ""; - dragStylesApplied = false; - } - wheelHandler.teardown(); - } - - attach(); - animLoop.start(); - - function update(partial: PolyOrbitControlsOptions): void { - const wasAnimating = !!opts.animate; - opts = resolveOptions(opts, partial); - if (!stopped && activePointerId === null) { - syncDragStyles(); - } - const isAnimating = !!opts.animate; - if (wasAnimating && !isAnimating) { - animLoop.stop(); - } else if (!wasAnimating && isAnimating) { - animLoop.start(); - } - } - - function resume(): void { - if (!stopped) return; - stopped = false; - attach(); - animLoop.start(); - } - - function pause(): void { - if (stopped) return; - stopped = true; - detach(); - animLoop.stop(); - activePointerId = null; - rightDragActive = false; - animPaused = false; - wheelHandler.teardown(); - } - - function destroy(): void { - pause(); - changeListeners.length = 0; - startListeners.length = 0; - endListeners.length = 0; - } - - function addEventListener( - type: T, - listener: PolyControlsListener>, - ): void { - const arr = listenerArray(type); - if (!arr.includes(listener as PolyControlsListener)) arr.push(listener as PolyControlsListener); - } - - function removeEventListener( - type: T, - listener: PolyControlsListener>, - ): void { - const arr = listenerArray(type); - const idx = arr.indexOf(listener as PolyControlsListener); - if (idx >= 0) arr.splice(idx, 1); - } - - function hasEventListener( - type: T, - listener: PolyControlsListener>, - ): boolean { - return listenerArray(type).includes(listener as PolyControlsListener); - } - - return { update, resume, pause, destroy, addEventListener, removeEventListener, hasEventListener }; + return createPointerControls(scene, "orbit", options); } diff --git a/packages/polycss/src/elements/PolyDirectionalLightHelperElement.ts b/packages/polycss/src/elements/PolyDirectionalLightHelperElement.ts index da3ba26ac..442a480ba 100644 --- a/packages/polycss/src/elements/PolyDirectionalLightHelperElement.ts +++ b/packages/polycss/src/elements/PolyDirectionalLightHelperElement.ts @@ -14,6 +14,7 @@ import { octahedronPolygons } from "@layoutit/polycss-core"; import type { ParseResult, Vec3 } from "@layoutit/polycss-core"; import type { PolyMeshHandle } from "../api/createPolyScene"; import type { PolySceneElement } from "./PolySceneElement"; +import { parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -36,15 +37,6 @@ function findScene(el: HTMLElement): PolySceneElement | null { return (el.closest("poly-scene") as unknown as PolySceneElement | null) ?? null; } -function parseVec3(value: string | null): Vec3 | undefined { - if (!value) return undefined; - const parts = value.split(",").map((p) => parseFloat(p.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) { - return undefined; - } - return [parts[0], parts[1], parts[2]]; -} - function parseNumber(value: string | null, fallback: number): number { if (value == null) return fallback; const n = parseFloat(value); diff --git a/packages/polycss/src/elements/PolyIframeElement.ts b/packages/polycss/src/elements/PolyIframeElement.ts index 64d332c18..4eee141f4 100644 --- a/packages/polycss/src/elements/PolyIframeElement.ts +++ b/packages/polycss/src/elements/PolyIframeElement.ts @@ -20,9 +20,12 @@ * wrapper div + iframe inside the scene's `.polycss-scene` element so * the CSS camera transform applies. On disconnect: removes the wrapper. */ -import { BASE_TILE } from "@layoutit/polycss-core"; +import { BASE_TILE, buildPolyIframeTransform } from "@layoutit/polycss-core"; import type { Vec3 } from "@layoutit/polycss-core"; import type { PolySceneElement } from "./PolySceneElement"; +import { parseVec3 } from "./parseAttr"; + +export { buildPolyIframeTransform as buildIframeTransform }; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -43,13 +46,6 @@ const OBSERVED_ATTRS = [ "title", ] as const; -function parseVec3(value: string | null): Vec3 | undefined { - if (!value) return undefined; - const parts = value.split(",").map((p) => parseFloat(p.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) return undefined; - return [parts[0], parts[1], parts[2]]; -} - function parseScale(value: string | null): number | Vec3 | undefined { if (!value) return undefined; if (!value.includes(",")) { @@ -75,50 +71,6 @@ function findSceneRoot(el: HTMLElement): HTMLElement | null { return sceneCustomEl.querySelector(".polycss-scene") as HTMLElement | null; } -/** - * Build the wrapper transform string. Mirrors `buildMeshTransform` in - * `packages/polycss/src/api/scene/transforms.ts` exactly — world→CSS axis - * swap on position, rotation conjugation (`rotateY(-rx) rotateX(-ry) - * rotateZ(-rz)` because the swap reflects axes, det=-1), scale at the - * end. The trailing `translate(-w/2, -h/2)` is the only addition: it - * centers the iframe content at the wrapper's local origin (otherwise the - * iframe would extend from (0,0) to (w,h) and rotation would pivot at the - * iframe's corner). - */ -export function buildIframeTransform( - position: Vec3 | undefined, - rotation: Vec3 | undefined, - scale: number | Vec3 | undefined, - cssWidth: number, - cssHeight: number, -): string { - const sx = typeof scale === "number" ? scale : (scale?.[0] ?? 1); - const sy = typeof scale === "number" ? scale : (scale?.[1] ?? 1); - const sz = typeof scale === "number" ? scale : (scale?.[2] ?? 1); - const hasScale = sx !== 1 || sy !== 1 || sz !== 1; - const hasRotation = !!rotation && (!!rotation[0] || !!rotation[1] || !!rotation[2]); - const cssX = (position?.[1] ?? 0) * BASE_TILE; - const cssY = (position?.[0] ?? 0) * BASE_TILE; - const cssZ = (position?.[2] ?? 0) * BASE_TILE; - - const parts: string[] = []; - parts.push(`translate3d(${cssX}px, ${cssY}px, ${cssZ}px)`); - if (hasRotation) { - if (rotation![0]) parts.push(`rotateY(${-rotation![0]}deg)`); - if (rotation![1]) parts.push(`rotateX(${-rotation![1]}deg)`); - if (rotation![2]) parts.push(`rotateZ(${-rotation![2]}deg)`); - } - if (hasScale) { - parts.push(`scale3d(${sx}, ${sy}, ${sz})`); - } - // 2D translate at the end: rotation/scale operate on the centered - // iframe, then the centering offset is applied. Order matters — placing - // this before rotation would rotate the offset itself and the iframe - // would orbit instead of spinning in place. - parts.push(`translate(${-cssWidth / 2}px, ${-cssHeight / 2}px)`); - return parts.join(" "); -} - export class PolyIframeElement extends ELEMENT_BASE { static get observedAttributes(): string[] { return [...OBSERVED_ATTRS]; @@ -210,7 +162,7 @@ export class PolyIframeElement extends ELEMENT_BASE { const position = parseVec3(this.getAttribute("position")); const rotation = parseVec3(this.getAttribute("rotation")); const scale = parseScale(this.getAttribute("scale")); - this._wrapper.style.transform = buildIframeTransform(position, rotation, scale, cssW, cssH); + this._wrapper.style.transform = buildPolyIframeTransform(position, rotation, scale, cssW, cssH); } private _teardown(): void { diff --git a/packages/polycss/src/elements/PolyMapControlsElement.ts b/packages/polycss/src/elements/PolyMapControlsElement.ts index 6c127f1ef..be79d6fd0 100644 --- a/packages/polycss/src/elements/PolyMapControlsElement.ts +++ b/packages/polycss/src/elements/PolyMapControlsElement.ts @@ -1,141 +1,19 @@ /** * — declarative wrapper around `createPolyMapControls`. - * - * Behavior element: no rendered output. Sits inside and walks - * up via parent nodes to attach itself to the parent scene. - * Left-drag pans target (slippy-map semantics); right-drag or Shift+left - * orbits. The full options surface is exposed via kebab-case attributes: - * - * */ -import { PolySceneElement } from "./PolySceneElement"; +import type { PolySceneHandle } from "../api/createPolyScene"; import { createPolyMapControls, type PolyMapControlsHandle, type PolyMapControlsOptions, } from "../api/createPolyMapControls"; -import { parseNumber, parseBoolAttr, parseInvert, parseAxis } from "./parseAttr"; - -const ELEMENT_BASE: typeof HTMLElement = - typeof HTMLElement !== "undefined" - ? HTMLElement - : (class {} as unknown as typeof HTMLElement); - -const OBSERVED_ATTRS = [ - "drag", - "wheel", - "dolly", - "min-distance", - "max-distance", - "invert", - "zoom-min", - "zoom-max", - "animate-speed", - "animate-axis", - "animate-pause-on-interaction", -] as const; - - -export class PolyMapControlsElement extends ELEMENT_BASE { - static get observedAttributes(): string[] { - return [...OBSERVED_ATTRS]; - } - - private _controls: PolyMapControlsHandle | null = null; - - private _readAnimate(): PolyMapControlsOptions["animate"] | undefined { - const speed = parseNumber(this.getAttribute("animate-speed")); - const axis = parseAxis(this.getAttribute("animate-axis")); - const pauseAttr = this.getAttribute("animate-pause-on-interaction"); - const hasAny = - this.hasAttribute("animate-speed") || - this.hasAttribute("animate-axis") || - this.hasAttribute("animate-pause-on-interaction"); - if (!hasAny) return undefined; - return { - ...(speed !== undefined ? { speed } : {}), - ...(axis !== undefined ? { axis } : {}), - ...(pauseAttr !== null ? { pauseOnInteraction: parseBoolAttr(pauseAttr) } : {}), - }; - } - - private _readOptions(): PolyMapControlsOptions { - const opts: PolyMapControlsOptions = {}; - const drag = parseBoolAttr(this.getAttribute("drag")); - if (drag !== undefined) opts.drag = drag; - const wheel = parseBoolAttr(this.getAttribute("wheel")); - if (wheel !== undefined) opts.wheel = wheel; - if (this.hasAttribute("dolly")) opts.dolly = true; - const minDistance = parseNumber(this.getAttribute("min-distance")); - if (minDistance !== undefined) opts.minDistance = minDistance; - const maxDistance = parseNumber(this.getAttribute("max-distance")); - if (maxDistance !== undefined) opts.maxDistance = maxDistance; - const invert = parseInvert(this.getAttribute("invert")); - if (invert !== undefined) opts.invert = invert; - const zoomMin = parseNumber(this.getAttribute("zoom-min")); - const zoomMax = parseNumber(this.getAttribute("zoom-max")); - if (zoomMin !== undefined) opts.minZoom = zoomMin; - if (zoomMax !== undefined) opts.maxZoom = zoomMax; - opts.animate = this._readAnimate() ?? false; - return opts; - } - - private _findScene(): PolySceneElement | null { - let node: Node | null = this.parentNode; - while (node) { - if (node instanceof PolySceneElement) return node; - node = node.parentNode; - } - return null; - } - - private _attach(): void { - if (this._controls) return; - const sceneEl = this._findScene(); - const handle = sceneEl?.getScene(); - if (!handle) { - if (sceneEl) { - const onReady = (): void => { - sceneEl.removeEventListener("polycss:scene-ready", onReady); - this._attach(); - }; - sceneEl.addEventListener("polycss:scene-ready", onReady); - } - return; - } - this._controls = createPolyMapControls(handle, this._readOptions()); - } - - connectedCallback(): void { - this._attach(); - } - - disconnectedCallback(): void { - if (this._controls) { - this._controls.destroy(); - this._controls = null; - } - } - - attributeChangedCallback( - _name: string, - oldValue: string | null, - newValue: string | null, - ): void { - if (oldValue === newValue) return; - if (!this._controls) return; - this._controls.update(this._readOptions()); +import { PolyPointerControlsElement } from "./PolyPointerControlsElement"; + +export class PolyMapControlsElement extends PolyPointerControlsElement { + protected _createControls( + scene: PolySceneHandle, + options: PolyMapControlsOptions, + ): PolyMapControlsHandle { + return createPolyMapControls(scene, options); } } diff --git a/packages/polycss/src/elements/PolyMeshElement.ts b/packages/polycss/src/elements/PolyMeshElement.ts index b75491250..b8b081c84 100644 --- a/packages/polycss/src/elements/PolyMeshElement.ts +++ b/packages/polycss/src/elements/PolyMeshElement.ts @@ -10,10 +10,11 @@ * `auto-center` is currently honored by recentering vertices in-place before * registering; this matches `` semantics. */ -import type { MeshResolution, ObjParseOptions, ParseResult, Polygon, Vec3 } from "@layoutit/polycss-core"; -import { computeSceneBbox, loadMesh } from "@layoutit/polycss-core"; +import type { MeshResolution, ObjParseOptions, ParseResult, Vec3 } from "@layoutit/polycss-core"; +import { loadMesh, recenterPolygons as recenter } from "@layoutit/polycss-core"; import type { PolyMeshHandle } from "../api/createPolyScene"; import type { PolySceneElement } from "./PolySceneElement"; +import { parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -37,15 +38,6 @@ const OBSERVED_ATTRS = [ "exclude-objects", ] as const; -function parseVec3(value: string | null): Vec3 | undefined { - if (!value) return undefined; - const parts = value.split(",").map((p) => parseFloat(p.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) { - return undefined; - } - return [parts[0], parts[1], parts[2]]; -} - function parseScale(value: string | null): number | Vec3 | undefined { if (!value) return undefined; if (!value.includes(",")) { @@ -85,28 +77,6 @@ function findScene(el: HTMLElement): PolySceneElement | null { return found ?? null; } -function recenter(polygons: Polygon[]): Polygon[] { - if (polygons.length === 0) return polygons; - const bbox = computeSceneBbox(polygons); - const cx = (bbox.min[0] + bbox.max[0]) / 2; - const cy = (bbox.min[1] + bbox.max[1]) / 2; - const cz = (bbox.min[2] + bbox.max[2]) / 2; - if (cx === 0 && cy === 0 && cz === 0) return polygons; - const shift = (v: Vec3): Vec3 => [v[0] - cx, v[1] - cy, v[2] - cz]; - return polygons.map((p) => ({ - ...p, - vertices: p.vertices.map(shift), - ...(p.textureTriangles?.length - ? { - textureTriangles: p.textureTriangles.map((triangle) => ({ - ...triangle, - vertices: triangle.vertices.map(shift) as [Vec3, Vec3, Vec3], - })), - } - : null), - })); -} - export class PolyMeshElement extends ELEMENT_BASE { static get observedAttributes(): string[] { return [...OBSERVED_ATTRS]; diff --git a/packages/polycss/src/elements/PolyOrbitControlsElement.ts b/packages/polycss/src/elements/PolyOrbitControlsElement.ts index 99183eaed..9b773d191 100644 --- a/packages/polycss/src/elements/PolyOrbitControlsElement.ts +++ b/packages/polycss/src/elements/PolyOrbitControlsElement.ts @@ -1,149 +1,19 @@ /** * — declarative wrapper around `createPolyOrbitControls`. - * - * Behavior element: no rendered output. Sits inside and walks - * up via parent nodes to attach itself to the parent scene. - * The full options surface from createPolyOrbitControls is exposed via - * kebab-case attributes: - * - * */ -import { PolySceneElement } from "./PolySceneElement"; +import type { PolySceneHandle } from "../api/createPolyScene"; import { createPolyOrbitControls, type PolyOrbitControlsHandle, type PolyOrbitControlsOptions, } from "../api/createPolyOrbitControls"; -import { parseNumber, parseBoolAttr, parseInvert, parseAxis } from "./parseAttr"; - -const ELEMENT_BASE: typeof HTMLElement = - typeof HTMLElement !== "undefined" - ? HTMLElement - : (class {} as unknown as typeof HTMLElement); - -const OBSERVED_ATTRS = [ - "drag", - "wheel", - "dolly", - "min-distance", - "max-distance", - "invert", - "zoom-min", - "zoom-max", - "animate-speed", - "animate-axis", - "animate-pause-on-interaction", -] as const; - - -export class PolyOrbitControlsElement extends ELEMENT_BASE { - static get observedAttributes(): string[] { - return [...OBSERVED_ATTRS]; - } - - private _controls: PolyOrbitControlsHandle | null = null; - - /** Returns the wrapped PolyOrbitControlsHandle once the element has - * connected to its `` ancestor. Lets external callers attach - * `change` listeners (or call `update()` / `pause()`) the same way they - * would on a vanilla `createPolyOrbitControls(scene, ...)` handle. */ - getControls(): PolyOrbitControlsHandle | null { - return this._controls; - } - - private _readAnimate(): PolyOrbitControlsOptions["animate"] | undefined { - const speed = parseNumber(this.getAttribute("animate-speed")); - const axis = parseAxis(this.getAttribute("animate-axis")); - const pauseAttr = this.getAttribute("animate-pause-on-interaction"); - const hasAny = - this.hasAttribute("animate-speed") || - this.hasAttribute("animate-axis") || - this.hasAttribute("animate-pause-on-interaction"); - if (!hasAny) return undefined; - return { - ...(speed !== undefined ? { speed } : {}), - ...(axis !== undefined ? { axis } : {}), - ...(pauseAttr !== null ? { pauseOnInteraction: parseBoolAttr(pauseAttr) } : {}), - }; - } - - private _readOptions(): PolyOrbitControlsOptions { - const opts: PolyOrbitControlsOptions = {}; - const drag = parseBoolAttr(this.getAttribute("drag")); - if (drag !== undefined) opts.drag = drag; - const wheel = parseBoolAttr(this.getAttribute("wheel")); - if (wheel !== undefined) opts.wheel = wheel; - if (this.hasAttribute("dolly")) opts.dolly = true; - const minDistance = parseNumber(this.getAttribute("min-distance")); - if (minDistance !== undefined) opts.minDistance = minDistance; - const maxDistance = parseNumber(this.getAttribute("max-distance")); - if (maxDistance !== undefined) opts.maxDistance = maxDistance; - const invert = parseInvert(this.getAttribute("invert")); - if (invert !== undefined) opts.invert = invert; - const zoomMin = parseNumber(this.getAttribute("zoom-min")); - const zoomMax = parseNumber(this.getAttribute("zoom-max")); - if (zoomMin !== undefined) opts.minZoom = zoomMin; - if (zoomMax !== undefined) opts.maxZoom = zoomMax; - opts.animate = this._readAnimate() ?? false; - return opts; - } - - private _findScene(): PolySceneElement | null { - let node: Node | null = this.parentNode; - while (node) { - if (node instanceof PolySceneElement) return node; - node = node.parentNode; - } - return null; - } - - private _attach(): void { - if (this._controls) return; - const sceneEl = this._findScene(); - const handle = sceneEl?.getScene(); - if (!handle) { - if (sceneEl) { - const onReady = (): void => { - sceneEl.removeEventListener("polycss:scene-ready", onReady); - this._attach(); - }; - sceneEl.addEventListener("polycss:scene-ready", onReady); - } - return; - } - this._controls = createPolyOrbitControls(handle, this._readOptions()); - } - - connectedCallback(): void { - this._attach(); - } - - disconnectedCallback(): void { - if (this._controls) { - this._controls.destroy(); - this._controls = null; - } - } - - attributeChangedCallback( - _name: string, - oldValue: string | null, - newValue: string | null, - ): void { - if (oldValue === newValue) return; - if (!this._controls) return; - this._controls.update(this._readOptions()); +import { PolyPointerControlsElement } from "./PolyPointerControlsElement"; + +export class PolyOrbitControlsElement extends PolyPointerControlsElement { + protected _createControls( + scene: PolySceneHandle, + options: PolyOrbitControlsOptions, + ): PolyOrbitControlsHandle { + return createPolyOrbitControls(scene, options); } } diff --git a/packages/polycss/src/elements/PolyPointerControlsElement.ts b/packages/polycss/src/elements/PolyPointerControlsElement.ts new file mode 100644 index 000000000..c8ebba2b5 --- /dev/null +++ b/packages/polycss/src/elements/PolyPointerControlsElement.ts @@ -0,0 +1,128 @@ +/** + * Shared base custom element for `` and + * ``. + */ +import { PolySceneElement } from "./PolySceneElement"; +import type { PolySceneHandle } from "../api/createPolyScene"; +import type { PolyControlsBaseOptions, PolyControlsHandle } from "../api/controls/common"; +import { parseNumber, parseBoolAttr, parseInvert, parseAxis } from "./parseAttr"; + +const ELEMENT_BASE: typeof HTMLElement = + typeof HTMLElement !== "undefined" + ? HTMLElement + : (class {} as unknown as typeof HTMLElement); + +const OBSERVED_ATTRS = [ + "drag", + "wheel", + "dolly", + "min-distance", + "max-distance", + "invert", + "zoom-min", + "zoom-max", + "animate-speed", + "animate-axis", + "animate-pause-on-interaction", +] as const; + +export abstract class PolyPointerControlsElement extends ELEMENT_BASE { + static get observedAttributes(): string[] { + return [...OBSERVED_ATTRS]; + } + + private _controls: PolyControlsHandle | null = null; + + protected abstract _createControls( + scene: PolySceneHandle, + options: PolyControlsBaseOptions, + ): PolyControlsHandle; + + getControls(): PolyControlsHandle | null { + return this._controls; + } + + private _readAnimate(): PolyControlsBaseOptions["animate"] | undefined { + const speed = parseNumber(this.getAttribute("animate-speed")); + const axis = parseAxis(this.getAttribute("animate-axis")); + const pauseAttr = this.getAttribute("animate-pause-on-interaction"); + const hasAny = + this.hasAttribute("animate-speed") || + this.hasAttribute("animate-axis") || + this.hasAttribute("animate-pause-on-interaction"); + if (!hasAny) return undefined; + return { + ...(speed !== undefined ? { speed } : {}), + ...(axis !== undefined ? { axis } : {}), + ...(pauseAttr !== null ? { pauseOnInteraction: parseBoolAttr(pauseAttr) } : {}), + }; + } + + private _readOptions(): PolyControlsBaseOptions { + const opts: PolyControlsBaseOptions = {}; + const drag = parseBoolAttr(this.getAttribute("drag")); + if (drag !== undefined) opts.drag = drag; + const wheel = parseBoolAttr(this.getAttribute("wheel")); + if (wheel !== undefined) opts.wheel = wheel; + if (this.hasAttribute("dolly")) opts.dolly = true; + const minDistance = parseNumber(this.getAttribute("min-distance")); + if (minDistance !== undefined) opts.minDistance = minDistance; + const maxDistance = parseNumber(this.getAttribute("max-distance")); + if (maxDistance !== undefined) opts.maxDistance = maxDistance; + const invert = parseInvert(this.getAttribute("invert")); + if (invert !== undefined) opts.invert = invert; + const zoomMin = parseNumber(this.getAttribute("zoom-min")); + const zoomMax = parseNumber(this.getAttribute("zoom-max")); + if (zoomMin !== undefined) opts.minZoom = zoomMin; + if (zoomMax !== undefined) opts.maxZoom = zoomMax; + opts.animate = this._readAnimate() ?? false; + return opts; + } + + private _findScene(): PolySceneElement | null { + let node: Node | null = this.parentNode; + while (node) { + if (node instanceof PolySceneElement) return node; + node = node.parentNode; + } + return null; + } + + private _attach(): void { + if (this._controls) return; + const sceneEl = this._findScene(); + const handle = sceneEl?.getScene(); + if (!handle) { + if (sceneEl) { + const onReady = (): void => { + sceneEl.removeEventListener("polycss:scene-ready", onReady); + this._attach(); + }; + sceneEl.addEventListener("polycss:scene-ready", onReady); + } + return; + } + this._controls = this._createControls(handle, this._readOptions()); + } + + connectedCallback(): void { + this._attach(); + } + + disconnectedCallback(): void { + if (this._controls) { + this._controls.destroy(); + this._controls = null; + } + } + + attributeChangedCallback( + _name: string, + oldValue: string | null, + newValue: string | null, + ): void { + if (oldValue === newValue) return; + if (!this._controls) return; + this._controls.update(this._readOptions()); + } +} diff --git a/packages/polycss/src/elements/PolyPolygonElement.ts b/packages/polycss/src/elements/PolyPolygonElement.ts index 5a9b85e47..05ad1f73d 100644 --- a/packages/polycss/src/elements/PolyPolygonElement.ts +++ b/packages/polycss/src/elements/PolyPolygonElement.ts @@ -11,6 +11,7 @@ import type { ParseResult, Polygon, Vec2, Vec3 } from "@layoutit/polycss-core"; import type { PolyMeshHandle } from "../api/createPolyScene"; import type { PolySceneElement } from "./PolySceneElement"; +import { parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -36,15 +37,6 @@ function parseJsonOrNull(value: string | null): T | null { } } -function parseVec3(value: string | null): Vec3 | undefined { - if (!value) return undefined; - const parts = value.split(",").map((p) => parseFloat(p.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) { - return undefined; - } - return [parts[0], parts[1], parts[2]]; -} - function parseScale(value: string | null): number | Vec3 | undefined { if (!value) return undefined; if (!value.includes(",")) { diff --git a/packages/polycss/src/elements/PolySceneElement.ts b/packages/polycss/src/elements/PolySceneElement.ts index c09eeaf1d..21412732d 100644 --- a/packages/polycss/src/elements/PolySceneElement.ts +++ b/packages/polycss/src/elements/PolySceneElement.ts @@ -37,6 +37,7 @@ import { type PolyOrthographicCameraHandle, type PolyPerspectiveCameraHandle, } from "../api/createPolyCamera"; +import { parseNumber, parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -64,26 +65,11 @@ const OBSERVED_ATTRS = [ "auto-center", ] as const; -function parseNumber(value: string | null): number | undefined { - if (value == null) return undefined; - const n = parseFloat(value); - return Number.isFinite(n) ? n : undefined; -} - function parsePerspective(value: string | null): number | false | undefined { if (value === "false") return false; return parseNumber(value); } -function parseVec3(value: string | null): Vec3 | undefined { - if (!value) return undefined; - const parts = value.split(",").map((p) => parseFloat(p.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) { - return undefined; - } - return [parts[0], parts[1], parts[2]]; -} - function parseTextureLighting(value: string | null): PolyTextureLightingMode | undefined { if (value === "baked" || value === "dynamic") return value; return undefined; diff --git a/packages/polycss/src/elements/PolyShapeElements.ts b/packages/polycss/src/elements/PolyShapeElements.ts index e23245ba8..62bc7dcb1 100644 --- a/packages/polycss/src/elements/PolyShapeElements.ts +++ b/packages/polycss/src/elements/PolyShapeElements.ts @@ -23,10 +23,11 @@ import { cylinderPolygons, conePolygons, torusPolygons, - computeSceneBbox, + recenterPolygons as recenter, } from "@layoutit/polycss-core"; import type { PolyMeshHandle, PolySceneHandle } from "../api/createPolyScene"; import type { PolySceneElement } from "./PolySceneElement"; +import { parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -52,22 +53,7 @@ function strAttr(el: HTMLElement, name: string, fallback?: string): string | und } function parseVec3Attr(el: HTMLElement, name: string): Vec3 | undefined { - const raw = el.getAttribute(name); - if (!raw) return undefined; - const parts = raw.split(",").map((s) => parseFloat(s.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) return undefined; - return [parts[0], parts[1], parts[2]]; -} - -function recenter(polygons: Polygon[]): Polygon[] { - if (polygons.length === 0) return polygons; - const bbox = computeSceneBbox(polygons); - const cx = (bbox.min[0] + bbox.max[0]) / 2; - const cy = (bbox.min[1] + bbox.max[1]) / 2; - const cz = (bbox.min[2] + bbox.max[2]) / 2; - if (cx === 0 && cy === 0 && cz === 0) return polygons; - const shift = (v: Vec3): Vec3 => [v[0] - cx, v[1] - cy, v[2] - cz]; - return polygons.map((p) => ({ ...p, vertices: p.vertices.map(shift) })); + return parseVec3(el.getAttribute(name)); } /** diff --git a/packages/react/src/scene/PolyIframe.tsx b/packages/react/src/scene/PolyIframe.tsx index 8d420365b..b77268f53 100644 --- a/packages/react/src/scene/PolyIframe.tsx +++ b/packages/react/src/scene/PolyIframe.tsx @@ -16,7 +16,7 @@ * whose vertices straddle the origin. */ import type { CSSProperties, IframeHTMLAttributes } from "react"; -import { BASE_TILE, type Vec3 } from "@layoutit/polycss-core"; +import { BASE_TILE, buildPolyIframeTransform, type Vec3 } from "@layoutit/polycss-core"; export interface PolyIframeProps { /** Iframe URL — forwarded to the underlying