Prompt specification
Build or customize the Three.js 3D scene "Spacecraft Body Axes and Antenna Direction" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Spacecraft Body Axes and Antenna Direction
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/spacecraft-body-axes-and-antenna-direction-x3821
Scene Description Prompt:
Spacecraft body axes and antenna direction. Model an original simple spacecraft with body axes, solar panels, and a directional antenna. Distinguish its orientation from a separate arrow showing travel direction. Please build this with Three.js from cdnjs in one self-contained HTML file, using stylized solid shapes.
Working Three.js Starter (spacecraft-body-axes-and-antenna-direction-x3821):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Spacecraft Attitude vs Travel Vector</title>
<style>
:root{ --gold:#ffc247; --mag:#ff5fd2; }
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#04060d;
font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;color:#dbe6f7}
#view{position:fixed;inset:0}
canvas{display:block}
#panel{
position:fixed;left:14px;top:14px;width:278px;padding:14px 15px 13px;
background:rgba(9,14,26,.80);border:1px solid rgba(120,150,200,.22);
border-radius:14px;backdrop-filter:blur(9px);
box-shadow:0 14px 44px rgba(0,0,0,.55);user-select:none}
#panel h1{margin:0 0 5px;font-size:12.5px;letter-spacing:.15em;font-weight:700}
#panel h1 span{color:#8ea6c6;font-weight:400}
#panel p.sub{margin:0 0 10px;font-size:11px;line-height:1.45;color:#93a7c4}
#compass{display:block;margin:2px auto 8px;border-radius:50%;
background:rgba(5,9,18,.6);border:1px solid rgba(120,150,200,.18)}
.rows{font-size:11px;margin-bottom:9px}
.rows div{display:flex;justify-content:space-between;padding:2.5px 0;
border-bottom:1px dashed rgba(120,150,200,.14)}
.rows b{font-variant-numeric:tabular-nums;letter-spacing:.03em}
.legend{font-size:10.5px;line-height:1.7;margin-bottom:9px}
.legend i{display:inline-block;width:16px;height:3px;margin-right:7px;
vertical-align:middle;border-radius:2px}
.ctrls{font-size:11px;display:grid;grid-template-columns:1fr 1fr;gap:5px 8px}
.ctrls label{display:flex;align-items:center;gap:6px;cursor:pointer;color:#bcd0ea}
.ctrls input{accent-color:var(--gold);margin:0}
.btns{display:flex;flex-wrap:wrap;gap:5px;margin-top:9px}
button{font:inherit;font-size:10.5px;color:#cfe0f5;background:rgba(120,160,220,.13);
border:1px solid rgba(140,175,225,.28);border-radius:7px;padding:5px 8px;cursor:pointer}
button:hover{background:rgba(140,175,225,.26)}
#hint{position:fixed;left:50%;bottom:12px;transform:translateX(-50%);
font-size:11px;color:#8ea6c6;background:rgba(9,14,26,.7);padding:6px 14px;
border-radius:20px;border:1px solid rgba(120,150,200,.18);pointer-events:none}
</style>
</head>
<body>
<div id="view"></div>
<div id="panel">
<h1>SPACECRAFT <span>ATTITUDE</span> vs <span>TRAVEL</span></h1>
<p class="sub">Solid red/green/blue arrows are the <b>body axes</b> — they rotate with the
vehicle. The amber arrow is the <b>travel vector</b> — fixed in the world frame.</p>
<canvas id="compass" width="192" height="192"></canvas>
<div class="rows">
<div><span>Course — travel direction (world)</span><b id="rCourse">—</b></div>
<div><span>Heading — body +Z (vehicle)</span><b id="rHead">—</b></div>
<div><span>Angle offset Δ</span><b id="rOff">—</b></div>
</div>
<div class="legend">
<div><i style="background:#ff4d5a"></i>Body X — solar array span</div>
<div><i style="background:#57e08a"></i>Body Y — up / deck</div>
<div><i style="background:#4ea8ff"></i>Body Z — forward / antenna boresight</div>
<div><i style="background:#ffc247"></i>Travel direction (world frame)</div>
<div><i style="background:#ff5fd2"></i>Angle between heading and course</div>
</div>
<div class="ctrls">
<label><input type="checkbox" id="cSpin" checked>Attitude rotation</label>
<label><input type="checkbox" id="cAxes" checked>Body axes</label>
<label><input type="checkbox" id="cTravel" checked>Travel arrow</label>
<label><input type="checkbox" id="cWorld" checked>World frame</label>
<label><input type="checkbox" id="cArc" checked>Angle arc</label>
<label><input type="checkbox" id="cLabels" checked>Part labels</label>
</div>
<div class="btns">
<button id="bAlign">Align nose to course</button>
<button data-view="iso">Reset view</button>
<button data-view="top">Top</button>
<button data-view="front">Front</button>
<button data-view="side">Side</button>
</div>
</div>
<div id="hint">drag = orbit · wheel = zoom · shift‑drag / right‑drag = pan</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ------------------------------------------------------------------ setup */
const viewEl = document.getElementById('view');
const renderer = new THREE.WebGLRenderer({ antialias:true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
viewEl.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x04060d);
const camera = new THREE.PerspectiveCamera(46, innerWidth/innerHeight, 0.1, 600);
scene.add(new THREE.HemisphereLight(0x93b4ff, 0x0a1020, 0.50));
const key = new THREE.DirectionalLight(0xffffff, 1.35);
key.position.set(9, 14, 7); key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
const sc = key.shadow.camera;
sc.left = -13; sc.right = 13; sc.top = 13; sc.bottom = -13; sc.near = 1; sc.far = 42;
key.shadow.bias = -0.0006;
scene.add(key);
const rim = new THREE.DirectionalLight(0x3f7dff, 0.75); rim.position.set(-10, 3, -9); scene.add(rim);
const fill = new THREE.DirectionalLight(0xff9a55, 0.30); fill.position.set(2, -6, -4); scene.add(fill);
/* starfield */
{
const N = 1600, p = new Float32Array(N*3);
for (let i = 0; i < N; i++) {
const th = Math.random()*Math.PI*2, ph = Math.acos(2*Math.random()-1), r = 70 + Math.random()*130;
p[i*3] = r*Math.sin(ph)*Math.cos(th);
p[i*3+1] = r*Math.cos(ph);
p[i*3+2] = r*Math.sin(ph)*Math.sin(th);
}
const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(p,3));
scene.add(new THREE.Points(g, new THREE.PointsMaterial({
color:0xcfe0ff, size:0.85, sizeAttenuation:true, transparent:true, opacity:0.85, depthWrite:false })));
}
/* ------------------------------------------------------------- utilities */
const UP = new THREE.Vector3(0,1,0);
function mat(color, opts={}) {
return new THREE.MeshStandardMaterial(Object.assign(
{ color, roughness:0.45, metalness:0.25, flatShading:true }, opts));
}
function mesh(parent, geo, material, pos) {
const m = new THREE.Mesh(geo, material);
if (pos) m.position.set(pos[0], pos[1], pos[2]);
m.castShadow = true; m.receiveShadow = true;
parent.add(m); return m;
}
function strut(a, b, r, material) {
const dir = new THREE.Vector3().subVectors(b, a), len = dir.length();
const m = new THREE.Mesh(new THREE.CylinderGeometry(r, r, len, 10), material);
m.position.copy(a).add(b).multiplyScalar(0.5);
m.quaternion.setFromUnitVectors(UP, dir.normalize());
m.castShadow = true; return m;
}
/* solid arrow: shaft + cone head, built along +Y, length L */
function makeArrow(color, L, shaftR=0.05, headR=0.15, headL=0.34, emissive=0.22) {
const g = new THREE.Group();
const m = new THREE.MeshStandardMaterial({
color, roughness:0.35, metalness:0.15, flatShading:true,
emissive:new THREE.Color(color), emissiveIntensity:emissive });
const shaft = new THREE.Mesh(new THREE.CylinderGeometry(shaftR, shaftR, L-headL, 14), m);
shaft.position.y = (L-headL)/2; shaft.castShadow = true; g.add(shaft);
const head = new THREE.Mesh(new THREE.ConeGeometry(headR, headL, 18), m);
head.position.y = L-headL/2; head.castShadow = true; g.add(head);
return g;
}
function makeLabel(text, color='#ffffff', width=2.4) {
const c = document.createElement('canvas'); c.width = 512; c.height = 128;
const x = c.getContext('2d');
x.clearRect(0,0,512,128);
x.font = 'bold 52px "Helvetica Neue", Helvetica, Arial, sans-serif';
x.textAlign = 'center'; x.textBaseline = 'middle';
x.shadowColor = 'rgba(0,0,0,0.95)'; x.shadowBlur = 14;
x.fillStyle = color; x.fillText(text, 256, 66);
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace;
tex.anisotropy = renderer.capabilities.getMaxAnisotropy();
const s = new THREE.Sprite(new THREE.SpriteMaterial({
map:tex, transparent:true, depthWrite:false }));
s.scale.set(width, width*128/512, 1);
return s;
}
/* ------------------------------------------------------------ the craft */
const M = {
hull: mat(0xd9dee8, { roughness:0.34, metalness:0.38 }),
dark: mat(0x39425c, { roughness:0.60, metalness:0.30 }),
gold: mat(0xf0b64b, { roughness:0.22, metalness:0.85 }),
teal: mat(0x2fa8a0, { roughness:0.45, metalness:0.25 }),
frame: mat(0xb9c2d0, { roughness:0.40, metalness:0.50 }),
cell: mat(0x16327a, { roughness:0.22, metalness:0.65 }),
cell2: mat(0x2f5bd6, { roughness:0.22, metalness:0.60 }),
dish: mat(0xf4f2e7, { roughness:0.50, metalness:0.12, side:THREE.DoubleSide }),
nozzle: mat(0x3a3f4a, { roughness:0.50, metalness:0.70, side:THREE.DoubleSide }),
flame: mat(0xff9a3c, { emissive:0xff7a10, emissiveIntensity:1.8, roughness:1 })
};
const craft = new THREE.Group(); // <-- everything that rotates = BODY frame
craft.rotation.y = 1.15; // initial attitude (not aligned with course)
scene.add(craft);
/* core bus + band */
mesh(craft, new THREE.CylinderGeometry(1.05,1.05,1.5,8), M.hull, [0,0,0]);
mesh(craft, new THREE.CylinderGeometry(1.08,1.08,0.24,8), M.dark, [0,0.02,0]);
/* top equipment deck + greebles */
mesh(craft, new THREE.CylinderGeometry(0.86,0.96,0.42,8), M.dark, [0,0.95,0]);
mesh(craft, new THREE.BoxGeometry(0.42,0.26,0.34), M.gold, [0.34,1.28,-0.18]);
mesh(craft, new THREE.BoxGeometry(0.26,0.30,0.26), M.teal, [-0.38,1.29,0.20]);
mesh(craft, new THREE.BoxGeometry(0.20,0.46,0.20), M.hull, [0.05,1.30,0.36]);
/* omni whip antennas */
mesh(craft, new THREE.CylinderGeometry(0.025,0.025,0.85,8), M.gold, [-0.62,1.60,-0.35]);
mesh(craft, new THREE.CylinderGeometry(0.025,0.025,0.60,8), M.gold, [0.58,1.52,0.42]);
/* main engine bell + plume */
mesh(craft, new THREE.CylinderGeometry(0.22,0.62,0.85,18,1,true), M.nozzle, [0,-1.16,0]);
mesh(craft, new THREE.CylinderGeometry(0.17,0.04,0.55,18), M.flame, [0,-1.82,0]);
/* side radiators */
mesh(craft, new THREE.BoxGeometry(1.05,0.66,0.07), M.frame, [0,0.12,1.06]);
mesh(craft, new THREE.BoxGeometry(1.05,0.66,0.07), M.frame, [0,0.12,-1.06]);
/* solar arrays (slightly below the equator so the X axis arrow stays readable) */
function solarArray(sign) {
const g = new THREE.Group();
g.add(strut(new THREE.Vector3(sign*0.95,-0.05,0), new THREE.Vector3(sign*1.85,-0.40,0), 0.075, M.dark));
mesh(g, new THREE.BoxGeometry(2.50,0.09,1.50), M.frame, [sign*2.90,-0.42,0]);
mesh(g, new THREE.BoxGeometry(2.36,0.03,1.36), M.cell, [sign*2.90,-0.36,0]);
for (let i = 0; i < 4; i++)
mesh(g, new THREE.BoxGeometry(0.035,0.02,1.36), M.cell2, [sign*(1.84+i*0.70),-0.345,0]);
for (let i = -1; i <= 1; i++)
mesh(g, new THREE.BoxGeometry(2.36,0.02,0.035), M.cell2, [sign*2.90,-0.345,i*0.46]);
craft.add(g);
}
solarArray(1); solarArray(-1);
/* directional (high-gain) antenna: parabolic lathe dish on a forward boom */
const dishPivot = new THREE.Group();
dishPivot.position.set(0, 1.25, 1.50);
dishPivot.rotation.x = Math.PI/3; // boresight -> (0,.5,.866)
{
const pts = [];
for (let i = 0; i <= 16; i++) { const r = 0.80*i/16; pts.push(new THREE.Vector2(r, (r*r)/(4*0.32))); }
mesh(dishPivot, new THREE.LatheGeometry(pts, 30), M.dish);
const rim = mesh(dishPivot, new THREE.TorusGeometry(0.80,0.035,8,34), M.gold,
[0, (0.80*0.80)/(4*0.32), 0]);
rim.rotation.x = Math.PI/2;
const feed = mesh(dishPivot, new THREE.ConeGeometry(0.13,0.30,14), M.gold, [0,0.58,0]);
feed.rotation.x = Math.PI;
mesh(dishPivot, new THREE.SphereGeometry(0.09,12,10), M.teal, [0,0.58,0]);
}
craft.add(dishPivot);
craft.add(strut(new THREE.Vector3(0,0.95,0.85), new THREE.Vector3(0,1.18,1.38), 0.06, M.hull));
/* small omni dish on the deck */
const omni = new THREE.Group(); omni.position.set(-0.62, 1.55, -0.35); omni.rotation.z = 0.35;
mesh(omni, new THREE.SphereGeometry(0.22, 16, 10, 0, Math.PI*2, 0, Math.PI/2), M.hull);
craft.add(omni);
/* ---- body axis triad (rigidly attached to the craft) ---- */
const axes = new THREE.Group(); craft.add(axes);
const AX_COL = { x:0xff4d5a, y:0x57e08a, z:0x4ea8ff };
const axisDefs = [
{ dir:new THREE.Vector3(1,0,0), len:5.05, col:AX_COL.x, lab:'X' },
{ dir:new THREE.Vector3(0,1,0), len:3.60, col:AX_COL.y, lab:'Y' },
{ dir:new THREE.Vector3(0,0,1), len:4.35, col:AX_COL.z, lab:'Z' }
];
for (const a of axisDefs) {
const g = makeArrow(a.col, a.len, 0.055, 0.17, 0.42, 0.35);
g.quaternion.setFromUnitVectors(UP, a.dir);
axes.add(g);
const lab = makeLabel(a.lab, '#ffffff', 0.62);
lab.position.copy(a.dir).multiplyScalar(a.len + 0.42);
axes.add(lab);
}
mesh(axes, new THREE.SphereGeometry(0.10,14,12),
mat(0xffffff, { emissive:0xffffff, emissiveIntensity:0.6 }), [0,0,0]);
/* part labels (toggleable) */
const partLabels = new THREE.Group(); craft.add(partLabels);
{
const l1 = makeLabel('SOLAR ARRAY', '#9fd0ff', 2.15); l1.position.set(4.55,0.05,0); partLabels.add(l1);
const l2 = makeLabel('HIGH-GAIN ANTENNA', '#ffd98a', 2.75); l2.position.set(0.05,2.15,2.15); partLabels.add(l2);
const l3 = makeLabel('MAIN ENGINE', '#ffb27a', 1.95); l3.position.set(0.05,-2.05,-0.95); partLabels.add(l3);
}
/* ------------------------------------------------- world frame / travel */
const travelDir = new THREE.Vector3(0.70, 0.10, 0.71).normalize(); // course, fixed in world
const courseAz = Math.atan2(travelDir.x, travelDir.z); // measured from +Z toward +X
const travelGroup = new THREE.Group(); scene.add(travelGroup);
{
const base = travelDir.clone().multiplyScalar(4.6);
const arr = makeArrow(0xffc247, 5.9, 0.11, 0.34, 0.90, 0.55);
arr.position.copy(base);
arr.quaternion.setFromUnitVectors(UP, travelDir);
travelGroup.add(arr);
const pathGeo = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0,0,0), base]);
const path = new THREE.Line(pathGeo, new THREE.LineDashedMaterial({
color:0xffc247, dashSize:0.38, gapSize:0.26, transparent:true, opacity:0.8 }));
path.computeLineDistances();
travelGroup.add(path);
const lab = makeLabel('TRAVEL DIRECTION · WORLD FRAME', '#ffc247', 3.6);
lab.position.copy(base).addScaledVector(travelDir, 3.0).add(new THREE.Vector3(0,0.45,0));
travelGroup.add(lab);
}
/* small pale world-frame triad (inertial reference, never rotates) */
const worldTriad = new THREE.Group();
worldTriad.position.set(-5.7, -2.7, 2.3);
scene.add(worldTriad);
{
const pale = 0xa9c4e8;
const defs = [ [new THREE.Vector3(1,0,0),'X' ], [new THREE.Vector3(0,1,0),'Y' ], [new THREE.Vector3(0,0,1),'Z' ] ];
for (const [d, t] of defs) {
const g = makeArrow(pale, 1.55, 0.028, 0.085, 0.20, 0.08);
g.quaternion.setFromUnitVectors(UP, d);
worldTriad.add(g);
const l = makeLabel(t, '#a9c4e8', 0.42);
l.position.copy(d).multiplyScalar(1.78);
worldTriad.add(l);
}
const lab = makeLabel('WORLD FRAME', '#a9c4e8', 1.85);
lab.position.set(0,-0.55,0); worldTriad.add(lab);
}
/* magenta angle arc between course and heading */
const ARC_R = 5.55;
const arcGroup = new THREE.Group(); scene.add(arcGroup);
const arcGeo = new THREE.BufferGeometry();
arcGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(49*3),3));
const arcLine = new THREE.Line(arcGeo, new THREE.LineBasicMaterial({
color:0xff5fd2, transparent:true, opacity:0.95 }));
arcLine.frustumCulled = false;
arcGroup.add(arcLine);
const markCourse = mesh(arcGroup, new THREE.SphereGeometry(0.10,14,12),
mat(0xffc247,{ emissive:0xffc247, emissiveIntensity:0.5 }), [0,0,0]);
const markHead = mesh(arcGroup, new THREE.SphereGeometry(0.10,14,12),
mat(0x4ea8ff,{ emissive:0x4ea8ff, emissiveIntensity:0.5 }), [0,0,0]);
const arcLabel = makeLabel('ANGLE OFFSET', '#ff5fd2', 2.0);
arcGroup.add(arcLabel);
/* --------------------------------------------------------- camera rig */
const cam = {
tTheta:2.20, tPhi:1.15, tRadius:20.0,
theta:2.20, phi:1.15, radius:20.0,
target:new THREE.Vector3(0,0.30,0)
};
function applyCamera(dt) {
const k = Math.min(1, dt*9);
cam.theta += (cam.tTheta-cam.theta)*k;
cam.phi += (cam.tPhi-cam.phi)*k;
cam.radius += (cam.tRadius-cam.radius)*k;
const sp = Math.sin(cam.phi), cp = Math.cos(cam.phi);
camera.position.set(
cam.target.x + cam.radius*sp*Math.sin(cam.theta),
cam.target.y + cam.radius*cp,
cam.target.z + cam.radius*sp*Math.cos(cam.theta));
camera.lookAt(cam.target);
}
const VIEWS = {
iso: { theta:2.20, phi:1.15, radius:20.0 },
top: { theta:2.20, phi:0.16, radius:22.0 },
front:{ theta:0.02, phi:1.32, radius:19.0 },
side: { theta:Math.PI/2, phi:1.32, radius:20.0 }
};
document.querySelectorAll('[data-view]').forEach(b => b.addEventListener('click', () => {
const v = VIEWS[b.dataset.view];
cam.tTheta = v.theta; cam.tPhi = v.phi; cam.tRadius = v.radius;
}));
/* hand-rolled orbit / zoom / pan controls */
const dom = renderer.domElement;
let drag = null;
dom.addEventListener('contextmenu', e => e.preventDefault());
dom.addEventListener('pointerdown', e => {
drag = { x:e.clientX, y:e.clientY, pan:(e.shiftKey || e.button === 2) };
dom.setPointerCapture(e.pointerId);
});
dom.addEventListener('pointermove', e => {
if (!drag) return;
const dx = e.clientX - drag.x, dy = e.clientY - drag.y;
drag.x = e.clientX; drag.y = e.clientY;
if (drag.pan) {
const dir = new THREE.Vector3(); camera.getWorldDirection(dir);
const right = new THREE.Vector3().crossVectors(dir, camera.up).normalize();
const upv = new THREE.Vector3().crossVectors(right, dir).normalize();
const s = cam.radius*0.0016;
cam.target.addScaledVector(right, -dx*s).addScaledVector(upv, dy*s);
} else {
cam.tTheta -= dx*0.006;
cam.tPhi = Math.min(Math.PI-0.12, Math.max(0.10, cam.tPhi - dy*0.006));
}
});
const endDrag = () => { drag = null; };
dom.addEventListener('pointerup', endDrag);
dom.addEventListener('pointercancel', endDrag);
dom.addEventListener('wheel', e => {
e.preventDefault();
cam.tRadius = Math.min(70, Math.max(4.5, cam.tRadius * (1 + Math.sign(e.deltaY)*0.09)));
}, { passive:false });
window.addEventListener('resize', () => {
camera.aspect = innerWidth/innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
/* --------------------------------------------------------------- UI wiring */
const el = id => document.getElementById(id);
const state = { spin:true, axes:true, travel:true, world:true, arc:true, labels:true };
['cSpin','cAxes','cTravel','cWorld','cArc','cLabels'].forEach(id => {
el(id).addEventListener('change', e => {
const key = { cSpin:'spin', cAxes:'axes', cTravel:'travel', cWorld:'world', cArc:'arc', cLabels:'labels' }[id];
state[key] = e.target.checked;
if (key === 'axes') axes.visible = state.axes;
if (key === 'travel') travelGroup.visible = state.travel;
if (key === 'world') worldTriad.visible = state.world;
if (key === 'arc') arcGroup.visible = state.arc;
if (key === 'labels') partLabels.visible = state.labels;
});
});
el('bAlign').addEventListener('click', () => {
craft.rotation.y = courseAz; craft.rotation.x = 0; craft.rotation.z = 0;
el('cSpin').checked = false; state.spin = false;
});
/* ------------------------------------------------------------- compass HUD */
const comp = el('compass'), ctx = comp.getContext('2d');
function drawCompass(hdg, crs) {
const W = comp.width, cx = W/2, cy = W/2, R = W*0.39;
ctx.clearRect(0,0,W,W);
ctx.beginPath(); ctx.arc(cx,cy,R+11,0,Math.PI*2);
ctx.fillStyle = 'rgba(6,11,21,.92)'; ctx.fill();
ctx.strokeStyle = 'rgba(130,160,210,.35)'; ctx.lineWidth = 1.5; ctx.stroke();
ctx.lineWidth = 1;
for (let i = 0; i < 36; i++) {
const a = i*Math.PI/18, big = (i % 9 === 0);
ctx.beginPath();
ctx.moveTo(cx+Math.sin(a)*(R-(big?10:5)), cy-Math.cos(a)*(R-(big?10:5)));
ctx.lineTo(cx+Math.sin(a)*R, cy-Math.cos(a)*R);
ctx.strokeStyle = big ? 'rgba(165,195,240,.75)' : 'rgba(130,160,210,.28)';
ctx.lineWidth = big ? 2 : 1; ctx.stroke();
}
ctx.font = 'bold 10px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillStyle = '#9fb4d8'; ctx.fillText('N', cx, cy-R+4); // world +Z = north
/* angle arc between heading and course */
let d = crs - hdg; while (d > Math.PI) d -= Math.PI*2; while (d < -Math.PI) d += Math.PI*2;
ctx.beginPath();
ctx.arc(cx, cy, R-17, hdg-Math.PI/2, crs-Math.PI/2, d < 0);
ctx.strokeStyle = '#ff5fd2'; ctx.lineWidth = 3; ctx.stroke();
const tip = (a, len, col, w, tag) => {
const dirX = Math.sin(a), dirY = -Math.cos(a);
const px = cx+dirX*len, py = cy+dirY*len;
ctx.beginPath(); ctx.moveTo(cx,cy); ctx.lineTo(px,py);
ctx.strokeStyle = col; ctx.lineWidth = w; ctx.stroke();
const bX = px-dirX*9, bY = py-dirY*9, pX = Math.cos(a)*4.5, pY = Math.sin(a)*4.5;
ctx.beginPath(); ctx.moveTo(px,py); ctx.lineTo(bX+pX,bY+pY); ctx.lineTo(bX-pX,bY-pY);
ctx.closePath(); ctx.fillStyle = col; ctx.fill();
ctx.font = 'bold 9px Arial'; ctx.fillStyle = col;
ctx.fillText(tag, cx+dirX*(len+11), cy+dirY*(len+11));
};
tip(crs, R*0.86, '#ffc247', 3, 'CRS');
tip(hdg, R*0.66, '#e8f1ff', 2.5, 'HDG');
}
/* ------------------------------------------------------------------- loop */
const clock = new THREE.Clock();
const fwd = new THREE.Vector3();
const tmp = new THREE.Vector3();
function updateArc(hdg) {
let d = hdg - courseAz; while (d > Math.PI) d -= Math.PI*2; while (d < -Math.PI) d += Math.PI*2;
const n = 48, arr = arcGeo.attributes.position.array;
for (let i = 0; i <= n; i++) {
const a = courseAz + d*i/n;
arr[i*3] = Math.sin(a)*ARC_R; arr[i*3+1] = 0.02; arr[i*3+2] = Math.cos(a)*ARC_R;
}
arcGeo.attributes.position.needsUpdate = true;
arcGeo.computeBoundingSphere();
markCourse.position.set(Math.sin(courseAz)*ARC_R, 0.02, Math.cos(courseAz)*ARC_R);
markHead.position.set(Math.sin(hdg)*ARC_R, 0.02, Math.cos(hdg)*ARC_R);
const mid = courseAz + d/2;
arcLabel.position.set(Math.sin(mid)*(ARC_R+0.9), 0.25, Math.cos(mid)*(ARC_R+0.9));
}
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const t = clock.elapsedTime;
if (state.spin) {
craft.rotation.y += 0.22*dt;
craft.rotation.x = 0.10*Math.sin(t*0.45); // gentle pitch wobble
}
craft.updateMatrixWorld();
fwd.set(0,0,1).applyQuaternion(craft.quaternion); // body +Z in world
const hdg = Math.atan2(fwd.x, fwd.z);
const hdgDeg = ((hdg*180/Math.PI)%360+360)%360;
const crsDeg = ((courseAz*180/Math.PI)%360+360)%360;
let off = ((hdgDeg-crsDeg)%360+540)%360-180; // signed, -180..180
el('rCourse').textContent = crsDeg.toFixed(1).padStart(5,' ') + '°';
el('rHead').textContent = hdgDeg.toFixed(1).padStart(5,' ') + '°';
el('rOff').textContent = (off>=0?'+':'') + off.toFixed(1) + '°';
if (state.arc) updateArc(hdg);
drawCompass(hdg, courseAz);
applyCamera(dt);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```