From 1610e20978071316ee0817274f4703529801f31d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 22:02:13 +0000 Subject: [PATCH] fix(xr): one placement registry so panels never overlap (#81) - New virtual-screen runtime part placementRegistry.js: obstacles are other screens, any shown entity tagged data-codexr-panel-obstacle, and the analysis table plus 2.2 m of chart headroom; compared as oriented boxes with the separating-axis test instead of nine sampled points. - + Add screen and Bring land on the nearest free spot (right, left, up); follow goes through the same bumper as drag; a screen already inside an obstacle is never frozen. - Added screens read the scene's screen config (JSON script) and show their display name in the idle label. - Dependency graph: pinned cards get a close button and the stack is capped at two rows (legendSlotPosition maxRows); the legend board and the project evolution overlay register as obstacles. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKtAtQus8TVjhG9bhytC --- .claude/docs/V1.2.1_STATUS.md | 13 ++ apps/vscode-extension/CHANGELOG.md | 7 + .../templates/components/COMPONENTS.md | 1 + .../dependencyGraphRuntime/configAndStatus.js | 4 +- .../tooltipsAndSelection.js | 32 +++- .../overlayAndPanel.js | 4 +- .../codexrMultiScreenManagerRuntime.js | 9 +- .../followAndTransform.js | 50 ++++-- .../virtualScreenRuntime/manifest.json | 1 + .../virtualScreenRuntime/moduleAndConfig.js | 7 + .../virtualScreenRuntime/placementRegistry.js | 144 ++++++++++++++++++ .../virtualScreenRuntime/wiringAndApi.js | 2 + .../components/common/codexrCommonRuntime.js | 10 +- .../analysis/codexrCommonRuntime.test.cjs | 26 ++++ .../test/analysis/dependencyGraph.test.cjs | 8 + .../analysis/virtualScreenRuntime.test.cjs | 55 ++++++- .../baseline/featureBaseline.snapshot.json | 1 + 17 files changed, 349 insertions(+), 25 deletions(-) create mode 100644 apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/placementRegistry.js diff --git a/.claude/docs/V1.2.1_STATUS.md b/.claude/docs/V1.2.1_STATUS.md index fbcafcfa..9242b8f8 100644 --- a/.claude/docs/V1.2.1_STATUS.md +++ b/.claude/docs/V1.2.1_STATUS.md @@ -290,3 +290,16 @@ Then pushed `v1.2.1` to `origin` at the maintainer's request. **No merge and no **What changed**: `core/analysis/launch/` (new): `targetKey.ts`, `launchControl.ts` (AbortController + 10 min deadline + teardown stack per session, signal carried to the Python spawn via AsyncLocalStorage), `analysisTypes.ts` / `launchKinds.ts` / `storageFolders.ts` (descriptors; server capabilities, default controller views and router snapshot probes are derived). `launchPipeline.ts` is a transaction: server before watcher for every kind, rollback newest first, one error toast, silent on Close. Registry reserves the target before its first await. SSE + file map keyed by session id; `sessionServerManager.ts` and `sseNotificationManager.ts` deleted; close path matches servers by `metadata.sessionId` only. Startup cleanup sweeps the folders the launchers write. **Measured**: ESLint warnings 158 → 155 (budget `--max-warnings` lowered to 155); guardrails any.total 84 → 83, complexity.over10 53 → 52 (baseline regenerated). New suite `test/analysis/launchTransaction.test.cjs` (15 tests). Not done here: progress notifications are not cancellable (Close Analysis is the cancel path); LAUNCHER-11 belongs to another story. + +### XR bug-fix epic #72 — S6 cancellable jobs (#78) [confirmed by unit tests] (2026-11-25, PR #91 merged into `v1.2.1`) + +**What changed**: `core/analysis/launch/jobRunner.ts` (new) replaces `SingleJobGate`: atomic `tryReserve` before the first await, cancel that reaches the Git/Python children through the launch signal, a deadline per job (evolution 30 min, comparison 15, dependency graph 10), late results discarded, slot held until the work ends (grace 5 s). Per-revision watchdog (5 min) and per-Git-command timeout (3 min); a cancelled analysis is never recorded as a deterministic exclusion. Evolution and comparison runtimes gained Cancel. `projectEvolutionArtifacts.ts` split out of the service (filesOver500 must not grow). + +**Measured**: `npm test` 1,135/1,135; ESLint warnings 155 → 154 (budget lowered). Not done: the real Python kill path needs a manual check; HIST-10 and the piling-up dependency dataset revisions (second half of DEPGRAPH-9) are out of scope. + +### XR bug-fix epic #72 — S9 panels without overlaps (#81) [confirmed by unit tests + a real A-Frame page] (2026-11-25, branch `claude/project-thread-kvvyg6-panels`) + +**What changed**: new runtime part `virtual-screen/virtualScreenRuntime/placementRegistry.js`: the obstacle registry (other screens, any shown entity tagged `data-codexr-panel-obstacle`, the analysis table plus 2.2 m of chart headroom), an oriented-box separating-axis test replacing the 9-point sampling against obstacles, `findFreePlacement` (right, left, up, rings of one screen size plus 0.25 m) used by add/Bring, and an escape so a screen already inside an obstacle is not frozen. Follow now goes through `constrainPosition`. Added screens read the scene config (`readSceneConfig`, JSON script first) and label with their display name. Dependency-graph legend: `legendSlotPosition` gained `maxRows` (2), pinned cards a close button; the legend board and the evolution playback overlay register as obstacles. + +**Measured**: `npm test` 1,138/1,138; ESLint warnings unchanged at 154. In Chromium + A-Frame 1.7.1 (scratch page, not committed): before, two added screens both at (0, 2.30, -10.20); after, (0, 2.40, -10.40) and (5.05, 2.40, -10.40); with the table in front of the user the screen goes above the chart volume (y 5.35); a followed screen stops at another screen. Not done: text sizes for VR legibility need a headset (manual guide); the evolution overlay keeps its fixed position (now an obstacle, not moved). + diff --git a/apps/vscode-extension/CHANGELOG.md b/apps/vscode-extension/CHANGELOG.md index 10dcc609..a9d32d4c 100644 --- a/apps/vscode-extension/CHANGELOG.md +++ b/apps/vscode-extension/CHANGELOG.md @@ -87,6 +87,13 @@ - A double click on Generate or Compare, or two participants starting at once, no longer shows an error to everyone while the first job runs: "already running" goes only to the person who asked. A participant who joins mid-job sees it running. - A cancelled analysis is no longer recorded as "this revision has no data", which hid that commit from both Git pickers until the session ended. - Git-history exports no longer wait forever on one file: a file analysis is stopped after 2 minutes and retried once, and a Python worker that is slow to start (antivirus on Windows) reduces the number of workers instead of failing the export. +- **Panels in the XR room no longer land on top of each other or on the table.** + - Two screens added with **+ Add screen** used to appear in exactly the same spot, one hidden inside the other. An added or brought screen (**+ Add screen**, **Bring**) now goes to the nearest free spot beside the one in front of you: to the right, to the left, then above. + - Screens now keep clear of the analysis table and the space its charts stand in, the project evolution playback banner, and the dependency graph's card stack, as well as of walls and other screens. + - A screen set to **follow** you now stops at walls and other screens like a dragged one, instead of passing through them. + - Two screens turned toward you at an angle could still pass through each other while you dragged or followed them. The collision check now compares the whole panel, not a few points on it. + - Added screens now use the scene's screen settings (sizes, distance in front of you, collision) instead of built-in defaults, and their idle label shows the screen's name ("vscreen 2") instead of an internal id. + - Dependency graph cards now have a close button (**X**, at the top-right corner of a pinned card). The stack stays at most two rows high and grows sideways, so six pinned cards no longer climb through the ceiling. - A source file of the XR chart-mapping runtime contained a raw control character typed into a string. Behaviour was correct, but the file was invisible to code search and review tools. It now uses the equivalent escape sequence; the runtime value is identical. ## [1.2.0] - 2026-07-30 diff --git a/apps/vscode-extension/templates/components/COMPONENTS.md b/apps/vscode-extension/templates/components/COMPONENTS.md index c0138b54..2cb895a5 100644 --- a/apps/vscode-extension/templates/components/COMPONENTS.md +++ b/apps/vscode-extension/templates/components/COMPONENTS.md @@ -81,6 +81,7 @@ its parts directory. Manual harnesses load assembled copies from - `codexr/virtual-screen/virtualScreenRuntime.js` - Owns a shared virtual screen and screen broadcast interaction. Also the base for screen subtypes: `contentKind: 'fixed'` + `registerContentProvider(id, build)` hosts immutable locally-rendered content (no video surface, no share button) while inheriting chrome, drag/resize, follow and the shared `screen` entity. - Collision bumpers: look-at, drag and resize stop at the room shell (bounds derived from the `codexr-room` entity, `collisionBounds` override) and at other screens; dragging slides along obstacles. `collisionEnabled: false` opts out. **In `ar-mode` the room-derived bounds are skipped entirely** (checked live, before the cache, so desktop/VR keep the cached shell exactly as before and an explicit `collisionBounds` override still applies): screens move freely in the user's own space instead of bumping into invisible walls. Screen-vs-screen obstacles stay on in every mode. + - **Placement registry** (`placementRegistry.js` part, 1.2.1): the obstacles are other screens, every shown entity carrying `data-codexr-panel-obstacle` (a panel registers by carrying the attribute and releases by being hidden or removed: the project evolution playback overlay, the dependency graph's legend board) and `#codexr-analysis-table-geometry` extended upward by `tableChartHeadroom` (default 2.2 m, the standing charts). Obstacles are oriented boxes tested against the whole panel with the separating-axis test, not against sampled points (two screens crossing at an angle slipped between the points). **Placement** (`placeInFrontOfUser`: + Add screen, Bring) runs `findFreePlacement`: the front spot if free, else one screen size plus 0.25 m to the right, left, up, then further rings. **Follow** goes through the same bumper as drag. A screen whose current pose is already blocked moves and turns freely, so a panel appearing over it cannot freeze it. To make a new panel avoidable, tag its root entity; nothing else to register. - Drag depth ("grab and reach"): while a `move` drag is live, the mouse wheel steps the screen along the camera→screen axis (`dragDepthStep`), and the **grabbing controller's thumbstick** does the same continuously — the handler only records the deflection (thumbstickmoved fires on change, not while held) and the drag loop applies `controllerDepthSpeed` m/s per frame; stick forward pushes away, and stick x slides the screen sideways along `depthAxis × up` at the same speed. Depth works by shifting the interaction PLANE (that is what slides the ray-plane intersection along the ray); the lateral offset must shift ONLY the screen's reference position — a plane shifted parallel to itself leaves the intersection untouched, so routing lateral through the plane moves the screen by a tiny depth-coupled residual instead (observed live). The depth target is clamped (`dragDepthMaxLead` against bumper accumulation, `dragDepthMinDistance` so pulling stops before the user's head); the lateral target gets the same lead clamp. A controller drag also claims its hand in `CodeXRStickGateRuntime` (that stick stops walking/turning; the other hand keeps its role) and holds the scene state `codexr-screen-drag` so `codexr-pointer-policy` never hands the laser away mid-grab — both released on every endDrag path. - Media transport is chosen per viewer: same network → direct WebRTC; through the tunnel → frames relayed by the server (`relayTransport.js` part, VP8/Opus via diff --git a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/configAndStatus.js b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/configAndStatus.js index c2828067..3ae20d96 100644 --- a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/configAndStatus.js +++ b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/configAndStatus.js @@ -25,8 +25,10 @@ var MAX_PINNED_LEGENDS = 6; // cardHeight must cover the tallest rendered card (a navigable node card with // 7 metrics + an action button is ~1.72) so grid rows never overlap. + // maxRows caps the stack at two rows: six pins grow sideways (3 per row) + // instead of climbing a third row through the ceiling (PANELS-7). var LEGEND_SLOT = { - perRow: 2, cardWidth: 2.5, cardHeight: 1.85, gapX: 0.34, gapY: 0.3, originYOffset: 1.05, z: 0.18 + perRow: 2, maxRows: 2, cardWidth: 2.5, cardHeight: 1.85, gapX: 0.34, gapY: 0.3, originYOffset: 1.05, z: 0.18 }; // Flow-particle catalogues — part of the SHARED room contract: the ids travel // in the dependency-graph entity as `flowSize` / `flowSpeed` (validated by the diff --git a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/tooltipsAndSelection.js b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/tooltipsAndSelection.js index 41be7556..5a3512be 100644 --- a/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/tooltipsAndSelection.js +++ b/apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/tooltipsAndSelection.js @@ -39,7 +39,12 @@ // ever rotating into each other (their relative layout never changes). ensureLegendBoard: function () { if (this.legendBoard?.isConnected) { return this.legendBoard; } - this.legendBoard = entity('a-entity', { class: 'codexr-legend-board' }); + // Registered with the screens' placement registry (PANELS-5): a + // placed screen never lands on the card stack. + this.legendBoard = entity('a-entity', { + class: 'codexr-legend-board', + 'data-codexr-panel-obstacle': 'dependency-legend-board' + }); this.legendBoardYaw = null; this.el.appendChild(this.legendBoard); return this.legendBoard; @@ -81,6 +86,7 @@ var card = this.legendCards[key]; if (!card) { return; } if (card.action?.parentNode) { card.action.parentNode.removeChild(card.action); } + if (card.closeButton?.parentNode) { card.closeButton.parentNode.removeChild(card.closeButton); } root.CodeXRCommonRuntime?.hideTooltip?.(card); if (card.connectorRoot?.parentNode) { card.connectorRoot.parentNode.removeChild(card.connectorRoot); } if (card.root?.parentNode) { card.root.parentNode.removeChild(card.root); } @@ -97,6 +103,8 @@ && (record.data.kind === 'group' || record.data.kind === 'file' || record.data.syntheticExternal); if (card.action?.parentNode) { card.action.parentNode.removeChild(card.action); } card.action = null; + if (card.closeButton?.parentNode) { card.closeButton.parentNode.removeChild(card.closeButton); } + card.closeButton = null; root.CodeXRCommonRuntime.updateTooltip(card, detail, slotPosition, { width: LEGEND_SLOT.cardWidth, columns: 2, @@ -125,6 +133,27 @@ ); card.root.appendChild(card.action); } + if (this.isPinned(selection)) { + // A pinned card closes on its own (PANELS-7): before, the only + // way out was finding its node again or the global clear. + var self = this; + var pinnedSelection = { type: selection.type, id: selection.id }; + card.closeButton = button( + 'X', + // Just outside the top-right corner, inside the grid gap (0.28 + // wide < gapX 0.34): it never covers the title or a neighbour. + (LEGEND_SLOT.cardWidth / 2 + .17) + ' ' + (card.height / 2 - .14) + ' 0.03', + .28, + function (event) { + event.stopPropagation?.(); + if (self.isPinned(pinnedSelection)) { self.togglePinnedSelection(pinnedSelection); } + }, + '#475569' + ); + card.closeButton.setAttribute('height', .28); + card.closeButton.setAttribute('data-codexr-role', 'legend-close'); + card.root.appendChild(card.closeButton); + } }, // Re-place every visible legend into a non-overlapping grid slot above the // graph, drop cards whose selection is gone, and refresh the shared visuals. @@ -149,6 +178,7 @@ if (!card) { return; } var slot = root.CodeXRCommonRuntime.legendSlotPosition(index, active.length, { perRow: LEGEND_SLOT.perRow, + maxRows: LEGEND_SLOT.maxRows, cardWidth: LEGEND_SLOT.cardWidth, cardHeight: LEGEND_SLOT.cardHeight, gapX: LEGEND_SLOT.gapX, diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/overlayAndPanel.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/overlayAndPanel.js index 4db3ba27..d10a71e7 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/overlayAndPanel.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/overlayAndPanel.js @@ -7,7 +7,9 @@ id: 'codexr-project-evolution-playback-overlay', position: '0 3.35 -18', visible: 'false', - 'data-codexr-role': 'project-evolution playback-overlay' + 'data-codexr-role': 'project-evolution playback-overlay', + // Registered with the screens' placement registry while shown (PANELS-9). + 'data-codexr-panel-obstacle': 'project-evolution-overlay' }); overlay.appendChild(entity('a-plane', { width: 6.2, diff --git a/apps/vscode-extension/templates/components/codexr/virtual-screen/codexrMultiScreenManagerRuntime.js b/apps/vscode-extension/templates/components/codexr/virtual-screen/codexrMultiScreenManagerRuntime.js index 2ad35dc8..0a30a98e 100644 --- a/apps/vscode-extension/templates/components/codexr/virtual-screen/codexrMultiScreenManagerRuntime.js +++ b/apps/vscode-extension/templates/components/codexr/virtual-screen/codexrMultiScreenManagerRuntime.js @@ -523,7 +523,12 @@ }, buildRuntimeInitConfig: function (instanceId, options) { - const sharedConfig = root.__CODEXR_VIRTUAL_SCREEN_CONFIG__ || {}; + // Same source as the scene's own screens (the JSON config script): + // the global alone is unset in the XR templates, so added screens + // used to fall back to the runtime defaults (PANELS-8). + const sharedConfig = this.runtimeFactory?.readSceneConfig?.(root) + || root.__CODEXR_VIRTUAL_SCREEN_CONFIG__ + || {}; const collaborationConfig = root.__CODEXR_COLLABORATION_CONFIG__ || {}; const transform = options?.transform || {}; const position = transform.position || options?.anchoredPosition || sharedConfig.anchoredPosition || { x: 0, y: 8, z: 6 }; @@ -572,7 +577,7 @@ }, labels: { ...(sharedConfig.labels || {}), - idle: options?.idleLabel || `${instanceId}: choose source independently.`, + idle: options?.idleLabel || `${options?.displayName || instanceId}: choose source independently.`, }, }; }, diff --git a/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/followAndTransform.js b/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/followAndTransform.js index 2ef8d24b..5e6680de 100644 --- a/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/followAndTransform.js +++ b/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/followAndTransform.js @@ -82,11 +82,13 @@ return; } el.object3D.updateMatrixWorld(true); - obstacles.push({ - inverseMatrix: el.object3D.matrixWorld.clone().invert(), - halfExtents: { x: width / 2, y: height / 2, z: 0.15 }, - }); + const center = new global.THREE.Vector3(); + const orientation = new global.THREE.Quaternion(); + el.object3D.getWorldPosition(center); + el.object3D.getWorldQuaternion(orientation); + obstacles.push(orientedBox(center, orientation, width / 2, height / 2, 0.15)); }); + collectPanelObstacles(obstacles); refs.obstacleCache = obstacles; refs.obstacleCacheTime = now; return obstacles; @@ -98,12 +100,16 @@ const effectiveWidth = Number(width) > 0 ? Number(width) : state.screenWidth; const w = effectiveWidth / 2; const h = (effectiveWidth / refs.config.aspectRatio) / 2; - return [ + const points = [ [-w, -h], [w, -h], [-w, h], [w, h], [0, -h], [0, h], [-w, 0], [w, 0], [0, 0], ].map(([x, y]) => new global.THREE.Vector3(x, y, 0) .applyQuaternion(worldQuaternion) .add(worldPosition)); + // The points test the room shell (a box contains the panel when it + // contains its corners); the box tests the obstacles. + points.box = orientedBox(worldPosition.clone(), worldQuaternion, w, h, 0.02); + return points; } function violatesCollision(samplePoints) { @@ -117,15 +123,12 @@ } } } - const local = new global.THREE.Vector3(); + if (!samplePoints.box) { + return false; + } for (const obstacle of getScreenObstacles()) { - for (const point of samplePoints) { - local.copy(point).applyMatrix4(obstacle.inverseMatrix); - if (Math.abs(local.x) < obstacle.halfExtents.x - && Math.abs(local.y) < obstacle.halfExtents.y - && Math.abs(local.z) < obstacle.halfExtents.z) { - return true; - } + if (orientedBoxesOverlap(samplePoints.box, obstacle)) { + return true; } } return false; @@ -141,6 +144,9 @@ if (!violatesCollision(collectScreenSamplePoints(worldPosition, targetQuaternion))) { return targetQuaternion; } + if (isCurrentPoseBlocked()) { + return targetQuaternion; + } const currentQuaternion = getWorldQuaternion(refs.root); if (!currentQuaternion?.clone) { return targetQuaternion; @@ -167,6 +173,9 @@ if (!violatesCollision(collectScreenSamplePoints(targetWorldPosition, orientation))) { return targetWorldPosition; } + if (isCurrentPoseBlocked()) { + return targetWorldPosition; + } const current = getWorldPosition(refs.root); if (!current?.clone) { return targetWorldPosition; @@ -301,7 +310,7 @@ } state.follow = false; state.followTransform = followTransform; - if (!applyFollowTransform()) { + if (!applyFollowTransform({ resolveFreeSpot: true })) { console.log('[CodeXR][VirtualScreen] placeInFrontOfUser failed: applyFollowTransform returned false', { screenId: getScreenId(), followTransform: { @@ -560,7 +569,7 @@ }; } - function applyFollowTransform() { + function applyFollowTransform(options) { if (!state.followTransform?.position?.clone) { console.log('[CodeXR][VirtualScreen] applyFollowTransform failed: missing followTransform position', { screenId: getScreenId(), @@ -581,9 +590,18 @@ return false; } - const targetWorldPosition = state.followTransform.position.clone() + const desiredWorldPosition = state.followTransform.position.clone() .applyQuaternion(cameraWorldQuaternion.clone()) .add(cameraWorldPosition.clone()); + // A placement looks for a free spot; following is a bumper like + // dragging, so a followed screen no longer passes through walls, + // screens, panels or the table (PANELS-3). + const targetWorldPosition = options?.resolveFreeSpot === true + ? findFreePlacement( + desiredWorldPosition, + computeFaceUserQuaternion(desiredWorldPosition, cameraWorldPosition), + ) + : constrainPosition(desiredWorldPosition); const targetWorldQuaternion = computeFaceUserQuaternion(targetWorldPosition, cameraWorldPosition); const applied = applyWorldTransform(refs.root, targetWorldPosition, targetWorldQuaternion); if (applied && updateLegendSide()) { diff --git a/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/manifest.json b/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/manifest.json index f2acb07c..fc85e92b 100644 --- a/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/manifest.json +++ b/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/manifest.json @@ -8,6 +8,7 @@ "webrtcPeers.js", "relayTransport.js", "signalingAndRemote.js", + "placementRegistry.js", "followAndTransform.js", "pointerAndDrag.js", "wiringAndApi.js" diff --git a/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/moduleAndConfig.js b/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/moduleAndConfig.js index b449ee88..12bfe636 100644 --- a/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/moduleAndConfig.js +++ b/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/moduleAndConfig.js @@ -273,6 +273,13 @@ } } + // The scene's own screen config: the JSON script the templates and the + // export write, then the legacy global. Screens added at runtime read it + // too, so they share the scene's sizes, offsets and collision (PANELS-8). + function readSceneConfig(win) { + return readConfigFromJsonScript(win) || win?.__CODEXR_VIRTUAL_SCREEN_CONFIG__ || null; + } + function createRuntime(win) { const state = { initialized: false, diff --git a/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/placementRegistry.js b/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/placementRegistry.js new file mode 100644 index 00000000..60b6e456 --- /dev/null +++ b/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/placementRegistry.js @@ -0,0 +1,144 @@ +// == virtualScreenRuntime.js | placementRegistry (assembled per manifest.json; see COMPONENTS.md) == + // The shared placement registry (PANELS-3/5/9): besides other screens, + // a screen keeps clear of every shown entity tagged + // data-codexr-panel-obstacle (mode overlays, boards) and of the analysis + // table plus the volume its charts stand in. A panel registers by + // carrying the attribute and releases by being hidden or removed, so a + // mode's panels leave the registry with the mode. + const TABLE_GEOMETRY_SELECTOR = '#codexr-analysis-table-geometry'; + const DEFAULT_TABLE_CHART_HEADROOM = 2.2; + + function isShown(object3D) { + for (let node = object3D; node; node = node.parent) { + if (node.visible === false) { + return false; + } + } + return true; + } + + function worldBoxObstacle(object3D, extraHeight) { + object3D.updateMatrixWorld?.(true); + const box = new global.THREE.Box3().setFromObject(object3D); + if (box.isEmpty?.()) { + return null; + } + box.max.y += Number(extraHeight) || 0; + const center = new global.THREE.Vector3(); + const size = new global.THREE.Vector3(); + box.getCenter(center); + box.getSize(size); + return orientedBox(center, new global.THREE.Quaternion(), size.x / 2, size.y / 2, size.z / 2); + } + + // Obstacles and the moving screen are oriented boxes compared with the + // separating-axis test: sampling a few points of the screen missed two + // screens crossing at an angle (look-at turns them), which then + // interpenetrated (PANELS-3). + function orientedBox(center, quaternion, halfX, halfY, halfZ) { + return { + center, + axes: [ + new global.THREE.Vector3(1, 0, 0).applyQuaternion(quaternion), + new global.THREE.Vector3(0, 1, 0).applyQuaternion(quaternion), + new global.THREE.Vector3(0, 0, 1).applyQuaternion(quaternion), + ], + half: [halfX, halfY, halfZ], + }; + } + + function projectedRadius(box, axis) { + return (box.half[0] * Math.abs(box.axes[0].dot(axis))) + + (box.half[1] * Math.abs(box.axes[1].dot(axis))) + + (box.half[2] * Math.abs(box.axes[2].dot(axis))); + } + + function orientedBoxesOverlap(a, b) { + const between = b.center.clone().sub(a.center); + const candidates = [...a.axes, ...b.axes]; + for (const axisA of a.axes) { + for (const axisB of b.axes) { + const cross = new global.THREE.Vector3().crossVectors(axisA, axisB); + if (cross.lengthSq() > 1e-8) { + candidates.push(cross.normalize()); + } + } + } + for (const axis of candidates) { + if (Math.abs(between.dot(axis)) > projectedRadius(a, axis) + projectedRadius(b, axis)) { + return false; + } + } + return true; + } + + function collectPanelObstacles(obstacles) { + if (!global.THREE?.Box3) { + return; + } + const document = getDocument(); + document?.querySelectorAll?.('[data-codexr-panel-obstacle]').forEach((el) => { + if (!el.object3D || refs.root?.contains?.(el) || !isShown(el.object3D)) { + return; + } + const obstacle = worldBoxObstacle(el.object3D, 0); + if (obstacle) { + obstacles.push(obstacle); + } + }); + const table = document?.querySelector?.(TABLE_GEOMETRY_SELECTOR); + if (table?.object3D && isShown(table.object3D)) { + const headroom = Number(refs.config.tableChartHeadroom) >= 0 + ? Number(refs.config.tableChartHeadroom) + : DEFAULT_TABLE_CHART_HEADROOM; + const obstacle = worldBoxObstacle(table.object3D, headroom); + if (obstacle) { + obstacles.push(obstacle); + } + } + } + + // A placement (add, Bring, recenter) lands on the nearest free spot + // beside its target instead of on top of whatever is there: one screen + // width (or height) plus a gap at a time, right, left, up, then further + // out. Nothing free keeps the target, so a crowded room still places. + const PLACEMENT_GAP = 0.25; + const PLACEMENT_RINGS = 3; + + function findFreePlacement(targetWorldPosition, worldQuaternion) { + if (!global.THREE || !targetWorldPosition?.clone || !worldQuaternion?.clone) { + return targetWorldPosition; + } + refs.obstacleCache = null; + if (!violatesCollision(collectScreenSamplePoints(targetWorldPosition, worldQuaternion))) { + return targetWorldPosition; + } + const stepX = state.screenWidth + PLACEMENT_GAP; + const stepY = (state.screenWidth / refs.config.aspectRatio) + PLACEMENT_GAP; + const right = new global.THREE.Vector3(1, 0, 0).applyQuaternion(worldQuaternion); + const up = new global.THREE.Vector3(0, 1, 0); + for (let ring = 1; ring <= PLACEMENT_RINGS; ring += 1) { + const offsets = [[ring, 0], [-ring, 0], [0, ring], [ring, ring], [-ring, ring], [0, -ring]]; + for (const [dx, dy] of offsets) { + const candidate = targetWorldPosition.clone() + .addScaledVector(right, dx * stepX) + .addScaledVector(up, dy * stepY); + if (!violatesCollision(collectScreenSamplePoints(candidate, worldQuaternion))) { + return candidate; + } + } + } + return targetWorldPosition; + } + + // A screen that already sits inside an obstacle (a scene anchored it + // there, a panel appeared over it) must still move and turn freely, or + // the bumpers would freeze it in place. + function isCurrentPoseBlocked() { + const position = getWorldPosition(refs.root); + const orientation = getWorldQuaternion(refs.root); + if (!position?.clone || !orientation?.clone) { + return false; + } + return violatesCollision(collectScreenSamplePoints(position, orientation)); + } diff --git a/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/wiringAndApi.js b/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/wiringAndApi.js index 3121e3e0..8b8e790a 100644 --- a/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/wiringAndApi.js +++ b/apps/vscode-extension/templates/components/codexr/virtual-screen/virtualScreenRuntime/wiringAndApi.js @@ -286,6 +286,7 @@ api.DEFAULT_CONFIG = DEFAULT_CONFIG; api.mergeConfig = mergeConfig; + api.readSceneConfig = readSceneConfig; api.createRuntime = createRuntime; api.registerContentProvider = registerContentProvider; api.getContentProvider = getContentProvider; @@ -300,6 +301,7 @@ const runtime = createRuntime(global); runtime.DEFAULT_CONFIG = DEFAULT_CONFIG; runtime.mergeConfig = mergeConfig; + runtime.readSceneConfig = readSceneConfig; runtime.createRuntime = createRuntime; runtime.registerContentProvider = registerContentProvider; runtime.getContentProvider = getContentProvider; diff --git a/apps/vscode-extension/templates/components/common/codexrCommonRuntime.js b/apps/vscode-extension/templates/components/common/codexrCommonRuntime.js index 95978e85..55c617b8 100644 --- a/apps/vscode-extension/templates/components/common/codexrCommonRuntime.js +++ b/apps/vscode-extension/templates/components/common/codexrCommonRuntime.js @@ -359,10 +359,15 @@ // Non-overlapping grid slot for the Nth of `count` legend cards — a shared // primitive so any Code-XR legend surface can lay multiple cards out without - // them overlapping (centered rows, wrapping upward into a grid). + // them overlapping (centered rows, wrapping upward into a grid). With + // `maxRows` the grid grows sideways instead of past that many rows, so a + // full stack never climbs through the ceiling (PANELS-7). function legendSlotPosition(index, count, options) { const opts = options || {}; - const perRow = Math.max(1, Math.round(Number(opts.perRow) || 3)); + const total = Math.max(1, Number(count) || 1); + const basePerRow = Math.max(1, Math.round(Number(opts.perRow) || 3)); + const maxRows = Math.round(Number(opts.maxRows) || 0); + const perRow = maxRows > 0 ? Math.max(basePerRow, Math.ceil(total / maxRows)) : basePerRow; const cardWidth = Number(opts.cardWidth) || 2.8; const cardHeight = Number(opts.cardHeight) || 1.1; const gapX = opts.gapX != null ? Number(opts.gapX) : .3; @@ -370,7 +375,6 @@ const originX = Number(opts.originX) || 0; const originY = Number(opts.originY) || 0; const z = opts.z != null ? Number(opts.z) : 0; - const total = Math.max(1, Number(count) || 1); const i = Math.max(0, Number(index) || 0); const row = Math.floor(i / perRow); const col = i % perRow; diff --git a/apps/vscode-extension/test/analysis/codexrCommonRuntime.test.cjs b/apps/vscode-extension/test/analysis/codexrCommonRuntime.test.cjs index 1cc3fd8e..87832f04 100644 --- a/apps/vscode-extension/test/analysis/codexrCommonRuntime.test.cjs +++ b/apps/vscode-extension/test/analysis/codexrCommonRuntime.test.cjs @@ -260,6 +260,32 @@ test('legendSlotPosition lays legends out in a non-overlapping grid', () => { assert.ok(Math.abs(first.x + second.x) < 1e-6); }); +test('legendSlotPosition with maxRows grows sideways instead of climbing (PANELS-7)', () => { + const runtime = loadRuntime().CodeXRCommonRuntime; + const opts = { perRow: 2, maxRows: 2, cardWidth: 2.5, cardHeight: 1.85, gapX: 0.34, gapY: 0.3, originY: 0 }; + // The dependency graph's full stack: six pinned cards plus one hovered. + for (const count of [1, 2, 3, 4, 5, 6, 7]) { + const rows = new Set(); + const boxes = []; + for (let i = 0; i < count; i++) { + const p = runtime.legendSlotPosition(i, count, opts); + rows.add(p.y); + boxes.push({ x: p.x, y: p.y }); + } + assert.ok(rows.size <= 2, `${count} cards use ${rows.size} rows`); + for (let i = 0; i < boxes.length; i++) { + for (let j = i + 1; j < boxes.length; j++) { + const ox = opts.cardWidth - Math.abs(boxes[i].x - boxes[j].x); + const oy = opts.cardHeight - Math.abs(boxes[i].y - boxes[j].y); + assert.ok(!(ox > 0.001 && oy > 0.001), `${count} cards: slots ${i} and ${j} overlap`); + } + } + } + // Without maxRows the old behaviour is kept: six cards, three rows. + const legacy = new Set([0, 1, 2, 3, 4, 5].map((i) => runtime.legendSlotPosition(i, 6, { ...opts, maxRows: 0 }).y)); + assert.equal(legacy.size, 3); +}); + test('common faceCamera and hitbox helpers tolerate missing scene state', () => { const context = loadRuntime(); const runtime = context.CodeXRCommonRuntime; diff --git a/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs b/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs index 8c259522..d532efc1 100644 --- a/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs +++ b/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs @@ -37,6 +37,14 @@ test('dependency runtime uses a worker and owns three layouts', () => { assert.match(runtime, /drawAxes/); // Legends are laid out in a non-overlapping grid above the graph. assert.match(runtime, /graphTopY \+ LEGEND_SLOT\.originYOffset/); + // PANELS-7: the stack is capped at two rows and every pinned card closes + // on its own; the card board is registered with the screens' placement. + assert.match(runtime, /perRow: 2, maxRows: 2,/); + assert.match(runtime, /maxRows: LEGEND_SLOT\.maxRows/); + assert.match(runtime, /'data-codexr-role', 'legend-close'/); + assert.match(runtime, /if \(self\.isPinned\(pinnedSelection\)\) \{ self\.togglePinnedSelection\(pinnedSelection\); \}/); + assert.match(runtime, /card\.closeButton\.parentNode\.removeChild\(card\.closeButton\)/); + assert.match(runtime, /'data-codexr-panel-obstacle': 'dependency-legend-board'/); assert.match(runtime, /CodeXRCommonRuntime\.legendSlotPosition/); assert.doesNotMatch(runtime, /tooltipCameraPosition/); assert.match(runtime, /transitionDuration.*600/); diff --git a/apps/vscode-extension/test/analysis/virtualScreenRuntime.test.cjs b/apps/vscode-extension/test/analysis/virtualScreenRuntime.test.cjs index 714338b8..170f3234 100644 --- a/apps/vscode-extension/test/analysis/virtualScreenRuntime.test.cjs +++ b/apps/vscode-extension/test/analysis/virtualScreenRuntime.test.cjs @@ -427,7 +427,7 @@ test('collision bumpers stop look-at, drag, and resize at walls and screens', () assert.match(runtimeSource, /refs\.config\.collisionBounds/); // Other screens are thin oriented-box obstacles. assert.match(runtimeSource, /function getScreenObstacles/); - assert.match(runtimeSource, /inverseMatrix/); + assert.match(runtimeSource, /function orientedBoxesOverlap/); // Rotation bumper: full look-at first, then shrinking slerp fractions, // else hold the pose (a stop, never a limit while clear of obstacles). assert.match(runtimeSource, /function constrainOrientation/); @@ -448,6 +448,59 @@ test('collision bumpers stop look-at, drag, and resize at walls and screens', () assert.match(xrTemplate, /"anchoredPosition":\{"x":0,"y":4\.2,"z":-22\}/); }); +test('one placement registry: added and brought screens land on a free spot (PANELS-3/5/9)', () => { + // Placement (add, Bring) searches beside its target instead of stacking. + assert.match(runtimeSource, /function findFreePlacement/); + assert.match(runtimeSource, /applyFollowTransform\(\{ resolveFreeSpot: true \}\)/); + assert.match(runtimeSource, /options\?\.resolveFreeSpot === true\s*\? findFreePlacement\(/); + // Following is a bumper too, no longer a pass-through. + assert.match(runtimeSource, /: constrainPosition\(desiredWorldPosition\)/); + // The registry: other screens, any shown panel tagged as an obstacle, and + // the table plus the volume its charts stand in. + assert.match(runtimeSource, /querySelectorAll\?\.\('\[data-codexr-panel-obstacle\]'\)/); + assert.match(runtimeSource, /'#codexr-analysis-table-geometry'/); + assert.match(runtimeSource, /DEFAULT_TABLE_CHART_HEADROOM = 2\.2/); + // A screen already inside an obstacle is never frozen by the bumpers. + assert.equal((runtimeSource.match(/if \(isCurrentPoseBlocked\(\)\) \{/g) || []).length, 2); + // Mode overlays register themselves while shown. + const overlay = readProjectFile('templates', 'components', 'codexr', 'project-evolution', 'projectEvolutionRuntime', 'overlayAndPanel.js'); + assert.match(overlay, /'data-codexr-panel-obstacle': 'project-evolution-overlay'/); +}); + +test('added screens use the scene screen config and their display name (PANELS-8)', () => { + const source = readProjectFile('templates', 'components', 'codexr', 'virtual-screen', 'codexrMultiScreenManagerRuntime.js'); + let definition = null; + const sceneConfig = { + anchoredPosition: { x: 0, y: 4.2, z: -22 }, + followOffset: { x: 0, y: 0.8, z: -2.4 }, + sizeSteps: [3.2, 4.8], + collisionBounds: { min: { x: -5, y: 0, z: -5 }, max: { x: 5, y: 5, z: 5 } }, + }; + const fakeRoot = { + AFRAME: { components: {}, registerComponent(name, def) { definition = def; } }, + document: { + getElementById: (id) => (id === 'codexr-tooling-config-virtual-screen' + ? { textContent: JSON.stringify(sceneConfig) } + : null), + querySelector: () => null, + }, + addEventListener() {}, + }; + new Function('globalThis', source)(fakeRoot); + assert.ok(definition, 'the manager registers its component'); + const context = { + ...definition, + runtimeFactory: { readSceneConfig: runtimeModule.readSceneConfig }, + collaborationClient: null, + }; + const config = definition.buildRuntimeInitConfig.call(context, 'screen:peer:3', { displayName: 'vscreen 3' }); + assert.deepEqual(config.followOffset, sceneConfig.followOffset); + assert.deepEqual(config.sizeSteps, sceneConfig.sizeSteps); + assert.deepEqual(config.collisionBounds, sceneConfig.collisionBounds); + assert.equal(config.labels.idle, 'vscreen 3: choose source independently.'); + assert.equal(typeof runtimeModule.readSceneConfig, 'function'); +}); + test('AR frees the screens from the invisible room shell', () => { // In AR the room is hidden and functionally gone (its pieces drop the // raycast class in codexrRoomRuntime); the bumpers must not keep pinning diff --git a/apps/vscode-extension/test/baseline/featureBaseline.snapshot.json b/apps/vscode-extension/test/baseline/featureBaseline.snapshot.json index e00306f7..dca8727a 100644 --- a/apps/vscode-extension/test/baseline/featureBaseline.snapshot.json +++ b/apps/vscode-extension/test/baseline/featureBaseline.snapshot.json @@ -473,6 +473,7 @@ "components/codexr/virtual-screen/virtualScreenRuntime/followAndTransform.js", "components/codexr/virtual-screen/virtualScreenRuntime/manifest.json", "components/codexr/virtual-screen/virtualScreenRuntime/moduleAndConfig.js", + "components/codexr/virtual-screen/virtualScreenRuntime/placementRegistry.js", "components/codexr/virtual-screen/virtualScreenRuntime/pointerAndDrag.js", "components/codexr/virtual-screen/virtualScreenRuntime/relayTransport.js", "components/codexr/virtual-screen/virtualScreenRuntime/sharedState.js",