Skip to content

Commit cac36a0

Browse files
claudejjohare
andcommitted
feat(codescape): A5 decoupling, licence split, SpacePilot, ecosystem docs
Prepares Codescape for extraction to DreamLab-AI/codescape (ADR-2143 A5). - visionclaw-wire: the frozen 52-byte V3 record, V5 envelope, 0x34 ack and 0x23 framing move from visionclaw-protocol's wire_fixtures.rs into a new dependency-free crate (MIT OR Apache-2.0, no_std + alloc capable). visionclaw-protocol re-exports it, so every caller is unchanged; the XR wire test takes it as a dev-dependency; codescape-model depends on it instead of including the file by #[path]. Byte-exact fixtures unchanged. - CUDA PTX as a runtime artefact: codescape-layout loads the PTX and its build manifest from CODESCAPE_PTX_DIR (provenance=compiled, content tag, 212-byte c_params and kernel arities checked at load) and no longer depends on visionclaw-gpu. The compose entrypoint stages the pair from visionclaw-gpu's own build script into a fixed /codescape-target/ptx. - Licence split: codescape-model and codescape-collab are MIT OR Apache-2.0 with publish metadata, READMEs and compiling examples; ingest, layout, server and client stay AGPL-3.0-only. New isolation tests: visionclaw-wire is the only VisionClaw crate in either feature set, and no permissive crate ships with an AGPL dependency (mutation-checked). - SpacePilot / SpaceMouse over WebHID in the Codescape client: orbit camera with VisionClaw's hand feel (shared direction table in tests), puck buttons for overview, zoom, back, tiers, clear and hide tests, and a connect button beside push-to-talk. - Docs: README Codescape section and ports, docs index, CHANGELOG, AGENTS.md isolation rule, BASELINE 0.4.0, ADR-2143 A5 with three steps ticked and two drifts fixed. Gate (raw output in docs/evidence/codescape/P1/gate-raw-A5.txt): Codescape workspace tests, clippy -D warnings and rustdoc with and without cuda; visionclaw-wire and visionclaw-protocol; XR wire tests; client tsc, 81 Codescape tests, 116 control-centre tests. GPU conformance on the staged runtime PTX 5/5 (gate-gpu-A5-runtime-ptx.txt). visionclaw-server and all its targets type-check against the wire change in a clean worktree. Co-Authored-By: jjohare <[email protected]>
1 parent 5390ceb commit cac36a0

50 files changed

Lines changed: 2941 additions & 821 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ The ADR pack for any domain = its living governing document in `docs/` (BASELINE
1212
- **Client**: `cd client && npm install && npm run dev` (Vite); `npm test` runs Vitest; `npm run build` regenerates types first.
1313
- **Type generation**: `cargo run --bin generate_types` updates `client/src/types/` from Rust structs — run it after changing any API or data struct; never hand-edit generated types.
1414
- **Docker**: `./scripts/launch.sh up dev` (source-only) or `rebuild dev` (Dockerfile/deps) — never plain `docker compose`. To deploy code into a running dev container use `./scripts/launch.sh redeploy dev`, not a raw `supervisorctl restart rust-backend`: only redeploy republishes the root build files (`.dev-inputs/`, ADR-2008). From inside the agentbox container, launch it in the host shell (see the workspace environment notes), never directly.
15+
- **Codescape** (ADR-2143): its own Cargo workspace and lock under `crates/codescape/`. Build with `CARGO_TARGET_DIR` set outside the root `target/` and run `cargo test --workspace` from that directory. Client: from `client/`, `vite build --config src/codescape/vite.config.ts` and `vitest run --config src/codescape/vitest.config.ts`. Isolation rule: never list it in the root `members`, and never add a path dependency from the root workspace on it or from it on the root, except one: `crates/visionclaw-wire` (the frozen position wire, MIT OR Apache-2.0), which Codescape depends on and `visionclaw-protocol` re-exports. The CUDA PTX reaches Codescape as a runtime artefact (`CODESCAPE_PTX_DIR`), never as a crate dependency; `tests/isolation.rs` enforces both.
1516
- **Env**: `.env` is not committed; start from `env.development.template` or `env.example`.
1617

1718
## Code conventions

‎CHANGELOG.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### 2026-10-18: Codescape section (ADR-2143)
11+
12+
Codescape, a separate section for human and agent voice collaboration over a live 3D code graph,
13+
landed in `b63068e3d^..098d3ff98`. That range also carries unrelated commits (`a12ebedee`, `cefd9d1d7`,
14+
`2bf892c3f`, `392628eef`: TODO rows, ER-13, ER-24).
15+
`implementation_status: partial`; P0 done, P1 gate green, P2-P6 open.
16+
17+
- **Crates.** Own Cargo workspace and lock at `crates/codescape/`, never a root member:
18+
`codescape-model`, `codescape-ingest` (graphicle at a pinned rev), `codescape-layout`,
19+
`codescape-collab`, `codescape-server`, all AGPL-3.0-only today. A build-graph isolation test
20+
bans ontology, vault, RuVector and VisionClaw-server crates; the server exits 2 when handed
21+
`RUVECTOR_PG_CONNINFO` (ADR-2143 I1, I8).
22+
- **Ports and service.** `:4100` serves clients (loopback by default), `:4101` takes hook ingest
23+
with a bearer token on `visionclaw_network` only. Opt-in compose service via
24+
`CODESCAPE=1 ./scripts/launch.sh up dev`; the token is readable with `DAC_READ_SEARCH` alone (A3).
25+
- **Proxy.** The dev nginx serves it at `http://<host>:3001/codescape/` as a network peer
26+
(lazy DNS, 502 when down, one copy of COOP/COEP/CORP), with `--trust-proxy` and
27+
`--trust-proxy-from` gating forwarded headers. Dev-only LAN waiver; prod untouched (A4).
28+
- **Wire and XR.** No new wire format: frozen V3 records in V5 envelopes, `0x23` agent actions,
29+
`0x34` ack pacing, `/wss` emulation with a file-tier `initialGraphLoad` and a `/ws/presence`
30+
shim. `xr-client/rust/tests/codescape_wire.rs` pins captured frames with the Godot client's own
31+
decoders; the headset rendered 1,699 file nodes at 90 FPS through `:3001`. Mode switches in the
32+
VisionClaw control bar, the Codescape client and the XR HUD (ADR-2018, ADR-2019, ADR-2141).
33+
- **Voice.** Push-to-talk on `/ws/voice` with a single floor, nemotron-asr, pocket-tts and the Loom
34+
door for out-of-grammar parsing; every action is a typed command, and LLM output that fails the
35+
schema is spoken, never executed.
36+
- **GPU.** visionclaw-gpu's build-compiled PTX through a thin cust driver, refused unless
37+
`c_params` is 212 B, the launched kernels' arities match and the manifest says
38+
`provenance=compiled`; CPU Barnes-Hut is the fallback and conformance oracle (A1, A2). The 100k
39+
step (7.8 ms) and cold-settle (13.7 s) targets are still missed.
40+
- **Next.** Extraction to DreamLab-AI/codescape with a licence split, in progress (A5).
41+
1042
### 2026-09-14 — augmentation conditions, VisionClaw substrate (ADR-2110)
1143

1244
The judgment surfaces are instrumented against the six augmentation conditions

‎Cargo.lock‎

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ members = [
44
"crates/visionclaw-contracts",
55
"crates/visionclaw-domain",
66
"crates/visionclaw-protocol",
7+
"crates/visionclaw-wire",
78
"crates/visionclaw-adapters",
89
"crates/visionclaw-gpu",
910
"crates/visionclaw-ontology",

‎README.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,22 @@ flowchart LR
137137

138138
A Cargo workspace of extracted crates makes up the backend (`contracts → domain → {gpu, ontology, protocol} → adapters → actors → xr-presence → server`) with hexagonal boundaries and direct dispatch, no CQRS bus. Oxigraph plus SQLite is the single canonical store ([ADR-2004](docs/adr/ADR-2004-oxigraph-sqlite-persistence.md)); the governing documents for stores, identity, data ownership, wire protocol, identifiers, security profiles, GPU ABI, the XR client and the corpus are indexed in [`docs/adr/README.md`](docs/adr/README.md). Longer reads: [System overview](docs/explanation/system-overview.md) · [Bounded contexts](docs/explanation/bounded-contexts.md).
139139

140+
### Codescape
141+
142+
Codescape is a separate section for humans and agents working together by voice over a near-real-time 3D view of a codebase: files and symbols laid out by the same force model, with agents shown at the node they are touching. It is not part of the knowledge-work system. It has its own Cargo workspace and lock at `crates/codescape/`, its own compose service, and a tested isolation boundary (no ontology, vault, RuVector or VisionClaw-server crate in its build graph; the server exits at boot if it is handed `RUVECTOR_PG_CONNINFO`). It speaks the frozen V3/V5 wire, so the desktop and XR clients need no protocol change. Enable it with `CODESCAPE=1 ./scripts/launch.sh up dev`, then open `http://<host>:3001/codescape/` (through the dev nginx) or `http://localhost:4100` directly. The direct port binds to loopback; LAN access through `:3001` is a dev-only waiver with open auth until NIP-98 lands in P6.
143+
144+
| Crate | Role | Licence |
145+
|---|---|---|
146+
| `codescape-model` | pure types, interned ids, LOD, wire mapping | AGPL-3.0-only |
147+
| `codescape-ingest` | code-graph extraction (the only crate that uses graphicle) | AGPL-3.0-only |
148+
| `codescape-layout` | CPU Barnes-Hut oracle; `cuda` feature for the GPU | AGPL-3.0-only |
149+
| `codescape-collab` | actors, heat, voice floor, command grammar | AGPL-3.0-only |
150+
| `codescape-server` | actix: every network adapter | AGPL-3.0-only |
151+
152+
A licence split (`codescape-model` and `codescape-collab` to MIT OR Apache-2.0) and extraction to a standalone `DreamLab-AI/codescape` repository (not yet created) are in progress under ADR-2143 Amendment A5.
153+
154+
**Voice.** Hold backtick (or the talk button) and say "go to graph underscore service dot rs" or "callers of main" (both are goldens in `codescape-collab/tests/grammar_golden.rs`); Ctrl/Cmd-K or `/` takes the same commands typed. The microphone needs a secure context, so voice works at `localhost` or over https, not at plain `http://<lan-host>:3001`. Decision and phase plan: [ADR-2143](docs/adr/ADR-2143-codescape-section-separate-workspace-and-port.md) · evidence: [P1](docs/evidence/codescape/P1/README.md).
155+
140156
---
141157

142158
## Quick start
@@ -153,6 +169,9 @@ cd VisionClaw && cp env.example .env # set GITHUB_REPO, GITHUB_BASE_PATH, PR
153169
|:--------|:----|
154170
| Desktop client | http://localhost:3001 |
155171
| REST + WebSocket API | http://localhost:4000/api |
172+
| Codescape, through the dev nginx (needs `CODESCAPE=1`) | http://localhost:3001/codescape/ |
173+
| Codescape, direct (bound to loopback) | http://localhost:4100 |
174+
| Codescape hook ingest | `codescape:4101` on `visionclaw_network` only, bearer token, never published |
156175

157176
<details>
158177
<summary>Native build with CUDA, and the XR client</summary>

‎client/src/codescape/src/App.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { CommandPalette } from './ui/CommandPalette';
77
import { Hud, Inspector } from './ui/Hud';
88
import { Legend } from './ui/Legend';
99
import { PttButton } from './ui/PttButton';
10+
import { SpacePilotButton } from './ui/SpacePilotButton';
1011
import { Timeline } from './ui/Timeline';
1112

1213
function Connecting({ session }: { session: Session }) {
@@ -53,6 +54,7 @@ function Shell({ session }: { session: Session }) {
5354
<Captions />
5455
<div className="cs-bottom-row">
5556
<Timeline />
57+
<SpacePilotButton />
5658
<PttButton session={session} />
5759
</div>
5860
</div>
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
import { describe, expect, it } from 'vitest';
2+
import * as THREE from 'three';
3+
import { parseReport, SpacePilotDevice } from '../input/spacePilot';
4+
import { cameraDelta, DEFAULT_MOTION, isIdle, shape } from '../input/spaceMotion';
5+
import { applyDelta } from '../input/SpacePilotRig';
6+
7+
function i16(...vals: number[]): DataView {
8+
const b = new ArrayBuffer(vals.length * 2);
9+
const v = new DataView(b);
10+
vals.forEach((x, i) => v.setInt16(i * 2, x, true));
11+
return v;
12+
}
13+
14+
describe('SpacePilot report parsing', () => {
15+
it('decodes a 6-byte translation report', () => {
16+
expect(parseReport(1, i16(10, -20, 30))).toEqual({ axes: { tx: 10, ty: -20, tz: 30 } });
17+
});
18+
it('decodes a combined 12-byte 6-axis report with the driver sign convention', () => {
19+
const r = parseReport(1, i16(1, 2, 3, 4, 5, 6));
20+
expect(r.axes).toEqual({ tx: 1, ty: 2, tz: 3, rx: -4, ry: -5, rz: 6 });
21+
});
22+
it('decodes rotation and button reports; ignores unknown ids', () => {
23+
expect(parseReport(2, i16(7, 8, 9)).axes).toEqual({ rx: -7, ry: -8, rz: 9 });
24+
const b = new DataView(new ArrayBuffer(2));
25+
b.setUint16(0, 0b101, true);
26+
expect(parseReport(3, b)).toEqual({ buttons: 5 });
27+
expect(parseReport(9, i16(1))).toEqual({});
28+
});
29+
it('tolerates short payloads', () => {
30+
expect(parseReport(1, i16(5)).axes).toEqual({ tx: 5, ty: 0, tz: 0 });
31+
expect(parseReport(3, new DataView(new ArrayBuffer(0)))).toEqual({ buttons: 0 });
32+
});
33+
});
34+
35+
describe('SpacePilotDevice ingest', () => {
36+
it('merges axes across reports and fires rising-edge buttons once', () => {
37+
const d = new SpacePilotDevice();
38+
const pressed: number[] = [];
39+
d.onButton = (i) => pressed.push(i);
40+
d.ingest(1, i16(100, 0, 0));
41+
d.ingest(2, i16(0, 0, 50));
42+
expect(d.sample).toMatchObject({ tx: 100, rz: 50 });
43+
const b = new DataView(new ArrayBuffer(2));
44+
b.setUint16(0, 0b11, true);
45+
d.ingest(3, b);
46+
d.ingest(3, b); // held, no new edge
47+
b.setUint16(0, 0b10, true);
48+
d.ingest(3, b); // button 1 released
49+
b.setUint16(0, 0b11, true);
50+
d.ingest(3, b); // button 1 pressed again
51+
expect(pressed).toEqual([1, 2, 1]);
52+
});
53+
});
54+
55+
describe('camera motion mapping', () => {
56+
it('applies deadzone, clamps and a monotonic curve', () => {
57+
expect(shape(0, DEFAULT_MOTION)).toBe(0);
58+
expect(shape(10, DEFAULT_MOTION)).toBe(0);
59+
expect(shape(350, DEFAULT_MOTION)).toBeCloseTo(1, 6);
60+
expect(shape(-9999, DEFAULT_MOTION)).toBeCloseTo(-1, 6);
61+
const a = shape(100, DEFAULT_MOTION);
62+
const b = shape(200, DEFAULT_MOTION);
63+
expect(a).toBeGreaterThan(0);
64+
expect(b).toBeGreaterThan(a);
65+
});
66+
67+
const rest = { tx: 0, ty: 0, tz: 0, rx: 0, ry: 0, rz: 0 };
68+
69+
it('is idle at rest and ignores nothing but the deadzone', () => {
70+
expect(isIdle(rest)).toBe(true);
71+
expect(isIdle({ ...rest, ry: 350 })).toBe(false);
72+
});
73+
74+
/**
75+
* Direction contract shared with VisionClaw's SpacePilotController (camera
76+
* mode): the same puck gesture must move the camera the same way in both
77+
* apps. Values after the driver's sign convention (rx, ry negated).
78+
* VisionClaw: theta -= ry; phi += rx; camera += -tz forward; pan +tx, +ty.
79+
*/
80+
const table: Array<[string, Partial<typeof rest>, (d: ReturnType<typeof cameraDelta>) => boolean]> = [
81+
['sideways tilt +ry orbits left (theta decreases)', { ry: 350 }, (d) => d.azimuth < 0],
82+
['twist +rz orbits the same way as +ry', { rz: 350 }, (d) => d.azimuth < 0],
83+
['forward tilt +rx orbits up (phi increases)', { rx: 350 }, (d) => d.elevation > 0],
84+
['push +tz moves closer', { tz: 350 }, (d) => d.dollyFactor < 1],
85+
['pull -tz moves away', { tz: -350 }, (d) => d.dollyFactor > 1],
86+
['slide right +tx pans right', { tx: 350 }, (d) => d.panRight > 0],
87+
['slide up +ty pans up', { ty: 350 }, (d) => d.panUp > 0],
88+
];
89+
for (const [name, input, check] of table) {
90+
it(name, () => {
91+
expect(check(cameraDelta({ ...rest, ...input }, 0.1))).toBe(true);
92+
});
93+
}
94+
95+
it('clamps a stalled frame and combines yaw sources', () => {
96+
const push = cameraDelta({ ...rest, tz: 350 }, 1);
97+
expect(push.dollyFactor).toBeCloseTo(Math.exp(-DEFAULT_MOTION.dollyRate * 0.1), 6);
98+
const both = cameraDelta({ ...rest, ry: 350, rz: 350 }, 0.1);
99+
const one = cameraDelta({ ...rest, ry: 350 }, 0.1);
100+
// Yaw is clamped to full deflection, so tilt plus twist is no faster than either.
101+
expect(both.azimuth).toBeCloseTo(one.azimuth, 6);
102+
});
103+
104+
it('honours axis inversion', () => {
105+
const cfg = { ...DEFAULT_MOTION, invert: { ...DEFAULT_MOTION.invert, tz: true } };
106+
const d = cameraDelta({ ...rest, tz: 350 }, 0.1, cfg);
107+
expect(d.dollyFactor).toBeGreaterThan(1);
108+
});
109+
});
110+
111+
describe('applyDelta on an orbit camera', () => {
112+
it('keeps the camera looking at the target and respects distance limits', () => {
113+
const cam = new THREE.PerspectiveCamera();
114+
cam.position.set(0, 0, 10);
115+
const c = { target: new THREE.Vector3(0, 0, 0), minDistance: 2, maxDistance: 20 };
116+
applyDelta(cam, c, { azimuth: Math.PI / 2, elevation: 0, dollyFactor: 0.5, panRight: 0, panUp: 0 });
117+
expect(cam.position.distanceTo(c.target)).toBeCloseTo(5, 5);
118+
expect(Math.abs(cam.position.x)).toBeCloseTo(5, 5);
119+
const dir = new THREE.Vector3(0, 0, -1).applyQuaternion(cam.quaternion);
120+
expect(dir.dot(c.target.clone().sub(cam.position).normalize())).toBeCloseTo(1, 5);
121+
applyDelta(cam, c, { azimuth: 0, elevation: 0, dollyFactor: 0.01, panRight: 0, panUp: 0 });
122+
expect(cam.position.distanceTo(c.target)).toBeCloseTo(2, 5);
123+
});
124+
it('pans the target in the camera plane by a fraction of distance', () => {
125+
const cam = new THREE.PerspectiveCamera();
126+
cam.position.set(0, 0, 10);
127+
cam.lookAt(0, 0, 0);
128+
const c = { target: new THREE.Vector3(0, 0, 0), minDistance: 0, maxDistance: 0 };
129+
applyDelta(cam, c, { azimuth: 0, elevation: 0, dollyFactor: 1, panRight: 0.1, panUp: 0 });
130+
expect(c.target.x).toBeCloseTo(1, 5);
131+
expect(cam.position.x).toBeCloseTo(1, 5);
132+
});
133+
});
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/**
2+
* SpacePilot → camera, applied from inside `CameraRig`'s frame loop so the
3+
* puck and the fly-to animation never fight (the puck wins and cancels it).
4+
*
5+
* `useSpacePilotMotion` returns a per-frame function the rig calls just before
6+
* `controls.update()`. It also binds the puck's buttons to the same actions the
7+
* palette and voice grammar expose:
8+
*
9+
* 1 Overview · 2 Zoom in · 3 Zoom out · 4 Back · 5 Tier auto · 6 Tier L0 ·
10+
* 7 Tier L1 · 8 Tier L2 · 9 Clear selection · 10 Toggle hide tests
11+
*/
12+
import { useEffect, useMemo, useRef } from 'react';
13+
import * as THREE from 'three';
14+
import { dispatch } from '../store';
15+
import { cameraDelta, DEFAULT_MOTION, isIdle, type MotionConfig } from './spaceMotion';
16+
import { spacePilot } from './spacePilot';
17+
18+
const BUTTON_ACTIONS: Record<number, () => void> = {
19+
1: () => dispatch({ type: 'camera', kind: 'overview' }),
20+
2: () => dispatch({ type: 'camera', kind: 'zoom_in' }),
21+
3: () => dispatch({ type: 'camera', kind: 'zoom_out' }),
22+
4: () => dispatch({ type: 'back' }),
23+
5: () => dispatch({ type: 'tier_mode', mode: 'auto' }),
24+
6: () => dispatch({ type: 'tier_mode', mode: 'l0' }),
25+
7: () => dispatch({ type: 'tier_mode', mode: 'l1' }),
26+
8: () => dispatch({ type: 'tier_mode', mode: 'l2' }),
27+
9: () => dispatch({ type: 'select', id: null }),
28+
10: () => dispatch({ type: 'toggle_hide_tests' }),
29+
};
30+
31+
/** Bind puck buttons to store actions for the lifetime of the component. */
32+
export function useSpacePilotButtons(): void {
33+
useEffect(() => {
34+
const dev = spacePilot();
35+
dev.onButton = (i) => BUTTON_ACTIONS[i]?.();
36+
return () => {
37+
dev.onButton = () => {};
38+
};
39+
}, []);
40+
}
41+
42+
export interface OrbitLike {
43+
target: THREE.Vector3;
44+
minDistance: number;
45+
maxDistance: number;
46+
}
47+
48+
/**
49+
* Per-frame puck application. Returns `true` when the puck moved the camera
50+
* this frame, so the caller can drop any fly-to in progress.
51+
*/
52+
export function useSpacePilotMotion(motion?: Partial<MotionConfig>) {
53+
const cfg = useMemo<MotionConfig>(() => ({ ...DEFAULT_MOTION, ...motion }), [motion]);
54+
const offset = useRef(new THREE.Vector3());
55+
const spherical = useRef(new THREE.Spherical());
56+
const right = useRef(new THREE.Vector3());
57+
const up = useRef(new THREE.Vector3());
58+
59+
return (cam: THREE.PerspectiveCamera, c: OrbitLike, dt: number): boolean => {
60+
const dev = spacePilot();
61+
if (dev.state !== 'connected') return false;
62+
const s = dev.sample;
63+
if (isIdle(s, cfg)) return false;
64+
const d = cameraDelta(s, dt, cfg);
65+
applyDelta(cam, c, d, offset.current, spherical.current, right.current, up.current);
66+
return true;
67+
};
68+
}
69+
70+
/** Apply a delta to a camera orbiting `c.target`. Exported for tests. */
71+
export function applyDelta(
72+
cam: THREE.PerspectiveCamera,
73+
c: OrbitLike,
74+
d: ReturnType<typeof cameraDelta>,
75+
offset = new THREE.Vector3(),
76+
spherical = new THREE.Spherical(),
77+
right = new THREE.Vector3(),
78+
up = new THREE.Vector3(),
79+
): void {
80+
offset.copy(cam.position).sub(c.target);
81+
spherical.setFromVector3(offset);
82+
spherical.theta += d.azimuth;
83+
spherical.phi = THREE.MathUtils.clamp(spherical.phi - d.elevation, 0.05, Math.PI - 0.05);
84+
spherical.radius = THREE.MathUtils.clamp(spherical.radius * d.dollyFactor, c.minDistance || 0.01, c.maxDistance || Infinity);
85+
spherical.makeSafe();
86+
offset.setFromSpherical(spherical);
87+
88+
if (d.panRight !== 0 || d.panUp !== 0) {
89+
const dist = spherical.radius;
90+
cam.updateMatrix();
91+
right.setFromMatrixColumn(cam.matrix, 0).multiplyScalar(d.panRight * dist);
92+
up.setFromMatrixColumn(cam.matrix, 1).multiplyScalar(d.panUp * dist);
93+
c.target.add(right).add(up);
94+
}
95+
cam.position.copy(c.target).add(offset);
96+
cam.lookAt(c.target);
97+
}

0 commit comments

Comments
 (0)