Cutaway skill: build, film and score a 3D object that takes itself apart from one picture
The skill (SKILL.md), the kit for building one HTML page and capturing a 60 fps film, the procedural sound engine, the green page and look, and 3 complete examples: a tarantula, a piranha and a wasp, each with a full film and a 10-second version. The method docs move into docs/ with the README's GIFs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+212
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/env python
|
||||
"""Beat map for a music track, so a sim can cut and hit on the music.
|
||||
|
||||
python sims/beats.py music/track.mp3 [--duration 30] [--start auto|SECONDS] [-o out.json]
|
||||
|
||||
Decodes with ffmpeg, then in pure Python:
|
||||
- tempo from the autocorrelation of the onset envelope (prefers 100-160 BPM),
|
||||
- the beat grid, aligned to the onsets,
|
||||
- downbeats (the beat phase with the most low-band attack),
|
||||
- kicks (low-band onset peaks, with strength 0..1),
|
||||
- energy per bar, and the drop (the biggest sustained jump in energy).
|
||||
|
||||
With --start auto the 30 s window is placed so the drop lands at ~40 % of the
|
||||
clip, snapped to a bar. All times in the output are relative to the window start.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from array import array
|
||||
|
||||
FFMPEG = os.environ.get('FFMPEG', 'ffmpeg')
|
||||
SR = 11025
|
||||
HOP = 256
|
||||
FPS = SR / HOP # envelope frames per second (~43)
|
||||
|
||||
|
||||
def decode(path, filt=None):
|
||||
cmd = [FFMPEG, '-v', 'error', '-i', path, '-ac', '1', '-ar', str(SR)]
|
||||
if filt:
|
||||
cmd += ['-af', filt]
|
||||
cmd += ['-f', 's16le', '-']
|
||||
raw = subprocess.run(cmd, check=True, capture_output=True).stdout
|
||||
a = array('h')
|
||||
a.frombytes(raw[: len(raw) // 2 * 2])
|
||||
return a
|
||||
|
||||
|
||||
def frame_energy(samples):
|
||||
n = len(samples) // HOP
|
||||
out = array('d', bytes(8 * n))
|
||||
for i in range(n):
|
||||
s = 0
|
||||
for x in samples[i * HOP:(i + 1) * HOP]:
|
||||
s += x * x
|
||||
out[i] = s / HOP
|
||||
return out
|
||||
|
||||
|
||||
def onset(env):
|
||||
"""Positive change of log energy, lightly smoothed."""
|
||||
lg = [math.log(1e-3 + e) for e in env]
|
||||
d = [0.0] + [max(0.0, lg[i] - lg[i - 1]) for i in range(1, len(lg))]
|
||||
return [0.5 * d[i] + 0.25 * (d[i - 1] if i else 0) + 0.25 * (d[i + 1] if i + 1 < len(d) else 0)
|
||||
for i in range(len(d))]
|
||||
|
||||
|
||||
def tempo(nov):
|
||||
"""Best period in frames from the autocorrelation, weighted toward ~126 BPM."""
|
||||
n = len(nov)
|
||||
mean = sum(nov) / n
|
||||
x = [v - mean for v in nov]
|
||||
best, best_lag = -1e18, None
|
||||
scores = {}
|
||||
lo = int(FPS * 60 / 190)
|
||||
hi = int(FPS * 60 / 70) + 1
|
||||
for lag in range(lo, hi):
|
||||
s = 0.0
|
||||
for i in range(n - lag):
|
||||
s += x[i] * x[i + lag]
|
||||
bpm = 60 * FPS / lag
|
||||
w = math.exp(-0.5 * (math.log2(bpm / 126) / 0.6) ** 2)
|
||||
scores[lag] = s
|
||||
if s * w > best:
|
||||
best, best_lag = s * w, lag
|
||||
# parabolic refinement
|
||||
l = best_lag
|
||||
if l - 1 in scores and l + 1 in scores:
|
||||
a, b, c = scores[l - 1], scores[l], scores[l + 1]
|
||||
den = a - 2 * b + c
|
||||
if den:
|
||||
l = l + 0.5 * (a - c) / den
|
||||
return l
|
||||
|
||||
|
||||
def beat_grid(nov, period):
|
||||
"""Phase of the grid that sits on the most onset energy, then local snapping."""
|
||||
n = len(nov)
|
||||
best, best_off = -1, 0
|
||||
for off in range(int(period) + 1):
|
||||
s, k = 0.0, 0
|
||||
while True:
|
||||
i = int(round(off + k * period))
|
||||
if i >= n:
|
||||
break
|
||||
s += nov[i]
|
||||
k += 1
|
||||
if s > best:
|
||||
best, best_off = s, off
|
||||
beats = []
|
||||
while best_off - period >= 0: # grid back to the very start
|
||||
best_off -= period
|
||||
k = 0
|
||||
while True:
|
||||
c = best_off + k * period
|
||||
if c >= n:
|
||||
break
|
||||
i = int(round(c))
|
||||
lo, hi = max(0, i - 2), min(n - 1, i + 2)
|
||||
j = max(range(lo, hi + 1), key=lambda q: nov[q])
|
||||
# only snap if the peak is clearly there, else keep the grid
|
||||
beats.append(j if nov[j] > 1.5 * nov[i] + 1e-9 else i)
|
||||
k += 1
|
||||
return beats
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('track')
|
||||
ap.add_argument('--duration', type=float, default=30)
|
||||
ap.add_argument('--start', default='auto')
|
||||
ap.add_argument('-o', '--out')
|
||||
args = ap.parse_args()
|
||||
|
||||
full = decode(args.track)
|
||||
low = decode(args.track, 'lowpass=f=140,lowpass=f=140')
|
||||
total = len(full) / SR
|
||||
env = frame_energy(full)
|
||||
envl = frame_energy(low)
|
||||
nov = onset(env)
|
||||
novl = onset(envl)
|
||||
comb = [a + 1.5 * b for a, b in zip(nov, novl)]
|
||||
|
||||
period = tempo(comb)
|
||||
bpm = 60 * FPS / period
|
||||
beats = beat_grid(comb, period)
|
||||
# downbeat phase: most low-band attack
|
||||
phase = max(range(4), key=lambda p: sum(novl[b] for b in beats[p::4]))
|
||||
downs = beats[phase::4]
|
||||
|
||||
# kicks: low-band onset peaks above an adaptive threshold
|
||||
srt = sorted(novl)
|
||||
thr = srt[int(len(srt) * 0.9)]
|
||||
peak = max(novl) or 1
|
||||
kicks = []
|
||||
for i in range(1, len(novl) - 1):
|
||||
if novl[i] > thr and novl[i] >= novl[i - 1] and novl[i] > novl[i + 1]:
|
||||
if not kicks or i - kicks[-1][0] > FPS * 0.18:
|
||||
kicks.append((i, novl[i] / peak))
|
||||
|
||||
# energy per bar
|
||||
bar_e = []
|
||||
for b in range(len(downs) - 1):
|
||||
seg = env[downs[b]:downs[b + 1]]
|
||||
bar_e.append(math.sqrt(sum(seg) / max(1, len(seg))))
|
||||
mx = max(bar_e) or 1
|
||||
bar_e = [e / mx for e in bar_e]
|
||||
|
||||
# drop: biggest jump vs the previous 4 bars that holds for the next 2
|
||||
drop_bar, best = None, 0
|
||||
for b in range(4, len(bar_e) - 2):
|
||||
before = sum(bar_e[b - 4:b]) / 4
|
||||
after = min(bar_e[b:b + 2])
|
||||
j = after - before
|
||||
if j > best:
|
||||
best, drop_bar = j, b
|
||||
drop_t = downs[drop_bar] / FPS if drop_bar is not None else None
|
||||
|
||||
D = args.duration
|
||||
if args.start == 'auto':
|
||||
if drop_t is not None and best > 0.12:
|
||||
want = drop_t - 0.4 * D
|
||||
else:
|
||||
# loudest window
|
||||
nb = max(1, int(D / (240 / bpm)))
|
||||
want_bar = max(range(max(1, len(bar_e) - nb)), key=lambda b: sum(bar_e[b:b + nb]))
|
||||
want = downs[want_bar] / FPS
|
||||
want = min(max(0.0, want), max(0.0, total - D))
|
||||
start = min((d / FPS for d in downs), key=lambda d: abs(d - want))
|
||||
if start + D > total:
|
||||
start = max(0.0, total - D)
|
||||
else:
|
||||
start = float(args.start)
|
||||
end = start + D
|
||||
|
||||
rel = lambda f: round(f / FPS - start, 3)
|
||||
inwin = lambda f: start - 1e-6 <= f / FPS < end
|
||||
bar_starts = [d for d in downs if inwin(d)]
|
||||
out = {
|
||||
'track': os.path.abspath(args.track),
|
||||
'start': round(start, 3),
|
||||
'duration': D,
|
||||
'bpm': round(bpm, 2),
|
||||
'beats': [rel(b) for b in beats if inwin(b)],
|
||||
'downbeats': [rel(d) for d in bar_starts],
|
||||
'kicks': [[rel(i), round(s, 3)] for i, s in kicks if inwin(i)],
|
||||
'barEnergy': [round(bar_e[downs.index(d)], 3) for d in bar_starts if downs.index(d) < len(bar_e)],
|
||||
'drop': round(drop_t - start, 3) if drop_t is not None and start <= drop_t < end else None,
|
||||
}
|
||||
path = args.out or os.path.splitext(args.track)[0] + f'.beats-{int(round(start))}.json'
|
||||
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
||||
with open(path, 'w') as f:
|
||||
json.dump(out, f)
|
||||
print(f'{os.path.basename(args.track)}: {out["bpm"]} bpm, window {start:.2f}-{end:.2f} s, '
|
||||
f'drop {"%.2f" % out["drop"] if out["drop"] is not None else "none"} (clip time), '
|
||||
f'{len(out["beats"])} beats, {len(out["kicks"])} kicks -> {path}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env node
|
||||
// Bundles every sims/<name>/main.js into one self-contained HTML file:
|
||||
// cutaway-out/dist/<name>.html (three.js, fonts, CSS inlined). Opens from file://,
|
||||
// works offline, can be published as-is.
|
||||
//
|
||||
// node sims/build.mjs every example in sims/
|
||||
// node sims/build.mjs v8-live one example
|
||||
// node sims/build.mjs ./my-machine your own sim: any folder with a main.js. Import the kit as
|
||||
// 'cutaway-kit/runtime.js', 'cutaway-kit/util.js' and so on.
|
||||
//
|
||||
// An entry may carry build.json with {"swap": {"heavy.glb": "light.glb"}}: every import of a file named heavy.glb is
|
||||
// served from light.glb in the same folder (a site page with lighter models than its film). {"external": {...}} does
|
||||
// the same but leaves the model out of the page: the import becomes the string "url:light.glb", the file is copied
|
||||
// next to the page and listed in <name>.assets.json (the site build copies those too). The page stays small enough
|
||||
// for link crawlers (X reads the share card from it). {"files": [...]} copies more files from node_modules next to the
|
||||
// page the same way (decoders a loader fetches at runtime).
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {DEPS, DIST, fromDeps} from '../paths.mjs';
|
||||
|
||||
const esbuild = fromDeps('esbuild');
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
fs.mkdirSync(DIST, {recursive: true});
|
||||
|
||||
const font = (weight) => {
|
||||
const file = path.join(
|
||||
DEPS,
|
||||
`@fontsource/jetbrains-mono/files/jetbrains-mono-latin-${weight}-normal.woff2`,
|
||||
);
|
||||
const b64 = fs.readFileSync(file).toString('base64');
|
||||
return `@font-face{font-family:'JetBrains Mono';font-weight:${weight};font-style:normal;font-display:block;src:url(data:font/woff2;base64,${b64}) format('woff2');}`;
|
||||
};
|
||||
const inter = fs.readFileSync(path.join(DEPS, '@fontsource-variable/inter/files/inter-latin-wght-normal.woff2')).toString('base64');
|
||||
const FONTS = [400, 600, 700].map(font).join('\n') +
|
||||
`\n@font-face{font-family:'Inter';font-weight:100 900;font-style:normal;font-display:block;src:url(data:font/woff2;base64,${inter}) format('woff2');}`;
|
||||
const KIT_CSS = fs.readFileSync(path.join(HERE, 'kit/style.css'), 'utf8');
|
||||
|
||||
const names = process.argv.slice(2).length
|
||||
? process.argv.slice(2)
|
||||
: fs
|
||||
.readdirSync(HERE)
|
||||
.filter((d) => fs.existsSync(path.join(HERE, d, 'main.js')));
|
||||
|
||||
// `cutaway-kit/x.js` resolves to sims/kit/x.js, so a sim outside this folder can use the kit.
|
||||
const kitPlugin = {
|
||||
name: 'cutaway-kit',
|
||||
setup(b) {
|
||||
b.onResolve({filter: /^cutaway-kit\//}, (args) => ({path: path.join(HERE, 'kit', args.path.slice('cutaway-kit/'.length))}));
|
||||
},
|
||||
};
|
||||
|
||||
for (const arg of names) {
|
||||
const dir = fs.existsSync(path.join(HERE, arg, 'main.js')) ? path.join(HERE, arg) : path.resolve(arg);
|
||||
if (!fs.existsSync(path.join(dir, 'main.js'))) {
|
||||
console.error(`no main.js in ${dir}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const name = path.basename(dir);
|
||||
const t0 = Date.now();
|
||||
const cfgFile = path.join(dir, 'build.json');
|
||||
const bcfg = fs.existsSync(cfgFile) ? JSON.parse(fs.readFileSync(cfgFile, 'utf8')) : {};
|
||||
const swap = bcfg.swap || {};
|
||||
const external = bcfg.external || {};
|
||||
const assets = [];
|
||||
const plugins = Object.keys(external).length
|
||||
? [
|
||||
{
|
||||
name: 'external',
|
||||
setup(b) {
|
||||
b.onResolve({filter: /\.glb$/}, (args) => {
|
||||
const base = path.basename(args.path);
|
||||
if (!external[base]) return undefined;
|
||||
const src = path.join(args.resolveDir, path.dirname(args.path), external[base]);
|
||||
if (!assets.includes(src)) assets.push(src);
|
||||
return {path: external[base], namespace: 'ext'};
|
||||
});
|
||||
b.onLoad({filter: /.*/, namespace: 'ext'}, (args) => ({contents: `export default ${JSON.stringify('url:' + args.path)};`, loader: 'js'}));
|
||||
},
|
||||
},
|
||||
]
|
||||
: Object.keys(swap).length
|
||||
? [
|
||||
{
|
||||
name: 'swap',
|
||||
setup(b) {
|
||||
b.onResolve({filter: /\.glb$/}, (args) => {
|
||||
const base = path.basename(args.path);
|
||||
if (!swap[base]) return undefined;
|
||||
return {path: path.join(args.resolveDir, path.dirname(args.path), swap[base])};
|
||||
});
|
||||
},
|
||||
},
|
||||
]
|
||||
: [];
|
||||
const res = await esbuild.build({
|
||||
plugins: [kitPlugin, ...plugins],
|
||||
entryPoints: [path.join(dir, 'main.js')],
|
||||
bundle: true,
|
||||
nodePaths: [DEPS],
|
||||
format: 'esm',
|
||||
minify: !process.env.SIMS_DEBUG,
|
||||
write: false,
|
||||
target: 'es2022',
|
||||
legalComments: 'none',
|
||||
loader: {'.glb': 'base64', '.woff2': 'base64'},
|
||||
logLevel: 'warning',
|
||||
});
|
||||
const js = res.outputFiles[0].text.replace(/<\/script/g, '<\\/script');
|
||||
const css = fs.existsSync(path.join(dir, 'style.css')) ? fs.readFileSync(path.join(dir, 'style.css'), 'utf8') : '';
|
||||
const html = `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>${name}</title>
|
||||
<style>
|
||||
${FONTS}
|
||||
${KIT_CSS}
|
||||
${css}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module">
|
||||
${js}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
const out = path.join(DIST, `${name}.html`);
|
||||
fs.writeFileSync(out, html);
|
||||
const listFile = path.join(DIST, `${name}.assets.json`);
|
||||
assets.push(...(bcfg.files || []).map((f) => path.join(DEPS, f)));
|
||||
if (assets.length) {
|
||||
for (const a of assets) fs.copyFileSync(a, path.join(DIST, path.basename(a)));
|
||||
fs.writeFileSync(listFile, JSON.stringify(assets.map((a) => path.basename(a))));
|
||||
} else if (fs.existsSync(listFile)) fs.rmSync(listFile);
|
||||
console.log(`${out} ${(html.length / 1024).toFixed(0)} KB ${Date.now() - t0} ms`);
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env node
|
||||
// Frame-accurate capture of a sim page to mp4: steps window.SIM.render(t) for
|
||||
// every frame in headless Chromium, screenshots, pipes to ffmpeg, then muxes
|
||||
// a music track if given.
|
||||
//
|
||||
// node sims/capture.mjs <name> [--config post.json] [--out cutaway-out/x.mp4]
|
||||
// [--size 1080x1350] [--dpr 1.3333] [--fps 60] [--from 0] [--to <duration>]
|
||||
// (--size is the layout in CSS px; --dpr multiplies the output: 1080x1350
|
||||
// at the default 4/3 gives a 1440x1800 video. Default 60 fps, crf 16.)
|
||||
// [--music music/track.mp3 [--music-start auto|SEC] [--no-sync] [--lufs -21]] [--crf 21]
|
||||
// [--still 12.5] (--still: one PNG, no video)
|
||||
// [--stills 0,4,9,14 --cols 3] (tiled review sheet, every tile labelled t=)
|
||||
// [--stills beats [--timeline f.json]] (one tile per timeline beat, +0.3 s so motion settles)
|
||||
// [--stills every:0.2 --from 3 --to 5] (scrub a transition)
|
||||
//
|
||||
// <name> is a sim built into cutaway-out/dist, or a path to any .html
|
||||
// that exposes window.seek(seconds) and freezes its clock on ?render
|
||||
// (motion-effects, vox-explainer, milestone-reveal, model-showdown). An .html
|
||||
// needs --to <seconds> unless it sets window.DURATION.
|
||||
import {spawn} from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {fileURLToPath, pathToFileURL} from 'node:url';
|
||||
import {CHROMIUM, CHROMIUM_ARGS, DIST, FFMPEG, OUT, PYTHON, playwright} from '../paths.mjs';
|
||||
|
||||
const {chromium} = playwright();
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const argv = process.argv.slice(2);
|
||||
const name = argv[0];
|
||||
const opt = (k, d) => {
|
||||
const i = argv.indexOf(`--${k}`);
|
||||
return i === -1 ? d : argv[i + 1];
|
||||
};
|
||||
if (!name) {
|
||||
console.error('usage: node sims/capture.mjs <name|file.html> [--config f.json] [--out f.mp4] [--music f.wav]');
|
||||
process.exit(1);
|
||||
}
|
||||
const SEEK = name.endsWith('.html');
|
||||
const html = SEEK ? path.resolve(name) : path.join(DIST, `${name}.html`);
|
||||
const label = SEEK ? path.basename(name, '.html') : name;
|
||||
if (!fs.existsSync(html)) {
|
||||
console.error(SEEK ? `missing ${html}` : `missing ${html}; run node sims/build.mjs ${name}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const [W, H] = opt('size', '1080x1350').split('x').map(Number);
|
||||
const config = opt('config') ? JSON.parse(fs.readFileSync(opt('config'), 'utf8')) : {};
|
||||
// --music <file> [--music-start auto|SECONDS]: analyse the track (sims/beats.py),
|
||||
// cut the window so the drop lands ~40% in, and give the beat map to the director.
|
||||
const music = opt('music');
|
||||
let beats = null;
|
||||
if (music) {
|
||||
const dur = Number(opt('to', config.duration ?? 30)) - Number(opt('from', 0));
|
||||
const ms = opt('music-start', 'auto');
|
||||
const cache = path.join(OUT, 'beats', `${path.basename(music).replace(/\.[^.]+$/, '')}-${ms}-${dur}.json`);
|
||||
fs.mkdirSync(path.dirname(cache), {recursive: true});
|
||||
const {execFileSync} = await import('node:child_process');
|
||||
if (!fs.existsSync(cache) || fs.statSync(cache).mtimeMs < fs.statSync(music).mtimeMs) {
|
||||
execFileSync(PYTHON, ['-I', path.join(HERE, 'beats.py'), music, '--duration', String(dur), '--start', ms, '-o', cache], {stdio: 'inherit'});
|
||||
}
|
||||
beats = JSON.parse(fs.readFileSync(cache, 'utf8'));
|
||||
if (!opt('no-sync')) config.beats = beats;
|
||||
}
|
||||
const still = opt('still');
|
||||
const stamp = new Date().toISOString().slice(5, 16).replace(/[-:T]/g, '');
|
||||
const out = path.resolve(opt('out', path.join(OUT, still ? `${label}-${still}.png` : `${label}-${stamp}.mp4`)));
|
||||
fs.mkdirSync(path.dirname(out), {recursive: true});
|
||||
|
||||
// Browser and GPU flags come from ../paths.mjs.
|
||||
const exe = CHROMIUM;
|
||||
const browser = await chromium.launch({
|
||||
executablePath: exe,
|
||||
args: CHROMIUM_ARGS,
|
||||
});
|
||||
const dpr = Number(opt('dpr', 4 / 3));
|
||||
const page = await browser.newPage({viewport: {width: W, height: H}, deviceScaleFactor: dpr});
|
||||
page.on('console', (m) => m.type() === 'error' && console.error('[page]', m.text()));
|
||||
page.on('pageerror', (e) => console.error('[page error]', e.message));
|
||||
await page.addInitScript((cfg) => {
|
||||
window.__CAPTURE = true;
|
||||
window.__SIM_CONFIG = cfg;
|
||||
}, config);
|
||||
await page.goto(pathToFileURL(html).href + (SEEK ? '?render' : ''));
|
||||
await page.waitForFunction(
|
||||
(seek) => (seek ? typeof window.seek === 'function' : window.SIM && window.SIM.ready),
|
||||
SEEK,
|
||||
{timeout: 60000},
|
||||
);
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
const info = await page.evaluate((seek) => {
|
||||
const gl = document.createElement('canvas').getContext('webgl2');
|
||||
const ext = gl && gl.getExtension('WEBGL_debug_renderer_info');
|
||||
return {
|
||||
duration: seek ? window.DURATION : window.SIM.duration,
|
||||
fps: seek ? window.FPS : window.SIM.fps,
|
||||
gpu: ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : 'unknown',
|
||||
};
|
||||
}, SEEK);
|
||||
console.log(`gpu: ${info.gpu}`);
|
||||
// One entry point for both contracts: a sim's SIM.render(t) or a page's seek(t).
|
||||
const draw = (t) => page.evaluate(([x, seek]) => (seek ? window.seek(x) : window.SIM.render(x)), [t, SEEK]);
|
||||
const end = Number(opt('to', info.duration));
|
||||
if (!Number.isFinite(end)) {
|
||||
console.error('no duration: pass --to <seconds> or set window.DURATION in the page');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// --stills: a list, `beats` (every number in the timeline, +0.3 s), or `every:<step>`.
|
||||
const stillTimes = (arg) => {
|
||||
if (arg === 'beats') {
|
||||
const file = opt('timeline', path.join(HERE, name, 'timeline.json'));
|
||||
const tl = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
const ts = [];
|
||||
const walk = (v, key) => {
|
||||
if (key === 'fps' || key === 'duration') return;
|
||||
if (typeof v === 'number') ts.push(v + 0.3);
|
||||
else if (Array.isArray(v)) v.forEach((x) => walk(x));
|
||||
else if (v && typeof v === 'object') Object.entries(v).forEach(([k, x]) => walk(x, k));
|
||||
};
|
||||
walk(tl);
|
||||
return [0, ...ts];
|
||||
}
|
||||
if (arg.startsWith('every:')) {
|
||||
const step = Number(arg.slice(6));
|
||||
const ts = [];
|
||||
for (let t = Number(opt('from', 0)); t <= end + 1e-6; t += step) ts.push(t);
|
||||
return ts;
|
||||
}
|
||||
return arg.split(',').map(Number);
|
||||
};
|
||||
|
||||
const stills = opt('stills');
|
||||
if (stills) {
|
||||
const ts = [...new Set(stillTimes(stills).map((t) => Math.min(Math.max(t, 0), end - 1 / 120).toFixed(2)))]
|
||||
.map(Number)
|
||||
.sort((a, b) => a - b);
|
||||
const dir = out.replace(/\.(png|mp4)$/, '') + '-frames';
|
||||
fs.mkdirSync(dir, {recursive: true});
|
||||
for (const [i, t] of ts.entries()) {
|
||||
await draw(t);
|
||||
// The t= label goes into the DOM for the screenshot only, so no ffmpeg font setup is needed.
|
||||
await page.evaluate((txt) => {
|
||||
const el = document.createElement('div');
|
||||
el.id = '__t';
|
||||
el.textContent = txt;
|
||||
el.style.cssText =
|
||||
'position:fixed;right:12px;top:12px;z-index:2147483647;font:600 28px monospace;color:#fff;background:rgba(0,0,0,.65);padding:4px 10px;border-radius:4px';
|
||||
document.body.appendChild(el);
|
||||
}, `t=${t.toFixed(2)}`);
|
||||
await page.screenshot({path: path.join(dir, `${String(i).padStart(3, '0')}.png`)});
|
||||
await page.evaluate(() => document.getElementById('__t')?.remove());
|
||||
}
|
||||
await browser.close();
|
||||
const cols = Math.min(ts.length, Number(opt('cols', 3)));
|
||||
const sheet = out.endsWith('.png') ? out : out.replace(/\.mp4$/, '') + '-sheet.png';
|
||||
const tw = Math.round(W * 0.4);
|
||||
const th = Math.round(H * 0.4);
|
||||
await new Promise((r) =>
|
||||
spawn(FFMPEG, ['-loglevel', 'error', '-y', '-framerate', '1', '-i', path.join(dir, '%03d.png'),
|
||||
'-vf', `scale=${tw}:${th},tile=${cols}x${Math.ceil(ts.length / cols)}:padding=4:color=0x333333`, '-frames:v', '1', sheet],
|
||||
{stdio: 'inherit'}).on('close', r),
|
||||
);
|
||||
console.log(`→ ${sheet} (full frames in ${dir})`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (still !== undefined) {
|
||||
await draw(Number(still));
|
||||
await page.screenshot({path: out});
|
||||
await browser.close();
|
||||
console.log(`→ ${out}`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const fps = Number(opt('fps', 60));
|
||||
const from = Number(opt('from', 0));
|
||||
const to = end;
|
||||
const frames = Math.round((to - from) * fps);
|
||||
const silent = music ? out.replace(/\.mp4$/, '-silent.mp4') : out;
|
||||
|
||||
const ff = spawn(
|
||||
FFMPEG,
|
||||
['-loglevel', 'error', '-y', '-f', 'image2pipe', '-framerate', String(fps), '-i', '-',
|
||||
'-c:v', 'libx264', '-preset', 'slow', '-crf', String(opt('crf', 16)), '-pix_fmt', 'yuv420p', '-movflags', '+faststart', silent],
|
||||
{stdio: ['pipe', 'inherit', 'inherit']},
|
||||
);
|
||||
const t0 = Date.now();
|
||||
for (let i = 0; i < frames; i++) {
|
||||
await draw(from + i / fps);
|
||||
const buf = await page.screenshot({type: 'jpeg', quality: 97});
|
||||
if (!ff.stdin.write(buf)) await new Promise((r) => ff.stdin.once('drain', r));
|
||||
if (i % fps === 0) process.stdout.write(`\r${i}/${frames} frames ${((Date.now() - t0) / 1000).toFixed(0)} s`);
|
||||
}
|
||||
ff.stdin.end();
|
||||
await new Promise((r) => ff.on('close', r));
|
||||
await browser.close();
|
||||
console.log(`\r${frames}/${frames} frames ${((Date.now() - t0) / 1000).toFixed(0)} s`);
|
||||
|
||||
if (music) {
|
||||
await new Promise((r, j) =>
|
||||
spawn(
|
||||
FFMPEG,
|
||||
['-loglevel', 'error', '-y', '-i', silent, '-ss', String(beats.start), '-i', music, '-map', '0:v', '-map', '1:a',
|
||||
'-c:v', 'copy', '-c:a', 'aac', '-b:a', '256k', '-af', `loudnorm=I=${opt('lufs', -21)}:TP=-3,afade=t=in:d=0.04,afade=t=out:st=${(to - from - 0.6).toFixed(2)}:d=0.6`,
|
||||
'-shortest', '-movflags', '+faststart', out],
|
||||
{stdio: 'inherit'},
|
||||
).on('close', (c) => (c === 0 ? r() : j(new Error('mux failed')))),
|
||||
);
|
||||
fs.rmSync(silent);
|
||||
}
|
||||
console.log(`→ ${out}`);
|
||||
@@ -0,0 +1,18 @@
|
||||
// print a film's anchor table A, the parts' rest points the close-up cameras aim at (node sims/green/anchors_dump.mjs <entry> <global>)
|
||||
import {pathToFileURL} from 'node:url';
|
||||
import path from 'node:path';
|
||||
import {CHROMIUM, CHROMIUM_ARGS, DIST, playwright} from '../../paths.mjs';
|
||||
|
||||
const [entry, glob] = process.argv.slice(2);
|
||||
const {chromium} = playwright();
|
||||
const browser = await chromium.launch({executablePath: CHROMIUM, args: CHROMIUM_ARGS});
|
||||
const page = await browser.newPage({viewport: {width: 1600, height: 900}, deviceScaleFactor: 1});
|
||||
await page.addInitScript(() => {
|
||||
window.__CAPTURE = true;
|
||||
window.__SIM_CONFIG = {};
|
||||
});
|
||||
await page.goto(pathToFileURL(path.join(DIST, `${entry}.html`)).href);
|
||||
await page.waitForFunction(() => window.SIM && window.SIM.ready, null, {timeout: 60000});
|
||||
const out = await page.evaluate((g) => JSON.stringify(Object.fromEntries(Object.entries(window[g].A).map(([k, v]) => [k, v.map((x) => +x.toFixed(2))]))), glob);
|
||||
console.log(out);
|
||||
await browser.close();
|
||||
@@ -0,0 +1,23 @@
|
||||
// print a film's camera every 0.5 s (node sims/green/cam_track.mjs <entry> <global> [step])
|
||||
import {pathToFileURL} from 'node:url';
|
||||
import path from 'node:path';
|
||||
import {CHROMIUM, CHROMIUM_ARGS, DIST, playwright} from '../../paths.mjs';
|
||||
const [entry, glob, step = '0.5'] = process.argv.slice(2);
|
||||
const {chromium} = playwright();
|
||||
const browser = await chromium.launch({executablePath: CHROMIUM, args: CHROMIUM_ARGS});
|
||||
const page = await browser.newPage({viewport: {width: 1600, height: 900}, deviceScaleFactor: 1});
|
||||
await page.addInitScript(() => { window.__CAPTURE = true; window.__SIM_CONFIG = {}; });
|
||||
await page.goto(pathToFileURL(path.join(DIST, `${entry}.html`)).href);
|
||||
await page.waitForFunction(() => window.SIM && window.SIM.ready, null, {timeout: 60000});
|
||||
const rows = await page.evaluate(([glob, step]) => {
|
||||
const T = window[glob].T;
|
||||
const out = [];
|
||||
for (let t = 0; t <= window.SIM.duration + 1e-6; t += Number(step)) {
|
||||
const s = T.stateAt(t);
|
||||
const c = s.cam;
|
||||
out.push(`${t.toFixed(1).padStart(5)} ${String(s.view).padEnd(9)} az ${c.az.toFixed(0).padStart(4)} el ${c.el.toFixed(0).padStart(3)} d ${c.d.toFixed(1)}`);
|
||||
}
|
||||
return out;
|
||||
}, [glob, step]);
|
||||
console.log(rows.join('\n'));
|
||||
await browser.close();
|
||||
@@ -0,0 +1,187 @@
|
||||
// The green page around a creature, in the look of a model-launch blog (first made for longcat/wasp, Vespera-07): white
|
||||
// paper with mint haze in the top corners, a wordmark, a centred title with a green rule and a row of pill buttons the
|
||||
// operator's cursor presses, a section list on the left that follows the act, white metric cards on the right, labels
|
||||
// as soft cards with leader lines. Shared by every creature's green film; what changes per creature (name, title, the
|
||||
// acts and their notes) comes in as options. 1600 x 900 layout px. update(s) redraws every live part from one frame.
|
||||
export const VIEWPORT = {x0: 250, x1: 1320, y0: 236, y1: 836};
|
||||
export const REST = [1250, 272];
|
||||
export const GREEN = '#16b364';
|
||||
|
||||
const CSS = `
|
||||
#app{width:1600px!important;height:900px!important;inset:auto!important;left:0;top:0;transform-origin:0 0;background:#fff}
|
||||
.vp{position:absolute;inset:0;pointer-events:none;font-family:'Inter',system-ui,sans-serif;color:#0f172a;-webkit-font-smoothing:antialiased}
|
||||
.vp *{box-sizing:border-box}
|
||||
.vp .haze{position:absolute;inset:0;mix-blend-mode:multiply;background:
|
||||
radial-gradient(520px 360px at 60px -40px, rgba(22,179,100,.16), rgba(22,179,100,0) 70%),
|
||||
radial-gradient(620px 420px at 1600px 20px, rgba(22,179,100,.14), rgba(22,179,100,0) 70%)}
|
||||
.vp .dots{position:absolute;right:0;top:0;width:420px;height:300px;opacity:.5;mix-blend-mode:multiply;
|
||||
background-image:radial-gradient(rgba(22,179,100,.35) 1px, transparent 1.4px);background-size:9px 9px;
|
||||
-webkit-mask-image:radial-gradient(360px 240px at 100% 0%, #000, transparent 75%);mask-image:radial-gradient(360px 240px at 100% 0%, #000, transparent 75%)}
|
||||
.vp .logo{position:absolute;left:46px;top:22px;display:flex;align-items:center;gap:10px;font:800 23px/1 'Inter',sans-serif;letter-spacing:-.3px}
|
||||
.vp .logo i{width:30px;height:30px;border-radius:9px;background:linear-gradient(135deg,#22c55e,#0e9f55);position:relative;display:block}
|
||||
.vp .logo i:after{content:'';position:absolute;left:8px;top:8px;width:14px;height:14px;border:3px solid #fff;border-radius:50%;border-right-color:transparent}
|
||||
.vp .lang{position:absolute;right:46px;top:20px;height:32px;padding:0 14px;border:1px solid #e2e8f0;border-radius:16px;display:flex;align-items:center;gap:8px;font:600 13px/1 'Inter',sans-serif;background:#fff}
|
||||
.vp .lang b{width:8px;height:8px;border-radius:50%;background:${GREEN};display:block;box-shadow:0 0 0 4px rgba(22,179,100,.15)}
|
||||
.vp .head{position:absolute;left:0;right:0;top:52px;text-align:center}
|
||||
.vp .head .ver{font:800 22px/1 'Inter',sans-serif;letter-spacing:-.3px}
|
||||
.vp .head .ver em{font-style:normal;color:${GREEN}}
|
||||
.vp .head h1{margin:10px 0 0;font:800 36px/1.05 'Inter',sans-serif;letter-spacing:-.8px}
|
||||
.vp .head .rule{width:84px;height:4px;border-radius:3px;margin:12px auto 0;background:linear-gradient(90deg,rgba(22,179,100,0),${GREEN} 30%,${GREEN} 70%,rgba(22,179,100,0))}
|
||||
.vp .head .date{margin-top:9px;font:500 13px/1 'Inter',sans-serif;color:#64748b}
|
||||
.vp .pills{position:absolute;left:0;right:0;top:180px;display:flex;justify-content:center;gap:10px}
|
||||
.vp .pill{height:34px;padding:0 15px;border:1px solid #e2e8f0;border-radius:17px;background:#fff;display:flex;align-items:center;gap:8px;font:600 13px/1 'Inter',sans-serif;color:#334155;transition:none}
|
||||
.vp .pill i{width:15px;height:15px;border-radius:50%;border:1.6px solid #94a3b8;display:block;position:relative}
|
||||
.vp .pill i:after{content:'';position:absolute;left:4px;top:3px;border-left:5px solid #94a3b8;border-top:3.5px solid transparent;border-bottom:3.5px solid transparent}
|
||||
.vp .pill.on{border-color:${GREEN};background:#effbf4;color:#0b7a43}
|
||||
.vp .pill.on i{border-color:${GREEN}}
|
||||
.vp .pill.on i:after{border-left-color:${GREEN}}
|
||||
.vp .pill.press{transform:scale(.95)}
|
||||
.vp .nav{position:absolute;left:58px;top:300px;width:190px;border-left:1.5px solid #e2e8f0;padding-left:0}
|
||||
.vp .nav div{position:relative;padding:7px 0 7px 18px;font:500 15px/1.2 'Inter',sans-serif;color:#94a3b8}
|
||||
.vp .nav div.on{color:#0f172a;font-weight:700}
|
||||
.vp .nav div.on:before{content:'';position:absolute;left:-2px;top:7px;bottom:7px;width:3px;border-radius:2px;background:#0f172a}
|
||||
.vp .nav div.sub{padding:4px 0 4px 30px;font:500 12.5px/1.2 'Inter',sans-serif;color:#64748b}
|
||||
.vp .cards{position:absolute;left:1340px;top:290px;width:220px;display:flex;flex-direction:column;gap:12px}
|
||||
.vp .card{background:rgba(255,255,255,.92);border:1px solid #e8edf3;border-radius:14px;padding:14px 16px;box-shadow:0 1px 2px rgba(15,23,42,.04),0 6px 18px rgba(15,23,42,.05)}
|
||||
.vp .card .k{font:600 11px/1 'Inter',sans-serif;letter-spacing:.6px;text-transform:uppercase;color:#64748b}
|
||||
.vp .card .v{margin-top:8px;font:800 28px/1 'Inter',sans-serif;letter-spacing:-.5px;font-variant-numeric:tabular-nums}
|
||||
.vp .card .v small{font-size:14px;font-weight:600;color:#64748b;margin-left:4px}
|
||||
.vp .card svg{display:block;margin-top:8px}
|
||||
.vp .bar{height:6px;border-radius:3px;background:#edf2f7;margin-top:10px;overflow:hidden}
|
||||
.vp .bar b{display:block;height:100%;background:${GREEN};border-radius:3px}
|
||||
.vp .servos{display:flex;gap:6px;align-items:flex-end;height:46px;margin-top:10px}
|
||||
.vp .servos b{flex:1;background:${GREEN};border-radius:3px 3px 1px 1px;opacity:.9}
|
||||
.vp .foot{position:absolute;left:262px;right:280px;top:852px;display:flex;align-items:center;gap:14px}
|
||||
.vp .foot .st{height:28px;padding:0 12px;border-radius:14px;background:#effbf4;color:#0b7a43;font:600 12.5px/28px 'Inter',sans-serif;white-space:nowrap;display:flex;align-items:center;gap:7px}
|
||||
.vp .foot .st b{width:7px;height:7px;border-radius:50%;background:${GREEN};display:block}
|
||||
.vp .foot .track{flex:1;height:3px;border-radius:2px;background:#e2e8f0;position:relative}
|
||||
.vp .foot .track b{position:absolute;left:0;top:0;bottom:0;background:${GREEN};border-radius:2px}
|
||||
.vp .foot .tm{font:600 12.5px/1 'Inter',sans-serif;color:#64748b;font-variant-numeric:tabular-nums}
|
||||
.vp svg.lines{position:absolute;left:0;top:0;width:1600px;height:900px;overflow:visible}
|
||||
.vp .lab{position:absolute;padding:8px 12px;background:#fff;border:1px solid #e2e8f0;border-radius:10px;box-shadow:0 4px 14px rgba(15,23,42,.08);white-space:nowrap}
|
||||
.vp .lab b{display:block;font:700 13.5px/1.15 'Inter',sans-serif;color:#0f172a}
|
||||
.vp .lab span{display:block;margin-top:3px;font:500 11.5px/1.1 'Inter',sans-serif;color:#64748b}
|
||||
.vp .cur{position:absolute;left:0;top:0;width:26px;height:26px}
|
||||
.vp .ring{position:absolute;width:46px;height:46px;margin:-23px 0 0 -23px;border-radius:50%;border:2px solid ${GREEN}}
|
||||
`;
|
||||
|
||||
export function createConsole(app, opts) {
|
||||
const {name, code, title, date} = opts;
|
||||
// the 4 cards: a value with a trace ('wave'), a value with a bar ('bar') or a row of load bars ('bars'); a plain
|
||||
// title string keeps the flying creatures' set (wingbeat, lift, servo load, battery)
|
||||
const KIND = ['wave', 'bar', 'bars', 'bar'];
|
||||
const UNIT = ['Hz', '%', '', '%'];
|
||||
const CARDS = (opts.cards ?? ['Wingbeat', 'Lift', 'Servo load', 'Battery']).map((c, i) => (typeof c === 'string' ? {k: c, kind: KIND[i], unit: UNIT[i], n: 6} : {n: 6, unit: '', ...c}));
|
||||
const cardHtml = (c, i) =>
|
||||
c.kind === 'wave'
|
||||
? `<div class="card"><div class="k">${c.k}</div><div class="v" data-c="${i}">0<small>${c.unit}</small></div><svg width="188" height="38" viewBox="0 0 188 38"><path data-w="${i}" fill="none" stroke="${GREEN}" stroke-width="2" stroke-linejoin="round"/></svg></div>`
|
||||
: c.kind === 'bars'
|
||||
? `<div class="card"><div class="k">${c.k}</div><div class="servos" data-s="${i}">${'<b></b>'.repeat(c.n)}</div></div>`
|
||||
: `<div class="card"><div class="k">${c.k}</div><div class="v" data-c="${i}">0<small>${c.unit}</small></div><div class="bar"><b data-b="${i}"></b></div></div>`;
|
||||
const NAV = opts.nav;
|
||||
const SUB = opts.sub;
|
||||
const PILLS = opts.pills;
|
||||
const st = document.createElement('style');
|
||||
st.textContent = CSS;
|
||||
document.head.appendChild(st);
|
||||
const root = document.createElement('div');
|
||||
root.className = 'vp';
|
||||
root.innerHTML = `
|
||||
<div class="haze"></div><div class="dots"></div>
|
||||
<div class="logo"><i></i>${name}</div>
|
||||
<div class="lang"><b></b>Live sim</div>
|
||||
<div class="head"><div class="ver">${name} <em>${code}</em></div><h1>${title}</h1><div class="rule"></div><div class="date">${date}</div></div>
|
||||
<div class="pills">${PILLS.map(([k, t]) => `<div class="pill" data-p="${k}"><i></i>${t}</div>`).join('')}</div>
|
||||
<div class="nav"></div>
|
||||
<div class="cards">${CARDS.map(cardHtml).join('')}
|
||||
</div>
|
||||
<div class="foot"><div class="st"><b></b><span data-v="status">Banking in</span></div><div class="track"><b data-v="prog"></b></div><div class="tm" data-v="time">00:00.0</div></div>
|
||||
<svg class="lines"></svg>
|
||||
<div class="labs"></div>
|
||||
<div class="ring" style="opacity:0"></div>
|
||||
<svg class="cur" viewBox="0 0 26 26" style="display:none"><path d="M3 2 L3 22 L8.5 17 L12.5 25 L16 23.4 L12 15.5 L19 15.5 Z" fill="#0f172a" stroke="#fff" stroke-width="1.6" stroke-linejoin="round"/></svg>`;
|
||||
app.appendChild(root);
|
||||
const $ = (q) => root.querySelector(q);
|
||||
const V = Object.fromEntries([...root.querySelectorAll('[data-v]')].map((e) => [e.dataset.v, e]));
|
||||
const pills = Object.fromEntries([...root.querySelectorAll('[data-p]')].map((e) => [e.dataset.p, e]));
|
||||
const cardV = CARDS.map((c, i) => root.querySelector(`[data-c="${i}"]`));
|
||||
const cardW = CARDS.map((c, i) => root.querySelector(`[data-w="${i}"]`));
|
||||
const cardB = CARDS.map((c, i) => root.querySelector(`[data-b="${i}"]`));
|
||||
const cardS = CARDS.map((c, i) => [...root.querySelectorAll(`[data-s="${i}"] b`)]);
|
||||
const nav = $('.nav');
|
||||
const lines = $('svg.lines');
|
||||
const labs = $('.labs');
|
||||
const cur = $('.cur');
|
||||
const ring = $('.ring');
|
||||
const spots = Object.fromEntries(Object.entries(pills).map(([k, e]) => [k, [e.offsetLeft + e.parentElement.offsetLeft + e.offsetWidth * 0.42, e.offsetTop + e.parentElement.offsetTop + e.offsetHeight * 0.58]]));
|
||||
let lastNav = '';
|
||||
const pool = [];
|
||||
const pad = (n) => String(Math.floor(n)).padStart(2, '0');
|
||||
|
||||
return {
|
||||
root,
|
||||
spots,
|
||||
pills,
|
||||
update(s) {
|
||||
// pills and the section list follow the act
|
||||
for (const [k, e] of Object.entries(pills)) e.classList.toggle('on', k === s.view);
|
||||
if (s.view !== lastNav) {
|
||||
lastNav = s.view;
|
||||
nav.innerHTML = NAV.map(([k, t]) => (k === s.view ? `<div class="on">${t}</div>${(SUB[k] ?? []).map((x) => `<div class="sub">${x}</div>`).join('')}` : `<div>${t}</div>`)).join('');
|
||||
}
|
||||
// cards: s.cards [{v, wave (-1..1) | bar (0..1) | bars (0..1 each)}], or the flying creatures' fields
|
||||
const cards = s.cards ?? [
|
||||
{v: s.freq.toFixed(1), wave: s.stroke.map((a) => a / 32)},
|
||||
{v: Math.round(Math.min(1, s.lift) * 100), bar: Math.min(1, s.lift)},
|
||||
{bars: s.servos},
|
||||
{v: Math.round(s.battery * 100), bar: s.battery},
|
||||
];
|
||||
cards.forEach((c, i) => {
|
||||
if (cardV[i]) cardV[i].innerHTML = `${c.v}<small>${CARDS[i].unit}</small>`;
|
||||
if (cardW[i] && c.wave) cardW[i].setAttribute('d', `M${c.wave.map((a, j) => `${((j / (c.wave.length - 1)) * 188).toFixed(1)},${(19 - Math.max(-1, Math.min(1, a)) * 15).toFixed(1)}`).join(' L')}`);
|
||||
if (cardB[i]) cardB[i].style.width = `${Math.round(Math.max(0, Math.min(1, c.bar ?? 0)) * 100)}%`;
|
||||
cardS[i].forEach((e, j) => (e.style.height = `${Math.round(8 + 38 * Math.max(0, Math.min(1, c.bars?.[j] ?? 0)))}px`));
|
||||
});
|
||||
V.status.textContent = s.status + (s.apart > 2 && s.status !== 'Hovering' ? ` · ${s.apart}% apart` : '');
|
||||
V.prog.style.width = `${Math.min(100, (s.time / s.dur) * 100)}%`;
|
||||
V.time.textContent = `00:${pad(s.time)}.${Math.floor((s.time % 1) * 10)}`;
|
||||
// labels
|
||||
let path = '';
|
||||
(s.callouts || []).forEach((c, i) => {
|
||||
let el = pool[i];
|
||||
if (!el) {
|
||||
el = document.createElement('div');
|
||||
el.className = 'lab';
|
||||
labs.appendChild(el);
|
||||
pool[i] = el;
|
||||
}
|
||||
el.style.display = 'block';
|
||||
el.style.opacity = String(c.o);
|
||||
el.innerHTML = `<b>${c.name}</b><span>${c.sub}</span>`;
|
||||
const w = el.offsetWidth;
|
||||
const left = c.w === 'l' ? c.label[0] : c.label[0] - w;
|
||||
el.style.left = `${left}px`;
|
||||
el.style.top = `${c.label[1]}px`;
|
||||
const ex = c.w === 'l' ? left + w : left;
|
||||
const ey = c.label[1] + 21;
|
||||
const k = Math.min(1, c.o * 1.2);
|
||||
const ax = ex + (c.at[0] - ex) * k;
|
||||
const ay = ey + (c.at[1] - ey) * k;
|
||||
path += `<path d="M${ex} ${ey} L${(ex + ax) / 2} ${ey} L${ax} ${ay}" stroke="rgba(100,116,139,${0.8 * c.o})" stroke-width="1.3" fill="none"/><circle cx="${c.at[0]}" cy="${c.at[1]}" r="${4.5 * k}" fill="${GREEN}" fill-opacity="${c.o}" stroke="#fff" stroke-width="1.5"/>`;
|
||||
});
|
||||
for (let i = (s.callouts || []).length; i < pool.length; i++) pool[i].style.display = 'none';
|
||||
lines.innerHTML = path;
|
||||
// cursor
|
||||
const c = s.cursor;
|
||||
if (c) {
|
||||
cur.style.display = 'block';
|
||||
cur.style.transform = `translate(${c.x - 3}px, ${c.y - 2}px) scale(${c.press ? 0.86 : 1})`;
|
||||
ring.style.opacity = String(c.ring * 0.9);
|
||||
ring.style.left = `${c.ringX}px`;
|
||||
ring.style.top = `${c.ringY}px`;
|
||||
ring.style.transform = `scale(${0.45 + (1 - c.ring) * 0.9})`;
|
||||
for (const [k, e] of Object.entries(pills)) e.classList.toggle('press', c.press && Math.hypot(spots[k][0] - c.x, spots[k][1] - c.y) < 40);
|
||||
} else cur.style.display = 'none';
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
// The green look for any creature film (first made for longcat/wasp and longcat/tarantula): the palette swap, the warm
|
||||
// glows turned green, the labels as two columns of soft cards inside the green page's viewport, and the operator's
|
||||
// pointer on its pill buttons. A creature's own film keeps its tour (movement, cameras, timing) and only routes its
|
||||
// state through these.
|
||||
import * as THREE from 'three';
|
||||
import {REST, VIEWPORT} from './console.js';
|
||||
|
||||
export const HUE = 0.405;
|
||||
export const ORANGE_TO = '#17b865';
|
||||
export const PAPER_GREEN = {top: '#ffffff', mid: '#fcfefd', low: '#f0f6f2', shadow: '#b4c6bd'};
|
||||
// the old consoles centre the subject in a 3D window at (800, 426); the green page's window centres at (785, 536)
|
||||
export const SHIFT = [-15, 110];
|
||||
|
||||
const ss = (a, b, t) => {
|
||||
const u = Math.min(1, Math.max(0, (t - a) / (b - a)));
|
||||
return u * u * u * (u * (u * 6 - 15) + 10);
|
||||
};
|
||||
|
||||
/** Every warm accent left in a creature's materials and lights (glows, tints, rims) turned to the same green. */
|
||||
export function retint(root) {
|
||||
const hsl = {};
|
||||
const fix = (c, minS = 0.4) => {
|
||||
if (!c?.isColor) return;
|
||||
// a glow colour above 1 (an HDR basic material, the octopus's coils and rings) is read and written at unit peak
|
||||
const k = Math.max(1, c.r, c.g, c.b);
|
||||
c.multiplyScalar(1 / k);
|
||||
c.getHSL(hsl);
|
||||
if ((hsl.h < 0.15 || hsl.h > 0.96) && hsl.s > minS) c.setHSL(HUE, Math.min(0.85, hsl.s), hsl.l);
|
||||
c.multiplyScalar(k);
|
||||
};
|
||||
const vc = new THREE.Color();
|
||||
root.traverse((o) => {
|
||||
// colours baked into a geometry's vertices (the shark's fang tips), turned once per geometry
|
||||
const ca = o.geometry?.attributes?.color;
|
||||
if (ca && !o.geometry.userData.tinted && [].concat(o.material || []).some((m) => m.vertexColors)) {
|
||||
o.geometry.userData.tinted = true;
|
||||
for (let i = 0; i < ca.count; i++) {
|
||||
vc.setRGB(ca.getX(i), ca.getY(i), ca.getZ(i));
|
||||
fix(vc);
|
||||
ca.setXYZ(i, vc.r, vc.g, vc.b);
|
||||
}
|
||||
ca.needsUpdate = true;
|
||||
}
|
||||
if (o.isLight && !o.userData.tinted) {
|
||||
o.userData.tinted = true;
|
||||
fix(o.color, 0.3);
|
||||
}
|
||||
for (const m of [].concat(o.material || [])) {
|
||||
// a colour the creature's pose rewrites every frame (the octopus's pulsing core) is turned again whenever it no
|
||||
// longer matches what was last written here
|
||||
const done = (m.userData.tinted ??= {});
|
||||
for (const key of ['color', 'emissive', 'attenuationColor']) {
|
||||
const c = m[key];
|
||||
if (!c?.isColor || done[key]?.equals(c)) continue;
|
||||
fix(c);
|
||||
done[key] = c.clone();
|
||||
}
|
||||
const u = m.uniforms?.uColor?.value;
|
||||
if (u?.isColor && !done.u?.equals(u)) {
|
||||
fix(u, 0.2);
|
||||
done.u = u.clone();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// the old consoles' capitals in the page's voice: units, axes and part codes keep their case
|
||||
const fixCase = (x) =>
|
||||
x
|
||||
.replace(/ø/g, 'Ø')
|
||||
.replace(/\bn·m\b/g, 'N·m')
|
||||
.replace(/\b(cpu|imu|ar|dof|led)\b/g, (m) => m.toUpperCase())
|
||||
.replace(/\b([lr])(\d)\b/g, (m, a, d) => a.toUpperCase() + d)
|
||||
.replace(/(\d) k\b/g, '$1 K');
|
||||
/** A part name in capitals, in sentence case. */
|
||||
export const nice = (s) => {
|
||||
const x = fixCase(s.toLowerCase());
|
||||
return x.charAt(0).toUpperCase() + x.slice(1);
|
||||
};
|
||||
/** A part's note in capitals, lower case with commas. */
|
||||
export const niceSub = (s) => fixCase(s.toLowerCase().replace(/ · /g, ', '));
|
||||
|
||||
/** Labels in two columns at the green viewport's edges; text: old capital name -> [name, sub] (or [name] to keep the
|
||||
* converted note) in the page's voice, anything missing converted by nice / niceSub. */
|
||||
export function makeLabels(st, anchors, text = {}) {
|
||||
const p = new THREE.Vector3();
|
||||
return ({set, o}) => {
|
||||
if (o < 0.02) return [];
|
||||
const pts = [];
|
||||
for (const [key, name, sub] of set) {
|
||||
const A = anchors[key];
|
||||
if (!A) continue;
|
||||
// an anchor is {obj, at} (a point on a part) or a function giving the world point (the octopus's)
|
||||
let w;
|
||||
if (typeof A === 'function') w = A();
|
||||
else {
|
||||
A.obj.updateWorldMatrix(true, false);
|
||||
w = A.obj.localToWorld(p.copy(A.at));
|
||||
}
|
||||
const at = st.project(w);
|
||||
const n2 = text[name]?.[0] ?? nice(name);
|
||||
const s2 = text[name]?.[1] ?? niceSub(sub);
|
||||
if (at && at[0] > VIEWPORT.x0 + 30 && at[0] < VIEWPORT.x1 - 30 && at[1] > VIEWPORT.y0 + 30 && at[1] < VIEWPORT.y1 - 60) pts.push({name: n2, sub: s2, at});
|
||||
}
|
||||
const mid = (VIEWPORT.x0 + VIEWPORT.x1) / 2;
|
||||
const out = [];
|
||||
const stack = (col, x, w) => {
|
||||
let y = Math.max(VIEWPORT.y0 + 30, Math.min(col.length ? col[0].at[1] - 10 : 0, VIEWPORT.y1 - 90 - 44 * col.length));
|
||||
for (const c of col) {
|
||||
y = Math.max(y, Math.min(VIEWPORT.y1 - 90, c.at[1] - 10));
|
||||
out.push({name: c.name, sub: c.sub, at: c.at, label: [x, y], w, o});
|
||||
y += 44;
|
||||
}
|
||||
};
|
||||
stack(pts.filter((x) => x.at[0] < mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x0 + 8, 'l');
|
||||
stack(pts.filter((x) => x.at[0] >= mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x1 - 8, 'r');
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
/** The operator's pointer on the pill buttons; button maps an act to its pill. */
|
||||
export function makeCursor(ui, SCRIPT, button = (act) => (act === 'assemble' ? 'exploded' : act)) {
|
||||
const EV = SCRIPT.filter((e) => e.t > 0 && ui.spots[button(e.act)]).map((e) => ({t: e.t, spot: ui.spots[button(e.act)]}));
|
||||
const [RX, RY] = REST;
|
||||
const WP = [[0, RX, RY + 40]];
|
||||
let [px, py, pt] = [RX, RY + 40, 0];
|
||||
EV.forEach((e) => {
|
||||
const [x, y] = e.spot;
|
||||
const travel = Math.min(0.6, 0.28 + Math.hypot(x - px, y - py) / 1000);
|
||||
const arrive = e.t - 0.08;
|
||||
WP.push([Math.max(pt + 0.01, arrive - travel), px, py]);
|
||||
WP.push([arrive, x, y], [e.t + 0.16, x, y]);
|
||||
[px, py, pt] = [x + 30, y + 46, e.t + 0.5];
|
||||
WP.push([pt, px, py]);
|
||||
});
|
||||
WP.push([pt + 0.8, RX, RY + 60]);
|
||||
return (t) => {
|
||||
let i = 0;
|
||||
while (i < WP.length - 2 && t > WP[i + 1][0]) i++;
|
||||
const [t0, x0, y0] = WP[i];
|
||||
const [t1, x1, y1] = WP[i + 1];
|
||||
const k = ss(t0, t1, t);
|
||||
const len = Math.hypot(x1 - x0, y1 - y0);
|
||||
const bow = Math.sin(Math.PI * k) * Math.min(20, len * 0.07);
|
||||
let press = false;
|
||||
let ring = 0;
|
||||
let rx = 0;
|
||||
let ry = 0;
|
||||
for (const e of EV) {
|
||||
if (t >= e.t - 0.07 && t < e.t + 0.09) press = true;
|
||||
if (t >= e.t && t < e.t + 0.5) {
|
||||
ring = 1 - (t - e.t) / 0.5;
|
||||
[rx, ry] = e.spot;
|
||||
}
|
||||
}
|
||||
return {x: x0 + (x1 - x0) * k + (len ? (-(y1 - y0) / len) * bow : 0), y: y0 + (y1 - y0) * k + (len ? ((x1 - x0) / len) * bow : 0), press, ring, ringX: rx, ringY: ry};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// list the warm colours left on a green film's creature at time t (node sims/green/probe_warm.mjs <entry> <t> <global>)
|
||||
import {pathToFileURL} from 'node:url';
|
||||
import path from 'node:path';
|
||||
import {CHROMIUM, CHROMIUM_ARGS, DIST, playwright} from '../../paths.mjs';
|
||||
const [entry, t, glob] = process.argv.slice(2);
|
||||
const {chromium} = playwright();
|
||||
const browser = await chromium.launch({executablePath: CHROMIUM, args: CHROMIUM_ARGS});
|
||||
const page = await browser.newPage({viewport: {width: 1600, height: 900}, deviceScaleFactor: 1});
|
||||
await page.addInitScript(() => { window.__CAPTURE = true; window.__SIM_CONFIG = {}; });
|
||||
await page.goto(pathToFileURL(path.join(DIST, `${entry}.html`)).href);
|
||||
await page.waitForFunction(() => window.SIM && window.SIM.ready, null, {timeout: 60000});
|
||||
const res = await page.evaluate(([t, glob]) => {
|
||||
window.SIM.render(Number(t));
|
||||
const out = {};
|
||||
const warm = (c) => {
|
||||
if (!c?.isColor) return false;
|
||||
const k = Math.max(1e-6, c.r, c.g, c.b);
|
||||
const r = c.r / k, g = c.g / k, b = c.b / k;
|
||||
return r > 0.9 && b < 0.6 && g < 0.85 && r - b > 0.3;
|
||||
};
|
||||
const hex = (c) => [c.r, c.g, c.b].map((v) => v.toFixed(2)).join(',');
|
||||
const scene = window[glob].st.scene ?? null;
|
||||
const roots = [window[glob].oc?.root ?? window[glob].sp?.root ?? window[glob].fish?.root ?? window[glob].bee?.root];
|
||||
if (scene) roots.push(scene);
|
||||
for (const [ri, r] of roots.entries()) r.traverse((o) => {
|
||||
if (o.isLight && warm(o.color)) out[`${ri} light ${o.type} ${hex(o.color)}`] = (out[`${ri} light ${o.type} ${hex(o.color)}`] ?? 0) + 1;
|
||||
for (const m of [].concat(o.material || [])) for (const key of ['color', 'emissive', 'attenuationColor', 'sheenColor', 'specularColor']) if (warm(m[key])) { const id = `${ri} ${m.type} ${key} ${hex(m[key])} map:${!!m.map} emap:${!!m.emissiveMap} vc:${!!m.vertexColors}`; out[id] = (out[id] ?? 0) + 1; }
|
||||
for (const [nm, at] of [['vertex', o.geometry?.attributes?.color], ['instance', o.instanceColor]]) {
|
||||
if (!at) continue;
|
||||
let n = 0;
|
||||
const c = {isColor: true, r: 0, g: 0, b: 0};
|
||||
for (let i = 0; i < at.count; i++) {
|
||||
c.r = at.getX(i); c.g = at.getY(i); c.b = at.getZ(i);
|
||||
if (warm(c)) n++;
|
||||
}
|
||||
if (n) out[`${ri} ${nm} colours warm: ${n} of ${at.count}`] = (out[`${ri} ${nm} colours warm: ${n} of ${at.count}`] ?? 0) + 1;
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}, [t, glob]);
|
||||
console.log(JSON.stringify(res, null, 1));
|
||||
await browser.close();
|
||||
@@ -0,0 +1,300 @@
|
||||
import {clamp01, easeOutExpo, fmt, hash, smooth} from './util.js';
|
||||
|
||||
/**
|
||||
* The director edits a sim to the music: hard cuts between wide and tight
|
||||
* shots on bar lines, punch-ins on kicks, a shake and flash on the drop,
|
||||
* glitches on stage changes, and big readable story captions on the beat.
|
||||
*
|
||||
* Beats come from cfg.beats (sims/beats.py output, injected by capture.mjs).
|
||||
* Without music it runs on a synthetic grid (cfg.director.bpm) so live pages
|
||||
* still feel edited.
|
||||
*
|
||||
* Shots crop the 3D render (crisp re-render of a sub-rectangle) when the sim
|
||||
* uses kit/stage3d; otherwise they scale the target element with CSS.
|
||||
* Sims can return `foci: [{x, y}]` (screen px) in their render info: tight
|
||||
* shots frame those points.
|
||||
*
|
||||
* Story: cfg.story = [{at | bar | drop, text, sub, kind: 'hero'|'num', hold,
|
||||
* from, to, prefix, suffix, tag}]. `drop` is in bars relative to the drop,
|
||||
* `bar` counts bars from the clip start, `hold` is in beats. *word* gets the
|
||||
* accent box.
|
||||
*/
|
||||
export const DIRECTOR = {
|
||||
enabled: true,
|
||||
bpm: 128,
|
||||
drop: null,
|
||||
hero: null,
|
||||
// cut every N beats before / after the drop
|
||||
cutBeats: [4, 2],
|
||||
shots: [
|
||||
{z: 1},
|
||||
{z: 1.75, f: 0},
|
||||
{z: 1.3, f: 1},
|
||||
{z: 2.2, f: 2},
|
||||
{z: 1.12, f: 0},
|
||||
{z: 1.6, f: 1},
|
||||
],
|
||||
punch: [0.03, 0.07],
|
||||
shake: 1,
|
||||
flash: 1,
|
||||
glitch: 1,
|
||||
target: '#gl',
|
||||
};
|
||||
|
||||
const before = (arr, t) => {
|
||||
let lo = 0;
|
||||
let hi = arr.length;
|
||||
while (lo < hi) {
|
||||
const m = (lo + hi) >> 1;
|
||||
if (arr[m] <= t) lo = m + 1;
|
||||
else hi = m;
|
||||
}
|
||||
return lo - 1;
|
||||
};
|
||||
|
||||
export function createDirector(app, cfg) {
|
||||
const d = {...DIRECTOR, ...(cfg.director || {})};
|
||||
const D = cfg.duration;
|
||||
const music = cfg.beats && cfg.beats.beats && cfg.beats.beats.length > 4;
|
||||
const spb = music ? 60 / cfg.beats.bpm : 60 / d.bpm;
|
||||
const beats = music ? cfg.beats.beats : Array.from({length: Math.ceil(D / spb) + 8}, (_, i) => i * spb);
|
||||
// pad the grid past both ends so lookups never fall off
|
||||
while (beats[0] > 0) beats.unshift(beats[0] - spb);
|
||||
while (beats[beats.length - 1] < D + 4 * spb) beats.push(beats[beats.length - 1] + spb);
|
||||
let downs = music && cfg.beats.downbeats.length ? cfg.beats.downbeats.slice() : beats.filter((_, i) => i % 4 === 0);
|
||||
while (downs[0] > 0) downs.unshift(downs[0] - 4 * spb);
|
||||
while (downs[downs.length - 1] < D + 8 * spb) downs.push(downs[downs.length - 1] + 4 * spb);
|
||||
const kicks = music ? cfg.beats.kicks : beats.map((b) => [b, 0.8]);
|
||||
const kickT = kicks.map((k) => k[0]);
|
||||
const energy = music ? cfg.beats.barEnergy : null;
|
||||
const drop = (music && cfg.beats.drop) ?? d.drop ?? Math.round((0.4 * D) / (4 * spb)) * 4 * spb;
|
||||
const dropBar = before(downs, drop + 0.01);
|
||||
|
||||
const barTime = (b) => downs[Math.max(0, Math.min(downs.length - 1, b))];
|
||||
|
||||
// ---- time warp: the sim's hero moment lands on the drop
|
||||
const warp = (t) => {
|
||||
if (d.hero == null || !d.enabled) return t;
|
||||
const h = d.hero;
|
||||
if (t <= drop) return (t / drop) * h;
|
||||
return h + ((t - drop) / (D - drop)) * (D - h);
|
||||
};
|
||||
|
||||
const beat = (t) => {
|
||||
const sh = shotAt(t);
|
||||
const bi = before(beats, t);
|
||||
const b0 = beats[Math.max(0, bi)];
|
||||
const b1 = beats[bi + 1] ?? b0 + spb;
|
||||
const ri = before(downs, t);
|
||||
const r0 = downs[Math.max(0, ri)];
|
||||
const r1 = downs[ri + 1] ?? r0 + 4 * spb;
|
||||
const ki = before(kickT, t);
|
||||
const kick = ki >= 0 ? kicks[ki][1] * Math.exp(-(t - kicks[ki][0]) / 0.11) : 0;
|
||||
const down = Math.exp(-(t - r0) / 0.18);
|
||||
return {
|
||||
music,
|
||||
bpm: 60 / spb,
|
||||
beat: bi,
|
||||
beatPhase: clamp01((t - b0) / (b1 - b0)),
|
||||
bar: ri,
|
||||
barPhase: clamp01((t - r0) / (r1 - r0)),
|
||||
kick,
|
||||
down,
|
||||
energy: energy ? energy[Math.max(0, Math.min(energy.length - 1, ri))] ?? 1 : 1,
|
||||
drop,
|
||||
sinceDrop: t - drop,
|
||||
isDrop: t >= drop,
|
||||
// current shot: sims may change camera angle per shot index
|
||||
shot: sh.k,
|
||||
shotZ: sh.shot.z || 1,
|
||||
};
|
||||
};
|
||||
|
||||
// ---- story timing
|
||||
const story = (cfg.story || []).map((s, i) => {
|
||||
const start = s.at ?? (s.bar != null ? barTime(s.bar) : s.drop != null ? barTime(dropBar + s.drop) : 0);
|
||||
const b0 = before(beats, start + 0.02);
|
||||
const hold = s.hold ?? 8;
|
||||
const end = s.end ?? beats[Math.min(beats.length - 1, b0 + hold)] ?? start + hold * spb;
|
||||
return {...s, i, start, end, b0};
|
||||
});
|
||||
|
||||
// ---- DOM layers
|
||||
app.insertAdjacentHTML(
|
||||
'beforeend',
|
||||
`<canvas class="dir-glitch"></canvas><div class="dir-flash"></div><div class="dir-story"></div>`,
|
||||
);
|
||||
const gcv = app.querySelector('.dir-glitch');
|
||||
const gctx = gcv.getContext('2d');
|
||||
const flash = app.querySelector('.dir-flash');
|
||||
const storyEl = app.querySelector('.dir-story');
|
||||
|
||||
let foci = [];
|
||||
let crop = {z: 1, x0: 0, y0: 0};
|
||||
let built = -1;
|
||||
let parts = null;
|
||||
|
||||
const stageCuts = (cfg.stages || []).map((s) => s.at).filter((a) => a > 0.2);
|
||||
|
||||
const dropBeat = before(beats, drop + 0.01);
|
||||
function shotAt(t) {
|
||||
const bi = before(beats, t);
|
||||
const isDrop = t >= drop;
|
||||
const every = isDrop ? d.cutBeats[1] : d.cutBeats[0];
|
||||
// the first beats of the drop always open wide
|
||||
if (isDrop && bi - dropBeat < every) return {shot: d.shots[0], k: 0};
|
||||
const rel = isDrop ? bi - dropBeat : bi - before(beats, 0.01);
|
||||
const k = Math.floor(rel / every) + (isDrop ? 1000 : 0);
|
||||
return {shot: d.shots[((k % d.shots.length) + d.shots.length) % d.shots.length], k};
|
||||
}
|
||||
|
||||
const target = () => document.querySelector(d.target);
|
||||
|
||||
return {
|
||||
warp,
|
||||
beat,
|
||||
/** Before the sim renders: set this frame's crop. */
|
||||
pre(t) {
|
||||
if (!d.enabled) return;
|
||||
const {shot} = shotAt(t);
|
||||
const b = beat(t);
|
||||
const punch = 1 + (b.isDrop ? d.punch[1] : d.punch[0]) * b.kick;
|
||||
const drift = 1 + 0.035 * b.barPhase;
|
||||
let z = (shot.z || 1) * punch * (shot.z > 1 ? drift : 1);
|
||||
const vw = innerWidth;
|
||||
const vh = innerHeight;
|
||||
let f = {x: vw / 2, y: vh / 2};
|
||||
if (shot.z > 1 && foci.length) f = foci[(shot.f ?? 0) % foci.length];
|
||||
else if (window.__STAGE) {
|
||||
const vp = window.__STAGE.hudViewport();
|
||||
f = {x: vw / 2, y: (vp.top + vh - vp.bottom) / 2};
|
||||
}
|
||||
// drop shake (decays over ~0.6 s)
|
||||
const sk = d.shake * (b.sinceDrop >= 0 ? Math.exp(-b.sinceDrop / 0.25) : 0);
|
||||
const sx = sk * (hash(t * 91.7) - 0.5) * 26;
|
||||
const sy = sk * (hash(t * 53.3 + 7) - 0.5) * 26;
|
||||
const st = window.__STAGE;
|
||||
if (st) {
|
||||
crop = st.setCrop(z, f.x + sx, f.y + sy);
|
||||
} else {
|
||||
const el = target();
|
||||
if (el) {
|
||||
el.style.transformOrigin = `${f.x}px ${f.y}px`;
|
||||
el.style.transform = `translate(${sx}px, ${sy}px) scale(${z})`;
|
||||
}
|
||||
crop = {z: 1, x0: 0, y0: 0};
|
||||
}
|
||||
},
|
||||
/** After the sim renders: remember its foci, draw overlays and the story. */
|
||||
post(t, info = {}) {
|
||||
if (!d.enabled) return;
|
||||
if (info.foci && info.foci.length) {
|
||||
// convert from this frame's cropped screen back to base screen coords
|
||||
foci = info.foci.map((p) => ({x: crop.x0 + p.x / crop.z, y: crop.y0 + p.y / crop.z}));
|
||||
}
|
||||
const b = beat(t);
|
||||
const vw = innerWidth;
|
||||
const vh = innerHeight;
|
||||
|
||||
// flash: accent bloom on downbeats after the drop, white hit on the drop
|
||||
const dropHit = b.sinceDrop >= 0 ? Math.exp(-b.sinceDrop / 0.22) : 0;
|
||||
const onBar = b.isDrop ? 0.16 * b.down * b.energy : 0;
|
||||
flash.style.opacity = String(d.flash * Math.min(0.85, dropHit * 0.7 + onBar));
|
||||
|
||||
// glitch: 3 frames around each stage change and the drop
|
||||
const gl = [...stageCuts, b.drop].some((c) => t >= c - 0.03 && t < c + 0.1);
|
||||
if (gcv.width !== vw || gcv.height !== vh) {
|
||||
gcv.width = vw;
|
||||
gcv.height = vh;
|
||||
}
|
||||
gctx.clearRect(0, 0, vw, vh);
|
||||
const src = document.getElementById('gl');
|
||||
if (gl && d.glitch && src && src.width) {
|
||||
const n = 7;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const y = Math.floor(hash(t * 13 + i) * vh);
|
||||
const h = 6 + Math.floor(hash(t * 7 + i * 3) * 60);
|
||||
const dx = (hash(t * 31 + i * 5) - 0.5) * 120;
|
||||
const sx = src.width / vw;
|
||||
gctx.globalAlpha = 0.9;
|
||||
gctx.drawImage(src, 0, y * sx, src.width, h * sx, dx, y, vw, h);
|
||||
}
|
||||
gctx.globalAlpha = 0.25;
|
||||
gctx.fillStyle = cfg.accent;
|
||||
gctx.fillRect(0, Math.floor(hash(t * 3.3) * vh), vw, 3 + hash(t) * 10);
|
||||
gctx.globalAlpha = 1;
|
||||
}
|
||||
|
||||
// ---- story
|
||||
const cur = story.find((s) => t >= s.start && t < s.end);
|
||||
if (!cur) {
|
||||
storyEl.style.opacity = '0';
|
||||
return;
|
||||
}
|
||||
if (built !== cur.i) {
|
||||
built = cur.i;
|
||||
const words = (cur.text || '').split(/\s+/).filter(Boolean);
|
||||
storyEl.innerHTML = `<div class="cap ${cur.kind || 'hero'}">
|
||||
${cur.tag ? `<div class="cap-tag">${cur.tag}</div>` : ''}
|
||||
<div class="cap-main">${
|
||||
cur.kind === 'num'
|
||||
? `<span class="w"><span class="n"></span></span>`
|
||||
: (() => {
|
||||
// *several words* → each word gets the accent box
|
||||
let on = false;
|
||||
return words
|
||||
.map((w) => {
|
||||
const open = w.startsWith('*');
|
||||
const close = w.endsWith('*') && (w.length > 1 || on);
|
||||
if (open) on = true;
|
||||
const hl = on;
|
||||
if (close) on = false;
|
||||
return `<span class="w${hl ? ' hl' : ''}">${w.replace(/^\*|\*$/g, '')}</span>`;
|
||||
})
|
||||
.join(' ');
|
||||
})()
|
||||
}</div>
|
||||
${cur.sub ? `<div class="cap-sub"></div>` : ''}
|
||||
</div>`;
|
||||
parts = {
|
||||
words: [...storyEl.querySelectorAll('.w')],
|
||||
num: storyEl.querySelector('.n'),
|
||||
sub: storyEl.querySelector('.cap-sub'),
|
||||
main: storyEl.querySelector('.cap-main'),
|
||||
};
|
||||
}
|
||||
const vp = window.__HUDVP ? window.__HUDVP() : {top: 0, bottom: 0};
|
||||
storyEl.style.top = `${vp.top}px`;
|
||||
storyEl.style.bottom = `${vp.bottom}px`;
|
||||
storyEl.style.opacity = '1';
|
||||
const ex = clamp01((t - (cur.end - 0.18)) / 0.18);
|
||||
// words slam in on successive beats (half-beats if the text is long)
|
||||
const step = parts.words.length > 4 ? 0.5 : 1;
|
||||
let lastIn = cur.start;
|
||||
parts.words.forEach((w, i) => {
|
||||
const bi = cur.b0 + i * step;
|
||||
const wt = Math.floor(bi) === bi ? beats[bi] : (beats[Math.floor(bi)] + beats[Math.ceil(bi)]) / 2;
|
||||
const k = cur.start <= 0.001 ? 1 : clamp01((t - wt) / 0.12);
|
||||
lastIn = Math.max(lastIn, wt);
|
||||
const s = 1 + 0.35 * (1 - easeOutExpo(k)) + 0.03 * b.kick;
|
||||
w.style.opacity = String(k > 0 ? 1 : 0);
|
||||
w.style.transform = `scale(${s}) translateY(${ex * -0.25}em)`;
|
||||
w.style.filter = k < 1 ? `blur(${(1 - k) * 8}px)` : 'none';
|
||||
});
|
||||
if (cur.kind === 'num' && parts.num) {
|
||||
const roll = cur.roll ?? 6;
|
||||
const k = easeOutExpo(clamp01((t - cur.start) / (roll * spb)));
|
||||
const v = cur.from + (cur.to - cur.from) * k;
|
||||
parts.num.textContent = `${cur.prefix ?? ''}${fmt(v, cur.decimals ?? 0)}${cur.suffix ?? ''}`;
|
||||
lastIn = cur.start + roll * spb * 0.6;
|
||||
}
|
||||
if (parts.sub) {
|
||||
const n = Math.floor(Math.max(0, t - lastIn - 0.15) / 0.022);
|
||||
parts.sub.textContent = cur.sub.slice(0, n);
|
||||
}
|
||||
parts.main.style.opacity = String(1 - ex);
|
||||
if (parts.sub) parts.sub.style.opacity = String(1 - ex);
|
||||
storyEl.firstElementChild.style.transform = `translateX(${ex * (hash(t * 41) - 0.5) * 40}px)`;
|
||||
},
|
||||
};
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
import {clamp01, pad} from './util.js';
|
||||
|
||||
/**
|
||||
* Instrument-style HUD: header with stage/command/clock, annotations over the
|
||||
* viewport, a terminal log and a side panel (minimap + stats) at the bottom.
|
||||
* Everything is derived from `t` and the config's stages, so it's deterministic.
|
||||
*
|
||||
* cfg.stages: [{at, name, cmd, logs: [string]}]. A log line starting with "!"
|
||||
* is highlighted in the accent. {key} tokens are replaced from `facts`.
|
||||
*/
|
||||
export function createHud(root, cfg) {
|
||||
const h = cfg.hud;
|
||||
root.insertAdjacentHTML(
|
||||
'beforeend',
|
||||
`<div class="hud">
|
||||
<div class="ann"></div>
|
||||
<div class="wm"></div>
|
||||
<div class="hdr">
|
||||
<div class="row row1">
|
||||
<div class="title"><i class="bar"></i><span class="t"></span></div>
|
||||
<div class="sub"></div>
|
||||
<div class="right"></div>
|
||||
</div>
|
||||
<div class="row row2">
|
||||
<div class="stage accent"></div>
|
||||
<div class="cmd"></div>
|
||||
<div class="time accent"></div>
|
||||
</div>
|
||||
<div class="prog"><i></i></div>
|
||||
</div>
|
||||
<div class="bot">
|
||||
<div class="term">
|
||||
<div class="thead">
|
||||
<span class="host accent"></span><span class="path"></span>
|
||||
<span class="status accent"><i></i><span></span></span>
|
||||
</div>
|
||||
<div class="prompt"></div>
|
||||
<div class="logs"></div>
|
||||
<div class="tfoot"></div>
|
||||
</div>
|
||||
<div class="side">
|
||||
<div class="shead accent"></div>
|
||||
<canvas class="mini"></canvas>
|
||||
<div class="stats"></div>
|
||||
<div class="sfoot"></div>
|
||||
</div>
|
||||
<div class="baseline"><i></i></div>
|
||||
</div>
|
||||
</div>`,
|
||||
);
|
||||
const $ = (s) => root.querySelector(s);
|
||||
const el = {
|
||||
hud: $('.hud'),
|
||||
ann: $('.ann'),
|
||||
stage: $('.row2 .stage'),
|
||||
cmd: $('.row2 .cmd'),
|
||||
time: $('.row2 .time'),
|
||||
prog: $('.prog i'),
|
||||
prompt: $('.prompt'),
|
||||
logs: $('.logs'),
|
||||
tfoot: $('.tfoot'),
|
||||
status: $('.thead .status span'),
|
||||
stats: $('.stats'),
|
||||
sfoot: $('.sfoot'),
|
||||
base: $('.baseline i'),
|
||||
mini: $('.mini'),
|
||||
};
|
||||
$('.title .t').textContent = h.title;
|
||||
$('.sub').textContent = h.subtitle;
|
||||
$('.right').textContent = h.right;
|
||||
$('.wm').textContent = cfg.watermark;
|
||||
$('.thead .host').textContent = h.host;
|
||||
$('.thead .path').textContent = h.path;
|
||||
$('.shead').textContent = h.sideTitle;
|
||||
|
||||
const stages = cfg.stages;
|
||||
const D = cfg.duration;
|
||||
const TYPE_CMD = 0.028;
|
||||
const TYPE_LOG = 0.011;
|
||||
|
||||
// Log line schedule: each stage types its command, then its lines spread
|
||||
// over the stage.
|
||||
const lines = [];
|
||||
stages.forEach((s, i) => {
|
||||
const end = i + 1 < stages.length ? stages[i + 1].at : D;
|
||||
const t0 = s.at + 0.25 + s.cmd.length * TYPE_CMD + 0.2;
|
||||
const n = s.logs.length;
|
||||
const gap = Math.min(0.8, Math.max(0.22, (end - t0 - 0.4) / Math.max(1, n)));
|
||||
s.logs.forEach((text, j) => lines.push({at: t0 + j * gap, text, stage: i}));
|
||||
});
|
||||
|
||||
const stageAt = (t) => {
|
||||
let i = 0;
|
||||
while (i + 1 < stages.length && stages[i + 1].at <= t) i++;
|
||||
return i;
|
||||
};
|
||||
const fill = (text, facts) => text.replace(/\{(\w+)\}/g, (m, k) => (k in facts ? facts[k] : m));
|
||||
const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<');
|
||||
|
||||
let lastStats = '';
|
||||
let lastLogs = '';
|
||||
const annPool = [];
|
||||
|
||||
return {
|
||||
minimap: el.mini,
|
||||
stageAt,
|
||||
setVisible(v) {
|
||||
el.hud.classList.toggle('hidden', !v);
|
||||
},
|
||||
/** Viewport between header and bottom panel, in CSS px. */
|
||||
viewport() {
|
||||
const fs = parseFloat(getComputedStyle(document.documentElement).fontSize);
|
||||
return {top: 13.4 * fs, bottom: 30.5 * fs};
|
||||
},
|
||||
render(t, frame, info = {}) {
|
||||
const facts = {...cfg.facts, ...(info.facts || {})};
|
||||
const si = stageAt(t);
|
||||
const s = stages[si];
|
||||
const dt = t - s.at;
|
||||
const typed = Math.floor(Math.max(0, dt - 0.15) / TYPE_CMD);
|
||||
const cmd = fill(s.cmd, facts);
|
||||
const typing = typed < cmd.length;
|
||||
const caretOn = typing || Math.floor(t * 2.4) % 2 === 0;
|
||||
|
||||
el.stage.textContent = `${pad(si + 1, 2)} / ${s.name}`;
|
||||
el.cmd.textContent = cmd.slice(0, typed);
|
||||
el.time.textContent = `${t.toFixed(2).padStart(5, '0')} / ${D}`;
|
||||
el.prog.style.width = `${(clamp01(t / D) * 100).toFixed(2)}%`;
|
||||
el.base.style.width = `${(clamp01(dt / ((stages[si + 1]?.at ?? D) - s.at)) * 100).toFixed(2)}%`;
|
||||
el.prompt.innerHTML = `<span class="accent">></span> ${esc(cmd.slice(0, typed))}${
|
||||
caretOn ? '<i class="caret"></i>' : ''
|
||||
}`;
|
||||
|
||||
const shown = lines.filter((l) => l.at <= t);
|
||||
const rows = shown.slice(-h.logRows);
|
||||
const offset = shown.length - rows.length;
|
||||
const html = rows
|
||||
.map((l, j) => {
|
||||
const full = fill(l.text, facts);
|
||||
const hl = full.startsWith('!');
|
||||
const text = hl ? full.slice(1) : full;
|
||||
const n = Math.floor((t - l.at) / TYPE_LOG);
|
||||
const isLast = j === rows.length - 1 && n < text.length;
|
||||
return `<div><span class="ln">${pad(offset + j, 3)}</span><span class="${hl ? 'hl' : ''}">${esc(
|
||||
text.slice(0, n),
|
||||
)}</span>${isLast ? '<i class="caret"></i>' : ''}</div>`;
|
||||
})
|
||||
.join('');
|
||||
if (html !== lastLogs) {
|
||||
el.logs.innerHTML = html;
|
||||
lastLogs = html;
|
||||
}
|
||||
|
||||
el.tfoot.textContent = `frame ${pad(frame, 4)} delta ${pad((dt * 7.3) % 100, 2)} / ${s.name.toLowerCase()}`;
|
||||
el.status.textContent = info.status ?? (t >= D - 0.05 ? 'DONE' : 'RUNNING');
|
||||
el.sfoot.textContent = `view ${pad(si + 1, 2)} / ${pad(h.views, 2)} seed ${cfg.seed} · t+${dt.toFixed(2)}s`;
|
||||
|
||||
const stats = (info.stats || []).map((x) => `<div>${esc(x.label)}<b>${esc(String(x.value))}</b></div>`).join('');
|
||||
if (stats !== lastStats) {
|
||||
el.stats.innerHTML = stats;
|
||||
lastStats = stats;
|
||||
}
|
||||
|
||||
const anns = info.annotations || [];
|
||||
while (annPool.length < anns.length) {
|
||||
const d = document.createElement('div');
|
||||
el.ann.appendChild(d);
|
||||
annPool.push(d);
|
||||
}
|
||||
annPool.forEach((d, i) => {
|
||||
const a = anns[i];
|
||||
if (!a) {
|
||||
d.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
d.style.display = '';
|
||||
d.className = a.cls || '';
|
||||
d.style.left = `${a.x}px`;
|
||||
d.style.top = `${a.y}px`;
|
||||
d.style.opacity = a.opacity ?? 1;
|
||||
if (a.html !== undefined) d.innerHTML = a.html;
|
||||
else d.textContent = a.text;
|
||||
// keep labels inside the viewport (between header and bottom panel)
|
||||
const vp = this.viewport();
|
||||
const w = d.offsetWidth;
|
||||
const hh = d.offsetHeight;
|
||||
const x = Math.min(Math.max(a.x, 8), innerWidth - w - 40);
|
||||
const y = Math.min(Math.max(a.y, vp.top + hh / 2 + 8), innerHeight - vp.bottom - hh / 2 - 8);
|
||||
d.style.left = `${x}px`;
|
||||
d.style.top = `${y}px`;
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import {createDirector, DIRECTOR} from './director.js';
|
||||
import {createHud} from './hud.js';
|
||||
import {merge} from './util.js';
|
||||
|
||||
/** Config every sim starts from; a sim's defaults and the post config merge over it. */
|
||||
export const BASE = {
|
||||
duration: 30,
|
||||
fps: 30,
|
||||
seed: 746337560,
|
||||
theme: 'dark',
|
||||
accent: '#f2b632',
|
||||
watermark: '',
|
||||
hud: {
|
||||
title: 'AGENT MESH',
|
||||
subtitle: '/ SIMULATION',
|
||||
right: 'VISUAL SIMULATION',
|
||||
host: 'agent@local',
|
||||
path: '~/session-01',
|
||||
sideTitle: 'LOCAL VIEW',
|
||||
logRows: 5,
|
||||
views: 10,
|
||||
},
|
||||
stages: [{at: 0, name: 'RUN', cmd: 'run', logs: []}],
|
||||
facts: {},
|
||||
director: DIRECTOR,
|
||||
story: [],
|
||||
beats: null,
|
||||
};
|
||||
|
||||
const fromBase64 = (s) => decodeURIComponent(escape(atob(s.replace(/-/g, '+').replace(/_/g, '/'))));
|
||||
|
||||
/**
|
||||
* Config sources, later wins: BASE, the sim's defaults, window.__SIM_CONFIG
|
||||
* (injected by the capture script), ?config=<base64 json>, and a few plain
|
||||
* query params (?title= ?accent= ?seed= ?theme= ?duration=).
|
||||
*/
|
||||
export function loadConfig(defaults) {
|
||||
let cfg = merge(BASE, defaults);
|
||||
if (window.__SIM_CONFIG) cfg = merge(cfg, window.__SIM_CONFIG);
|
||||
const q = new URLSearchParams(location.search);
|
||||
if (q.get('config')) {
|
||||
try {
|
||||
cfg = merge(cfg, JSON.parse(fromBase64(q.get('config'))));
|
||||
} catch (e) {
|
||||
console.warn('bad ?config', e);
|
||||
}
|
||||
}
|
||||
if (q.get('title')) cfg = merge(cfg, {hud: {title: q.get('title')}});
|
||||
if (q.get('accent')) cfg.accent = '#' + q.get('accent').replace('#', '');
|
||||
if (q.get('seed')) cfg.seed = Number(q.get('seed'));
|
||||
if (q.get('theme')) cfg.theme = q.get('theme');
|
||||
if (q.get('duration')) cfg.duration = Number(q.get('duration'));
|
||||
if (q.has('nodirector')) cfg.director = {...cfg.director, enabled: false};
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Boots a sim. `setup({cfg, canvas, hud, capture})` returns (or resolves to)
|
||||
* `{render(t) -> hudInfo, resize()}`. render must be a pure function of t.
|
||||
*
|
||||
* Live mode loops in real time. Keys: space pause, h hide HUD, f fullscreen,
|
||||
* r restart, ←/→ seek 2 s, 1–9 jump to a stage.
|
||||
* Capture mode (?capture or window.__CAPTURE) exposes window.SIM.render(t).
|
||||
*/
|
||||
export async function runSim(defaults, setup) {
|
||||
const cfg = loadConfig(defaults);
|
||||
const q = new URLSearchParams(location.search);
|
||||
const capture = !!window.__CAPTURE || q.has('capture');
|
||||
const root = document.documentElement;
|
||||
root.dataset.theme = cfg.theme;
|
||||
root.style.setProperty('--accent', cfg.accent);
|
||||
document.title = `${cfg.hud.title} ${cfg.hud.subtitle}`.trim();
|
||||
|
||||
const scale = () => {
|
||||
root.style.fontSize = `${10 * Math.min(innerWidth / 1080, innerHeight / 1350)}px`;
|
||||
};
|
||||
scale();
|
||||
|
||||
const app = document.getElementById('app');
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.id = 'gl';
|
||||
app.appendChild(canvas);
|
||||
// cfg.hud.enabled === false: no instrument chrome (UI demos, infographics).
|
||||
const hud =
|
||||
cfg.hud.enabled === false
|
||||
? {minimap: null, stageAt: () => 0, setVisible() {}, viewport: () => ({top: 0, bottom: 0}), render() {}}
|
||||
: createHud(app, cfg);
|
||||
|
||||
await Promise.all([
|
||||
document.fonts.load('400 20px "JetBrains Mono"'),
|
||||
document.fonts.load('600 20px "JetBrains Mono"'),
|
||||
document.fonts.load('800 20px "Inter"'),
|
||||
]).catch(() => {});
|
||||
|
||||
window.__HUDVP = () => hud.viewport();
|
||||
const sim = await setup({cfg, canvas, hud, capture});
|
||||
if (!capture && sim.warm) await sim.warm();
|
||||
const dir = createDirector(app, cfg);
|
||||
// The sim and HUD run on warped time (hero lands on the drop); the
|
||||
// director's cuts, punches and story run on real (music) time.
|
||||
const draw = (t) => {
|
||||
const tw = dir.warp(t);
|
||||
dir.pre(t);
|
||||
const info = sim.render(tw, dir.beat(t)) || {};
|
||||
hud.render(tw, Math.round(t * cfg.fps), info);
|
||||
dir.post(t, info);
|
||||
};
|
||||
|
||||
let cur = 0;
|
||||
let paused = false;
|
||||
const resize = () => {
|
||||
scale();
|
||||
sim.resize?.();
|
||||
if (paused || capture) draw(cur);
|
||||
};
|
||||
addEventListener('resize', resize);
|
||||
resize();
|
||||
|
||||
window.SIM = {
|
||||
cfg,
|
||||
duration: cfg.duration,
|
||||
fps: cfg.fps,
|
||||
ready: true,
|
||||
render: (t) => {
|
||||
cur = t;
|
||||
draw(t);
|
||||
},
|
||||
};
|
||||
if (capture) {
|
||||
draw(0);
|
||||
return;
|
||||
}
|
||||
|
||||
let start = performance.now();
|
||||
const seek = (t) => {
|
||||
cur = ((t % cfg.duration) + cfg.duration) % cfg.duration;
|
||||
start = performance.now() - cur * 1000;
|
||||
};
|
||||
let hudOn = true;
|
||||
addEventListener('keydown', (e) => {
|
||||
if (e.key === ' ') {
|
||||
paused = !paused;
|
||||
if (!paused) seek(cur);
|
||||
} else if (e.key === 'h') {
|
||||
hudOn = !hudOn;
|
||||
hud.setVisible(hudOn);
|
||||
} else if (e.key === 'f') {
|
||||
if (document.fullscreenElement) document.exitFullscreen();
|
||||
else document.documentElement.requestFullscreen();
|
||||
} else if (e.key === 'r') seek(0);
|
||||
else if (e.key === 'ArrowRight') seek(cur + 2);
|
||||
else if (e.key === 'ArrowLeft') seek(cur - 2);
|
||||
else if (/^[1-9]$/.test(e.key) && cfg.stages[+e.key - 1]) seek(Math.max(0, cfg.stages[+e.key - 1].at));
|
||||
else return;
|
||||
e.preventDefault();
|
||||
});
|
||||
const loop = (now) => {
|
||||
if (!paused) cur = Math.max(0, (now - start) / 1000) % cfg.duration;
|
||||
draw(cur);
|
||||
// the site page swaps its poster for the canvas on this
|
||||
if (!window.SIM_SHOWN) {
|
||||
window.SIM_SHOWN = true;
|
||||
dispatchEvent(new Event('simframe'));
|
||||
}
|
||||
requestAnimationFrame(loop);
|
||||
};
|
||||
requestAnimationFrame(loop);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import * as THREE from 'three';
|
||||
import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';
|
||||
import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';
|
||||
import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';
|
||||
import {UnrealBloomPass} from 'three/addons/postprocessing/UnrealBloomPass.js';
|
||||
|
||||
/**
|
||||
* Renderer + scene + camera + bloom. The camera's projection centre is shifted
|
||||
* to the middle of the HUD viewport (between header and bottom panel), so the
|
||||
* subject is centred in the visible area, not behind the terminal.
|
||||
*/
|
||||
export function createStage(canvas, hud, opts = {}) {
|
||||
const {
|
||||
bg = '#09090a',
|
||||
fov = 38,
|
||||
bloom = {strength: 0.85, radius: 0.55, threshold: 0.62},
|
||||
capture = false,
|
||||
exposure = 1,
|
||||
} = opts;
|
||||
const renderer = new THREE.WebGLRenderer({
|
||||
canvas,
|
||||
antialias: false,
|
||||
preserveDrawingBuffer: true,
|
||||
powerPreference: 'high-performance',
|
||||
});
|
||||
renderer.setClearColor(new THREE.Color(bg), 1);
|
||||
renderer.toneMapping = THREE.ACESFilmicToneMapping;
|
||||
renderer.toneMappingExposure = exposure;
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
|
||||
const scene = new THREE.Scene();
|
||||
scene.background = new THREE.Color(bg);
|
||||
const camera = new THREE.PerspectiveCamera(fov, 1, 0.5, 6000);
|
||||
|
||||
const target = new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: 4});
|
||||
const composer = new EffectComposer(renderer, target);
|
||||
composer.addPass(new RenderPass(scene, camera));
|
||||
const bloomPass = new UnrealBloomPass(new THREE.Vector2(4, 4), bloom.strength, bloom.radius, bloom.threshold);
|
||||
composer.addPass(bloomPass);
|
||||
composer.addPass(new OutputPass());
|
||||
|
||||
const size = {w: 1, h: 1, centre: 0.5};
|
||||
// Director crop: render a sub-rectangle of the base view (crisp punch-ins).
|
||||
const crop = {z: 1, fx: 0, fy: 0, x0: 0, y0: 0};
|
||||
const applyView = () => {
|
||||
const {w, h, centre} = size;
|
||||
const offY = h / 2 - centre;
|
||||
if (crop.z <= 1.0001) {
|
||||
crop.x0 = 0;
|
||||
crop.y0 = 0;
|
||||
camera.setViewOffset(w, h, 0, offY, w, h);
|
||||
} else {
|
||||
const cw = w / crop.z;
|
||||
const ch = h / crop.z;
|
||||
crop.x0 = Math.min(Math.max(crop.fx - cw / 2, 0), w - cw);
|
||||
crop.y0 = Math.min(Math.max(crop.fy - ch / 2, 0), h - ch);
|
||||
camera.setViewOffset(w, h, crop.x0, offY + crop.y0, cw, ch);
|
||||
}
|
||||
camera.updateProjectionMatrix();
|
||||
};
|
||||
// opts.pr fixes the pixel ratio (a capture that wants the 3D at the output resolution, a page that adapts it)
|
||||
let prFixed = opts.pr;
|
||||
const resize = () => {
|
||||
const w = canvas.clientWidth || innerWidth;
|
||||
const h = canvas.clientHeight || innerHeight;
|
||||
const pr = prFixed ?? (capture ? 1 : Math.min(devicePixelRatio || 1, 2));
|
||||
size.w = w;
|
||||
size.h = h;
|
||||
renderer.setPixelRatio(pr);
|
||||
renderer.setSize(w, h, false);
|
||||
composer.setPixelRatio(pr);
|
||||
composer.setSize(w, h);
|
||||
const vp = hud.viewport();
|
||||
size.centre = (vp.top + (h - vp.bottom)) / 2;
|
||||
camera.aspect = w / h;
|
||||
applyView();
|
||||
};
|
||||
/** Zoom z around base-screen point (fx, fy); returns {z, x0, y0} for mapping back. */
|
||||
const setCrop = (z, fx, fy) => {
|
||||
crop.z = Math.max(1, z);
|
||||
crop.fx = fx;
|
||||
crop.fy = fy;
|
||||
applyView();
|
||||
return {z: crop.z, x0: crop.x0, y0: crop.y0};
|
||||
};
|
||||
|
||||
const v = new THREE.Vector3();
|
||||
/** World point → CSS px on screen, plus whether it's in front of the camera. */
|
||||
const project = (p) => {
|
||||
v.set(p[0] ?? p.x, p[1] ?? p.y, p[2] ?? p.z).project(camera);
|
||||
return {x: (v.x * 0.5 + 0.5) * size.w, y: (-v.y * 0.5 + 0.5) * size.h, visible: v.z < 1};
|
||||
};
|
||||
|
||||
const st = {
|
||||
THREE,
|
||||
renderer,
|
||||
scene,
|
||||
camera,
|
||||
composer,
|
||||
bloomPass,
|
||||
size,
|
||||
resize,
|
||||
setPixelRatio: (v) => {
|
||||
prFixed = v;
|
||||
resize();
|
||||
},
|
||||
project,
|
||||
render: () => composer.render(),
|
||||
setCrop,
|
||||
hudViewport: () => hud.viewport(),
|
||||
};
|
||||
window.__STAGE = st;
|
||||
return st;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/* HUD chrome shared by every sim. 1rem = 10px at the 1080x1350 reference
|
||||
size; runtime sets html font-size from the viewport so it scales. */
|
||||
|
||||
:root {
|
||||
--bg: #09090a;
|
||||
--fg: #ece6d6;
|
||||
--dim: rgba(236, 230, 214, 0.64);
|
||||
--mute: rgba(236, 230, 214, 0.38);
|
||||
--faint: rgba(236, 230, 214, 0.16);
|
||||
--line: rgba(236, 230, 214, 0.14);
|
||||
--panel: rgba(9, 9, 10, 0.9);
|
||||
--accent: #f2b632;
|
||||
--top: 13.4rem;
|
||||
--bot: 30.5rem;
|
||||
}
|
||||
:root[data-theme='light'] {
|
||||
--bg: #f3f2ee;
|
||||
--fg: #151515;
|
||||
--dim: rgba(21, 21, 21, 0.66);
|
||||
--mute: rgba(21, 21, 21, 0.42);
|
||||
--faint: rgba(21, 21, 21, 0.16);
|
||||
--line: rgba(21, 21, 21, 0.16);
|
||||
--panel: rgba(243, 242, 238, 0.93);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; height: 100%; background: var(--bg); overflow: hidden; }
|
||||
#app {
|
||||
position: fixed; inset: 0; color: var(--fg);
|
||||
font-family: 'JetBrains Mono', ui-monospace, monospace;
|
||||
font-variant-ligatures: none; -webkit-font-smoothing: antialiased;
|
||||
}
|
||||
#gl { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
|
||||
.hud { position: absolute; inset: 0; pointer-events: none; }
|
||||
.hud.hidden { display: none; }
|
||||
.accent { color: var(--accent); }
|
||||
|
||||
/* header */
|
||||
.hdr {
|
||||
position: absolute; left: 0; right: 0; top: 0; height: var(--top);
|
||||
padding: 2.4rem 2.8rem 0;
|
||||
background: linear-gradient(var(--bg) 0%, var(--bg) 78%, transparent 100%);
|
||||
}
|
||||
.row { display: flex; align-items: baseline; white-space: nowrap; }
|
||||
.row1 { gap: 5.6rem; }
|
||||
.title { display: flex; align-items: center; gap: 1.3rem; font-size: 3.6rem; font-weight: 600; letter-spacing: 0.04em; }
|
||||
.title .bar { display: inline-block; width: 0.75rem; height: 3.6rem; background: var(--accent); }
|
||||
.sub { font-size: 1.75rem; color: var(--dim); letter-spacing: 0.08em; }
|
||||
.right { margin-left: auto; font-size: 1.6rem; color: var(--dim); letter-spacing: 0.1em; }
|
||||
.row2 { margin-top: 2rem; font-size: 1.95rem; }
|
||||
.row2 .stage { width: 21rem; letter-spacing: 0.05em; }
|
||||
.row2 .cmd { color: var(--fg); }
|
||||
.row2 .time { margin-left: auto; letter-spacing: 0.05em; }
|
||||
.prog { position: absolute; left: 2.8rem; right: 2.8rem; bottom: 1.2rem; height: 0.35rem; }
|
||||
.prog i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }
|
||||
|
||||
/* viewport overlays */
|
||||
.ann { position: absolute; inset: 0; overflow: hidden; }
|
||||
.ann div {
|
||||
position: absolute; transform: translate(1.4rem, -50%); white-space: nowrap;
|
||||
font-size: 1.7rem; letter-spacing: 0.04em; color: var(--fg);
|
||||
text-shadow: 0 0 0.6rem var(--bg), 0 0 1.2rem var(--bg);
|
||||
}
|
||||
.ann div.a { color: var(--accent); }
|
||||
.ann div.box {
|
||||
padding: 0.8rem 1.1rem; border: 1px solid var(--line); background: var(--panel);
|
||||
text-shadow: none; line-height: 1.45; font-size: 1.55rem;
|
||||
}
|
||||
.ann div.box b { color: var(--accent); font-weight: 600; }
|
||||
.wm {
|
||||
position: absolute; right: 3rem; bottom: calc(var(--bot) + 1.6rem);
|
||||
font-size: 2.3rem; letter-spacing: 0.06em; color: var(--fg); opacity: 0.3;
|
||||
}
|
||||
|
||||
/* bottom panel */
|
||||
.bot {
|
||||
position: absolute; left: 0; right: 0; bottom: 0; height: var(--bot);
|
||||
display: flex; border-top: 1px solid var(--line); background: var(--panel);
|
||||
padding: 2rem 2.8rem 1.6rem;
|
||||
}
|
||||
.term { flex: 1; min-width: 0; display: flex; flex-direction: column; padding-right: 2.6rem; }
|
||||
.thead { display: flex; align-items: baseline; gap: 2.4rem; font-size: 1.75rem; white-space: nowrap; }
|
||||
.thead .host { font-size: 2.1rem; }
|
||||
.thead .path { color: var(--dim); }
|
||||
.thead .status { margin-left: auto; font-size: 1.5rem; letter-spacing: 0.1em; display: flex; align-items: center; gap: 0.9rem; }
|
||||
.thead .status i { width: 1rem; height: 1rem; border-radius: 50%; background: var(--accent); display: inline-block; }
|
||||
.prompt { margin-top: 1.9rem; font-size: 2.2rem; white-space: nowrap; overflow: hidden; }
|
||||
.logs { margin-top: 1.1rem; font-size: 1.85rem; line-height: 1.52; flex: 1; overflow: hidden; }
|
||||
.logs div { white-space: nowrap; overflow: hidden; text-overflow: clip; }
|
||||
.logs .ln { color: var(--mute); display: inline-block; width: 6.4rem; }
|
||||
.logs .hl { color: var(--accent); }
|
||||
.caret { display: inline-block; width: 0.95em; height: 1.05em; vertical-align: -0.15em; background: var(--accent); margin-left: 0.15em; }
|
||||
.tfoot { font-size: 1.35rem; color: var(--mute); white-space: nowrap; letter-spacing: 0.04em; }
|
||||
.side {
|
||||
width: 31%; border-left: 1px solid var(--line); padding-left: 2.2rem;
|
||||
display: flex; flex-direction: column;
|
||||
}
|
||||
.shead { font-size: 1.45rem; letter-spacing: 0.12em; }
|
||||
.mini { width: 100%; flex: 1; min-height: 0; display: block; margin: 0.8rem 0; }
|
||||
.stats { display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem 1.4rem; font-size: 1.35rem; color: var(--mute); }
|
||||
.stats b { display: block; font-size: 2rem; color: var(--fg); font-weight: 600; letter-spacing: 0.02em; }
|
||||
.sfoot { margin-top: 0.8rem; font-size: 1.3rem; color: var(--mute); letter-spacing: 0.05em; }
|
||||
.baseline { position: absolute; left: 2.8rem; right: 2.8rem; bottom: 0.9rem; height: 0.25rem; background: var(--line); }
|
||||
.baseline i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }
|
||||
|
||||
/* director layers */
|
||||
.dir-glitch { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; }
|
||||
.dir-flash {
|
||||
position: absolute; inset: 0; pointer-events: none; opacity: 0; mix-blend-mode: screen;
|
||||
background: radial-gradient(ellipse 75% 55% at 50% 45%, var(--accent) 0%, transparent 70%), rgba(255,255,255,0.18);
|
||||
}
|
||||
.dir-story {
|
||||
position: absolute; left: 0; right: 0; top: 0; bottom: 0; pointer-events: none;
|
||||
display: flex; align-items: flex-end; justify-content: center; padding: 0 4.5rem 6rem; opacity: 0;
|
||||
}
|
||||
.cap { text-align: center; max-width: 96rem; position: relative; }
|
||||
.cap::before {
|
||||
content: ''; position: absolute; inset: -6rem -10rem; z-index: -1;
|
||||
background: radial-gradient(ellipse 50% 50% at 50% 55%, rgba(0,0,0,0.62) 0%, rgba(0,0,0,0) 100%);
|
||||
}
|
||||
:root[data-theme='light'] .cap::before { background: radial-gradient(ellipse 50% 50% at 50% 55%, rgba(243,242,238,0.8) 0%, rgba(243,242,238,0) 100%); }
|
||||
.cap-main {
|
||||
font-family: 'Inter', 'Inter Variable', system-ui, sans-serif; font-weight: 800;
|
||||
font-size: 11.5rem; line-height: 0.98; letter-spacing: -0.035em; color: var(--fg);
|
||||
text-shadow: 0 0.4rem 2.4rem rgba(0,0,0,0.55);
|
||||
}
|
||||
.cap.num .cap-main { font-size: 15rem; font-variant-numeric: tabular-nums; letter-spacing: -0.045em; }
|
||||
.cap-main .w { display: inline-block; transform-origin: 50% 70%; }
|
||||
.cap-main .w.hl { background: var(--accent); color: #0a0a0a; padding: 0 0.14em; text-shadow: none; border-radius: 0.06em; }
|
||||
.cap-sub {
|
||||
margin-top: 2rem; font-size: 2.7rem; letter-spacing: 0.08em; text-transform: uppercase;
|
||||
color: var(--fg); opacity: 0.85; min-height: 1.3em;
|
||||
}
|
||||
.cap-tag {
|
||||
display: inline-block; margin-bottom: 1.8rem; padding: 0.5rem 1.2rem; font-size: 2.2rem; letter-spacing: 0.12em;
|
||||
border: 1px solid var(--accent); color: var(--accent); background: rgba(0,0,0,0.5);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Small pure helpers shared by every sim. Everything animated must be a pure
|
||||
// function of `t` (seconds) so live playback and frame capture match.
|
||||
|
||||
export const clamp01 = (x) => Math.min(1, Math.max(0, x));
|
||||
export const lerp = (a, b, k) => a + (b - a) * k;
|
||||
export const smooth = (x) => {
|
||||
const k = clamp01(x);
|
||||
return k * k * (3 - 2 * k);
|
||||
};
|
||||
export const easeOutCubic = (x) => 1 - Math.pow(1 - clamp01(x), 3);
|
||||
export const easeInOutCubic = (x) => {
|
||||
const k = clamp01(x);
|
||||
return k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2;
|
||||
};
|
||||
export const easeOutExpo = (x) => (x >= 1 ? 1 : 1 - Math.pow(2, -10 * clamp01(x)));
|
||||
export const easeOutBack = (x, s = 1.7) => {
|
||||
const k = clamp01(x) - 1;
|
||||
return 1 + (s + 1) * k * k * k + s * k * k;
|
||||
};
|
||||
/** 0..1 progress of t between t0 and t1, eased. */
|
||||
export const prog = (t, t0, t1, ease = easeInOutCubic) => ease((t - t0) / (t1 - t0));
|
||||
|
||||
/** Seeded PRNG (mulberry32). Same seed → same sequence. */
|
||||
export const rng = (seed) => {
|
||||
let s = seed >>> 0;
|
||||
return () => {
|
||||
s = (s + 0x6d2b79f5) >>> 0;
|
||||
let x = s;
|
||||
x = Math.imul(x ^ (x >>> 15), x | 1);
|
||||
x ^= x + Math.imul(x ^ (x >>> 7), x | 61);
|
||||
return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
};
|
||||
|
||||
/** Stateless hash noise in [0,1). */
|
||||
export const hash = (n) => {
|
||||
const x = Math.sin(n * 127.1 + 311.7) * 43758.5453;
|
||||
return x - Math.floor(x);
|
||||
};
|
||||
|
||||
/** Random unit vector from a PRNG. */
|
||||
export const randDir = (r) => {
|
||||
const u = r() * 2 - 1;
|
||||
const a = r() * Math.PI * 2;
|
||||
const s = Math.sqrt(1 - u * u);
|
||||
return [s * Math.cos(a), u, s * Math.sin(a)];
|
||||
};
|
||||
|
||||
/**
|
||||
* Keyframed value: keys = [[t, value], ...] with numbers or arrays of numbers.
|
||||
* Eased between keys, held outside.
|
||||
*/
|
||||
export const keyed = (keys, t, ease = easeInOutCubic) => {
|
||||
if (t <= keys[0][0]) return keys[0][1];
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
const [t0, v0] = keys[i];
|
||||
const [t1, v1] = keys[i + 1];
|
||||
if (t <= t1) {
|
||||
const k = ease((t - t0) / (t1 - t0));
|
||||
return Array.isArray(v0) ? v0.map((v, j) => lerp(v, v1[j], k)) : lerp(v0, v1, k);
|
||||
}
|
||||
}
|
||||
return keys[keys.length - 1][1];
|
||||
};
|
||||
|
||||
export const fmt = (n, d = 0) =>
|
||||
Number(n).toLocaleString('en-US', {minimumFractionDigits: d, maximumFractionDigits: d});
|
||||
export const pad = (n, w) => String(Math.max(0, Math.floor(n))).padStart(w, '0');
|
||||
|
||||
/** Deep merge plain objects; arrays and scalars from `b` replace `a`. */
|
||||
export const merge = (a, b) => {
|
||||
if (!b || typeof b !== 'object' || Array.isArray(b)) return b === undefined ? a : b;
|
||||
const out = {...a};
|
||||
for (const k of Object.keys(b)) {
|
||||
out[k] =
|
||||
a && typeof a[k] === 'object' && !Array.isArray(a[k]) && a[k] !== null ? merge(a[k], b[k]) : b[k];
|
||||
}
|
||||
return out;
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
// Shader warm-up before a live page's first frame. three.js links a program the first time something draws with it,
|
||||
// and the frame waits on every one in turn: 1-2 s on a phone or an integrated GPU, and a frozen page meanwhile. Here
|
||||
// all of them start at once and the page awaits them without blocking (renderer.compileAsync, KHR_parallel_shader_compile):
|
||||
// the scene's materials and the ones held by post passes (GTAO, bloom, ink, output), which compileAsync never meets
|
||||
// on its own because they only reach the renderer inside composer.render().
|
||||
//
|
||||
// A warmed program only helps when its cache key matches the one the frame asks for, so everything here mirrors the
|
||||
// frame: each set compiles against the target it draws into (tone mapping, colour space), pass quads have no normals
|
||||
// like three's fullscreen triangle, override materials (GTAO's normals) see the scene's lights and shadows, and the
|
||||
// two settings three only fixes on its first render (PCFSoftShadowMap, OutputPass defines) are fixed first.
|
||||
import * as THREE from 'three';
|
||||
|
||||
// three's FullScreenQuad geometry: position and uv, no normal
|
||||
const TRI = new THREE.BufferGeometry();
|
||||
TRI.setAttribute('position', new THREE.Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3));
|
||||
TRI.setAttribute('uv', new THREE.Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2));
|
||||
// a stand-in for the scene's meshes under an override material
|
||||
const MESH = new THREE.PlaneGeometry(1, 1);
|
||||
|
||||
// every material a pass holds directly or in an array (GTAOPass, UnrealBloomPass, ShaderPass, OutputPass)
|
||||
const materialsOf = (pass) => Object.values(pass).flatMap((v) => (v?.isMaterial ? [v] : Array.isArray(v) ? v.filter((m) => m?.isMaterial) : []));
|
||||
// drawn over the scene's own meshes instead of on a quad
|
||||
const isOverride = (m) => m.isMeshNormalMaterial || m.isMeshDepthMaterial || m.isMeshDistanceMaterial;
|
||||
|
||||
/**
|
||||
* jobs: [{scene, target}] or [{materials, target, lights, override}]; target null is the canvas, lights a scene whose
|
||||
* lights apply, override true for materials drawn as scene.overrideMaterial whatever their type.
|
||||
*/
|
||||
export function warmUp(renderer, camera, jobs) {
|
||||
// three swaps the removed PCFSoftShadowMap for PCFShadowMap inside its first shadow render, after any warm-up
|
||||
if (renderer.shadowMap.type === THREE.PCFSoftShadowMap) renderer.shadowMap.type = THREE.PCFShadowMap;
|
||||
const prev = renderer.getRenderTarget();
|
||||
const waits = jobs.map(({scene, materials = [], target = null, lights = null, override = false}) => {
|
||||
let root = scene;
|
||||
if (!root) {
|
||||
root = new THREE.Scene();
|
||||
for (const m of materials) root.add(new THREE.Mesh(override || isOverride(m) ? MESH : TRI, m));
|
||||
}
|
||||
renderer.setRenderTarget(target);
|
||||
return renderer.compileAsync(root, camera, lights);
|
||||
});
|
||||
renderer.setRenderTarget(prev);
|
||||
return Promise.all(waits);
|
||||
}
|
||||
|
||||
/** The scene and every enabled pass of an EffectComposer; the last pass draws to the canvas when the composer does. */
|
||||
export function warmComposer(renderer, composer, scene, camera, jobs = []) {
|
||||
const target = composer.renderTarget1;
|
||||
const passes = composer.passes.filter((p) => p.enabled);
|
||||
const last = composer.renderToScreen ? passes[passes.length - 1] : null;
|
||||
// OutputPass picks its defines from the renderer on its first render: run that part now, with the draw left out
|
||||
for (const p of passes.filter((x) => x.isOutputPass)) {
|
||||
const quad = p._fsQuad;
|
||||
p._fsQuad = {render() {}};
|
||||
p.render(renderer, composer.renderTarget2, composer.renderTarget1);
|
||||
p._fsQuad = quad;
|
||||
}
|
||||
const mats = passes.filter((p) => p !== last).flatMap(materialsOf);
|
||||
return warmUp(renderer, camera, [
|
||||
{scene, target},
|
||||
{materials: mats.filter((m) => !isOverride(m)), target},
|
||||
{materials: mats.filter(isOverride), target, lights: scene},
|
||||
{materials: last ? materialsOf(last) : [], target: null},
|
||||
...jobs,
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// SERRASAL PX-7, the 10-second demo for the article (2026-11-06), green: the swim-in, the jaw dropping with its glass
|
||||
// fangs shot from below, the explode with the camera swinging round the parts and the lunge at the lens. 11.2 s of the
|
||||
// tour played at 1.12x.
|
||||
import {runPiranhaGreen} from '../piranha-shared/sim_green.js';
|
||||
import TL from './timeline.json';
|
||||
|
||||
runPiranhaGreen(TL, 'piranha-demo');
|
||||
@@ -0,0 +1 @@
|
||||
{"duration": 11.2, "film": 10.0, "push": 0.72, "opt": 0.88, "pills": ["optics", "leg", "thorax", "abdomen", "exploded", "hero"], "script": [{"t": 2.6, "act": "abdomen"}, {"t": 5.0, "act": "exploded"}, {"t": 6.9, "act": "assemble"}, {"t": 7.9, "act": "hero"}]}
|
||||
@@ -0,0 +1,6 @@
|
||||
// SERRASAL PX-7, the robotic piranha's film on the green page (2026-11-06): the angler's approved tour with the piranha
|
||||
// body, the hammerhead cut's beats (eye, tail stalk, glass flank, jaw, explode, lunge). Code: ../piranha-shared/sim_green.js.
|
||||
import {runPiranhaGreen} from '../piranha-shared/sim_green.js';
|
||||
import TL from './timeline.json';
|
||||
|
||||
runPiranhaGreen(TL);
|
||||
@@ -0,0 +1 @@
|
||||
{"duration": 21.2, "push": 0.72, "opt": 0.88, "pills": ["optics", "leg", "thorax", "abdomen", "exploded", "hero"], "script": [{"t": 3.0, "act": "optics"}, {"t": 5.7, "act": "leg"}, {"t": 8.2, "act": "thorax"}, {"t": 10.8, "act": "abdomen"}, {"t": 13.3, "act": "exploded"}, {"t": 16.5, "act": "assemble"}, {"t": 17.7, "act": "hero"}]}
|
||||
@@ -0,0 +1,360 @@
|
||||
// The Vesper AX-6 console, copied from the hummingbird's (robohum-shared/console.js, itself the bee's) and laid out the
|
||||
// same at 1600 x 900: the orange AX-6 badge and title with the sim status cells, the fin stroke with its live chart of
|
||||
// the tail and the pectorals, power, the six fin, tail, jaw, lure and dorsal servos, dive telemetry with an attitude
|
||||
// ball and the bank, the assemblies, the display toggles, the subsystem registry, the dive log with the operator's
|
||||
// actions on its timeline, the swim-mode word in the viewport, the labels with leaders into the fish and the
|
||||
// operator's pointer. Panels are light paper over the near-white studio; the fish's orange is the one accent.
|
||||
// update(s) redraws every live part from the frame's state.
|
||||
export const C = {ink: '#24211d', mute: '#9a8f82', faint: '#e0d7ca', line: '#ece5da', panel: 'rgba(253,251,247,.95)', or: '#ff5a1f', green: '#2fa36b', track: '#efe8de'};
|
||||
export const VIEWS = ['hero', 'front', 'side', 'wing', 'legs'];
|
||||
export const VIEW_LABEL = {hero: 'HERO', front: 'FRONT', side: 'SIDE', wing: 'WING', legs: 'LEGS'};
|
||||
export const DISPLAY = ['labels', 'xray', 'exploded', 'blur', 'orbit'];
|
||||
export const DISPLAY_LABEL = {labels: 'LABELS', xray: 'X-RAY', exploded: 'EXPLODED', blur: 'MOTION BLUR', orbit: 'ORBIT'};
|
||||
// the viewport: the 3D shows between the side columns, above the flight log
|
||||
export const VIEWPORT = {x0: 330, x1: 1270, y0: 108, y1: 744};
|
||||
const CSS = `
|
||||
#app{font-family:Inter,system-ui,sans-serif;color:${C.ink};-webkit-font-smoothing:antialiased;font-variant-numeric:tabular-nums}
|
||||
.ui{position:absolute;inset:0;pointer-events:none}
|
||||
.mo{font-family:'JetBrains Mono',ui-monospace,monospace}
|
||||
.cp{position:absolute;background:${C.panel};border:1px solid ${C.line};border-radius:6px;box-shadow:0 2px 10px rgba(120,90,50,.07)}
|
||||
.ph{position:absolute;display:flex;align-items:center;gap:9px;font:700 10.5px 'JetBrains Mono',monospace;letter-spacing:1.8px}
|
||||
.ph i{display:block;width:3px;height:13px;background:${C.or}}
|
||||
.pn{position:absolute;font:500 9.5px 'JetBrains Mono',monospace;color:${C.mute};letter-spacing:1px}
|
||||
.sm{font:500 9px 'JetBrains Mono',monospace;letter-spacing:1.6px;color:${C.mute};text-transform:uppercase;white-space:nowrap}
|
||||
.v{font:600 11px 'JetBrains Mono',monospace;color:${C.ink};white-space:nowrap}
|
||||
.bt{position:absolute;height:23px;padding:0 10px;display:flex;align-items:center;justify-content:center;border:1px solid ${C.faint};border-radius:4px;background:#fffdf9;font:700 9.4px 'JetBrains Mono',monospace;letter-spacing:1.3px;color:${C.ink};white-space:nowrap;box-sizing:border-box}
|
||||
.call{position:absolute;white-space:nowrap;padding:3px 6px 3px 5px;margin:-3px 0 0 -5px;background:rgba(253,251,247,.86);border-radius:3px}
|
||||
.call b{display:flex;align-items:center;gap:6px;font:700 9.4px 'JetBrains Mono',monospace;letter-spacing:1.3px;color:${C.ink}}
|
||||
.call b i{display:block;width:6px;height:6px;background:${C.or}}
|
||||
.call span{display:block;font:500 7.8px 'JetBrains Mono',monospace;letter-spacing:1.2px;color:${C.mute};margin-top:2px}
|
||||
.chip{position:absolute;height:15px;padding:0 6px;border-radius:3px;font:700 7.6px 'JetBrains Mono',monospace;letter-spacing:1.1px;display:flex;align-items:center;white-space:nowrap}
|
||||
.cur{position:absolute;left:0;top:0;z-index:50;filter:drop-shadow(0 1px 2px rgba(0,0,0,.3))}
|
||||
.ring{position:absolute;width:34px;height:34px;margin:-17px 0 0 -17px;border-radius:50%;border:1.5px solid ${C.or};opacity:0;z-index:49}
|
||||
`;
|
||||
const el = (h) => {
|
||||
const d = document.createElement('div');
|
||||
d.innerHTML = h.trim();
|
||||
return d.firstElementChild;
|
||||
};
|
||||
const SUBS = [
|
||||
['OPTIC HEAD', '2 × 60 MM DOME · IRIS'],
|
||||
['LURE ARRAY', '7-LINK STALK · CAGED LAMP'],
|
||||
['RIBCAGE DRIVE', '2 DRIVE RINGS · 16 PISTONS'],
|
||||
['PECTORAL FINS', '2 × 10 RAYS · QUICK RELEASE'],
|
||||
['JAW & FANGS', 'HINGED JAW · 64 GLASS FANGS'],
|
||||
['HULL', '12 SHIELDS · 2,140 PARTS'],
|
||||
];
|
||||
const SERVOS = ['FIN R', 'FIN L', 'TAIL', 'JAW', 'LURE', 'DORSAL'];
|
||||
|
||||
// opts (all optional, the first film's console when absent): views / viewLabel / viewsTitle / viewRows for the view
|
||||
// panel (the second film puts its assemblies there, in two rows), display / displayLabel for the toggles; the panels
|
||||
// below move down to make room and the subsystem rows close up.
|
||||
export function createConsole(app, opts = {}) {
|
||||
const views = opts.views ?? VIEWS;
|
||||
const viewLabel = opts.viewLabel ?? VIEW_LABEL;
|
||||
const display = opts.display ?? DISPLAY;
|
||||
const displayLabel = opts.displayLabel ?? DISPLAY_LABEL;
|
||||
const viewRows = opts.viewRows ?? 1;
|
||||
const style = document.createElement('style');
|
||||
style.textContent = CSS;
|
||||
document.head.appendChild(style);
|
||||
const ui = el(`<div class="ui"></div>`);
|
||||
app.appendChild(ui);
|
||||
const add = (h) => {
|
||||
const n = el(h);
|
||||
ui.appendChild(n);
|
||||
return n;
|
||||
};
|
||||
const panel = (x, y, w, h, title, n) => {
|
||||
add(`<div class="cp" style="left:${x}px;top:${y}px;width:${w}px;height:${h}px"></div>`);
|
||||
add(`<div class="ph" style="left:${x + 14}px;top:${y + 13}px"><i></i>${title}</div>`);
|
||||
add(`<div class="pn" style="right:${1600 - x - w + 14}px;top:${y + 15}px">${n}</div>`);
|
||||
};
|
||||
const hr = (x, y, w) => add(`<div style="position:absolute;left:${x}px;top:${y}px;width:${w}px;height:1px;background:${C.line}"></div>`);
|
||||
const L = {x: 24, w: 290};
|
||||
const R = {x: 1286, w: 290};
|
||||
|
||||
// ------------------------------------------------------------ header: badge, title, the lift bar, the status cells
|
||||
add(`<div style="position:absolute;left:0;top:0;width:160px;height:88px;background:${C.or}"></div>`);
|
||||
add(`<svg style="position:absolute;left:20px;top:22px" width="52" height="44" viewBox="0 0 52 44"><g fill="none" stroke="#fff" stroke-width="2.1" stroke-linejoin="round" stroke-linecap="round"><path d="M8 30c4-9 13-13 22-11l9 4-9 3 9 3-9 4c-9 2-18-1-22-3z"/><path d="M8 30L1 24v13z"/><path d="M24 19c-2-7 2-14 10-16 7-1 12 4 11 10"/><circle cx="45" cy="17" r="3.4"/><circle cx="24" cy="26" r="1.6"/></g></svg>`);
|
||||
add(`<div class="mo" style="position:absolute;left:80px;top:34px;color:#fff;font-size:16px;font-weight:600;letter-spacing:3px">AX-6</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:182px;top:20px;letter-spacing:2.4px">ROBOTIC ANGLERFISH · DEEP-WATER SURVEY DRONE</div>`);
|
||||
add(`<div style="position:absolute;left:181px;top:35px;font-size:33px;font-weight:700;letter-spacing:-.6px;line-height:1">Vesper AX-6 <span style="color:${C.or};font-weight:400">/</span></div>`);
|
||||
add(`<div class="mo" style="position:absolute;left:182px;top:74px;font-size:11.2px;letter-spacing:2.2px;color:#6d6357">BIOLUMINESCENT LURE PLATFORM / FIELD SIMULATOR</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:700px;top:22px">THRUST LOAD</div>`);
|
||||
const liftPct = add(`<div class="mo" style="position:absolute;right:${1600 - 1040}px;top:21px;font-size:10px;font-weight:700"></div>`);
|
||||
const liftCells = [];
|
||||
for (let i = 0; i < 40; i++) liftCells.push(add(`<div style="position:absolute;left:${700 + i * 8.5}px;top:38px;width:6px;height:13px;border-radius:1px;background:${C.track}"></div>`));
|
||||
add(`<div class="sm" style="position:absolute;left:700px;top:57px;font-size:7.6px">IDLE</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:852px;top:57px;font-size:7.6px">CRUISE</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:1010px;top:57px;font-size:7.6px">LUNGE</div>`);
|
||||
const cells = [
|
||||
['SIM ID', 'AX6-1101'],
|
||||
['RUNTIME', ''],
|
||||
['STATUS', ''],
|
||||
['OPERATOR', 'LAB 4 · M.V.'],
|
||||
];
|
||||
const cellV = cells.map(([k, v], i) => {
|
||||
const x = 1086 + i * 118;
|
||||
if (i) add(`<div style="position:absolute;left:${x - 12}px;top:20px;width:1px;height:44px;background:${C.faint}"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:${x}px;top:22px">${k}</div>`);
|
||||
return add(`<div class="mo" style="position:absolute;left:${x}px;top:40px;font-size:12px;font-weight:600;letter-spacing:.4px">${v}</div>`);
|
||||
});
|
||||
{
|
||||
let h = '';
|
||||
for (let r = 0; r < 2; r++) for (let c = 0; c < 14; c++) h += `<path d="M${c * 25 + 4} ${r * 22}v8M${c * 25} ${r * 22 + 4}h8" stroke="${C.or}" stroke-width="1.1" opacity=".55"/>`;
|
||||
add(`<svg style="position:absolute;left:640px;top:84px" width="352" height="34">${h}</svg>`);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 01 wing beat
|
||||
panel(L.x, 108, L.w, 226, 'FIN STROKE', '01');
|
||||
const fq = add(`<div style="position:absolute;left:38px;top:140px;font-size:34px;font-weight:700;letter-spacing:-1px;line-height:1"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:39px;top:178px">STROKE FREQUENCY</div>`);
|
||||
const amp = add(`<div style="position:absolute;right:${1600 - 300}px;top:146px;font-size:22px;font-weight:700;line-height:1"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;right:${1600 - 300}px;top:178px">AMPLITUDE</div>`);
|
||||
const chart = add(`<svg style="position:absolute;left:38px;top:198px" width="262" height="96"></svg>`);
|
||||
hr(38, 302, 262);
|
||||
add(`<div class="sm" style="position:absolute;left:38px;top:312px">PLAYBACK</div>`);
|
||||
const pb = add(`<div class="v" style="position:absolute;left:104px;top:310px"></div>`);
|
||||
const shutter = add(`<div class="sm" style="position:absolute;right:${1600 - 300}px;top:312px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ 02 power
|
||||
panel(L.x, 346, L.w, 148, 'POWER', '02');
|
||||
const batt = add(`<div style="position:absolute;left:38px;top:378px;font-size:28px;font-weight:700;letter-spacing:-.8px;line-height:1"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:39px;top:410px">BATTERY</div>`);
|
||||
const battCells = [];
|
||||
for (let i = 0; i < 10; i++) battCells.push(add(`<div style="position:absolute;left:${150 + i * 15}px;top:383px;width:11px;height:20px;border-radius:2px;background:${C.track}"></div>`));
|
||||
hr(38, 428, 262);
|
||||
const pw = [['DRAW', 444], ['CELL', 444], ['MOTOR', 444]].map(([k], i) => {
|
||||
const x = 38 + i * 90;
|
||||
add(`<div class="sm" style="position:absolute;left:${x}px;top:440px">${k}</div>`);
|
||||
return add(`<div class="v" style="position:absolute;left:${x}px;top:458px;font-size:13px"></div>`);
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 03 servos: the wings, the fans, the tail, the neck
|
||||
panel(L.x, 506, L.w, 238, 'SERVOS', '03');
|
||||
const legState = add(`<div class="chip" style="right:${1600 - 300}px;top:536px"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:38px;top:540px">LOAD PER JOINT · TORQUE</div>`);
|
||||
const servo = SERVOS.map((n, i) => {
|
||||
const y = 566 + i * 27;
|
||||
add(`<div class="mo" style="position:absolute;left:38px;top:${y}px;font-size:10px;font-weight:700">${n}</div>`);
|
||||
add(`<div style="position:absolute;left:94px;top:${y + 4}px;width:150px;height:6px;background:${C.track};border-radius:3px"></div>`);
|
||||
const f = add(`<div style="position:absolute;left:94px;top:${y + 4}px;height:6px;background:${C.ink};border-radius:3px"></div>`);
|
||||
const v = add(`<div class="v" style="position:absolute;right:${1600 - 300}px;top:${y - 1}px"></div>`);
|
||||
return {f, v};
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 04 flight
|
||||
panel(R.x, 108, R.w, 196, 'DIVE', '04');
|
||||
const ball = add(`<svg style="position:absolute;left:1300px;top:142px" width="96" height="96"></svg>`);
|
||||
const fl = [['DEPTH', 0], ['CLIMB', 1], ['PITCH', 2], ['BANK', 3]].map(([k], i) => {
|
||||
const y = 142 + i * 24;
|
||||
add(`<div class="sm" style="position:absolute;left:1412px;top:${y + 2}px">${k}</div>`);
|
||||
return add(`<div class="v" style="position:absolute;right:${1600 - 1562}px;top:${y}px"></div>`);
|
||||
});
|
||||
hr(1300, 252, 262);
|
||||
add(`<div class="sm" style="position:absolute;left:1300px;top:264px">TRIM</div>`);
|
||||
const hold = add(`<div class="v" style="position:absolute;left:1350px;top:262px"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:1440px;top:264px">SPEED</div>`);
|
||||
const air = add(`<div class="v" style="position:absolute;right:${1600 - 1562}px;top:262px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ 05 views, 06 display
|
||||
const btn = {};
|
||||
const btnRow = (keys, labels, x0, y, wmax = 262, pad = 22) => {
|
||||
let x = x0;
|
||||
let yy = y;
|
||||
for (const k of keys) {
|
||||
const w = Math.round(labels[k].length * 7.1 + pad);
|
||||
if (x + w > x0 + wmax) {
|
||||
x = x0;
|
||||
yy += 30;
|
||||
}
|
||||
btn[k] = add(`<div class="bt" style="left:${x}px;top:${yy}px;width:${w}px">${labels[k]}</div>`);
|
||||
x += w + 6;
|
||||
}
|
||||
};
|
||||
const viewsH = 50 + 30 * viewRows;
|
||||
panel(R.x, 316, R.w, viewsH, opts.viewsTitle ?? 'VIEWS', '05');
|
||||
btnRow(views, viewLabel, 1300, 353, 262, 16);
|
||||
const dispY = 316 + viewsH + 12;
|
||||
panel(R.x, dispY, R.w, 110, 'DISPLAY', '06');
|
||||
btnRow(display, displayLabel, 1300, dispY + 37);
|
||||
const subY = dispY + 122;
|
||||
const subStep = Math.min(29, (744 - subY - 40) / 6);
|
||||
|
||||
// ------------------------------------------------------------ 07 subsystems
|
||||
panel(R.x, subY, R.w, 744 - subY, 'SUBSYSTEMS', '07');
|
||||
const subs = SUBS.map(([n, d], i) => {
|
||||
const y = subY + 34 + i * subStep;
|
||||
const bar = add(`<div style="position:absolute;left:1296px;top:${y}px;width:2px;height:22px;background:transparent"></div>`);
|
||||
add(`<div class="mo" style="position:absolute;left:1304px;top:${y + 1}px;font-size:9px;color:${C.mute}">0${i + 1}</div>`);
|
||||
const name = add(`<div class="mo" style="position:absolute;left:1328px;top:${y}px;font-size:9.4px;font-weight:700;letter-spacing:1.2px">${n}</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:1328px;top:${y + 13}px;font-size:7.6px">${d}</div>`);
|
||||
const chip = add(`<div class="chip" style="right:${1600 - 1562}px;top:${y + 3}px"></div>`);
|
||||
return {bar, name, chip};
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 08 flight log
|
||||
panel(330, 760, 940, 98, 'DIVE LOG', '08');
|
||||
add(`<div class="bt" style="left:346px;top:796px;width:44px;height:44px;border-radius:50%;border:none;background:${C.or};color:#fff;font-size:14px">❚❚</div>`);
|
||||
const logMode = add(`<div class="mo" style="position:absolute;left:406px;width:780px;top:790px;text-align:center;font-size:9.6px;font-weight:700;letter-spacing:1.6px;color:${C.or}"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:406px;top:791px">DESCENT</div>`);
|
||||
add(`<div class="sm" style="position:absolute;right:${1600 - 1250}px;top:791px">SURFACE</div>`);
|
||||
const TLB = {x: 408, w: 840};
|
||||
add(`<div style="position:absolute;left:${TLB.x}px;top:818px;width:${TLB.w}px;height:3px;background:${C.track};border-radius:2px"></div>`);
|
||||
const tlFill = add(`<div style="position:absolute;left:${TLB.x}px;top:818px;height:3px;background:${C.or};border-radius:2px"></div>`);
|
||||
const tlTicks = add(`<div style="position:absolute;inset:0"></div>`);
|
||||
const tlKnob = add(`<div style="position:absolute;top:812px;width:15px;height:15px;margin-left:-7.5px;border-radius:50%;background:#fff;border:2px solid ${C.or};box-sizing:border-box"></div>`);
|
||||
const tlTime = add(`<div class="mo" style="position:absolute;left:406px;top:834px;font-size:9.6px;color:${C.mute};letter-spacing:1px"></div>`);
|
||||
const tlNext = add(`<div class="sm" style="position:absolute;right:${1600 - 1250}px;top:836px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ viewport notes: model, the view, the flight mode
|
||||
add(`<div class="sm" style="position:absolute;left:346px;top:122px;letter-spacing:2px">MODEL AX-6 · REV A</div>`);
|
||||
const viewNote = add(`<div class="sm" style="position:absolute;right:${1600 - 1254}px;top:122px;letter-spacing:2px"></div>`);
|
||||
add(`<svg style="position:absolute;left:346px;top:140px" width="60" height="60"><path d="M0 60V0h60" fill="none" stroke="${C.or}" stroke-width="1" stroke-dasharray="3 3" opacity=".6"/></svg>`);
|
||||
add(`<svg style="position:absolute;left:1194px;top:680px" width="60" height="60"><path d="M60 0v60H0" fill="none" stroke="${C.or}" stroke-width="1" stroke-dasharray="3 3" opacity=".6"/></svg>`);
|
||||
add(`<div class="sm" style="position:absolute;left:346px;top:666px">SWIM MODE</div>`);
|
||||
const mode = add(`<div style="position:absolute;left:345px;top:680px;font-size:30px;font-weight:700;letter-spacing:-.4px;line-height:1;color:${C.or}"></div>`);
|
||||
const modeSub = add(`<div class="sm" style="position:absolute;left:346px;top:716px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ footer
|
||||
add(`<div class="sm" style="position:absolute;left:27px;top:878px;letter-spacing:2.2px">FIELD SIMULATOR · PROCEDURAL MODEL · 64 GLASS FANGS · 7-LINK LURE · 2 OPTICS</div>`);
|
||||
add(`<div class="sm" style="position:absolute;right:28px;top:878px;letter-spacing:2.2px">VESPER MARINE · ABYSS LAB <span style="color:${C.or}">//////</span></div>`);
|
||||
|
||||
// ------------------------------------------------------------ labels, the pointer
|
||||
const callSvg = add(`<svg style="position:absolute;inset:0;overflow:visible" width="1600" height="900"></svg>`);
|
||||
const callG = add(`<div style="position:absolute;inset:0"></div>`);
|
||||
const ring = add(`<div class="ring"></div>`);
|
||||
const cur = add(`<div class="cur"><svg width="22" height="22" viewBox="0 0 34 34"><path d="M4 3 L30 13.5 L17.5 17.5 L13.5 30 Z" fill="#111" stroke="#fff" stroke-width="2.2" stroke-linejoin="round"/></svg></div>`);
|
||||
const centre = (n) => {
|
||||
const r = n.getBoundingClientRect();
|
||||
return [r.left + r.width / 2, r.top + r.height / 2];
|
||||
};
|
||||
const spots = Object.fromEntries(Object.entries(btn).map(([k, n]) => [k, centre(n)]));
|
||||
const pointer = (c) => {
|
||||
cur.style.display = c.x < 0 ? 'none' : 'block';
|
||||
cur.style.transform = `translate(${(c.x - 3).toFixed(2)}px, ${(c.y - 2).toFixed(2)}px) scale(${c.press ? 0.88 : 1})`;
|
||||
ring.style.left = `${c.ringX}px`;
|
||||
ring.style.top = `${c.ringY}px`;
|
||||
ring.style.opacity = String(c.ring * 0.85);
|
||||
ring.style.transform = `scale(${(0.35 + 0.9 * (1 - c.ring)).toFixed(3)})`;
|
||||
};
|
||||
const clock = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(Math.floor(s) % 60).padStart(2, '0')}`;
|
||||
const chipStyle = (n, kind, text) => {
|
||||
const k = {ok: [C.green, '#fff'], warn: [C.or, '#fff'], idle: [C.track, C.mute]}[kind];
|
||||
n.style.background = k[0];
|
||||
n.style.color = k[1];
|
||||
n.textContent = text;
|
||||
};
|
||||
let tickKey = '';
|
||||
|
||||
return {
|
||||
spots,
|
||||
btn,
|
||||
root: ui,
|
||||
TLB,
|
||||
update(s) {
|
||||
// header
|
||||
const lift = Math.round(s.lift * 40);
|
||||
liftCells.forEach((c, i) => (c.style.background = i < lift ? (i > 30 ? C.or : C.ink) : C.track));
|
||||
liftPct.textContent = `${Math.round(s.lift * 100)}%`;
|
||||
cellV[1].textContent = `00:00:${String(Math.floor(s.time)).padStart(2, '0')}`;
|
||||
cellV[2].innerHTML = `<span style="color:${s.statusKind === 'ok' ? C.green : C.or}">●</span> ${s.status}`;
|
||||
// wing beat: the frequency, the amplitude, the stroke of the near wing (orange) and the far one (grey) over the
|
||||
// last 1.2 s of playback, with the now marker on the right
|
||||
fq.innerHTML = `${s.freq.toFixed(2)}<span style="font-size:14px;font-weight:600;color:${C.mute}"> HZ</span>`;
|
||||
amp.textContent = `±${Math.round(s.amp)}°`;
|
||||
{
|
||||
const W = 262;
|
||||
const H = 96;
|
||||
const Y = (a) => H / 2 - (a / (s.chartMax ?? 62)) * (H / 2 - 8);
|
||||
let g = `<line x1="0" x2="${W}" y1="${H / 2}" y2="${H / 2}" stroke="${C.faint}" stroke-width="1"/>`;
|
||||
for (const a of s.chartTicks ?? [-55, 55]) g += `<line x1="0" x2="${W}" y1="${Y(a)}" y2="${Y(a)}" stroke="${C.line}" stroke-width="1" stroke-dasharray="2 3"/><text x="${W - 2}" y="${Y(a) - 3}" text-anchor="end" font-size="7" fill="${C.mute}" font-family="JetBrains Mono">${a > 0 ? '+' : ''}${a}°</text>`;
|
||||
const path = (k) => s.stroke.map((p, i) => `${i ? 'L' : 'M'}${((i / (s.stroke.length - 1)) * (W - 10)).toFixed(1)} ${Y(p[k]).toFixed(1)}`).join('');
|
||||
g += `<path d="${path(1)}" fill="none" stroke="${C.mute}" stroke-width="1" opacity=".7"/><path d="${path(0)}" fill="none" stroke="${C.or}" stroke-width="1.6"/>`;
|
||||
const last = s.stroke[s.stroke.length - 1];
|
||||
g += `<line x1="${W - 10}" x2="${W - 10}" y1="4" y2="${H - 4}" stroke="${C.ink}" stroke-width=".8" stroke-dasharray="2 2"/><circle cx="${W - 10}" cy="${Y(last[0]).toFixed(1)}" r="3.4" fill="${C.or}"/>`;
|
||||
g += `<text x="0" y="${H - 1}" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">${s.chartSpan ?? '−1.2 S'}</text><text x="${W - 14}" y="${H - 1}" text-anchor="end" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">NOW</text>`;
|
||||
chart.innerHTML = g;
|
||||
}
|
||||
pb.textContent = `${s.playback.toFixed(1)}×`;
|
||||
shutter.textContent = s.shutter ?? (s.blur > 0.5 ? 'SHUTTER 1/60' : 'HI-SPEED 1/2000');
|
||||
// power
|
||||
batt.innerHTML = `${Math.round(s.battery * 100)}<span style="font-size:13px;color:${C.mute}">%</span>`;
|
||||
const bc = Math.round(s.battery * 10);
|
||||
battCells.forEach((c, i) => (c.style.background = i < bc ? (i < 2 ? C.or : C.green) : C.track));
|
||||
pw[0].textContent = `${s.power.toFixed(1)} W`;
|
||||
pw[1].textContent = `${s.volt.toFixed(2)} V`;
|
||||
pw[2].textContent = `${s.motorT.toFixed(0)} °C`;
|
||||
// servos
|
||||
chipStyle(legState, s.legsFree ? 'warn' : 'ok', s.legsFree ? 'DETACHED' : 'HOLDING');
|
||||
servo.forEach((b, i) => {
|
||||
const v = s.servos[i];
|
||||
b.f.style.width = `${(v * 150).toFixed(1)}px`;
|
||||
const free = s.legFreeEach ? s.legFreeEach[i] : s.legsFree;
|
||||
b.f.style.background = v > 0.6 ? C.or : C.ink;
|
||||
b.v.textContent = free ? 'DETACHED' : `${Math.round(v * 100)}%`;
|
||||
b.v.style.color = free ? C.or : C.ink;
|
||||
b.v.style.fontSize = free ? '8.6px' : '11px';
|
||||
});
|
||||
// flight: the attitude ball (the horizon tilts with roll and slides with pitch) and the numbers
|
||||
{
|
||||
const r = 44;
|
||||
const off = s.pitch * 2.2;
|
||||
ball.innerHTML = `<defs><clipPath id="bc"><circle cx="48" cy="48" r="${r}"/></clipPath></defs><circle cx="48" cy="48" r="${r}" fill="#fbf8f3" stroke="${C.faint}"/><g clip-path="url(#bc)"><g transform="rotate(${(-s.roll).toFixed(2)} 48 48) translate(0 ${off.toFixed(2)})"><rect x="-20" y="48" width="136" height="70" fill="${C.track}"/><line x1="-20" x2="116" y1="48" y2="48" stroke="${C.ink}" stroke-width="1"/>${[-20, -10, 10, 20].map((p) => `<line x1="${48 - (Math.abs(p) > 10 ? 12 : 7)}" x2="${48 + (Math.abs(p) > 10 ? 12 : 7)}" y1="${48 - p * 2.2}" y2="${48 - p * 2.2}" stroke="${C.mute}" stroke-width=".8"/>`).join('')}</g></g><path d="M26 48h14l4 5 4-5h22" fill="none" stroke="${C.or}" stroke-width="2"/><circle cx="48" cy="48" r="2" fill="${C.or}"/>`;
|
||||
fl[0].textContent = `${s.depth.toFixed(1)} M`;
|
||||
fl[1].textContent = `${s.vs >= 0 ? '+' : '−'}${Math.abs(s.vs).toFixed(2)} M/S`;
|
||||
fl[2].textContent = `${s.pitch >= 0 ? '+' : '−'}${Math.abs(s.pitch).toFixed(2)}°`;
|
||||
fl[3].textContent = `${s.roll >= 0 ? '+' : '−'}${Math.abs(s.roll).toFixed(2)}°`;
|
||||
hold.textContent = s.trim ?? 'NEUTRAL';
|
||||
air.textContent = `${s.airspeed.toFixed(2)} M/S`;
|
||||
}
|
||||
// views, display
|
||||
const onBtn = (k, on) => {
|
||||
btn[k].style.background = on ? C.or : '#fffdf9';
|
||||
btn[k].style.color = on ? '#fff' : C.ink;
|
||||
btn[k].style.borderColor = on ? C.or : C.faint;
|
||||
};
|
||||
for (const k of views) onBtn(k, s.view === k);
|
||||
for (const k of display) onBtn(k, !!s.display[k]);
|
||||
// subsystems: a status chip each, the row the current view looks at marked
|
||||
subs.forEach((r, i) => {
|
||||
const [kind, text] = s.subs[i];
|
||||
chipStyle(r.chip, kind, text);
|
||||
r.bar.style.background = s.focus === i ? C.or : 'transparent';
|
||||
r.name.style.color = s.focus === i ? C.or : C.ink;
|
||||
});
|
||||
// flight log: the film's progress, a tick for every press, the mode
|
||||
const kx = TLB.x + (s.time / s.dur) * TLB.w;
|
||||
tlFill.style.width = `${(kx - TLB.x).toFixed(1)}px`;
|
||||
tlKnob.style.left = `${kx.toFixed(1)}px`;
|
||||
const key = s.events.length;
|
||||
if (key !== tickKey) {
|
||||
tickKey = key;
|
||||
tlTicks.innerHTML = s.events.map((e) => `<div style="position:absolute;left:${(TLB.x + (e / s.dur) * TLB.w - 1).toFixed(1)}px;top:813px;width:2px;height:13px;background:${C.ink};opacity:.35"></div>`).join('');
|
||||
}
|
||||
tlTime.textContent = `${clock(s.time)} / ${clock(s.dur)}`;
|
||||
tlNext.textContent = s.next;
|
||||
logMode.textContent = s.log;
|
||||
viewNote.textContent = s.viewNote ?? `VIEW · ${viewLabel[s.view]}${s.display.orbit ? ' · ORBIT' : ''}`;
|
||||
mode.textContent = s.mode;
|
||||
modeSub.textContent = s.modeSub;
|
||||
// labels: an orange square, the name, the note, a thin leader to the part
|
||||
let lh = '';
|
||||
let ch = '';
|
||||
for (const c of s.callouts) {
|
||||
if (c.o < 0.02 || !c.at) continue;
|
||||
const [ax, ay] = c.at;
|
||||
const [lx, ly] = c.label;
|
||||
const right = lx > ax;
|
||||
const ex = right ? lx - 6 : lx + c.w + 6;
|
||||
lh += `<polyline points="${ax.toFixed(1)},${ay.toFixed(1)} ${ex.toFixed(1)},${(ly + 6).toFixed(1)}" fill="none" stroke="${C.or}" stroke-width=".9" opacity="${c.o.toFixed(2)}"/><circle cx="${ax.toFixed(1)}" cy="${ay.toFixed(1)}" r="2.4" fill="${C.or}" opacity="${c.o.toFixed(2)}"/>`;
|
||||
ch += `<div class="call" style="left:${lx.toFixed(1)}px;top:${(ly - 1).toFixed(1)}px;opacity:${c.o.toFixed(2)}"><b><i></i>${c.name}</b><span>${c.sub}</span></div>`;
|
||||
}
|
||||
callSvg.innerHTML = lh;
|
||||
callG.innerHTML = ch;
|
||||
pointer(s.cursor);
|
||||
},
|
||||
pointer,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// The construction drawing around the bee: hairline arcs and dashed circles in a few tilted planes, dots and small
|
||||
// hollow markers riding on them, short ticks. All in world space round the bee, so a camera orbit gives them depth.
|
||||
// Lines are fat lines with a width in device pixels; resize() keeps them hairline at any pixel ratio.
|
||||
import * as THREE from 'three';
|
||||
import {Line2} from 'three/addons/lines/Line2.js';
|
||||
import {LineGeometry} from 'three/addons/lines/LineGeometry.js';
|
||||
import {LineMaterial} from 'three/addons/lines/LineMaterial.js';
|
||||
import {rng} from '../kit/util.js';
|
||||
|
||||
const V3 = THREE.Vector3;
|
||||
const INK = '#8a8178';
|
||||
|
||||
export function buildGuides({centre = [0.05, 0.1, 0], seed = 5} = {}) {
|
||||
const R = rng(seed);
|
||||
const group = new THREE.Group();
|
||||
const lines = [];
|
||||
const C = new V3(...centre);
|
||||
// two unit vectors spanning the plane with normal n
|
||||
const basis = (n) => {
|
||||
const a = Math.abs(n.y) < 0.9 ? new V3(0, 1, 0) : new V3(1, 0, 0);
|
||||
const u = new V3().crossVectors(a, n).normalize();
|
||||
return [u, new V3().crossVectors(n, u)];
|
||||
};
|
||||
const circ = (c, r, n, a) => {
|
||||
const [u, v] = basis(n.clone().normalize());
|
||||
return c.clone().addScaledVector(u, Math.cos(a) * r).addScaledVector(v, Math.sin(a) * r);
|
||||
};
|
||||
const arc = (c, r, n, a0, a1, {dashed = false, width = 1, opacity = 0.5, dash = 0.045} = {}) => {
|
||||
const N = Math.max(24, Math.round(Math.abs(a1 - a0) * r * 60));
|
||||
const pts = [];
|
||||
for (let i = 0; i <= N; i++) {
|
||||
const p = circ(c, r, n, a0 + ((a1 - a0) * i) / N);
|
||||
pts.push(p.x, p.y, p.z);
|
||||
}
|
||||
const g = new LineGeometry();
|
||||
g.setPositions(pts);
|
||||
const m = new LineMaterial({color: INK, linewidth: width, transparent: true, opacity, dashed, dashSize: dash, gapSize: dash * 0.8, depthWrite: false, worldUnits: false});
|
||||
const l = new Line2(g, m);
|
||||
l.computeLineDistances();
|
||||
l.renderOrder = 4;
|
||||
group.add(l);
|
||||
lines.push({m, width, opacity});
|
||||
return l;
|
||||
};
|
||||
const seg = (a, b, opts = {}) => {
|
||||
const g = new LineGeometry();
|
||||
g.setPositions([a.x, a.y, a.z, b.x, b.y, b.z]);
|
||||
const m = new LineMaterial({color: INK, linewidth: opts.width ?? 1, transparent: true, opacity: opts.opacity ?? 0.45, dashed: !!opts.dashed, dashSize: 0.04, gapSize: 0.035, depthWrite: false});
|
||||
const l = new Line2(g, m);
|
||||
l.computeLineDistances();
|
||||
l.renderOrder = 4;
|
||||
group.add(l);
|
||||
lines.push({m, width: opts.width ?? 1, opacity: opts.opacity ?? 0.45});
|
||||
};
|
||||
|
||||
// the rings: [radius, normal, arcs, dashed, width, opacity]
|
||||
const RINGS = [
|
||||
[2.75, new V3(0.35, 0.25, 1), [[0.15, 1.9], [2.4, 3.5], [4.1, 5.6]], false, 1.0, 0.42],
|
||||
[2.05, new V3(0.1, 1, 0.3), [[0, Math.PI * 2]], true, 1.0, 0.45],
|
||||
[1.35, new V3(1, 0.15, 0.05), [[0.3, 2.6], [3.3, 5.5]], false, 1.1, 0.5],
|
||||
[3.45, new V3(0.55, 0.75, 0.35), [[0.6, 2.2], [3.6, 4.6]], false, 0.9, 0.32],
|
||||
[1.7, new V3(-0.4, 0.3, 1), [[0, Math.PI * 2]], true, 0.9, 0.36],
|
||||
[2.35, new V3(0.9, -0.2, 0.4), [[1.0, 2.9], [4.2, 5.9]], false, 0.9, 0.34],
|
||||
];
|
||||
const onRing = [];
|
||||
for (const [r, n, arcs, dashed, w, o] of RINGS) {
|
||||
for (const [a0, a1] of arcs) arc(C, r, n, a0, a1, {dashed, width: w, opacity: o});
|
||||
onRing.push([r, n, arcs]);
|
||||
}
|
||||
// a small ring round the eye and one round the tail, offset from the main centre
|
||||
arc(new V3(1.2, 0.14, 0.1), 0.62, new V3(0.55, 0.05, 0.85), 0, Math.PI * 2, {dashed: true, width: 0.9, opacity: 0.4, dash: 0.03});
|
||||
arc(new V3(-1.15, -0.25, 0), 0.75, new V3(-0.9, -0.3, 0.3), 0.4, 4.6, {width: 0.9, opacity: 0.38});
|
||||
|
||||
// dots and hollow markers riding on the rings, ticks across them
|
||||
const dots = [];
|
||||
const marks = new THREE.Group();
|
||||
group.add(marks);
|
||||
const dotGeo = new THREE.SphereGeometry(1, 10, 8);
|
||||
const dotMat = new THREE.MeshBasicMaterial({color: '#5d5751', transparent: true, opacity: 0.75, depthWrite: false});
|
||||
const ringGeo = new THREE.RingGeometry(0.62, 1, 28);
|
||||
const ringMat = new THREE.MeshBasicMaterial({color: '#6e675f', transparent: true, opacity: 0.7, depthWrite: false, side: THREE.DoubleSide});
|
||||
for (const [r, n, arcs] of onRing) {
|
||||
for (const [a0, a1] of arcs) {
|
||||
const k = Math.max(1, Math.round((a1 - a0) * 1.6));
|
||||
for (let i = 0; i < k; i++) {
|
||||
const a = a0 + (a1 - a0) * R();
|
||||
const p = circ(C, r, n, a);
|
||||
if (R() < 0.6) {
|
||||
const d = new THREE.Mesh(dotGeo, dotMat);
|
||||
d.position.copy(p);
|
||||
d.scale.setScalar(0.009 + R() * 0.012);
|
||||
d.renderOrder = 5;
|
||||
group.add(d);
|
||||
dots.push(d);
|
||||
} else {
|
||||
const m = new THREE.Mesh(ringGeo, ringMat);
|
||||
m.position.copy(p);
|
||||
m.scale.setScalar(0.022 + R() * 0.016);
|
||||
m.renderOrder = 5;
|
||||
marks.add(m);
|
||||
}
|
||||
// a short tick across the ring at some of them
|
||||
if (R() < 0.35) {
|
||||
const t = circ(C, r * 1.04, n, a);
|
||||
const b = circ(C, r * 0.96, n, a);
|
||||
seg(t, b, {width: 1, opacity: 0.5});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// a few straight dashed leaders out from the body
|
||||
for (const [a, b] of [
|
||||
[new V3(0.9, 0.55, 0.2), new V3(1.9, 1.6, 0.4)],
|
||||
[new V3(-0.6, -0.4, 0.3), new V3(-1.9, -1.1, 0.9)],
|
||||
[new V3(0.2, 0.5, -0.3), new V3(0.6, 1.9, -0.8)],
|
||||
]) {
|
||||
seg(a, b, {dashed: true, width: 0.9, opacity: 0.38});
|
||||
}
|
||||
|
||||
return {
|
||||
group,
|
||||
resize(w, h, pr) {
|
||||
for (const L of lines) {
|
||||
L.m.resolution.set(w, h);
|
||||
L.m.linewidth = L.width * pr;
|
||||
}
|
||||
},
|
||||
// ops.guides 0..1 fades the whole drawing
|
||||
update(camera, ops = {}) {
|
||||
const k = ops.guides ?? 1;
|
||||
group.userData.show = k > 0.001;
|
||||
group.visible = group.userData.show;
|
||||
for (const L of lines) L.m.opacity = Math.min(1, L.opacity * 1.1 * k);
|
||||
dotMat.opacity = 0.75 * k;
|
||||
ringMat.opacity = 0.7 * k;
|
||||
for (const m of marks.children) m.quaternion.copy(camera.quaternion);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
// The robotic anglerfish's kitbash shop, copied from the bee's (robobee-shared/parts.js): the materials (gloss white
|
||||
// shell, orange accent, graphite and black mechanism, steel, the lens, clear glass and the fin membrane) and the
|
||||
// geometry every part is cut from. Added here: taperTube (from the scorpion) and plate, a thick panel cut out of any
|
||||
// parametric surface, which the skull and the jaws are made of. Everything is
|
||||
// built along +x and placed by the caller: sweepX turns a closed (x, r) profile round the x axis, whole or as an arc
|
||||
// with capped ends, which gives rings, collars, domes, shell plates and capsules from one function; gearGeo cuts a
|
||||
// toothed wheel with a bore; tube runs a cable along points.
|
||||
import * as THREE from 'three';
|
||||
import {RoundedBoxGeometry} from 'three/addons/geometries/RoundedBoxGeometry.js';
|
||||
import {mergeGeometries} from 'three/addons/utils/BufferGeometryUtils.js';
|
||||
|
||||
export const V3 = THREE.Vector3;
|
||||
export const D2R = Math.PI / 180;
|
||||
export const PAL = {white: '#f4f2ee', orange: '#ff5a1f', graphite: '#2f3238', black: '#111214', steel: '#cdd1d6'};
|
||||
|
||||
export function makeMaterials() {
|
||||
const phys = (o) => new THREE.MeshPhysicalMaterial(o);
|
||||
const std = (o) => new THREE.MeshStandardMaterial(o);
|
||||
return {
|
||||
// the white plastic: a soft base under a hard clear coat, so the softboxes sit on it as crisp bars
|
||||
shell: phys({color: PAL.white, roughness: 0.34, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.05}),
|
||||
// inside faces of the shells, a shade darker and matte
|
||||
shellIn: phys({color: '#dedad4', roughness: 0.6, metalness: 0, clearcoat: 0.2, clearcoatRoughness: 0.4, side: THREE.DoubleSide}),
|
||||
orange: phys({color: PAL.orange, roughness: 0.3, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.08}),
|
||||
// the orange panel at a wing tip: a film on the membrane, both faces, pulled forward so it never fights it
|
||||
orangeFilm: phys({color: PAL.orange, roughness: 0.32, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.08, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2}),
|
||||
graphite: std({color: PAL.graphite, roughness: 0.36, metalness: 0.72}),
|
||||
gunmetal: std({color: '#555a62', roughness: 0.28, metalness: 0.9}),
|
||||
black: phys({color: PAL.black, roughness: 0.3, metalness: 0.15, clearcoat: 0.8, clearcoatRoughness: 0.12}),
|
||||
rubber: std({color: '#1b1c1f', roughness: 0.7, metalness: 0}),
|
||||
steel: std({color: PAL.steel, roughness: 0.2, metalness: 1}),
|
||||
// the camera eye: a deep black inner element under a dark glass dome; its colour darkens only what shows
|
||||
// through it, the highlights stay at full strength
|
||||
lens: phys({color: '#020203', roughness: 0.05, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.02, envMapIntensity: 1.4}),
|
||||
lensGlass: phys({color: '#6f7277', roughness: 0, metalness: 0, transmission: 1, thickness: 0, ior: 1.5, clearcoat: 1, clearcoatRoughness: 0, specularIntensity: 1, envMapIntensity: 2.4}),
|
||||
amber: std({color: '#000000', emissive: '#ffa040', emissiveIntensity: 4.5}),
|
||||
// circuit boards in the thorax: a dark green-black laminate
|
||||
pcb: std({color: '#1b241f', roughness: 0.55, metalness: 0.1}),
|
||||
// the clear abdomen window: real transmission, so the mechanism inside refracts a touch
|
||||
glass: phys({color: '#ffffff', roughness: 0.0, metalness: 0, transmission: 1, thickness: 0, ior: 1.3, specularIntensity: 0.6, clearcoat: 0.5, clearcoatRoughness: 0.02}),
|
||||
// the wing film: a faint grey-white sheet; the veins and the rim carry the read
|
||||
membrane: phys({color: '#eef0f2', roughness: 0.38, metalness: 0, transparent: true, opacity: 0.3, depthWrite: false, side: THREE.DoubleSide, clearcoat: 1, clearcoatRoughness: 0.04, iridescence: 0.35, iridescenceIOR: 1.3}),
|
||||
// the wing rim: a pale clear-ish tube
|
||||
rim: phys({color: '#e4e7ea', roughness: 0.12, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.04, transparent: true, opacity: 0.55, depthWrite: false}),
|
||||
vein: std({color: '#4a4d53', roughness: 0.5, metalness: 0.2, transparent: true, opacity: 0.72}),
|
||||
veinCore: std({color: '#5a5d63', roughness: 0.5, metalness: 0.2}),
|
||||
led: std({color: '#000000', emissive: PAL.orange, emissiveIntensity: 1.4}),
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ sweepX: a closed (x, r) profile turned round the x axis
|
||||
// profile: [[x, r], ...] closed loop, either winding. a0..a1: the arc, angle 0 at +y, 90° at +z. Profile corners
|
||||
// sharper than `smooth` degrees keep a hard edge; softer ones are shaded smooth. A partial arc gets capped ends.
|
||||
export function sweepX(profile, {a0 = 0, a1 = Math.PI * 2, segs = 64, smooth = 32} = {}) {
|
||||
let P = profile.map(([x, r]) => [x, Math.max(0, r)]);
|
||||
let area = 0;
|
||||
for (let i = 0; i < P.length; i++) {
|
||||
const [x0, r0] = P[i];
|
||||
const [x1, r1] = P[(i + 1) % P.length];
|
||||
area += x0 * r1 - x1 * r0;
|
||||
}
|
||||
if (area < 0) P = P.reverse();
|
||||
const n = P.length;
|
||||
// outward edge normals in the (x, r) plane
|
||||
const EN = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const [x0, r0] = P[i];
|
||||
const [x1, r1] = P[(i + 1) % n];
|
||||
const l = Math.hypot(x1 - x0, r1 - r0) || 1;
|
||||
EN.push([(r1 - r0) / l, -(x1 - x0) / l]);
|
||||
}
|
||||
const cosS = Math.cos(smooth * D2R);
|
||||
const vN = (i, e) => {
|
||||
// normal at vertex i as seen from edge e (e is i-1 or i)
|
||||
const other = e === i ? (i - 1 + n) % n : i;
|
||||
const a = EN[e];
|
||||
const b = EN[other];
|
||||
if (a[0] * b[0] + a[1] * b[1] < cosS) return a;
|
||||
const x = a[0] + b[0];
|
||||
const y = a[1] + b[1];
|
||||
const l = Math.hypot(x, y) || 1;
|
||||
return [x / l, y / l];
|
||||
};
|
||||
const full = Math.abs(a1 - a0) >= Math.PI * 2 - 1e-6;
|
||||
const pos = [];
|
||||
const nor = [];
|
||||
const idx = [];
|
||||
const cs = [];
|
||||
for (let j = 0; j <= segs; j++) {
|
||||
const th = a0 + ((a1 - a0) * j) / segs;
|
||||
cs.push([Math.cos(th), Math.sin(th)]);
|
||||
}
|
||||
for (let e = 0; e < n; e++) {
|
||||
const i0 = e;
|
||||
const i1 = (e + 1) % n;
|
||||
const [x0, r0] = P[i0];
|
||||
const [x1, r1] = P[i1];
|
||||
if (Math.hypot(x1 - x0, r1 - r0) < 1e-9) continue;
|
||||
const n0 = vN(i0, e);
|
||||
const n1 = vN(i1, e);
|
||||
const base = pos.length / 3;
|
||||
for (let j = 0; j <= segs; j++) {
|
||||
const [c, s] = cs[j];
|
||||
pos.push(x0, r0 * c, r0 * s, x1, r1 * c, r1 * s);
|
||||
nor.push(n0[0], n0[1] * c, n0[1] * s, n1[0], n1[1] * c, n1[1] * s);
|
||||
}
|
||||
for (let j = 0; j < segs; j++) {
|
||||
const a = base + j * 2;
|
||||
const b = a + 1;
|
||||
const c = a + 3;
|
||||
const d = a + 2;
|
||||
idx.push(a, b, c, a, c, d);
|
||||
}
|
||||
}
|
||||
if (!full) {
|
||||
const tri = THREE.ShapeUtils.triangulateShape(
|
||||
P.map(([x, r]) => new THREE.Vector2(x, r)),
|
||||
[],
|
||||
);
|
||||
for (const [th, flip] of [
|
||||
[a0, true],
|
||||
[a1, false],
|
||||
]) {
|
||||
const c = Math.cos(th);
|
||||
const s = Math.sin(th);
|
||||
// the cap's normal: -d/dθ at a0, +d/dθ at a1
|
||||
const nx = 0;
|
||||
const ny = flip ? s : -s;
|
||||
const nz = flip ? -c : c;
|
||||
const base = pos.length / 3;
|
||||
for (const [x, r] of P) {
|
||||
pos.push(x, r * c, r * s);
|
||||
nor.push(nx, ny, nz);
|
||||
}
|
||||
for (const t of tri) {
|
||||
if (flip) idx.push(base + t[0], base + t[2], base + t[1]);
|
||||
else idx.push(base + t[0], base + t[1], base + t[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
const g = new THREE.BufferGeometry();
|
||||
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
|
||||
g.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
|
||||
g.setIndex(idx);
|
||||
return g;
|
||||
}
|
||||
|
||||
// a rounded rectangle profile for a ring: x0..x1 wide, r0..r1 deep, corners rounded by `round`
|
||||
export function ringProfile(x0, x1, r0, r1, round = 0.01, steps = 3) {
|
||||
const rr = Math.min(round, (x1 - x0) / 2.01, (r1 - r0) / 2.01);
|
||||
const pts = [];
|
||||
const corner = (cx, cr, a0) => {
|
||||
for (let k = 0; k <= steps; k++) {
|
||||
const a = a0 + (k / steps) * (Math.PI / 2);
|
||||
pts.push([cx + Math.cos(a) * rr, cr + Math.sin(a) * rr]);
|
||||
}
|
||||
};
|
||||
corner(x1 - rr, r0 + rr, -Math.PI / 2);
|
||||
corner(x1 - rr, r1 - rr, 0);
|
||||
corner(x0 + rr, r1 - rr, Math.PI / 2);
|
||||
corner(x0 + rr, r0 + rr, Math.PI);
|
||||
return pts;
|
||||
}
|
||||
export const ring = (x0, x1, r0, r1, round, opts) => sweepX(ringProfile(x0, x1, r0, r1, round), opts);
|
||||
|
||||
// a thick spherical shell from polar angle p0 to p1 (0 = +x pole), outer radius R, wall t; the rims stay sharp so
|
||||
// the clear coat draws a crisp line along them
|
||||
export function domeProfile(R, t, p0, p1, steps = 24) {
|
||||
const out = [];
|
||||
const inn = [];
|
||||
for (let k = 0; k <= steps; k++) {
|
||||
const p = p0 + ((p1 - p0) * k) / steps;
|
||||
out.push([R * Math.cos(p), R * Math.sin(p)]);
|
||||
inn.push([(R - t) * Math.cos(p), (R - t) * Math.sin(p)]);
|
||||
}
|
||||
return [...out, ...inn.reverse()];
|
||||
}
|
||||
export const dome = (R, t, p0, p1, opts) => sweepX(domeProfile(R, t, p0, p1), opts);
|
||||
|
||||
// a solid of revolution from a radius function: r(u) for u in 0..1 along x0..x1, closed to the axis at both ends
|
||||
export function solidProfile(x0, x1, rFn, steps = 32) {
|
||||
const pts = [[x0, 0]];
|
||||
for (let k = 0; k <= steps; k++) {
|
||||
const u = k / steps;
|
||||
pts.push([x0 + (x1 - x0) * u, rFn(u)]);
|
||||
}
|
||||
pts.push([x1, 0]);
|
||||
return pts;
|
||||
}
|
||||
export const solid = (x0, x1, rFn, opts, steps) => sweepX(solidProfile(x0, x1, rFn, steps), opts);
|
||||
// a capsule-like rounded radius: r0 at the start, r1 at the end, ends rounded over `cap` of the length
|
||||
export const capsuleR = (r0, r1, cap = 0.12) => (u) => {
|
||||
const r = r0 + (r1 - r0) * u;
|
||||
const e = Math.min(u, 1 - u) / cap;
|
||||
return e >= 1 ? r : r * Math.sqrt(Math.max(0, 1 - (1 - e) * (1 - e)));
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------ gears, boxes, tubes
|
||||
// a spur gear around +z: `teeth` teeth between rRoot and rOut, `width` thick, a bore of holeR, lightening holes
|
||||
export function gearGeo(teeth, rOut, rRoot, width, holeR = 0, spokes = 0) {
|
||||
const sh = new THREE.Shape();
|
||||
for (let i = 0; i < teeth; i++) {
|
||||
const a0 = (i / teeth) * Math.PI * 2;
|
||||
const da = (Math.PI * 2) / teeth;
|
||||
const pts = [
|
||||
[rRoot, a0],
|
||||
[rRoot, a0 + da * 0.18],
|
||||
[rOut, a0 + da * 0.32],
|
||||
[rOut, a0 + da * 0.6],
|
||||
[rRoot, a0 + da * 0.74],
|
||||
];
|
||||
pts.forEach(([r, a], k) => (i === 0 && k === 0 ? sh.moveTo(r * Math.cos(a), r * Math.sin(a)) : sh.lineTo(r * Math.cos(a), r * Math.sin(a))));
|
||||
}
|
||||
sh.closePath();
|
||||
if (holeR) {
|
||||
const h = new THREE.Path();
|
||||
h.absarc(0, 0, holeR, 0, Math.PI * 2, true);
|
||||
sh.holes.push(h);
|
||||
}
|
||||
// round lightening holes between the bore and the rim
|
||||
if (spokes) {
|
||||
const rc = (holeR + rRoot) / 2;
|
||||
const rh = Math.min((rRoot - holeR) * 0.3, (Math.PI * rc) / spokes * 0.55);
|
||||
for (let k = 0; k < spokes; k++) {
|
||||
const a = (k / spokes) * Math.PI * 2;
|
||||
const h = new THREE.Path();
|
||||
h.absarc(Math.cos(a) * rc, Math.sin(a) * rc, rh, 0, Math.PI * 2, true);
|
||||
sh.holes.push(h);
|
||||
}
|
||||
}
|
||||
const bev = Math.min(width * 0.18, (rOut - rRoot) * 0.3);
|
||||
const g = new THREE.ExtrudeGeometry(sh, {depth: width - bev * 2, bevelEnabled: true, bevelThickness: bev, bevelSize: bev * 0.8, bevelSegments: 1, curveSegments: 10});
|
||||
g.translate(0, 0, -(width - bev * 2) / 2);
|
||||
return g;
|
||||
}
|
||||
// the same gear with its axis along +x
|
||||
export const gearX = (...a) => gearGeo(...a).rotateY(Math.PI / 2);
|
||||
|
||||
export const rbox = (w, h, d, r = 0.01) => new RoundedBoxGeometry(w, h, d, 3, Math.min(r, w / 2.01, h / 2.01, d / 2.01));
|
||||
export const cylX = (r0, r1, len, seg = 32) => new THREE.CylinderGeometry(r1, r0, len, seg).rotateZ(-Math.PI / 2);
|
||||
export const cylZ = (r0, r1, len, seg = 32) => new THREE.CylinderGeometry(r1, r0, len, seg).rotateX(Math.PI / 2);
|
||||
|
||||
/** A cable or rod through points (Vector3 or arrays), radius r. */
|
||||
export function tube(points, r, tubular = 64, radial = 10, closed = false) {
|
||||
const pts = points.map((p) => (p.isVector3 ? p : new V3(...p)));
|
||||
return new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts, closed, 'catmullrom', 0.5), tubular, r, radial, closed);
|
||||
}
|
||||
|
||||
/** A coil spring along +x: radius R, wire r, `turns` over len. */
|
||||
export function coil(R, r, turns, len, seg = 240) {
|
||||
const pts = [];
|
||||
for (let i = 0; i <= seg; i++) {
|
||||
const u = i / seg;
|
||||
const a = u * turns * Math.PI * 2;
|
||||
pts.push(new V3(u * len, Math.cos(a) * R, Math.sin(a) * R));
|
||||
}
|
||||
return new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), seg, r, 8, false);
|
||||
}
|
||||
|
||||
export const merge = (geos) => mergeGeometries(geos.map((g) => (g.index ? g.toNonIndexed() : g)).map((g) => {
|
||||
// mergeGeometries wants identical attribute sets: keep position and normal only
|
||||
const o = new THREE.BufferGeometry();
|
||||
o.setAttribute('position', g.attributes.position);
|
||||
o.setAttribute('normal', g.attributes.normal);
|
||||
return o;
|
||||
}));
|
||||
|
||||
/** Put a mesh of geo/mat at (x, y, z) into parent; returns it. Every mesh casts and takes shadows. */
|
||||
export function put(parent, geo, mat, x = 0, y = 0, z = 0) {
|
||||
const m = new THREE.Mesh(geo, mat);
|
||||
m.position.set(x, y, z);
|
||||
m.castShadow = true;
|
||||
m.receiveShadow = true;
|
||||
parent.add(m);
|
||||
return m;
|
||||
}
|
||||
|
||||
/** Rotate an object so its local +x points along dir. */
|
||||
export function aimX(obj, dir) {
|
||||
obj.quaternion.setFromUnitVectors(new V3(1, 0, 0), dir.clone().normalize());
|
||||
return obj;
|
||||
}
|
||||
|
||||
/** Instances of one geometry at a list of matrices (casts and takes shadows). */
|
||||
export function instances(parent, geo, mat, mats) {
|
||||
const im = new THREE.InstancedMesh(geo, mat, mats.length);
|
||||
mats.forEach((m, i) => im.setMatrixAt(i, m));
|
||||
im.castShadow = true;
|
||||
im.receiveShadow = true;
|
||||
parent.add(im);
|
||||
return im;
|
||||
}
|
||||
|
||||
/** A tube through points whose radius runs from r0 to r1 along its length (a fang, a fin ray, a tapered link). */
|
||||
export function taperTube(points, r0, r1, tubular = 48, radial = 14, pow = 1) {
|
||||
const pts = points.map((p) => (p.isVector3 ? p : new V3(...p)));
|
||||
const curve = new THREE.CatmullRomCurve3(pts, false, 'catmullrom', 0.5);
|
||||
const g = new THREE.TubeGeometry(curve, tubular, 1, radial, false);
|
||||
const pos = g.attributes.position;
|
||||
const nor = g.attributes.normal;
|
||||
const c = new V3();
|
||||
for (let i = 0; i <= tubular; i++) {
|
||||
const u = i / tubular;
|
||||
const r = r1 + (r0 - r1) * Math.pow(1 - u, pow);
|
||||
curve.getPointAt(u, c);
|
||||
for (let j = 0; j <= radial; j++) {
|
||||
const k = i * (radial + 1) + j;
|
||||
pos.setXYZ(k, c.x + nor.getX(k) * r, c.y + nor.getY(k) * r, c.z + nor.getZ(k) * r);
|
||||
}
|
||||
}
|
||||
pos.needsUpdate = true;
|
||||
g.computeVertexNormals();
|
||||
return g;
|
||||
}
|
||||
|
||||
/**
|
||||
* A thick panel cut from a parametric surface. S(u, v) -> Vector3 is the outer face over [u0, u1] x [v0, v1]; nrm(p)
|
||||
* gives the outward normal there (or null: taken from the surface's partials). t: the wall, nu x nv: the grid. The
|
||||
* outer and inner faces are smooth; the four edge walls are flat, and the outer face's border row leans its normal
|
||||
* toward the wall (bevel), so the clear coat draws a crisp line along every edge of the panel.
|
||||
*/
|
||||
export function plate(S, [u0, u1], [v0, v1], t, nu, nv, nrm = null, bevel = 0.55) {
|
||||
const P = [];
|
||||
const N = [];
|
||||
const e = 1e-4;
|
||||
for (let i = 0; i <= nu; i++) {
|
||||
for (let j = 0; j <= nv; j++) {
|
||||
const u = u0 + ((u1 - u0) * i) / nu;
|
||||
const v = v0 + ((v1 - v0) * j) / nv;
|
||||
const p = S(u, v);
|
||||
let n = nrm ? nrm(p) : null;
|
||||
if (!n) {
|
||||
const du = S(u + e, v).sub(S(u - e, v));
|
||||
const dv = S(u, v + e).sub(S(u, v - e));
|
||||
n = new V3().crossVectors(du, dv).normalize();
|
||||
}
|
||||
P.push(p);
|
||||
N.push(n);
|
||||
}
|
||||
}
|
||||
const id = (i, j) => i * (nv + 1) + j;
|
||||
// the orientation: the grid's own winding against the outward normal, at the middle of the panel
|
||||
const mi = Math.max(0, Math.floor(nu / 2) - (nu > 1 ? 0 : 0));
|
||||
const mj = Math.floor(nv / 2);
|
||||
const ia = Math.min(mi, nu - 1);
|
||||
const ja = Math.min(mj, nv - 1);
|
||||
const w = new V3().crossVectors(P[id(ia + 1, ja)].clone().sub(P[id(ia, ja)]), P[id(ia, ja + 1)].clone().sub(P[id(ia, ja)]));
|
||||
const ccw = w.dot(N[id(ia, ja)]) > 0;
|
||||
// bevel: the border row of the outer face leans toward the wall
|
||||
const NO = N.map((n) => n.clone());
|
||||
const lean = (i, j, d) => NO[id(i, j)].addScaledVector(d.normalize(), bevel).normalize();
|
||||
if (bevel > 0) {
|
||||
for (let i = 0; i <= nu; i++) {
|
||||
lean(i, 0, P[id(i, 0)].clone().sub(P[id(i, 1)]));
|
||||
lean(i, nv, P[id(i, nv)].clone().sub(P[id(i, nv - 1)]));
|
||||
}
|
||||
for (let j = 0; j <= nv; j++) {
|
||||
lean(0, j, P[id(0, j)].clone().sub(P[id(1, j)]));
|
||||
lean(nu, j, P[id(nu, j)].clone().sub(P[id(nu - 1, j)]));
|
||||
}
|
||||
}
|
||||
const pos = [];
|
||||
const nor = [];
|
||||
const idx = [];
|
||||
const V = (nGrid) => (nGrid + 1) * (nv + 1);
|
||||
// outer
|
||||
for (let k = 0; k < P.length; k++) {
|
||||
pos.push(P[k].x, P[k].y, P[k].z);
|
||||
nor.push(NO[k].x, NO[k].y, NO[k].z);
|
||||
}
|
||||
// inner
|
||||
for (let k = 0; k < P.length; k++) {
|
||||
pos.push(P[k].x - N[k].x * t, P[k].y - N[k].y * t, P[k].z - N[k].z * t);
|
||||
nor.push(-N[k].x, -N[k].y, -N[k].z);
|
||||
}
|
||||
const off = V(nu);
|
||||
for (let i = 0; i < nu; i++) {
|
||||
for (let j = 0; j < nv; j++) {
|
||||
const a = id(i, j);
|
||||
const b = id(i + 1, j);
|
||||
const c = id(i, j + 1);
|
||||
const d = id(i + 1, j + 1);
|
||||
if (ccw) idx.push(a, b, c, c, b, d, off + a, off + c, off + b, off + c, off + d, off + b);
|
||||
else idx.push(a, c, b, c, d, b, off + a, off + b, off + c, off + c, off + b, off + d);
|
||||
}
|
||||
}
|
||||
const face = new THREE.BufferGeometry();
|
||||
face.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
|
||||
face.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
|
||||
face.setIndex(idx);
|
||||
// the walls: a strip between the outer border and the inner one, flat shaded, facing away from the panel
|
||||
const wp = [];
|
||||
const edge = (list, outDir) => {
|
||||
for (let k = 0; k < list.length - 1; k++) {
|
||||
const [ka, kb] = [list[k], list[k + 1]];
|
||||
const oa = P[ka];
|
||||
const ob = P[kb];
|
||||
if (oa.distanceTo(ob) < 1e-7) continue;
|
||||
const ia2 = oa.clone().addScaledVector(N[ka], -t);
|
||||
const ib2 = ob.clone().addScaledVector(N[kb], -t);
|
||||
const fn = new V3().crossVectors(ob.clone().sub(oa), ia2.clone().sub(oa));
|
||||
const tri = fn.dot(outDir(k)) > 0 ? [oa, ob, ia2, ob, ib2, ia2] : [oa, ia2, ob, ob, ia2, ib2];
|
||||
for (const p of tri) wp.push(p.x, p.y, p.z);
|
||||
}
|
||||
};
|
||||
const row = (j) => [...Array(nu + 1).keys()].map((i) => id(i, j));
|
||||
const col = (i) => [...Array(nv + 1).keys()].map((j) => id(i, j));
|
||||
edge(row(0), (k) => P[id(k, 0)].clone().sub(P[id(k, 1)]));
|
||||
edge(row(nv), (k) => P[id(k, nv)].clone().sub(P[id(k, nv - 1)]));
|
||||
edge(col(0), (k) => P[id(0, k)].clone().sub(P[id(1, k)]));
|
||||
edge(col(nu), (k) => P[id(nu, k)].clone().sub(P[id(nu - 1, k)]));
|
||||
const walls = new THREE.BufferGeometry();
|
||||
walls.setAttribute('position', new THREE.Float32BufferAttribute(wp, 3));
|
||||
walls.computeVertexNormals();
|
||||
return wp.length ? merge([face, walls]) : face;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,104 @@
|
||||
"""Score for the VESPER AX-6 film cut 1:1 on the bee's (entry roboangler-film, tour_bee.js), mixed like the
|
||||
hummingbird's (robohum-shared/score_bee.py): a bed in D minor (Dm9, Bbmaj7, Gm9, A7sus at 92 bpm: e-piano, bass, soft
|
||||
drums and a pad on the same changes) at one level the whole way, a quiet click on every button press, and for every act
|
||||
short quiet accents on its own moves: a slow wash for the swim-in and a snap as the jaw shuts at its end, thread ticks
|
||||
as the lens rings unscrew and screw back, a swish as the fin leaves its root, air through its turn and a snap as it
|
||||
seats, a servo tick per lure link, a run of glass ticks as the cage blooms and a soft rising tone for the flare, a
|
||||
hinge click per rib shield and servo blips as the drive rings slide out, a drop and a run of glass ticks along the fang
|
||||
rows and a snap as the jaw seats, a whoosh into the explode and three clicks as the fish seats again, a rising air on
|
||||
the wind-up and a snap and a rush for the lunge. No drones.
|
||||
|
||||
python run_sfx.py sims/piranha-shared/score.py
|
||||
|
||||
Every cue comes from the script in roboangler-film/timeline.json, with the offsets inside each act taken from
|
||||
tour_bee.js (the bee's ACT clocks, WING_FLIP, CAGE, FLARE, the snap at 2.3 s, the explode out 0.2-1.8 s and home
|
||||
0-1.0 s, the lunge 1.0 s after HERO).
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
|
||||
from sfx.score_kit import airy, bed, chords, hz, thud # noqa: E402
|
||||
from sfx.synth import blip, click, envelope, pad # noqa: E402
|
||||
|
||||
# TL / OUT in the environment score another cut of the film (roboangler-cut) without touching this one
|
||||
TIMELINE = os.environ.get("TL", "../piranha-film/timeline.json")
|
||||
OUT = os.environ.get("OUT", os.path.join(os.environ.get("CUTAWAY_OUT", "cutaway-out"), "piranha-score.wav"))
|
||||
TARGET_LUFS = -14.0
|
||||
SEED = 41
|
||||
|
||||
CHORDS = chords("Dm9:D3 F3 A3 C4 E4/D2", "Bbmaj7:Bb2 D3 F3 A3 D4/Bb1", "Gm9:G2 Bb2 D3 F3 A3/G1", "A7sus:A2 D3 E3 G3 C4/A1")
|
||||
MOTIF = [(0.5, hz("A5")), (1.5, hz("F5")), (2.5, hz("E5"))]
|
||||
SNAP_IN = 2.3
|
||||
DEP = 1.0
|
||||
|
||||
|
||||
def snap(mix, t, level=0.06, pan=0.0):
|
||||
"""The jaw shutting: a short click on a soft low knock."""
|
||||
mix.put(t, click(1500, 0.03), level, pan=pan)
|
||||
mix.put(t, thud(110, 0.06, 0.25), level * 0.5, pan=pan)
|
||||
|
||||
|
||||
def score(mix, tl):
|
||||
dur = tl["duration"]
|
||||
left, right, low, drums = bed(dur, 92, CHORDS, MOTIF, motif_voice="blip", kicks=(0, 2.5), snares=(1, 3), hats=8, swing=0.08, keys_vel=0.75, keys_lp=3600)
|
||||
mix.put_stereo(0, left, right, 0.13)
|
||||
mix.put(0, low, 0.13)
|
||||
mix.put(0, drums, 0.05)
|
||||
bar = 4 * 60 / 92
|
||||
changes = [(0.12 + b * bar, [f for f in CHORDS[b % len(CHORDS)][0][:4]]) for b in range(int(dur / bar) + 1)]
|
||||
pl, pr = pad(dur, changes, volume=envelope([(0, 0), (1.0, 1), (dur - 1.6, 1), (dur, 0)]), detune=0.8, tremolo=0.18, xfade=0.5)
|
||||
mix.put_stereo(0, pl, pr, 0.07)
|
||||
# the swim-in and the snap at its end
|
||||
mix.put(0.0, airy(2.4, 400, 1200, 0.6), 0.02, pan=-0.3)
|
||||
snap(mix, SNAP_IN + 0.12, 0.05, pan=0.2)
|
||||
|
||||
for e in tl["script"]:
|
||||
t, act = e["t"], e["act"]
|
||||
mix.put(t, click(2400, 0.025), 0.055, pan=0.45)
|
||||
if act == "optics":
|
||||
mix.put(t + 0.35, airy(0.6, 1200, 2600, 0.5), 0.012, pan=-0.15)
|
||||
for i, dt in enumerate((0.45, 0.62, 0.79, 0.96, 1.13)):
|
||||
mix.put(t + dt, click(3200 - 180 * i, 0.018), 0.033, pan=-0.1)
|
||||
for i, dt in enumerate((2.2, 2.34, 2.48, 2.6)):
|
||||
mix.put(t + dt, click(2500 + 180 * i, 0.018), 0.03, pan=-0.1)
|
||||
elif act == "wing":
|
||||
mix.put(t + 0.45, airy(0.8, 600, 2000, 0.6), 0.024, pan=-0.3)
|
||||
mix.put(t + 0.9, airy(1.4, 800, 1400, 0.5), 0.016, pan=-0.2)
|
||||
mix.put(t + 2.35, airy(0.35, 1800, 800, 0.5), 0.012, pan=-0.3)
|
||||
mix.put(t + 2.68, click(1800, 0.03), 0.06, pan=-0.2)
|
||||
elif act == "leg":
|
||||
for k in range(7):
|
||||
mix.put(t + 0.35 + 0.07 * k, click(2800 + 90 * k, 0.016), 0.028, pan=0.3)
|
||||
for j in range(12):
|
||||
mix.put(t + 0.78 + 0.05 * (j % 4) + 0.012 * j, click(3600 + 60 * j, 0.012), 0.018, pan=0.35)
|
||||
mix.put(t + 1.05, blip(hz("D6"), 0.6, 0.25), 0.014, pan=0.35)
|
||||
mix.put(t + 1.05, airy(0.8, 900, 2400, 0.5), 0.012, pan=0.35)
|
||||
for k in range(4):
|
||||
mix.put(t + 2.15 + 0.09 * k, click(2600 - 120 * k, 0.016), 0.026, pan=0.3)
|
||||
mix.put(t + 2.55, click(1900, 0.03), 0.05, pan=0.3)
|
||||
elif act == "thorax":
|
||||
for k in range(5):
|
||||
mix.put(t + 0.3 + 0.077 * k, click(2300 - 90 * k, 0.022), 0.034, pan=0.1)
|
||||
for i, dt in enumerate((0.6, 0.85, 1.1)):
|
||||
mix.put(t + dt, blip(hz("A5") * 2 ** (i / 6), 0.18, 0.06), 0.016)
|
||||
mix.put(t + 2.1, airy(0.4, 1600, 800, 0.5), 0.011)
|
||||
mix.put(t + 2.6, click(2100, 0.03), 0.055)
|
||||
elif act == "abdomen":
|
||||
mix.put(t + 0.3, airy(0.7, 1400, 500, 0.6), 0.02, pan=0.15)
|
||||
for j in range(12):
|
||||
mix.put(t + 0.38 + 0.045 * j, click(3300 + 70 * j, 0.012), 0.02, pan=0.1 + 0.03 * j)
|
||||
mix.put(t + 2.0, airy(0.4, 600, 1600, 0.5), 0.012, pan=0.15)
|
||||
snap(mix, t + 2.42, 0.06, pan=0.15)
|
||||
elif act == "exploded":
|
||||
mix.put(t + 0.2, airy(1.4, 450, 2400, 0.7), 0.032, pan=-0.15)
|
||||
mix.put(t + 0.25, blip(hz("D6"), 0.3, 0.1), 0.025)
|
||||
elif act == "assemble":
|
||||
mix.put(t, airy(1.0, 2200, 600, 0.5), 0.02, pan=0.15)
|
||||
for i, dt in enumerate((0.6, 0.8, 1.0)):
|
||||
mix.put(t + dt, click(2000 + 300 * i, 0.03), 0.05, pan=-0.3 + 0.3 * i)
|
||||
mix.put(t + 0.9, airy(0.6, 400, 1300, 0.6), 0.016)
|
||||
elif act == "hero":
|
||||
mix.put(t + 0.1, airy(0.9, 500, 1500, 0.5), 0.016, pan=0.2)
|
||||
snap(mix, t + DEP + 0.12, 0.065, pan=0.3)
|
||||
mix.put(t + DEP, airy(2.2, 450, 2600, 0.7), 0.032, pan=0.45)
|
||||
@@ -0,0 +1,129 @@
|
||||
// SERRASAL PX-7, the robotic piranha's film on the green page (entry piranha-film), made 2026-11-06: the approved
|
||||
// angler film's tour (tour_bee.js, the cut's beats as the hammerhead ran them) with the piranha's body (piranha.js,
|
||||
// round 3 of its still). The beats: the eye, the tail stalk telescoping out, the glass flank opening over its gears, the
|
||||
// jaw dropping with its glass fangs, the explode on a turntable and the lunge at the lens. The scene is mirrored across
|
||||
// x (the fish and every camera, not the lights or the page) as its still was shot, head on the left, near side to the
|
||||
// key. Green look and page from ../green; TL.film plays the scene's timeline faster for a demo.
|
||||
import * as THREE from 'three';
|
||||
import {runSim} from '../kit/runtime.js';
|
||||
import {createConsole} from '../green/console.js';
|
||||
import {makeCursor, makeLabels, nice, ORANGE_TO, PAPER_GREEN, retint, SHIFT} from '../green/look.js';
|
||||
import {PAL} from './parts.js';
|
||||
import {buildPiranha, FLOOR_Y} from './piranha.js';
|
||||
import {createStage, PAPER} from './stage.js';
|
||||
import {makeBeeTour} from './tour_bee.js';
|
||||
|
||||
const D2R = Math.PI / 180;
|
||||
|
||||
Object.assign(PAL, {orange: ORANGE_TO});
|
||||
Object.assign(PAPER, PAPER_GREEN);
|
||||
|
||||
const ACTS = [['optics', 'Eye'], ['wing', 'Fin'], ['leg', 'Tail'], ['thorax', 'Glass flank'], ['abdomen', 'Jaw'], ['exploded', 'Teardown'], ['hero', 'Release']];
|
||||
const PAGE = {
|
||||
name: 'Serrasal',
|
||||
code: 'PX-7',
|
||||
title: 'Robotic Piranha, Taken Apart',
|
||||
date: '2026-11-6',
|
||||
sub: {
|
||||
overview: ['2 rows of glass fangs', 'Glass flank, 2 drive gears'],
|
||||
optics: ['Lens under the brow', 'Iris: 10 blades'],
|
||||
wing: ['Pectoral fin, frosted', 'Root: pivot drum'],
|
||||
leg: ['Tail stalk, 4 segments', 'Telescopes on servos'],
|
||||
thorax: ['Glass barrel, 2 big gears', '2 lit coils'],
|
||||
abdomen: ['Jaw drops off the hinge', 'Glass fangs fly out'],
|
||||
exploded: ['Every part apart', 'Turntable 330°'],
|
||||
hero: ['Tail to full stroke', 'Lunge at the lens'],
|
||||
},
|
||||
cards: [{k: 'Tail beat', kind: 'wave', unit: 'Hz'}, {k: 'Thrust', kind: 'bar', unit: '%'}, {k: 'Servo load', kind: 'bars', n: 6}, {k: 'Battery', kind: 'bar', unit: '%'}],
|
||||
};
|
||||
const STATUS = {BANKING: 'Banking in', CRUISE: 'Cruising', 'OPTICS OPEN': 'Eye open', 'FIN OFF': 'Fin off', 'TAIL OUT': 'Tail out', 'FLANK OPEN': 'Flank open', 'JAW DROPPED': 'Jaw dropped', TEARDOWN: 'Teardown', REASSEMBLY: 'Reassembly', 'WIND-UP': 'Winding up', LUNGE: 'Lunging'};
|
||||
|
||||
export function makePiranhaGreen(TL) {
|
||||
const FILM = TL.film ?? TL.duration;
|
||||
// the angler's camera distances, scaled by TL.push; the eye shot pushes in by TL.opt
|
||||
const PUSH = TL.push ?? 1;
|
||||
const OPT = TL.opt ?? 0.9;
|
||||
const SPEED = TL.duration / FILM;
|
||||
// only the acts this cut runs get a pill and a line in the list (a demo names its set in TL.pills)
|
||||
const used = new Set(TL.pills ?? TL.script.map((e) => (e.act === 'assemble' ? 'exploded' : e.act)));
|
||||
const acts = ACTS.filter(([k]) => used.has(k));
|
||||
return async ({canvas, capture}) => {
|
||||
const app = document.getElementById('app');
|
||||
const st = createStage({canvas, floorY: FLOOR_Y, span: 3.8});
|
||||
const fish = buildPiranha();
|
||||
fish.pose({t: 0, idle: 0});
|
||||
fish.root.updateMatrixWorld(true);
|
||||
const at = (k) => fish.anchorAt(k).toArray();
|
||||
const mid = (...ps) => ps.reduce((a, p) => a.map((v, i) => v + p[i] / ps.length), [0, 0, 0]);
|
||||
const A = {
|
||||
lens: at('lens'),
|
||||
eyeAxis: new THREE.Vector3(1, 0, 0).transformDirection(fish.anchors.lens.obj.matrixWorld).toArray(),
|
||||
finHub: at('finHub'),
|
||||
lureMid: mid(at('stalk'), at('joint'), at('bulb')),
|
||||
core: at('core'),
|
||||
jaw: at('jaw'),
|
||||
};
|
||||
const T = makeBeeTour(TL, A);
|
||||
st.addBody(fish);
|
||||
retint(fish.root);
|
||||
fish.root.rotation.order = 'YXZ';
|
||||
fish.root.scale.x = -1;
|
||||
const m = -1;
|
||||
const ui = createConsole(app, {...PAGE, nav: [['overview', 'Overview'], ...acts], pills: acts});
|
||||
const cursorAt = makeCursor(ui, T.SCRIPT);
|
||||
const labels = makeLabels(st, fish.anchors);
|
||||
const fit = () => (app.style.transform = `scale(${Math.min(innerWidth / 1600, innerHeight / 900)})`);
|
||||
const resize = () => {
|
||||
fit();
|
||||
st.resize(1600, 900, capture ? devicePixelRatio || 1 : Math.min(devicePixelRatio || 1, 2));
|
||||
};
|
||||
resize();
|
||||
window.PIRANHA = {st, fish, T, A};
|
||||
const sm = (x) => {
|
||||
const u = Math.min(1, Math.max(0, x));
|
||||
return u * u * u * (u * (u * 6 - 15) + 10);
|
||||
};
|
||||
const SCR = [...TL.script].sort((a, b) => a.t - b.t);
|
||||
const optWin = (t) => {
|
||||
let w = 0;
|
||||
SCR.forEach((e, i) => {
|
||||
if (e.act !== 'optics') return;
|
||||
const t1 = SCR[i + 1]?.t ?? TL.duration;
|
||||
w = Math.max(w, sm((t - e.t) / 0.85) * (1 - sm((t - t1) / 0.85)));
|
||||
});
|
||||
return w;
|
||||
};
|
||||
return {
|
||||
resize,
|
||||
render(tf) {
|
||||
// a demo plays the scene's timeline a little faster: TL.film seconds of film for TL.duration of scene
|
||||
const t = tf * SPEED;
|
||||
const s = T.stateAt(t);
|
||||
fish.pose({t, idle: 1, gape: s.gape, swim: s.swim, eye: s.eye, fin: s.fin, finFlip: s.finFlip, lure: s.lure, cage: s.cage, flare: s.flare, rib: s.rib, drop: s.drop, explode: s.explode, spinT: s.spinT, bend: s.bend});
|
||||
retint(fish.root);
|
||||
const f = s.flight;
|
||||
fish.root.position.set(m * f.pos.x, f.pos.y, f.pos.z);
|
||||
fish.root.rotation.set(f.roll * D2R, m * f.yaw * D2R, m * f.pitch * D2R);
|
||||
const c = s.cam;
|
||||
st.frame({...c, az: m * c.az * D2R, el: c.el * D2R, d: c.d * PUSH * (1 - (1 - OPT) * optWin(t)), tx: m * c.tx, sx: m * (c.sx ?? 0) + SHIFT[0], sy: (c.sy ?? 0) + SHIFT[1]}, {guides: s.guides});
|
||||
const tel = T.telemetry(t, s);
|
||||
const v = s.view;
|
||||
const lift = Math.min(1, tel.lift);
|
||||
ui.update({
|
||||
time: tf,
|
||||
dur: FILM,
|
||||
status: STATUS[tel.status] ?? nice(tel.status),
|
||||
cards: [{v: tel.freq.toFixed(1), wave: tel.stroke.map((p) => p[0] / 40)}, {v: Math.round(lift * 100), bar: lift}, {bars: tel.servos}, {v: Math.round(tel.battery * 100), bar: tel.battery}],
|
||||
apart: Math.round(Math.max(s.open?.[v] ?? 0, s.explode) * 100),
|
||||
view: v === 'intro' ? 'overview' : v,
|
||||
callouts: labels(tel.labelSet),
|
||||
cursor: cursorAt(t),
|
||||
});
|
||||
return {};
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export const runPiranhaGreen = (TL, title = 'piranha-film') =>
|
||||
runSim({duration: TL.film ?? TL.duration, fps: 60, theme: 'light', hud: {enabled: false, title, subtitle: ''}, director: {enabled: false}, watermark: ''}, makePiranhaGreen(TL));
|
||||
@@ -0,0 +1,345 @@
|
||||
// The robotic anglerfish's stage, copied from the bee's (robobee-shared/stage.js); the key's shadow box and the floor
|
||||
// shadow's window take a span (the fish is longer than the bee). A near-white product studio. A warm paper backdrop with no horizon, a soft shadow pooled
|
||||
// on the floor under the bee (the bee's silhouette seen from below, blurred wide, plus a tighter pass for what hangs
|
||||
// close to the floor), a softbox environment for the clear coat to catch, a key with VSM self-shadows, a rim and a
|
||||
// fill, GTAO kept off the backdrop and the clear parts, MSAA. The tone curve is linear up to 0.8 and rolls off
|
||||
// above, hue preserved; the backdrop writes the inverse of that curve, so the paper lands on its exact colour and the
|
||||
// floor shadow darkens it as drawn. frame(cam, ops) draws one frame; cam = {tx, ty, tz, az, el, d, sx, sy}.
|
||||
import * as THREE from 'three';
|
||||
import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';
|
||||
import {GTAOPass} from 'three/addons/postprocessing/GTAOPass.js';
|
||||
import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';
|
||||
import {FullScreenQuad, Pass} from 'three/addons/postprocessing/Pass.js';
|
||||
import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';
|
||||
import {buildGuides} from './guides.js';
|
||||
|
||||
const V3 = THREE.Vector3;
|
||||
// the paper: top, middle, the floor band (sRGB), and the shadow's tint
|
||||
export const PAPER = {top: '#fefcf8', mid: '#fcf9f3', low: '#f5efe7', shadow: '#c9bcae'};
|
||||
const KNEE = 0.8;
|
||||
THREE.ShaderChunk.tonemapping_pars_fragment = THREE.ShaderChunk.tonemapping_pars_fragment.replace(
|
||||
'vec3 CustomToneMapping( vec3 color ) { return color; }',
|
||||
`vec3 CustomToneMapping( vec3 color ) {
|
||||
color *= toneMappingExposure;
|
||||
float p = max( color.r, max( color.g, color.b ) );
|
||||
if ( p <= ${KNEE.toFixed(2)} ) return color;
|
||||
float np = ${KNEE.toFixed(2)} + ${(1 - KNEE).toFixed(2)} * ( 1.0 - exp( -( p - ${KNEE.toFixed(2)} ) / ${(1 - KNEE).toFixed(2)} ) );
|
||||
return color * ( np / p );
|
||||
}`,
|
||||
);
|
||||
export const BEE_LAYER = 1;
|
||||
|
||||
const BACK_VERT = /* glsl */ `varying vec3 vW;
|
||||
void main(){
|
||||
#ifdef SCREEN
|
||||
vW = vec3(0.0); gl_Position = vec4(position.xy, 0.99999, 1.0);
|
||||
#else
|
||||
vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w;
|
||||
#endif
|
||||
}`;
|
||||
const BACK_FRAG = /* glsl */ `uniform vec3 uTop, uMid, uLow, uTint; uniform vec2 uRes;
|
||||
uniform sampler2D tSoft, tNear; uniform mat4 uVP; uniform float uSoft, uNear;
|
||||
varying vec3 vW;
|
||||
vec3 paper(float y){ return y > 0.42 ? mix(uMid, uTop, smoothstep(0.42, 1.0, y)) : mix(uLow, uMid, smoothstep(0.0, 0.42, y)); }
|
||||
// the inverse of the tone curve's shoulder: what to write so the output lands on c
|
||||
vec3 untone(vec3 c){
|
||||
float p = max(c.r, max(c.g, c.b));
|
||||
if (p <= ${KNEE.toFixed(2)}) return c;
|
||||
float pin = ${KNEE.toFixed(2)} - ${(1 - KNEE).toFixed(2)} * log(max(1e-4, 1.0 - (p - ${KNEE.toFixed(2)}) / ${(1 - KNEE).toFixed(2)}));
|
||||
return c * (pin / p);
|
||||
}
|
||||
float tap(sampler2D t, vec3 w){
|
||||
vec4 c = uVP * vec4(w, 1.0);
|
||||
vec2 uv = c.xy / c.w * 0.5 + 0.5;
|
||||
if (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0) return 0.0;
|
||||
vec2 e = smoothstep(0.0, 0.08, uv) * smoothstep(0.0, 0.08, 1.0 - uv);
|
||||
return texture2D(t, uv).r * e.x * e.y;
|
||||
}
|
||||
void main(){
|
||||
vec3 c = paper(gl_FragCoord.y / uRes.y);
|
||||
#ifndef SCREEN
|
||||
float s = clamp(tap(tSoft, vW) * uSoft + tap(tNear, vW) * uNear, 0.0, 1.0);
|
||||
c = mix(c, c * uTint, s);
|
||||
#endif
|
||||
gl_FragColor = vec4(untone(c), 1.0);
|
||||
}`;
|
||||
const QUAD_VERT = /* glsl */ `varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;
|
||||
const BLUR_FRAG = /* glsl */ `uniform sampler2D tSrc; uniform vec2 uDir; varying vec2 vUv;
|
||||
void main(){
|
||||
float w[5]; w[0] = 0.2270270270; w[1] = 0.1945945946; w[2] = 0.1216216216; w[3] = 0.0540540541; w[4] = 0.0162162162;
|
||||
vec4 c = texture2D(tSrc, vUv) * w[0];
|
||||
for (int i = 1; i < 5; i++) { c += texture2D(tSrc, vUv + uDir * float(i)) * w[i]; c += texture2D(tSrc, vUv - uDir * float(i)) * w[i]; }
|
||||
gl_FragColor = c;
|
||||
}`;
|
||||
// silhouette from below: everything counts, what hangs low counts more
|
||||
const SIL_VERT = /* glsl */ `varying float vH; uniform float uFloor; void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vH = w.y - uFloor; gl_Position = projectionMatrix * viewMatrix * w; }`;
|
||||
const SIL_FRAG = /* glsl */ `varying float vH; uniform float uFar, uBase; void main(){ float k = 1.0 - clamp(vH / uFar, 0.0, 1.0); gl_FragColor = vec4(uBase + (1.0 - uBase) * k * k, 0.0, 0.0, 1.0); }`;
|
||||
|
||||
export function createStage({canvas, floorY = -1.55, span = 3.4}) {
|
||||
const renderer = new THREE.WebGLRenderer({canvas, antialias: false, preserveDrawingBuffer: true, powerPreference: 'high-performance'});
|
||||
renderer.toneMapping = THREE.CustomToneMapping;
|
||||
renderer.toneMappingExposure = 1.0;
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
renderer.shadowMap.enabled = true;
|
||||
renderer.shadowMap.type = THREE.VSMShadowMap;
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(30, 16 / 9, 0.05, 80);
|
||||
const composer = new EffectComposer(renderer, new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: 8}));
|
||||
composer.addPass(new RenderPass(scene, camera));
|
||||
const gtao = new GTAOPass(scene, camera, 4, 4);
|
||||
gtao.output = GTAOPass.OUTPUT.Default;
|
||||
gtao.blendIntensity = 1.0;
|
||||
gtao.updateGtaoMaterial({radius: 0.13, distanceExponent: 1.6, thickness: 0.9, scale: 1.0, samples: 16, distanceFallOff: 1.0, screenSpaceRadius: false});
|
||||
gtao.updatePdMaterial({lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 5, rings: 2, samples: 16});
|
||||
class Toggle extends Pass {
|
||||
constructor(fn) {
|
||||
super();
|
||||
this.needsSwap = false;
|
||||
this.fn = fn;
|
||||
}
|
||||
render() {
|
||||
this.fn();
|
||||
}
|
||||
}
|
||||
// the backdrop, the guides and every clear part stay out of the AO pass
|
||||
const skip = [];
|
||||
// extra: meshes skipped only while a mode asks (the shells under x-ray)
|
||||
let extra = [];
|
||||
const aoSkip = (on) => {
|
||||
for (const o of skip) o.visible = on && o.userData.show !== false;
|
||||
for (const o of extra) o.visible = on;
|
||||
};
|
||||
composer.addPass(new Toggle(() => aoSkip(false)));
|
||||
composer.addPass(gtao);
|
||||
composer.addPass(new Toggle(() => aoSkip(true)));
|
||||
composer.addPass(new OutputPass());
|
||||
|
||||
// ------------------------------------------------------------ the studio the clear coat reflects
|
||||
{
|
||||
const env = new THREE.Scene();
|
||||
env.background = new THREE.Color('#d8d4ce');
|
||||
const box = (w, h, pos, k, tint = [1, 0.985, 0.96]) => {
|
||||
const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({color: new THREE.Color(...tint).multiplyScalar(k), side: THREE.DoubleSide}));
|
||||
m.position.copy(pos);
|
||||
m.lookAt(0, 0, 0);
|
||||
env.add(m);
|
||||
};
|
||||
box(16, 10, new V3(-4, 16, 6), 3.2); // the big top box
|
||||
box(3, 16, new V3(-15, 4, 8), 2.6); // a tall strip, left front
|
||||
box(3, 16, new V3(14, 5, -6), 2.0, [0.96, 0.98, 1]); // the rim strip behind
|
||||
box(20, 3, new V3(2, 2, 16), 1.5); // a low card in front
|
||||
box(8, 8, new V3(10, 2, 12), 1.1); // fill, right front
|
||||
const g = new THREE.Mesh(new THREE.CircleGeometry(40, 32), new THREE.MeshBasicMaterial({color: '#e9e3da', side: THREE.DoubleSide}));
|
||||
g.rotation.x = -Math.PI / 2;
|
||||
g.position.y = -3;
|
||||
env.add(g);
|
||||
const pm = new THREE.PMREMGenerator(renderer);
|
||||
scene.environment = pm.fromScene(env, 0.025).texture;
|
||||
scene.environmentIntensity = 0.62;
|
||||
pm.dispose();
|
||||
}
|
||||
const KEY = new V3(-0.3, 0.86, 0.55).normalize();
|
||||
const key = new THREE.DirectionalLight('#fffaf3', 3.0);
|
||||
key.castShadow = true;
|
||||
Object.assign(key.shadow.camera, {left: -span, right: span, top: span, bottom: -span, near: 1, far: 18});
|
||||
key.shadow.mapSize.set(4096, 4096);
|
||||
key.shadow.radius = 6;
|
||||
key.shadow.blurSamples = 20;
|
||||
key.shadow.bias = -0.0005;
|
||||
key.shadow.normalBias = 0.01;
|
||||
scene.add(key, key.target);
|
||||
const rim = new THREE.DirectionalLight('#f2f6ff', 1.1);
|
||||
rim.position.set(3, 3, -5);
|
||||
scene.add(rim);
|
||||
const fill = new THREE.DirectionalLight('#fff6ec', 0.3);
|
||||
fill.position.set(4, -1, 5);
|
||||
scene.add(fill);
|
||||
scene.add(new THREE.HemisphereLight('#ffffff', '#d9cfc2', 0.32));
|
||||
|
||||
// ------------------------------------------------------------ backdrop: the paper behind, the floor with its shadow
|
||||
const lin = (hex) => new THREE.Color(hex);
|
||||
const backU = {
|
||||
uTop: {value: lin(PAPER.top)},
|
||||
uMid: {value: lin(PAPER.mid)},
|
||||
uLow: {value: lin(PAPER.low)},
|
||||
uTint: {value: lin(PAPER.shadow)},
|
||||
uRes: {value: new THREE.Vector2(1, 1)},
|
||||
tSoft: {value: null},
|
||||
tNear: {value: null},
|
||||
uVP: {value: new THREE.Matrix4()},
|
||||
uSoft: {value: 0.42},
|
||||
uNear: {value: 0.55},
|
||||
};
|
||||
const paper = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.ShaderMaterial({vertexShader: BACK_VERT, fragmentShader: BACK_FRAG, uniforms: backU, defines: {SCREEN: ''}, depthWrite: false, depthTest: false}));
|
||||
paper.frustumCulled = false;
|
||||
paper.renderOrder = -10;
|
||||
scene.add(paper);
|
||||
const floor = new THREE.Mesh(new THREE.PlaneGeometry(200, 200).rotateX(-Math.PI / 2), new THREE.ShaderMaterial({vertexShader: BACK_VERT, fragmentShader: BACK_FRAG, uniforms: backU, depthWrite: false}));
|
||||
floor.position.y = floorY;
|
||||
floor.renderOrder = -9;
|
||||
scene.add(floor);
|
||||
skip.push(paper, floor);
|
||||
|
||||
// the floor shadow: the bee from below into two targets, one blurred wide, one tight
|
||||
const SR = 512;
|
||||
const HALF = span + 0.8;
|
||||
const mkRT = () => new THREE.WebGLRenderTarget(SR, SR, {type: THREE.HalfFloatType});
|
||||
const soft = [mkRT(), mkRT()];
|
||||
const near = [mkRT(), mkRT()];
|
||||
backU.tSoft.value = soft[0].texture;
|
||||
backU.tNear.value = near[0].texture;
|
||||
const shCam = new THREE.OrthographicCamera(-HALF, HALF, HALF, -HALF, 0, 6);
|
||||
shCam.up.set(0, 0, -1);
|
||||
shCam.layers.set(BEE_LAYER);
|
||||
const silU = {uFloor: {value: floorY}, uFar: {value: 1.6}, uBase: {value: 1.0}};
|
||||
const silMat = new THREE.ShaderMaterial({vertexShader: SIL_VERT, fragmentShader: SIL_FRAG, uniforms: silU, side: THREE.DoubleSide});
|
||||
const blurMat = new THREE.ShaderMaterial({vertexShader: QUAD_VERT, fragmentShader: BLUR_FRAG, uniforms: {tSrc: {value: null}, uDir: {value: new THREE.Vector2()}}, depthTest: false, depthWrite: false});
|
||||
const blurQuad = new FullScreenQuad(blurMat);
|
||||
const blur = ([a, b], px, passes) => {
|
||||
for (let i = 0; i < passes; i++) {
|
||||
blurMat.uniforms.tSrc.value = a.texture;
|
||||
blurMat.uniforms.uDir.value.set(px / SR, 0);
|
||||
renderer.setRenderTarget(b);
|
||||
blurQuad.render(renderer);
|
||||
blurMat.uniforms.tSrc.value = b.texture;
|
||||
blurMat.uniforms.uDir.value.set(0, px / SR);
|
||||
renderer.setRenderTarget(a);
|
||||
blurQuad.render(renderer);
|
||||
}
|
||||
};
|
||||
const black = new THREE.Color(0, 0, 0);
|
||||
const prevClear = new THREE.Color();
|
||||
// floor: 'full' (a wide pass and a tight one), 'one' (the wide pass only), 'half' / 'quarter' (that, every 2nd / 4th
|
||||
// frame)
|
||||
let floorMode = 'full';
|
||||
let floorTick = 0;
|
||||
const floorShadow = (c) => {
|
||||
if ((floorMode === 'half' && floorTick++ % 2) || (floorMode === 'quarter' && floorTick++ % 4)) return;
|
||||
shCam.position.set(c.x, floorY - 0.01, c.z);
|
||||
shCam.lookAt(c.x, floorY + 1, c.z);
|
||||
shCam.updateMatrixWorld();
|
||||
shCam.updateProjectionMatrix();
|
||||
renderer.getClearColor(prevClear);
|
||||
const prevA = renderer.getClearAlpha();
|
||||
const prevOv = scene.overrideMaterial;
|
||||
const prevSh = renderer.shadowMap.autoUpdate;
|
||||
renderer.shadowMap.autoUpdate = false;
|
||||
renderer.setClearColor(black, 1);
|
||||
scene.overrideMaterial = silMat;
|
||||
const passes = floorMode === 'full' ? [
|
||||
[soft, 1.0, 1.0, 3.2, 4],
|
||||
[near, 0.0, 1.5, 1.2, 2],
|
||||
] : [[soft, 1.0, 1.0, 3.2, 3]];
|
||||
backU.uNear.value = floorMode === 'full' ? 0.55 : 0;
|
||||
for (const [rt, base, far, px, passes2] of passes) {
|
||||
silU.uBase.value = base;
|
||||
silU.uFar.value = far;
|
||||
renderer.setRenderTarget(rt[0]);
|
||||
renderer.clear();
|
||||
renderer.render(scene, shCam);
|
||||
blur(rt, px, passes2);
|
||||
}
|
||||
scene.overrideMaterial = prevOv;
|
||||
renderer.shadowMap.autoUpdate = prevSh;
|
||||
renderer.setRenderTarget(null);
|
||||
renderer.setClearColor(prevClear, prevA);
|
||||
backU.uVP.value.multiplyMatrices(shCam.projectionMatrix, shCam.matrixWorldInverse);
|
||||
};
|
||||
|
||||
// a dark studio for the camera lenses only: black all round with a few hard softboxes, so the glass reads deep
|
||||
// black with crisp highlights instead of mirroring the pale studio as a grey haze
|
||||
const lensEnv = (() => {
|
||||
const env = new THREE.Scene();
|
||||
env.background = new THREE.Color('#050506');
|
||||
const box = (w, h, dir, k) => {
|
||||
const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({color: new THREE.Color(1, 0.98, 0.95).multiplyScalar(k), side: THREE.DoubleSide}));
|
||||
m.position.copy(new V3(...dir).normalize().multiplyScalar(15));
|
||||
m.lookAt(0, 0, 0);
|
||||
env.add(m);
|
||||
};
|
||||
box(10, 6, [-0.2, 1, 0.2], 6); // overhead
|
||||
box(1.6, 12, [-0.85, 0.3, 0.45], 7); // a tall strip, left
|
||||
box(3.2, 2.2, [0.42, 0.62, 0.66], 9); // a small box above the camera: the hot spot on the dome
|
||||
box(1.2, 10, [0.75, 0.2, -0.6], 3); // a rim strip behind
|
||||
const pm = new THREE.PMREMGenerator(renderer);
|
||||
const tex = pm.fromScene(env, 0.01).texture;
|
||||
pm.dispose();
|
||||
return tex;
|
||||
})();
|
||||
|
||||
// ------------------------------------------------------------ the bee and the guides
|
||||
let bee = null;
|
||||
const addBee = (b) => {
|
||||
bee = b;
|
||||
scene.add(b.root);
|
||||
b.root.traverse((o) => {
|
||||
if (o.isMesh && !b.clear.includes(o)) o.layers.enable(BEE_LAYER);
|
||||
});
|
||||
skip.push(...b.clear);
|
||||
for (const m of [b.M.lens, b.M.lensGlass]) {
|
||||
if (!m) continue;
|
||||
m.envMap = lensEnv;
|
||||
m.needsUpdate = true;
|
||||
}
|
||||
};
|
||||
const guides = buildGuides();
|
||||
scene.add(guides.group);
|
||||
skip.push(guides.group);
|
||||
|
||||
const size = {w: 1920, h: 1080, pr: 1};
|
||||
const resize = (w, h, pr) => {
|
||||
Object.assign(size, {w, h, pr});
|
||||
renderer.setPixelRatio(pr);
|
||||
renderer.setSize(w, h, false);
|
||||
composer.setPixelRatio(pr);
|
||||
composer.setSize(w, h);
|
||||
camera.aspect = w / h;
|
||||
camera.updateProjectionMatrix();
|
||||
backU.uRes.value.set(Math.round(w * pr), Math.round(h * pr));
|
||||
guides.resize(Math.round(w * pr), Math.round(h * pr), pr);
|
||||
};
|
||||
// cam: target (tx, ty, tz), azimuth from +z toward +x, elevation, distance, screen shift sx/sy in CSS px
|
||||
const frame = (cam, ops = {}) => {
|
||||
const {tx, ty, tz, az, el, d} = cam;
|
||||
camera.position.set(tx + d * Math.cos(el) * Math.sin(az), ty + d * Math.sin(el), tz + d * Math.cos(el) * Math.cos(az));
|
||||
camera.lookAt(tx, ty, tz);
|
||||
camera.setViewOffset(size.w, size.h, -(cam.sx ?? 0), -(cam.sy ?? 0), size.w, size.h);
|
||||
camera.updateMatrixWorld();
|
||||
const c = bee ? bee.root.position : new V3();
|
||||
key.target.position.set(c.x + 0.1, c.y, c.z);
|
||||
key.position.copy(key.target.position).addScaledVector(KEY, 8);
|
||||
key.target.updateMatrixWorld();
|
||||
guides.update(camera, ops);
|
||||
floorShadow(c);
|
||||
composer.render();
|
||||
};
|
||||
const pv = new V3();
|
||||
/** World point to CSS px, or null behind the camera. Call after frame(). */
|
||||
const project = (p) => {
|
||||
pv.copy(p).project(camera);
|
||||
if (pv.z > 1) return null;
|
||||
return [(pv.x * 0.5 + 0.5) * size.w, (-pv.y * 0.5 + 0.5) * size.h];
|
||||
};
|
||||
const setAOSkip = (list) => {
|
||||
extra = list;
|
||||
};
|
||||
// a live page's quality knobs: MSAA samples, the AO pass, the key's shadow map
|
||||
const setQuality = ({samples, ao, shadow, floor, self, blur}) => {
|
||||
if (blur !== undefined) key.shadow.blurSamples = blur;
|
||||
if (floor !== undefined) floorMode = floor;
|
||||
if (self !== undefined) key.castShadow = self;
|
||||
if (samples !== undefined) {
|
||||
for (const t of [composer.renderTarget1, composer.renderTarget2]) {
|
||||
t.samples = samples;
|
||||
t.dispose();
|
||||
}
|
||||
}
|
||||
if (ao !== undefined) gtao.enabled = ao;
|
||||
if (shadow !== undefined && shadow !== key.shadow.mapSize.x) {
|
||||
key.shadow.mapSize.set(shadow, shadow);
|
||||
key.shadow.map?.dispose();
|
||||
key.shadow.map = null;
|
||||
}
|
||||
};
|
||||
return {renderer, scene, camera, composer, gtao, key, resize, frame, addBee, addBody: addBee, size, floorY, project, setAOSkip, setQuality};
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
// The Vesper AX-6 tour cut 1:1 on the bee's (robobee-shared/tour_v2.js, robobee-sim2/timeline.json), the way the
|
||||
// hummingbird's was (robohum-shared/tour_bee.js): the same beat times in the same order, the same push-ins and orbits,
|
||||
// the same 330° explode turntable with the fast reassembly, distances scaled to the fish. The bee's banking fly-in is
|
||||
// the fish swimming in with a bank and a roll, its tail sweeping and its jaw snapping once near the end of the 3 s; the
|
||||
// bee's fly-off is a lunge (the jaw snaps and it shoots past the camera). The five assemblies map beat for beat:
|
||||
// OPTICS = the eye (the bubble lifts, the lens rings unscrew out along the axis, the iris opens), WING = the near
|
||||
// pectoral fin (it leaves its root and turns over in the air), LEG = the lure (the stalk comes apart link by link with
|
||||
// a servo spinning in each joint, the cage blooms and the light flares), THORAX = the ribcage (the shields swing off
|
||||
// and the drive rings slide out spinning 5× faster), ABDOMEN = the jaw (it drops away, the fang rows fly out along their
|
||||
// rims and snap back).
|
||||
// The camera rules on top: frame 0 is already the front three-quarter hero view of the still (the eye side and
|
||||
// the open mouth toward the camera, the fish big and moving); every teardown is shot from that side within about ±35°
|
||||
// and pushed in on the part; sides change only in the orbits, the turntable and the exit; the camera rides smooth
|
||||
// splines and follows only the fish's path, never its sway. Labels show only while parts move.
|
||||
// Script: the entry's timeline.json, {duration, script: [{t, act}]}; act is optics, wing, leg, thorax, abdomen,
|
||||
// 'exploded', 'assemble' or 'hero' (the lunge). Everything is a pure function of film time t.
|
||||
import * as THREE from 'three';
|
||||
import {GAPE_LO} from './piranha.js';
|
||||
import {VIEWPORT} from './console.js';
|
||||
|
||||
const smoother = (x) => {
|
||||
const u = Math.min(1, Math.max(0, x));
|
||||
return u * u * u * (u * (u * 6 - 15) + 10);
|
||||
};
|
||||
const ss = (a, b, t) => smoother((t - a) / (b - a));
|
||||
const lerp = (a, b, k) => a + (b - a) * k;
|
||||
const D2R = Math.PI / 180;
|
||||
// the bee's distances scaled to the fish (tail tip to lure bulb about 5.3 units against the bee's 3)
|
||||
const S = 1.6;
|
||||
// the tail's stroke: radians per second of its sweep while swimming (about 0.5 Hz, heavy), and the cruise level
|
||||
const STROKE_W = 3.1;
|
||||
export const STROKE_HZ = STROKE_W / (2 * Math.PI);
|
||||
const CRUISE = 0.65;
|
||||
// fish units to metres for the dive panel (the fish is a 1.6 m drone)
|
||||
const M_PER = 0.3;
|
||||
const DEPTH0 = 412.6;
|
||||
|
||||
export const ASSEMBLIES = ['hero', 'optics', 'wing', 'leg', 'thorax', 'abdomen'];
|
||||
export const ASSEMBLY_LABEL = {hero: 'HERO', optics: 'OPTICS', wing: 'FIN', leg: 'TAIL', thorax: 'FLANK', abdomen: 'JAW'};
|
||||
export const DISPLAY2 = ['labels', 'exploded', 'flare', 'turntable'];
|
||||
export const DISPLAY2_LABEL = {labels: 'LABELS', exploded: 'EXPLODED', flare: 'COIL FLARE', turntable: 'TURNTABLE'};
|
||||
const BUTTON = {optics: 'optics', wing: 'wing', leg: 'leg', thorax: 'thorax', abdomen: 'abdomen', exploded: 'exploded', assemble: 'exploded', hero: 'hero'};
|
||||
|
||||
// each act's own clock, the bee's (seconds after its click): when it opens, when it closes, whether the swim eases off
|
||||
// (only the ribcage: the fish keeps its slow stroke through the others, its own motion between the beats)
|
||||
const ACT = {
|
||||
optics: {open: [0.35, 1.5], close: [2.2, 2.65], stop: false},
|
||||
wing: {open: [0.45, 1.25], close: [2.35, 2.7], stop: false},
|
||||
leg: {open: [0.35, 1.45], close: [2.15, 2.55], stop: false},
|
||||
thorax: {open: [0.3, 1.4], close: [2.1, 2.6], stop: true},
|
||||
abdomen: {open: [0.3, 1.3], close: [2.0, 2.45], stop: false},
|
||||
};
|
||||
// the fin: the bee's full turn over 0.9-2.3 s; the lure's cage blooms behind the stalk and the light flares in it
|
||||
const WING_FLIP = [0.9, 2.3];
|
||||
const CAGE = {open: [0.75, 1.6], close: [2.05, 2.5]};
|
||||
const FLARE = {open: [1.05, 1.5], close: [1.95, 2.4]};
|
||||
// the jaw's snaps: the one at the end of the swim-in and the one that starts the lunge (start of the shut, seconds)
|
||||
const SNAP_IN = 2.3;
|
||||
const DEP = 1.0;
|
||||
|
||||
// ------------------------------------------------------------ cameras: [az, el, d, tx, ty, tz, sx, sy], u = seconds on
|
||||
// az from +z (the fish's right flank, the near side) toward +x (its face): the still's hero view is az 30. The bee's
|
||||
// angles map onto the hero side: every teardown sits between az -5 and 65. A = the world points of the parts at rest.
|
||||
export function makeBeeCams(A) {
|
||||
const add = (p, d) => p.map((v, i) => v + d[i]);
|
||||
const mid = (a, b, k = 0.5) => a.map((v, i) => v + (b[i] - v) * k);
|
||||
// the fish's middle at rest (the bulb to the tail, the lure's top to the fins): every close-up aims between it and
|
||||
// its part, so the push-in lands on the part and the whole fish stays inside the viewport
|
||||
const C0 = [0.15, 0.3, 0.1];
|
||||
const lens = mid(C0, add(A.lens, A.eyeAxis.map((v) => v * 0.45)), 0.45).map((v, i) => (i === 1 ? C0[1] + 0.2 : v));
|
||||
const wing = mid(C0, add(A.finHub, [0.9, -0.35, 1.0]), 0.35).map((v, i) => (i === 1 ? 0.2 : v));
|
||||
const lure = add(mid(C0, A.lureMid, 0.3), [0.1, 0.06, 0]);
|
||||
const rib = mid(C0, A.core, 0.4).map((v, i) => (i === 1 ? C0[1] - 0.1 : i === 0 ? v + 0.25 : v));
|
||||
const jaw = mid(C0, A.jaw, 0.4).map((v, i) => (i === 1 ? -0.03 : v));
|
||||
// the piranha's close-up targets sit on the parts themselves
|
||||
const eye = mid(add(A.lens, A.eyeAxis.map((v) => v * 0.3)), C0, 0.15);
|
||||
const stalk = add(A.lureMid, [0.18, -0.05, 0.05]);
|
||||
const flank = add(A.core, [0, 0.05, 0.15]);
|
||||
const mouth = add(A.jaw, [-0.1, 0.25, 0]);
|
||||
// every close-up keeps pushing in through its whole act and keeps orbiting about 14°/s, so a hold never parks
|
||||
const push = (a, b, u) => lerp(a, b, ss(0, 2.5, u));
|
||||
// the explode: wide while it is apart, pushing in through the reassembly toward the hero distance
|
||||
const ASM = A.asm ?? 3.2;
|
||||
return {
|
||||
intro: (u) => {
|
||||
const k = ss(0, 3.0, u);
|
||||
return [lerp(2, 32, k), lerp(13, 8, k), lerp(11.2, 10.4, k), C0[0], C0[1] + 0.08, C0[2], 0, -24];
|
||||
},
|
||||
// 2026-11-06, the piranha's own cameras: the angler's ones parked the shot (az
|
||||
// 20-50, el 6-10, the same distance in every beat). Every beat now sits on its part from its own side and height
|
||||
// and pushes in while the part hangs open: the eye in macro from the face side, the tail stalk from behind, the
|
||||
// glass flank from above, the jaw from below, the explode passing low round the parts.
|
||||
optics: (u) => [72 - 8 * u, lerp(10, 18, ss(0, 2.5, u)), push(6.2, 5.0, u), ...eye, 0, -24],
|
||||
wing: (u) => [10 + 14 * u, 13, push(12.6, 11.1, u), ...wing, 0, -24],
|
||||
leg: (u) => [-42 + 9 * u, 14, push(8.0, 6.8, u), ...stalk, 0, -24],
|
||||
thorax: (u) => [4 + 8 * u, 40 - 3 * u, push(8.2, 6.9, u), ...flank, 0, -24],
|
||||
abdomen: (u) => [56 - 7 * u, -4 + 2 * u, push(8.8, 7.4, u), ...mouth, 0, -24],
|
||||
// the explode: while the parts fly the camera swings 38° toward the face and drops under them to look up, then
|
||||
// through the reassembly swings back against the turntable onto the hero side, rises and pushes in, so the whole
|
||||
// fish turns into the hero view as it snaps together
|
||||
exploded: (u) => {
|
||||
const go = ss(0.3, 2.8, u);
|
||||
const back = ss(ASM, ASM + 1.5, u);
|
||||
return [34 + 38 * go - 67 * back, lerp(16, 0, go) + 9 * back, lerp(lerp(16.8, 14.8, go), 11.0, ss(ASM + 0.1, ASM + 1.2, u)), 0.1, lerp(0.58, 0.3, ss(ASM, ASM + 1.0, u)) - 0.22 * Math.sin(Math.PI * ss(1.8, 3.0, u)), 0.0, 0, -24];
|
||||
},
|
||||
// the turntable stops at 330°, so the fish comes out of it turned -30°: the hero view after it sits 30° lower in
|
||||
// the world to land on the same side of the fish
|
||||
hero: (u) => [-2 + 12 * u, 8, 10.3, ...C0, 0, -24],
|
||||
};
|
||||
}
|
||||
|
||||
export function makeBeeTour(TL, A) {
|
||||
const CAM2 = makeBeeCams(A);
|
||||
const SCRIPT = [...TL.script].sort((a, b) => a.t - b.t);
|
||||
const DURATION = TL.duration;
|
||||
const EVENTS = SCRIPT.map((e) => e.t);
|
||||
const AT = {};
|
||||
for (const e of SCRIPT) (AT[e.act] ??= []).push(e.t);
|
||||
const at = (act) => AT[act] ?? [];
|
||||
const T_EXP = at('exploded')[0] ?? 999;
|
||||
const T_ASM = at('assemble')[0] ?? 999;
|
||||
const T_END = at('hero')[0] ?? 999;
|
||||
const T_LUNGE = T_END + DEP;
|
||||
const win = (act, W, t) => {
|
||||
let v = 0;
|
||||
for (const t0 of at(act)) v = Math.max(v, ss(t0 + W.open[0], t0 + W.open[1], t) * (1 - ss(t0 + W.close[0], t0 + W.close[1], t)));
|
||||
return v;
|
||||
};
|
||||
const openOf = (act, t) => win(act, ACT[act], t);
|
||||
// the full explode: out 0.2-1.8 s after EXPLODED, home 0-1.0 s after it goes off (fast, it snaps)
|
||||
const explodeAt = (t) => ss(T_EXP + 0.2, T_EXP + 1.8, t) * (1 - ss(T_ASM, T_ASM + 1.0, t));
|
||||
// the turntable: 330° from the explode to just after the fish is whole again, steady in the middle
|
||||
const TT = [T_EXP + 0.2, T_ASM + 1.5];
|
||||
const turnAt = (t) => {
|
||||
const [a, b] = TT;
|
||||
if (t <= a) return 0;
|
||||
const R = 0.6;
|
||||
const span = b - a;
|
||||
const v = 330 / (span - R);
|
||||
const x = Math.min(t, b) - a;
|
||||
if (x < R) return (v * x * x) / (2 * R);
|
||||
if (x < span - R) return v * (x - R / 2);
|
||||
const y = x - (span - R);
|
||||
return v * (span - 1.5 * R) + v * y - (v * y * y) / (2 * R);
|
||||
};
|
||||
const stopAt = (t) => {
|
||||
let v = 0;
|
||||
for (const act of Object.keys(ACT)) {
|
||||
if (!ACT[act].stop) continue;
|
||||
for (const t0 of at(act)) v = Math.max(v, ss(t0, t0 + 0.45, t) * (1 - ss(t0 + ACT[act].close[1], t0 + ACT[act].close[1] + 0.5, t)));
|
||||
}
|
||||
return Math.max(v, ss(T_EXP, T_EXP + 0.45, t) * (1 - ss(T_ASM + 0.9, T_ASM + 1.5, t)));
|
||||
};
|
||||
const activity = (t) => Math.max(...Object.keys(ACT).map((a) => openOf(a, t)), explodeAt(t));
|
||||
const DT = 1 / 240;
|
||||
const SPIN = [0];
|
||||
for (let i = 1; i * DT <= DURATION + 1; i++) SPIN.push(SPIN[i - 1] + (1 + 5 * activity((i - 0.5) * DT)) * DT);
|
||||
const look = (A2, t) => {
|
||||
const u = Math.max(0, Math.min(A2.length - 2, t / DT));
|
||||
const i = Math.floor(u);
|
||||
return A2[i] + (A2[i + 1] - A2[i]) * (u - i);
|
||||
};
|
||||
const spinAt = (t) => (t < 0 ? t : look(SPIN, t));
|
||||
|
||||
// the swim stroke: heavy while it swims in, a cruise between the beats, held still while a part is off, the full
|
||||
// stroke again for the wind-up and the lunge
|
||||
const swimAt = (t) => Math.max(1 - ss(2.5, 3.6, t), CRUISE * (1 - 0.6 * stopAt(t) - 0.4 * Math.min(1, explodeAt(t) * 3)), ss(T_END + 0.1, T_END + 0.8, t));
|
||||
// the jaw: its gape in degrees, with the snap at the end of the swim-in, the wide wind-up before the lunge and the
|
||||
// snap that starts it
|
||||
const snap = (t, t0) => ss(t0, t0 + 0.12, t) * (1 - ss(t0 + 0.2, t0 + 0.55, t));
|
||||
const gapeAt = (t) => GAPE_LO + 9 * ss(T_END + 0.15, T_END + 0.85, t) * (1 - ss(T_LUNGE, T_LUNGE + 0.12, t)) - 22 * snap(t, SNAP_IN) - 24 * snap(t, T_LUNGE);
|
||||
|
||||
// the swim: in from behind-left banking through a turn toward the camera, the cruise, the turntable, the wind-up and
|
||||
// the lunge past the camera. path is the smooth part the camera follows; the stroke's sway rides on top for the fish
|
||||
// alone.
|
||||
const flightAt = (t) => {
|
||||
const kIn = ss(-0.3, 2.6, t);
|
||||
const ex = explodeAt(t);
|
||||
const calm = 1 - Math.min(1, ex * 2.5);
|
||||
const sw = swimAt(t);
|
||||
const path = new THREE.Vector3(lerp(-1.3 * S, 0, kIn), lerp(0.4 * S, 0, kIn), lerp(-1.7 * S, 0, kIn));
|
||||
let yaw = lerp(-48, 0, kIn) + 12 * Math.sin(Math.PI * kIn);
|
||||
let roll = -22 * Math.sin(Math.PI * Math.min(1, kIn * 1.05)) + (2.2 * Math.sin(t * 1.3 + 1.1) + 3.2 * Math.sin(t * 0.85 + 0.4)) * calm;
|
||||
let pitch = 5 * Math.sin(Math.PI * kIn) + (1.6 * Math.sin(t * 1.9 + 0.6) + 2.4 * Math.sin(t * 1.2 + 2.0)) * calm;
|
||||
yaw += turnAt(t);
|
||||
// the wind-up: it draws back along its heading and turns its head a little toward the camera; the lunge turns it
|
||||
// back onto the hero line, so it shoots forward and toward the lens and passes the camera on the right
|
||||
const wind = ss(T_END + 0.1, T_END + 0.9, t);
|
||||
yaw -= 9 * wind;
|
||||
pitch += 4 * wind;
|
||||
{
|
||||
const h0 = new THREE.Vector3(Math.cos(yaw * D2R), 0, -Math.sin(yaw * D2R));
|
||||
path.addScaledVector(h0, -0.4 * wind * (1 - ss(T_LUNGE, T_LUNGE + 0.3, t)));
|
||||
}
|
||||
if (t > T_LUNGE) {
|
||||
const u = t - T_LUNGE;
|
||||
const k = ss(0, 0.8, u);
|
||||
yaw += 6 * k;
|
||||
roll += 16 * k;
|
||||
pitch -= 5 * k;
|
||||
const h = new THREE.Vector3(Math.cos(yaw * D2R), 0, -Math.sin(yaw * D2R));
|
||||
path.addScaledVector(h, 1.15 * S * u * u + 0.4 * S * u).add(new THREE.Vector3(0, 0.05 * S * u * u, 0));
|
||||
}
|
||||
// the stroke sways the head against the tail; the camera never sees it
|
||||
const sway = 3.4 * sw * Math.sin(t * STROKE_W + Math.PI) * calm;
|
||||
const pos = path.clone().add(new THREE.Vector3(0, 0.07 * S * Math.sin(t * 1.1) * calm, 0));
|
||||
return {pos, path, yaw: yaw + sway, roll, pitch, calm, swim: sw, heading: yaw};
|
||||
};
|
||||
// the lure lags the turns: each joint takes the turn the fish made a moment earlier
|
||||
const LAG = 0.085;
|
||||
const bendAt = (t) => {
|
||||
const out = [];
|
||||
let a = flightAt(t);
|
||||
for (let k = 0; k < 7; k++) {
|
||||
const b = flightAt(t - LAG * (k + 1));
|
||||
out.push([0.55 * D2R * (b.pitch - a.pitch), 0.55 * D2R * (b.yaw - a.yaw) + 0.25 * D2R * (b.roll - a.roll)]);
|
||||
a = b;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// the camera: each act's view, blended over 0.85 s with a short dolly out, tracking the fish's path
|
||||
const VIEWS = [{t: -1, key: 'intro'}, ...SCRIPT.map((e) => ({t: e.t, key: e.act === 'assemble' ? 'exploded' : e.act}))];
|
||||
const viewIdx = (t) => {
|
||||
let i = 0;
|
||||
while (i < VIEWS.length - 1 && VIEWS[i + 1].t <= t) i++;
|
||||
return i;
|
||||
};
|
||||
const camFn = (V, t) => CAM2[V.key](t - (V.key === 'intro' ? 0 : V.t));
|
||||
// the reassembly keeps the explode's camera running on the explode's clock, also while the next view blends in
|
||||
const runOf = (j) => {
|
||||
while (j > 0 && VIEWS[j].key === 'exploded' && VIEWS[j - 1].key === 'exploded') j--;
|
||||
return VIEWS[j];
|
||||
};
|
||||
const camAt = (t) => {
|
||||
const i = viewIdx(t);
|
||||
let o = camFn(runOf(i), t);
|
||||
if (i > 0 && runOf(i) === VIEWS[i]) {
|
||||
const k = ss(VIEWS[i].t, VIEWS[i].t + 0.85, t);
|
||||
if (k < 1) {
|
||||
const a = camFn(runOf(i - 1), t);
|
||||
const dAz = ((o[0] - a[0] + 540) % 360) - 180;
|
||||
const b = o.map((v, j) => lerp(a[j], v, k));
|
||||
b[0] = a[0] + dAz * k;
|
||||
b[2] += 0.9 * Math.sin(Math.PI * k);
|
||||
o = b;
|
||||
}
|
||||
}
|
||||
const f = flightAt(t);
|
||||
const track = 0.85 - 0.5 * ss(T_LUNGE, T_LUNGE + 1.0, t);
|
||||
return {az: o[0], el: o[1], d: o[2], tx: o[3] + f.path.x * track, ty: o[4] + f.path.y * track, tz: o[5] + f.path.z * track, sx: o[6], sy: o[7]};
|
||||
};
|
||||
const actAt = (t) => VIEWS[viewIdx(t)].key;
|
||||
|
||||
const stateAt = (t) => {
|
||||
const ex = explodeAt(t);
|
||||
const f = flightAt(t);
|
||||
const open = Object.fromEntries(Object.keys(ACT).map((a) => [a, openOf(a, t)]));
|
||||
let finFlip = 0;
|
||||
for (const t0 of at('wing')) finFlip = Math.max(finFlip, ss(t0 + WING_FLIP[0], t0 + WING_FLIP[1], t));
|
||||
if (finFlip >= 1) finFlip = 0;
|
||||
const cage = win('leg', CAGE, t);
|
||||
// the light flares in the lure act, glows up through the explode and flashes on the wind-up
|
||||
const flare = Math.max(win('leg', FLARE, t), 0.55 * ss(T_END + 0.2, T_END + 0.8, t) * (1 - ss(T_LUNGE + 0.6, T_LUNGE + 1.4, t)));
|
||||
const view = actAt(t);
|
||||
return {
|
||||
t,
|
||||
spinT: spinAt(t),
|
||||
explode: ex,
|
||||
swim: f.swim,
|
||||
gape: gapeAt(t),
|
||||
eye: open.optics,
|
||||
fin: open.wing,
|
||||
finFlip,
|
||||
lure: open.leg,
|
||||
cage,
|
||||
flare,
|
||||
rib: open.thorax,
|
||||
drop: open.abdomen,
|
||||
open,
|
||||
flight: f,
|
||||
bend: bendAt(t),
|
||||
cam: camAt(t),
|
||||
view,
|
||||
guides: 0.45 + 0.55 * Math.min(1, ex * 2.5 + activity(t)),
|
||||
turn: turnAt(t),
|
||||
};
|
||||
};
|
||||
|
||||
const LABELS = {
|
||||
optics: [['eyeGlass', 'EYE RING', 'LIT · UNDER THE BROW'], ['lensRing', 'LENS RINGS', '3 × THREADED'], ['iris', 'IRIS', '10 BLADES · OPENS 4×'], ['barrel', 'LENS BARREL', 'SLIDES OUT']],
|
||||
wing: [['fin', 'PECTORAL FIN', 'FROSTED FILM'], ['finHub', 'FIN ROOT', 'PIVOT DRUM']],
|
||||
leg: [['stalk', 'TAIL STALK', '4 SEGMENTS · TELESCOPING'], ['joint', 'SEGMENT SERVO', 'SPINNING FREE'], ['tailHub', 'TAIL HUB', 'BRACKET · 2 LOBES'], ['tail', 'TAIL FIN', '11 RAYS · FROSTED FILM']],
|
||||
thorax: [['flank', 'GLASS BARREL', 'CLEAR · LIFTS OFF'], ['rib', 'RIB BANDS', 'HINGED · SWING UP'], ['gear', 'DRIVE GEARS', '2 BIG · 5× SPEED'], ['coil', 'LIT COILS', '2 · GREEN']],
|
||||
abdomen: [['jaw', 'LOWER JAW', 'DROPS · UNDERBITE'], ['fang', 'LOWER FANGS', 'GLASS · 2 ROWS'], ['upfang', 'UPPER FANGS', 'GLASS · 2 ROWS']],
|
||||
exploded: [['lens', 'OPTIC HEAD', '2 × LENS'], ['tailHub', 'TAIL', '4 SEGMENTS'], ['gear', 'DRIVE GEARS', 'SPINNING FREE'], ['fin', 'PECTORAL FIN', 'FROSTED FILM'], ['jaw', 'LOWER JAW', 'GLASS FANGS']],
|
||||
};
|
||||
const labelAt = (t, s) => {
|
||||
const v = s.view;
|
||||
if (ACT[v]) {
|
||||
const t0 = at(v).filter((x) => x <= t).pop();
|
||||
const A2 = ACT[v];
|
||||
return {set: LABELS[v], o: ss(t0 + A2.open[0] + 0.1, t0 + A2.open[0] + 0.45, t) * (1 - ss(t0 + A2.close[0] - 0.25, t0 + A2.close[0], t))};
|
||||
}
|
||||
if (v === 'exploded') return {set: LABELS.exploded, o: ss(T_EXP + 0.4, T_EXP + 0.8, t) * (1 - ss(T_EXP + 2.3, T_EXP + 2.6, t))};
|
||||
return {set: [], o: 0};
|
||||
};
|
||||
|
||||
// the tail's and the near pectoral's angles in degrees, as pose() draws them
|
||||
const tailDeg = (tt) => (0.14 * Math.sin(tt * 1.6) + 0.4 * swimAt(tt) * Math.sin(tt * STROKE_W)) / D2R;
|
||||
const finDeg = (tt) => ((0.12 + 0.2 * swimAt(tt)) * Math.sin(tt * 2.2)) / D2R;
|
||||
const telemetry = (t, s) => {
|
||||
const f = s.flight;
|
||||
const stroke = [];
|
||||
for (let i = 0; i <= 90; i++) {
|
||||
const tt = t - 4 + (i / 90) * 4;
|
||||
stroke.push([tailDeg(tt), finDeg(tt)]);
|
||||
}
|
||||
const ex = s.explode > 0.04;
|
||||
const sw = s.swim;
|
||||
// the servos: FIN R, FIN L, TAIL, JAW, TAIL STALK, DORSAL; a part that is off its mount reads DETACHED
|
||||
const free = [ex || s.fin > 0.08, ex, ex, ex || s.drop > 0.08, ex || s.lure > 0.08, ex];
|
||||
const gapeLoad = Math.abs(s.gape - GAPE_LO) / 24;
|
||||
const base = [0.3 + 0.4 * sw, 0.28 + 0.4 * sw, 0.22 + 0.62 * sw, 0.24 + 0.6 * gapeLoad, 0.3 + 0.08 * Math.abs(s.bend[3][1]) * 40, 0.2 + 0.2 * sw];
|
||||
const servos = base.map((b, i) => (free[i] ? 0 : Math.max(0, Math.min(1, b + 0.04 * Math.sin(t * 7 + i) + 0.1 * Math.abs(f.roll) / 30))));
|
||||
const v = s.view;
|
||||
const opening = ACT[v] ? s.open[v] : 0;
|
||||
const NAME = {optics: 'OPTICS OPEN', wing: 'FIN OFF', leg: 'TAIL OUT', thorax: 'FLANK OPEN', abdomen: 'JAW DROPPED'};
|
||||
let status = 'CRUISE';
|
||||
let kind = 'ok';
|
||||
if (t < 2.6) status = 'BANKING';
|
||||
if (ACT[v] && opening > 0.05) [status, kind] = [NAME[v], 'warn'];
|
||||
if (v === 'exploded') [status, kind] = t < T_ASM ? ['TEARDOWN', 'warn'] : s.explode > 0.04 ? ['REASSEMBLY', 'warn'] : ['CRUISE', 'ok'];
|
||||
if (t > T_END + 0.1 && t <= T_LUNGE) status = 'WIND-UP';
|
||||
if (t > T_LUNGE) [status, kind] = ['LUNGE', 'warn'];
|
||||
const ROW = {optics: 0, leg: 1, thorax: 2, wing: 3, abdomen: 4};
|
||||
const sub = (i) => {
|
||||
if (ex) return ['warn', 'DETACHED'];
|
||||
if (ROW[v] === i && opening > 0.05) return ['warn', i === 3 || i === 4 ? 'DETACHED' : 'OPEN'];
|
||||
if (i === 3) return sw > 0.05 ? ['ok', `${(STROKE_HZ * 60).toFixed(0)} SPM`] : ['idle', 'FEATHERED'];
|
||||
if (i === 2) return sw > 0.05 ? ['ok', 'RUNNING'] : ['idle', 'IDLE'];
|
||||
if (i === 1) return s.flare > 0.1 ? ['warn', 'FLARE'] : ['ok', 'LIT 18%'];
|
||||
return ['ok', ['TRACKING', '', '', '', 'ARMED', 'SEALED'][i]];
|
||||
};
|
||||
const last = SCRIPT.filter((e) => e.t <= t).pop();
|
||||
const say = (e) => (e.act === 'exploded' ? 'EXPLODED ON' : e.act === 'assemble' ? 'EXPLODED OFF · REASSEMBLE' : e.act === 'hero' ? 'HERO · RELEASE' : `ISOLATE ${ASSEMBLY_LABEL[e.act]}`);
|
||||
const lungeV = t > T_LUNGE ? (2.3 * S * (t - T_LUNGE) + 0.4 * S) * M_PER : 0;
|
||||
const speed = lungeV + M_PER * (0.9 * (1 - ss(1.5, 3.0, t)) + 0.35 * sw);
|
||||
const labels = labelAt(t, s);
|
||||
const amp = (0.14 + 0.4 * sw) / D2R;
|
||||
return {
|
||||
time: t,
|
||||
dur: DURATION,
|
||||
lift: Math.max(0, Math.min(1, 0.18 + 0.55 * sw + 0.25 * ss(T_LUNGE, T_LUNGE + 0.4, t) + 0.05 * Math.sin(t * STROKE_W))),
|
||||
status,
|
||||
statusKind: kind,
|
||||
freq: STROKE_HZ * Math.min(1, 0.4 + sw),
|
||||
amp,
|
||||
stroke,
|
||||
chartMax: 40,
|
||||
chartTicks: [-30, 30],
|
||||
chartSpan: '−4 S',
|
||||
playback: 1,
|
||||
blur: 1,
|
||||
shutter: 'TAIL · R PECTORAL',
|
||||
battery: 0.912 - 0.0021 * t,
|
||||
power: 41 + 120 * Math.pow(sw, 1.4) + 60 * activity(t) + 8 * Math.sin(t * STROKE_W),
|
||||
volt: 48.2,
|
||||
motorT: 22 + 0.35 * t,
|
||||
servos,
|
||||
legsFree: free.some((x) => x),
|
||||
legFreeEach: free,
|
||||
depth: DEPTH0 - M_PER * f.pos.y * 4,
|
||||
vs: -M_PER * 0.07 * S * 1.1 * Math.cos(t * 1.1) * f.calm,
|
||||
pitch: f.pitch,
|
||||
roll: f.roll,
|
||||
airspeed: speed,
|
||||
trim: s.explode > 0.04 ? 'FREE' : t > T_LUNGE ? 'STRIKE' : 'NEUTRAL',
|
||||
view: v === 'intro' ? 'hero' : v === 'exploded' ? null : v,
|
||||
display: {labels: labels.o > 0.5, exploded: t >= T_EXP && t < T_ASM, flare: s.flare > 0.2, turntable: s.turn > 0 && t < TT[1]},
|
||||
subs: [0, 1, 2, 3, 4, 5].map(sub),
|
||||
focus: ROW[v] ?? (v === 'exploded' ? 5 : -1),
|
||||
events: EVENTS,
|
||||
next: `${EVENTS.length} OPERATOR ACTIONS`,
|
||||
log: last ? `OPERATOR · ${say(last)}` : 'INBOUND · BANKING IN',
|
||||
mode: status,
|
||||
modeSub:
|
||||
status === 'BANKING'
|
||||
? `BANK ${f.roll.toFixed(0)}° · INBOUND`
|
||||
: status === 'TEARDOWN' || status === 'REASSEMBLY'
|
||||
? `TURNTABLE ${Math.round(s.turn)}° · ${Math.round(s.explode * 100)}% APART`
|
||||
: status === 'LUNGE'
|
||||
? `STRIKE · ${speed.toFixed(1)} M/S`
|
||||
: status === 'WIND-UP'
|
||||
? `JAW ${s.gape.toFixed(0)}° · MOUTH OPEN`
|
||||
: ACT[v] && opening > 0.05
|
||||
? `${ASSEMBLY_LABEL[v]} · ${Math.round(opening * 100)}% APART`
|
||||
: `DEPTH ${(DEPTH0 - M_PER * f.pos.y * 4).toFixed(1)} M · STATION`,
|
||||
viewNote: `ISOLATE · ${v === 'intro' || v === 'hero' ? 'HERO' : v === 'exploded' ? 'ALL' : ASSEMBLY_LABEL[v]}`,
|
||||
labelSet: labels,
|
||||
};
|
||||
};
|
||||
|
||||
return {SCRIPT, DURATION, stateAt, telemetry, camAt, flightAt};
|
||||
}
|
||||
|
||||
/** Labels in two columns at the viewport's edges, from a set of anchors. */
|
||||
export function makeLabels(st, fish) {
|
||||
const p = new THREE.Vector3();
|
||||
return ({set, o}) => {
|
||||
if (o < 0.02) return [];
|
||||
const pts = [];
|
||||
for (const [key, name, sub] of set) {
|
||||
const A = fish.anchors[key];
|
||||
if (!A) continue;
|
||||
A.obj.updateWorldMatrix(true, false);
|
||||
const at = st.project(A.obj.localToWorld(p.copy(A.at)));
|
||||
if (at && at[0] > VIEWPORT.x0 + 30 && at[0] < VIEWPORT.x1 - 30 && at[1] > VIEWPORT.y0 + 40 && at[1] < VIEWPORT.y1 - 70) pts.push({name, sub, at});
|
||||
}
|
||||
const mid = (VIEWPORT.x0 + VIEWPORT.x1) / 2;
|
||||
const out = [];
|
||||
const stack = (col, x, w) => {
|
||||
let y = Math.max(VIEWPORT.y0 + 48, Math.min(col.length ? col[0].at[1] - 10 : 0, VIEWPORT.y1 - 110 - 34 * col.length));
|
||||
for (const c of col) {
|
||||
y = Math.max(y, Math.min(VIEWPORT.y1 - 110, c.at[1] - 10));
|
||||
out.push({name: c.name, sub: c.sub, at: c.at, label: [x, y], w, o});
|
||||
y += 34;
|
||||
}
|
||||
};
|
||||
stack(pts.filter((x) => x.at[0] < mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x0 + 16, 168);
|
||||
stack(pts.filter((x) => x.at[0] >= mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x1 - 160, 150);
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ the operator's pointer, on the act buttons
|
||||
const GUTTER_X = 1262;
|
||||
export function makeCursor(ui, SCRIPT) {
|
||||
const EV = SCRIPT.filter((e) => e.t > 0).map((e) => ({t: e.t, spot: ui.spots[BUTTON[e.act]]}));
|
||||
const WP = [[0, GUTTER_X, EV[0].spot[1] + 60]];
|
||||
let [px, py, pt] = [GUTTER_X, EV[0].spot[1] + 60, 0];
|
||||
EV.forEach((e, n) => {
|
||||
const [x, y] = e.spot;
|
||||
const travel = Math.min(0.7, 0.3 + Math.hypot(x - px, y - py) / 900);
|
||||
const arrive = e.t - 0.1;
|
||||
if (arrive - travel - pt > 1.4) {
|
||||
const rest = [GUTTER_X, Math.max(170, Math.min(720, y + 40))];
|
||||
WP.push([pt + 0.7, ...rest]);
|
||||
WP.push([arrive - travel, ...rest]);
|
||||
} else WP.push([Math.max(pt + 0.01, arrive - travel), px, py]);
|
||||
WP.push([arrive, x, y], [e.t + 0.18, x, y]);
|
||||
[px, py, pt] = [x, y, e.t + 0.18];
|
||||
const next = EV[n + 1];
|
||||
if (!next || next.t - 0.1 - 0.7 - pt > 0.8) {
|
||||
[px, py, pt] = [GUTTER_X, y + 12, pt + 0.55];
|
||||
WP.push([pt, px, py]);
|
||||
}
|
||||
});
|
||||
WP.push([pt + 0.9, GUTTER_X, Math.min(720, py + 50)]);
|
||||
return (t) => {
|
||||
let i = 0;
|
||||
while (i < WP.length - 2 && t > WP[i + 1][0]) i++;
|
||||
const [t0, x0, y0] = WP[i];
|
||||
const [t1, x1, y1] = WP[i + 1];
|
||||
const k = ss(t0, t1, t);
|
||||
const len = Math.hypot(x1 - x0, y1 - y0);
|
||||
const bow = Math.sin(Math.PI * k) * Math.min(22, len * 0.07);
|
||||
let press = false;
|
||||
let ring = 0;
|
||||
let rx = 0;
|
||||
let ry = 0;
|
||||
for (const e of EV) {
|
||||
if (t >= e.t - 0.07 && t < e.t + 0.09) press = true;
|
||||
if (t >= e.t && t < e.t + 0.55) {
|
||||
ring = 1 - (t - e.t) / 0.55;
|
||||
[rx, ry] = e.spot;
|
||||
}
|
||||
}
|
||||
return {x: x0 + (x1 - x0) * k + (len ? (-(y1 - y0) / len) * bow : 0), y: y0 + (y1 - y0) * k + (len ? ((x1 - x0) / len) * bow : 0), press, ring, ringX: rx, ringY: ry};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// THERAPHOS TH-8, the 10-second demo for the article (2026-11-06), green: the approved film's run-in and landing jump,
|
||||
// the glass abdomen opening on its coils, the explode, a few steps and the jump at the camera. 11.3 s of the tour
|
||||
// played at 1.13x (timeline.json: duration = scene seconds, film = film seconds).
|
||||
import {runTarantulaGreen} from '../tarantula-shared/sim_green.js';
|
||||
import TL from './timeline.json';
|
||||
|
||||
runTarantulaGreen(TL, 'tarantula-demo');
|
||||
@@ -0,0 +1 @@
|
||||
{"duration": 11.3, "film": 10.0, "script": [{"t": 2.7, "act": "abdomen"}, {"t": 5.2, "act": "exploded"}, {"t": 7.0, "act": "assemble"}, {"t": 7.8, "act": "hero"}, {"t": 9.6, "act": "jump"}]}
|
||||
@@ -0,0 +1,6 @@
|
||||
// THERAPHOS TH-8 on the green page, made 2026-11-06: the approved tarantula film (tarantula-film) with its movement,
|
||||
// cameras, timing and sound untouched, re-shot in green. Code: ../tarantula-shared/sim_green.js and ../green.
|
||||
import {runTarantulaGreen} from '../tarantula-shared/sim_green.js';
|
||||
import TL from './timeline.json';
|
||||
|
||||
runTarantulaGreen(TL);
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"duration": 24.8,
|
||||
"script": [
|
||||
{"t": 3.2, "act": "eyes"},
|
||||
{"t": 5.8, "act": "leg"},
|
||||
{"t": 8.4, "act": "abdomen"},
|
||||
{"t": 11.0, "act": "head"},
|
||||
{"t": 13.6, "act": "exploded"},
|
||||
{"t": 16.9, "act": "assemble"},
|
||||
{"t": 18.4, "act": "hero"},
|
||||
{"t": 21.4, "act": "jump"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
// The Theraphos TH-8 console (the Salticus JS-8's, renamed), copied from the scorpion's (roboscorp-shared/console.js, itself after the bee's): the
|
||||
// orange JS-8 badge and title with the drive load and the sim status cells; the gait with a live step diagram of the
|
||||
// eight legs; the jump with its arc gauge, airtime, launch and tuck; the eight leg servos; the optics with the iris,
|
||||
// its trace and both main lenses' apertures; the
|
||||
// assemblies the operator isolates, the display toggles, the subsystem registry; the operation log with the
|
||||
// operator's actions on its timeline; the mode word in the viewport; labels with leaders into the spider and the
|
||||
// operator's pointer. update(s) redraws every live part from the frame's state.
|
||||
export const C = {ink: '#24211d', mute: '#9a8f82', faint: '#e0d7ca', line: '#ece5da', panel: 'rgba(253,251,247,.95)', or: '#ff5a1f', green: '#2fa36b', track: '#efe8de'};
|
||||
export const VIEWS = ['hero', 'eyes', 'leg', 'abdomen', 'head', 'jump'];
|
||||
export const VIEW_LABEL = {hero: 'HERO', eyes: 'OPTICS', leg: 'LEG R1', abdomen: 'ABDOMEN', head: 'HEAD', jump: 'JUMP'};
|
||||
export const DISPLAY = ['labels', 'exploded', 'turntable', 'trace'];
|
||||
export const DISPLAY_LABEL = {labels: 'LABELS', exploded: 'EXPLODED', turntable: 'TURNTABLE', trace: 'GAIT TRACE'};
|
||||
// the viewport: the 3D shows between the side columns, above the flight log
|
||||
export const VIEWPORT = {x0: 330, x1: 1270, y0: 108, y1: 744};
|
||||
const CSS = `
|
||||
#app{font-family:Inter,system-ui,sans-serif;color:${C.ink};-webkit-font-smoothing:antialiased;font-variant-numeric:tabular-nums}
|
||||
.ui{position:absolute;inset:0;pointer-events:none}
|
||||
.mo{font-family:'JetBrains Mono',ui-monospace,monospace}
|
||||
.cp{position:absolute;background:${C.panel};border:1px solid ${C.line};border-radius:6px;box-shadow:0 2px 10px rgba(120,90,50,.07)}
|
||||
.ph{position:absolute;display:flex;align-items:center;gap:9px;font:700 10.5px 'JetBrains Mono',monospace;letter-spacing:1.8px}
|
||||
.ph i{display:block;width:3px;height:13px;background:${C.or}}
|
||||
.pn{position:absolute;font:500 9.5px 'JetBrains Mono',monospace;color:${C.mute};letter-spacing:1px}
|
||||
.sm{font:500 9px 'JetBrains Mono',monospace;letter-spacing:1.6px;color:${C.mute};text-transform:uppercase;white-space:nowrap}
|
||||
.v{font:600 11px 'JetBrains Mono',monospace;color:${C.ink};white-space:nowrap}
|
||||
.bt{position:absolute;height:23px;padding:0 10px;display:flex;align-items:center;justify-content:center;border:1px solid ${C.faint};border-radius:4px;background:#fffdf9;font:700 9.4px 'JetBrains Mono',monospace;letter-spacing:1.3px;color:${C.ink};white-space:nowrap;box-sizing:border-box}
|
||||
.call{position:absolute;white-space:nowrap;padding:3px 6px 3px 5px;margin:-3px 0 0 -5px;background:rgba(253,251,247,.86);border-radius:3px}
|
||||
.call b{display:flex;align-items:center;gap:6px;font:700 9.4px 'JetBrains Mono',monospace;letter-spacing:1.3px;color:${C.ink}}
|
||||
.call b i{display:block;width:6px;height:6px;background:${C.or}}
|
||||
.call span{display:block;font:500 7.8px 'JetBrains Mono',monospace;letter-spacing:1.2px;color:${C.mute};margin-top:2px}
|
||||
.chip{position:absolute;height:15px;padding:0 6px;border-radius:3px;font:700 7.6px 'JetBrains Mono',monospace;letter-spacing:1.1px;display:flex;align-items:center;white-space:nowrap}
|
||||
.cur{position:absolute;left:0;top:0;z-index:50;filter:drop-shadow(0 1px 2px rgba(0,0,0,.3))}
|
||||
.ring{position:absolute;width:34px;height:34px;margin:-17px 0 0 -17px;border-radius:50%;border:1.5px solid ${C.or};opacity:0;z-index:49}
|
||||
`;
|
||||
const el = (h) => {
|
||||
const d = document.createElement('div');
|
||||
d.innerHTML = h.trim();
|
||||
return d.firstElementChild;
|
||||
};
|
||||
const SUBS = [
|
||||
['OPTICS ARRAY', '2 MAIN + 6 SECONDARY LENSES'],
|
||||
['HEAD SHELL', 'CARAPACE · EYE PLATE · FANGS'],
|
||||
['ABDOMEN CORE', 'GLASS CAGE · GLOW COILS'],
|
||||
['JUMP DRIVE', 'CROUCH · LAUNCH · TUCK'],
|
||||
['LEG SERVOS', '8 LEGS × 4 JOINTS'],
|
||||
['FANGS & PALPS', '2 GLOWING FANGS · 2 PEDIPALPS'],
|
||||
];
|
||||
const LEGS = ['L1', 'L2', 'L3', 'L4', 'R1', 'R2', 'R3', 'R4'];
|
||||
|
||||
// opts (all optional, the first film's console when absent): views / viewLabel / viewsTitle / viewRows for the view
|
||||
// panel (the second film puts its assemblies there, in two rows), display / displayLabel for the toggles; the panels
|
||||
// below move down to make room and the subsystem rows close up.
|
||||
export function createConsole(app, opts = {}) {
|
||||
const views = opts.views ?? VIEWS;
|
||||
const viewLabel = opts.viewLabel ?? VIEW_LABEL;
|
||||
const display = opts.display ?? DISPLAY;
|
||||
const displayLabel = opts.displayLabel ?? DISPLAY_LABEL;
|
||||
const viewRows = opts.viewRows ?? 1;
|
||||
const style = document.createElement('style');
|
||||
style.textContent = CSS;
|
||||
document.head.appendChild(style);
|
||||
const ui = el(`<div class="ui"></div>`);
|
||||
app.appendChild(ui);
|
||||
const add = (h) => {
|
||||
const n = el(h);
|
||||
ui.appendChild(n);
|
||||
return n;
|
||||
};
|
||||
const panel = (x, y, w, h, title, n) => {
|
||||
add(`<div class="cp" style="left:${x}px;top:${y}px;width:${w}px;height:${h}px"></div>`);
|
||||
add(`<div class="ph" style="left:${x + 14}px;top:${y + 13}px"><i></i>${title}</div>`);
|
||||
add(`<div class="pn" style="right:${1600 - x - w + 14}px;top:${y + 15}px">${n}</div>`);
|
||||
};
|
||||
const hr = (x, y, w) => add(`<div style="position:absolute;left:${x}px;top:${y}px;width:${w}px;height:1px;background:${C.line}"></div>`);
|
||||
const L = {x: 24, w: 290};
|
||||
const R = {x: 1286, w: 290};
|
||||
|
||||
// ------------------------------------------------------------ header: badge, title, the drive load, the status cells
|
||||
add(`<div style="position:absolute;left:0;top:0;width:160px;height:88px;background:${C.or}"></div>`);
|
||||
add(`<svg style="position:absolute;left:22px;top:22px" width="48" height="44" viewBox="0 0 48 44"><g fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="24" cy="12" rx="8" ry="6"/><ellipse cx="24" cy="27" rx="10" ry="9"/><circle cx="21" cy="7" r="1.4"/><circle cx="27" cy="7" r="1.4"/><path d="M16 12l-8-5-5 9M32 12l8-5 5 9M15 15l-9 1-4 10M33 15l9 1 4 10M15 22l-8 6-2 10M33 22l8 6 2 10M17 31l-6 8M31 31l6 8"/></g></svg>`);
|
||||
add(`<div class="mo" style="position:absolute;left:80px;top:34px;color:#fff;font-size:16px;font-weight:600;letter-spacing:3px">TH-8</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:182px;top:20px;letter-spacing:2.4px">ROBOTIC TARANTULA · HEAVY HUNTER UNIT</div>`);
|
||||
add(`<div style="position:absolute;left:181px;top:35px;font-size:33px;font-weight:700;letter-spacing:-.6px;line-height:1">Theraphos TH-8 <span style="color:${C.or};font-weight:400">/</span></div>`);
|
||||
add(`<div class="mo" style="position:absolute;left:182px;top:74px;font-size:11.2px;letter-spacing:2.2px;color:#6d6357">OCTOPOD HUNTER / FIELD SIMULATOR</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:700px;top:22px">DRIVE LOAD</div>`);
|
||||
const liftPct = add(`<div class="mo" style="position:absolute;right:${1600 - 1040}px;top:21px;font-size:10px;font-weight:700"></div>`);
|
||||
const liftCells = [];
|
||||
for (let i = 0; i < 40; i++) liftCells.push(add(`<div style="position:absolute;left:${700 + i * 8.5}px;top:38px;width:6px;height:13px;border-radius:1px;background:${C.track}"></div>`));
|
||||
add(`<div class="sm" style="position:absolute;left:700px;top:57px;font-size:7.6px">IDLE</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:846px;top:57px;font-size:7.6px">CRUISE</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:1010px;top:57px;font-size:7.6px">MAX</div>`);
|
||||
const cells = [
|
||||
['SIM ID', 'TH8-1104'],
|
||||
['RUNTIME', ''],
|
||||
['STATUS', ''],
|
||||
['OPERATOR', 'BAY 2 · M.V.'],
|
||||
];
|
||||
const cellV = cells.map(([k, v], i) => {
|
||||
const x = 1086 + i * 118;
|
||||
if (i) add(`<div style="position:absolute;left:${x - 12}px;top:20px;width:1px;height:44px;background:${C.faint}"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:${x}px;top:22px">${k}</div>`);
|
||||
return add(`<div class="mo" style="position:absolute;left:${x}px;top:40px;font-size:12px;font-weight:600;letter-spacing:.4px">${v}</div>`);
|
||||
});
|
||||
{
|
||||
let h = '';
|
||||
for (let r = 0; r < 2; r++) for (let c = 0; c < 14; c++) h += `<path d="M${c * 25 + 4} ${r * 22}v8M${c * 25} ${r * 22 + 4}h8" stroke="${C.or}" stroke-width="1.1" opacity=".55"/>`;
|
||||
add(`<svg style="position:absolute;left:640px;top:84px" width="352" height="34">${h}</svg>`);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 01 gait: the stride rate, the speed, the step diagram
|
||||
panel(L.x, 108, L.w, 226, 'GAIT', '01');
|
||||
const fq = add(`<div style="position:absolute;left:38px;top:140px;font-size:34px;font-weight:700;letter-spacing:-1px;line-height:1"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:39px;top:178px">STRIDE RATE</div>`);
|
||||
const amp = add(`<div style="position:absolute;right:${1600 - 300}px;top:146px;font-size:22px;font-weight:700;line-height:1"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;right:${1600 - 300}px;top:178px">MM/S</div>`);
|
||||
const chart = add(`<svg style="position:absolute;left:38px;top:196px" width="262" height="100"></svg>`);
|
||||
hr(38, 302, 262);
|
||||
add(`<div class="sm" style="position:absolute;left:38px;top:312px">PATTERN</div>`);
|
||||
const pb = add(`<div class="v" style="position:absolute;left:100px;top:310px"></div>`);
|
||||
const shutter = add(`<div class="sm" style="position:absolute;right:${1600 - 300}px;top:312px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ 02 jump: the height, the arc gauge, the cells
|
||||
panel(L.x, 346, L.w, 148, 'JUMP', '02');
|
||||
const batt = add(`<div style="position:absolute;left:38px;top:378px;font-size:28px;font-weight:700;letter-spacing:-.8px;line-height:1"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:39px;top:410px">HEIGHT OVER STANCE</div>`);
|
||||
const gauge = add(`<svg style="position:absolute;left:176px;top:366px" width="124" height="58"></svg>`);
|
||||
hr(38, 428, 262);
|
||||
const pw = ['AIRTIME', 'LAUNCH', 'TUCK'].map((k, i) => {
|
||||
const x = 38 + i * 90;
|
||||
add(`<div class="sm" style="position:absolute;left:${x}px;top:440px">${k}</div>`);
|
||||
return add(`<div class="v" style="position:absolute;left:${x}px;top:458px;font-size:13px"></div>`);
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 03 leg servos, eight rows
|
||||
panel(L.x, 506, L.w, 238, 'LEG SERVOS', '03');
|
||||
const legState = add(`<div class="chip" style="right:${1600 - 300}px;top:536px"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:38px;top:540px">LOAD PER LEG · KNEE TORQUE</div>`);
|
||||
const servo = LEGS.map((n, i) => {
|
||||
const y = 562 + i * 21.5;
|
||||
add(`<div class="mo" style="position:absolute;left:38px;top:${y}px;font-size:10px;font-weight:700">${n}</div>`);
|
||||
add(`<div style="position:absolute;left:66px;top:${y + 4}px;width:170px;height:6px;background:${C.track};border-radius:3px"></div>`);
|
||||
const f = add(`<div style="position:absolute;left:66px;top:${y + 4}px;height:6px;background:${C.ink};border-radius:3px"></div>`);
|
||||
const v = add(`<div class="v" style="position:absolute;right:${1600 - 300}px;top:${y - 1}px"></div>`);
|
||||
return {f, v};
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 04 optics: the iris, a trace, both lenses
|
||||
panel(R.x, 108, R.w, 196, 'OPTICS', '04');
|
||||
const grip = add(`<div style="position:absolute;left:1300px;top:140px;font-size:34px;font-weight:700;letter-spacing:-1px;line-height:1"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:1301px;top:178px">IRIS · MAIN LENSES</div>`);
|
||||
const trace = add(`<svg style="position:absolute;left:1430px;top:136px" width="132" height="50"></svg>`);
|
||||
const fl = ['LENS L', 'LENS R'].map((k, i) => {
|
||||
const y = 200 + i * 24;
|
||||
add(`<div class="sm" style="position:absolute;left:1300px;top:${y + 2}px">${k}</div>`);
|
||||
add(`<div style="position:absolute;left:1356px;top:${y + 4}px;width:140px;height:6px;background:${C.track};border-radius:3px"></div>`);
|
||||
const f = add(`<div style="position:absolute;left:1356px;top:${y + 4}px;height:6px;background:${C.ink};border-radius:3px"></div>`);
|
||||
const v = add(`<div class="v" style="position:absolute;right:${1600 - 1562}px;top:${y}px"></div>`);
|
||||
return {f, v};
|
||||
});
|
||||
hr(1300, 252, 262);
|
||||
add(`<div class="sm" style="position:absolute;left:1300px;top:264px">MODE</div>`);
|
||||
const hold = add(`<div class="v" style="position:absolute;left:1346px;top:262px"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:1440px;top:264px">RANGE</div>`);
|
||||
const air = add(`<div class="v" style="position:absolute;right:${1600 - 1562}px;top:262px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ 05 views, 06 display
|
||||
const btn = {};
|
||||
const btnRow = (keys, labels, x0, y, wmax = 262, pad = 22) => {
|
||||
let x = x0;
|
||||
let yy = y;
|
||||
for (const k of keys) {
|
||||
const w = Math.round(labels[k].length * 7.1 + pad);
|
||||
if (x + w > x0 + wmax) {
|
||||
x = x0;
|
||||
yy += 30;
|
||||
}
|
||||
btn[k] = add(`<div class="bt" style="left:${x}px;top:${yy}px;width:${w}px">${labels[k]}</div>`);
|
||||
x += w + 6;
|
||||
}
|
||||
};
|
||||
const viewsH = 50 + 30 * viewRows;
|
||||
panel(R.x, 316, R.w, viewsH, opts.viewsTitle ?? 'VIEWS', '05');
|
||||
btnRow(views, viewLabel, 1300, 353, 262, 16);
|
||||
const dispY = 316 + viewsH + 12;
|
||||
panel(R.x, dispY, R.w, 110, 'DISPLAY', '06');
|
||||
btnRow(display, displayLabel, 1300, dispY + 37);
|
||||
const subY = dispY + 122;
|
||||
const subStep = Math.min(29, (744 - subY - 40) / 6);
|
||||
|
||||
// ------------------------------------------------------------ 07 subsystems
|
||||
panel(R.x, subY, R.w, 744 - subY, 'SUBSYSTEMS', '07');
|
||||
const subs = SUBS.map(([n, d], i) => {
|
||||
const y = subY + 34 + i * subStep;
|
||||
const bar = add(`<div style="position:absolute;left:1296px;top:${y}px;width:2px;height:22px;background:transparent"></div>`);
|
||||
add(`<div class="mo" style="position:absolute;left:1304px;top:${y + 1}px;font-size:9px;color:${C.mute}">0${i + 1}</div>`);
|
||||
const name = add(`<div class="mo" style="position:absolute;left:1328px;top:${y}px;font-size:9.4px;font-weight:700;letter-spacing:1.2px">${n}</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:1328px;top:${y + 13}px;font-size:7.6px">${d}</div>`);
|
||||
const chip = add(`<div class="chip" style="right:${1600 - 1562}px;top:${y + 3}px"></div>`);
|
||||
return {bar, name, chip};
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 08 flight log
|
||||
panel(330, 760, 940, 98, 'OPERATION LOG', '08');
|
||||
add(`<div class="bt" style="left:346px;top:796px;width:44px;height:44px;border-radius:50%;border:none;background:${C.or};color:#fff;font-size:14px">❚❚</div>`);
|
||||
const logMode = add(`<div class="mo" style="position:absolute;left:406px;width:780px;top:790px;text-align:center;font-size:9.6px;font-weight:700;letter-spacing:1.6px;color:${C.or}"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:406px;top:791px">DEPLOY</div>`);
|
||||
add(`<div class="sm" style="position:absolute;right:${1600 - 1250}px;top:791px">RECALL</div>`);
|
||||
const TLB = {x: 408, w: 840};
|
||||
add(`<div style="position:absolute;left:${TLB.x}px;top:818px;width:${TLB.w}px;height:3px;background:${C.track};border-radius:2px"></div>`);
|
||||
const tlFill = add(`<div style="position:absolute;left:${TLB.x}px;top:818px;height:3px;background:${C.or};border-radius:2px"></div>`);
|
||||
const tlTicks = add(`<div style="position:absolute;inset:0"></div>`);
|
||||
const tlKnob = add(`<div style="position:absolute;top:812px;width:15px;height:15px;margin-left:-7.5px;border-radius:50%;background:#fff;border:2px solid ${C.or};box-sizing:border-box"></div>`);
|
||||
const tlTime = add(`<div class="mo" style="position:absolute;left:406px;top:834px;font-size:9.6px;color:${C.mute};letter-spacing:1px"></div>`);
|
||||
const tlNext = add(`<div class="sm" style="position:absolute;right:${1600 - 1250}px;top:836px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ viewport notes: model, the view, the flight mode
|
||||
add(`<div class="sm" style="position:absolute;left:346px;top:122px;letter-spacing:2px">MODEL TH-8 · REV A</div>`);
|
||||
const viewNote = add(`<div class="sm" style="position:absolute;right:${1600 - 1254}px;top:122px;letter-spacing:2px"></div>`);
|
||||
add(`<svg style="position:absolute;left:346px;top:140px" width="60" height="60"><path d="M0 60V0h60" fill="none" stroke="${C.or}" stroke-width="1" stroke-dasharray="3 3" opacity=".6"/></svg>`);
|
||||
add(`<svg style="position:absolute;left:1194px;top:680px" width="60" height="60"><path d="M60 0v60H0" fill="none" stroke="${C.or}" stroke-width="1" stroke-dasharray="3 3" opacity=".6"/></svg>`);
|
||||
add(`<div class="sm" style="position:absolute;left:346px;top:666px">OPERATION MODE</div>`);
|
||||
const mode = add(`<div style="position:absolute;left:345px;top:680px;font-size:30px;font-weight:700;letter-spacing:-.4px;line-height:1;color:${C.or}"></div>`);
|
||||
const modeSub = add(`<div class="sm" style="position:absolute;left:346px;top:716px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ footer
|
||||
add(`<div class="sm" style="position:absolute;left:27px;top:878px;letter-spacing:2.2px">FIELD SIMULATOR · PROCEDURAL MODEL · 8 LEGS · 8 OPTICS · GLASS ABDOMEN</div>`);
|
||||
add(`<div class="sm" style="position:absolute;right:28px;top:878px;letter-spacing:2.2px">THERAPHOS DYNAMICS · OPTICS LAB <span style="color:${C.or}">//////</span></div>`);
|
||||
|
||||
// ------------------------------------------------------------ labels, the pointer
|
||||
const callSvg = add(`<svg style="position:absolute;inset:0;overflow:visible" width="1600" height="900"></svg>`);
|
||||
const callG = add(`<div style="position:absolute;inset:0"></div>`);
|
||||
const ring = add(`<div class="ring"></div>`);
|
||||
const cur = add(`<div class="cur"><svg width="22" height="22" viewBox="0 0 34 34"><path d="M4 3 L30 13.5 L17.5 17.5 L13.5 30 Z" fill="#111" stroke="#fff" stroke-width="2.2" stroke-linejoin="round"/></svg></div>`);
|
||||
const centre = (n) => {
|
||||
const r = n.getBoundingClientRect();
|
||||
return [r.left + r.width / 2, r.top + r.height / 2];
|
||||
};
|
||||
const spots = Object.fromEntries(Object.entries(btn).map(([k, n]) => [k, centre(n)]));
|
||||
const pointer = (c) => {
|
||||
cur.style.display = c.x < 0 ? 'none' : 'block';
|
||||
cur.style.transform = `translate(${(c.x - 3).toFixed(2)}px, ${(c.y - 2).toFixed(2)}px) scale(${c.press ? 0.88 : 1})`;
|
||||
ring.style.left = `${c.ringX}px`;
|
||||
ring.style.top = `${c.ringY}px`;
|
||||
ring.style.opacity = String(c.ring * 0.85);
|
||||
ring.style.transform = `scale(${(0.35 + 0.9 * (1 - c.ring)).toFixed(3)})`;
|
||||
};
|
||||
const clock = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(Math.floor(s) % 60).padStart(2, '0')}`;
|
||||
const chipStyle = (n, kind, text) => {
|
||||
const k = {ok: [C.green, '#fff'], warn: [C.or, '#fff'], idle: [C.track, C.mute]}[kind];
|
||||
n.style.background = k[0];
|
||||
n.style.color = k[1];
|
||||
n.textContent = text;
|
||||
};
|
||||
let tickKey = '';
|
||||
|
||||
return {
|
||||
spots,
|
||||
btn,
|
||||
root: ui,
|
||||
TLB,
|
||||
update(s) {
|
||||
// header
|
||||
const lift = Math.round(Math.min(1, s.lift) * 40);
|
||||
liftCells.forEach((c, i) => (c.style.background = i < lift ? (i > 30 ? C.or : C.ink) : C.track));
|
||||
liftPct.textContent = `${Math.round(s.lift * 100)}%`;
|
||||
cellV[1].textContent = `00:00:${String(Math.floor(s.time)).padStart(2, '0')}`;
|
||||
cellV[2].innerHTML = `<span style="color:${s.statusKind === 'ok' ? C.green : C.or}">●</span> ${s.status}`;
|
||||
// gait: the stride rate, the speed, the step diagram (a dark bar per leg while it stands, orange while it
|
||||
// swings, over the last 1.6 s with the now marker on the right)
|
||||
fq.innerHTML = `${s.freq.toFixed(1)}<span style="font-size:14px;font-weight:600;color:${C.mute}"> HZ</span>`;
|
||||
amp.textContent = `${Math.round(s.speed)}`;
|
||||
{
|
||||
const W = 262;
|
||||
const rows = s.steps.length;
|
||||
const rh = 11.2;
|
||||
let g = '';
|
||||
s.steps.forEach((row, r) => {
|
||||
const y = 4 + r * rh;
|
||||
g += `<text x="0" y="${y + 7.5}" font-size="7" fill="${C.mute}" font-family="JetBrains Mono">${LEGS[r]}</text>`;
|
||||
g += `<rect x="18" y="${y + 2}" width="${W - 30}" height="5" rx="1" fill="${C.track}"/>`;
|
||||
for (const [a, b, swing] of row) {
|
||||
const x0 = 18 + a * (W - 30);
|
||||
const x1 = 18 + b * (W - 30);
|
||||
if (x1 - x0 > 0.5) g += `<rect x="${x0.toFixed(1)}" y="${y + 2}" width="${(x1 - x0).toFixed(1)}" height="5" rx="1" fill="${swing ? C.or : C.ink}" opacity="${swing ? 1 : 0.85}"/>`;
|
||||
}
|
||||
});
|
||||
g += `<line x1="${W - 12}" x2="${W - 12}" y1="2" y2="${4 + rows * rh}" stroke="${C.ink}" stroke-width=".8" stroke-dasharray="2 2"/>`;
|
||||
g += `<text x="18" y="99" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">−1.6 S</text><text x="${W - 14}" y="99" text-anchor="end" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">NOW</text>`;
|
||||
chart.innerHTML = g;
|
||||
}
|
||||
pb.textContent = s.pattern;
|
||||
shutter.textContent = `DUTY ${Math.round(s.duty * 100)}%`;
|
||||
// jump: the height over the stance (negative in the crouch), a half-circle gauge from the crouch to the apex,
|
||||
// the airtime, the launch speed, the tuck
|
||||
batt.innerHTML = `${Math.round(s.jumpH)}<span style="font-size:13px;color:${C.mute}"> MM</span>`;
|
||||
{
|
||||
const cx = 62;
|
||||
const cy = 54;
|
||||
const r = 48;
|
||||
const pt = (a, rr) => [cx + Math.cos(Math.PI - a) * rr, cy - Math.sin(Math.PI - a) * rr];
|
||||
const arc = (a0, a1, rr) => {
|
||||
const [x0, y0] = pt(a0, rr);
|
||||
const [x1, y1] = pt(a1, rr);
|
||||
return `M${x0.toFixed(1)} ${y0.toFixed(1)}A${rr} ${rr} 0 0 1 ${x1.toFixed(1)} ${y1.toFixed(1)}`;
|
||||
};
|
||||
const k = Math.max(0, Math.min(1, s.jumpK));
|
||||
let g = `<path d="${arc(0, Math.PI, r)}" fill="none" stroke="${C.track}" stroke-width="6"/>`;
|
||||
if (k > 0.005) g += `<path d="${arc(0, Math.PI * k, r)}" fill="none" stroke="${k > 0.7 ? C.or : C.ink}" stroke-width="6"/>`;
|
||||
for (let i = 0; i <= 6; i++) {
|
||||
const [x0, y0] = pt((i / 6) * Math.PI, r - 9);
|
||||
const [x1, y1] = pt((i / 6) * Math.PI, r - 13);
|
||||
g += `<line x1="${x0.toFixed(1)}" y1="${y0.toFixed(1)}" x2="${x1.toFixed(1)}" y2="${y1.toFixed(1)}" stroke="${C.mute}" stroke-width=".8"/>`;
|
||||
}
|
||||
const [nx, ny] = pt(Math.PI * k, r - 16);
|
||||
g += `<line x1="${cx}" y1="${cy}" x2="${nx.toFixed(1)}" y2="${ny.toFixed(1)}" stroke="${C.or}" stroke-width="1.6"/><circle cx="${cx}" cy="${cy}" r="3" fill="${C.or}"/>`;
|
||||
gauge.innerHTML = g;
|
||||
}
|
||||
pw[0].textContent = `${s.airtime.toFixed(2)} S`;
|
||||
pw[1].textContent = `${s.launch.toFixed(1)} M/S`;
|
||||
pw[2].textContent = `${Math.round(s.tuck * 100)}%`;
|
||||
pw[2].style.color = s.tuck > 0.05 ? C.or : C.ink;
|
||||
// leg servos
|
||||
chipStyle(legState, s.legsFree ? 'warn' : 'ok', s.legsFree ? 'DETACHED' : s.walking ? 'STEPPING' : 'HOLDING');
|
||||
servo.forEach((b, i) => {
|
||||
const v = s.servos[i];
|
||||
b.f.style.width = `${(v * 170).toFixed(1)}px`;
|
||||
const free = s.legFreeEach ? s.legFreeEach[i] : s.legsFree;
|
||||
b.f.style.background = v > 0.6 ? C.or : C.ink;
|
||||
b.v.textContent = free ? 'DETACHED' : `${Math.round(v * 100)}%`;
|
||||
b.v.style.color = free ? C.or : C.ink;
|
||||
b.v.style.fontSize = free ? '8.6px' : '11px';
|
||||
});
|
||||
// optics: the iris f-stop, its trace over the last 2 s, both main lenses' apertures, the mode, the range
|
||||
grip.innerHTML = `<span style="font-size:16px;font-weight:600;color:${C.mute}">F/</span>${s.fstop.toFixed(1)}`;
|
||||
{
|
||||
const W = 132;
|
||||
const H = 50;
|
||||
const Y = (v) => (H - 4 - v * (H - 10)).toFixed(1);
|
||||
const tr = s.irisTrace;
|
||||
const path = tr.map((v, i) => `${i ? 'L' : 'M'}${((i / (tr.length - 1)) * (W - 4)).toFixed(1)} ${Y(v)}`).join('');
|
||||
trace.innerHTML = `<line x1="0" x2="${W}" y1="${H - 4}" y2="${H - 4}" stroke="${C.faint}"/><path d="${path}" fill="none" stroke="${C.or}" stroke-width="1.5"/><circle cx="${W - 4}" cy="${Y(tr[tr.length - 1])}" r="2.6" fill="${C.or}"/>`;
|
||||
}
|
||||
fl.forEach((b, i) => {
|
||||
const v = s.lensOpen[i];
|
||||
b.f.style.width = `${(v * 140).toFixed(1)}px`;
|
||||
b.f.style.background = v > 0.6 ? C.or : C.ink;
|
||||
const off = s.opticsOpen;
|
||||
b.v.textContent = off ? 'OPEN' : `${Math.round(v * 100)}%`;
|
||||
b.v.style.color = off ? C.or : C.ink;
|
||||
});
|
||||
hold.textContent = s.opticsMode;
|
||||
air.textContent = `${Math.round(s.range)} MM`;
|
||||
// views, display
|
||||
const onBtn = (k, on) => {
|
||||
btn[k].style.background = on ? C.or : '#fffdf9';
|
||||
btn[k].style.color = on ? '#fff' : C.ink;
|
||||
btn[k].style.borderColor = on ? C.or : C.faint;
|
||||
};
|
||||
for (const k of views) onBtn(k, s.view === k);
|
||||
for (const k of display) onBtn(k, !!s.display[k]);
|
||||
// subsystems: a status chip each, the row the current view looks at marked
|
||||
subs.forEach((r, i) => {
|
||||
const [kind, text] = s.subs[i];
|
||||
chipStyle(r.chip, kind, text);
|
||||
r.bar.style.background = s.focus === i ? C.or : 'transparent';
|
||||
r.name.style.color = s.focus === i ? C.or : C.ink;
|
||||
});
|
||||
// flight log: the film's progress, a tick for every press, the mode
|
||||
const kx = TLB.x + (s.time / s.dur) * TLB.w;
|
||||
tlFill.style.width = `${(kx - TLB.x).toFixed(1)}px`;
|
||||
tlKnob.style.left = `${kx.toFixed(1)}px`;
|
||||
const key = s.events.length;
|
||||
if (key !== tickKey) {
|
||||
tickKey = key;
|
||||
tlTicks.innerHTML = s.events.map((e) => `<div style="position:absolute;left:${(TLB.x + (e / s.dur) * TLB.w - 1).toFixed(1)}px;top:813px;width:2px;height:13px;background:${C.ink};opacity:.35"></div>`).join('');
|
||||
}
|
||||
tlTime.textContent = `${clock(s.time)} / ${clock(s.dur)}`;
|
||||
tlNext.textContent = s.next;
|
||||
logMode.textContent = s.log;
|
||||
viewNote.textContent = s.viewNote ?? `VIEW · ${viewLabel[s.view]}${s.display.orbit ? ' · ORBIT' : ''}`;
|
||||
mode.textContent = s.mode;
|
||||
modeSub.textContent = s.modeSub;
|
||||
// labels: an orange square, the name, the note, a thin leader to the part
|
||||
let lh = '';
|
||||
let ch = '';
|
||||
for (const c of s.callouts) {
|
||||
if (c.o < 0.02 || !c.at) continue;
|
||||
const [ax, ay] = c.at;
|
||||
const [lx, ly] = c.label;
|
||||
const right = lx > ax;
|
||||
const ex = right ? lx - 6 : lx + c.w + 6;
|
||||
lh += `<polyline points="${ax.toFixed(1)},${ay.toFixed(1)} ${ex.toFixed(1)},${(ly + 6).toFixed(1)}" fill="none" stroke="${C.or}" stroke-width=".9" opacity="${c.o.toFixed(2)}"/><circle cx="${ax.toFixed(1)}" cy="${ay.toFixed(1)}" r="2.4" fill="${C.or}" opacity="${c.o.toFixed(2)}"/>`;
|
||||
ch += `<div class="call" style="left:${lx.toFixed(1)}px;top:${(ly - 1).toFixed(1)}px;opacity:${c.o.toFixed(2)}"><b><i></i>${c.name}</b><span>${c.sub}</span></div>`;
|
||||
}
|
||||
callSvg.innerHTML = lh;
|
||||
callG.innerHTML = ch;
|
||||
pointer(s.cursor);
|
||||
},
|
||||
pointer,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// The spider's walk, copied from the scorpion's (roboscorp-shared/gait.js): a body path integrated from velocity keys and an alternating tetrapod gait for eight legs
|
||||
// (L1 R2 L3 R4 against R1 L2 R3 L4), after the hexapod's (hexsim-shared/motion.js) but simpler. Pure functions of t,
|
||||
// no three.js. World: y up; a yaw ψ turns the body's +x to (cos ψ, 0, -sin ψ), as three.js rotation.y does.
|
||||
// keys: [[t, speed, yawRate°/s], ...] eased between; the path is moved so that at tRef the body stands at the origin
|
||||
// facing +x. A step starts whenever the phase clock (∫ rate dt) crosses a group's mark; once started it always
|
||||
// finishes, and it lands where the leg's home spot will be a moment after touchdown, so the feet settle home when the
|
||||
// body stops. footLocal(i, t) gives a foot in the body frame of the path (the turntable turns on top of it).
|
||||
import {FLOOR_Y, legHome, WHEEL_R} from './spider.js';
|
||||
|
||||
const smoother = (x) => {
|
||||
const u = Math.min(1, Math.max(0, x));
|
||||
return u * u * u * (u * (u * 6 - 15) + 10);
|
||||
};
|
||||
const GA = [0, 5, 2, 7];
|
||||
const GB = [4, 1, 6, 3];
|
||||
export const STRIDE_HZ = 2.7;
|
||||
const SWING = 0.46 / STRIDE_HZ;
|
||||
const LIFT = 0.12;
|
||||
|
||||
export function buildGait({keys, duration, tRef = 2.8, t0 = -1.5}) {
|
||||
const HZ = 240;
|
||||
const N = Math.ceil((duration - t0) * HZ) + 2;
|
||||
const at = (t) => {
|
||||
// eased velocity between keys
|
||||
if (t <= keys[0][0]) return [keys[0][1], keys[0][2]];
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
const [ta, va, wa] = keys[i];
|
||||
const [tb, vb, wb] = keys[i + 1];
|
||||
if (t <= tb) {
|
||||
const k = smoother((t - ta) / (tb - ta));
|
||||
return [va + (vb - va) * k, wa + (wb - wa) * k];
|
||||
}
|
||||
}
|
||||
const l = keys[keys.length - 1];
|
||||
return [l[1], l[2]];
|
||||
};
|
||||
const X = new Float64Array(N);
|
||||
const Z = new Float64Array(N);
|
||||
const Y = new Float64Array(N);
|
||||
const RATE = new Float64Array(N);
|
||||
const PH = new Float64Array(N);
|
||||
const move = (t) => {
|
||||
const [v, w] = at(t);
|
||||
return Math.min(1, Math.abs(v) / 0.35 + Math.abs(w) / 45);
|
||||
};
|
||||
for (let i = 1; i < N; i++) {
|
||||
const t = t0 + (i - 0.5) / HZ;
|
||||
const [v, w] = at(t);
|
||||
const ym = Y[i - 1] + (w * Math.PI) / 180 / HZ / 2;
|
||||
X[i] = X[i - 1] + (v * Math.cos(ym)) / HZ;
|
||||
Z[i] = Z[i - 1] - (v * Math.sin(ym)) / HZ;
|
||||
Y[i] = Y[i - 1] + (w * Math.PI) / 180 / HZ;
|
||||
// the legs keep stepping for half a second after the body stops, so they settle
|
||||
RATE[i] = STRIDE_HZ * Math.max(move(t), move(t - 0.25), move(t - 0.5));
|
||||
PH[i] = PH[i - 1] + RATE[i] / HZ;
|
||||
}
|
||||
const idx = (t) => Math.min(N - 1.000001, Math.max(0, (t - t0) * HZ));
|
||||
const samp = (A, t) => {
|
||||
const f = idx(t);
|
||||
const i = Math.floor(f);
|
||||
return A[i] + (A[i + 1] - A[i]) * (f - i);
|
||||
};
|
||||
// the rigid move that puts the body at the origin facing +x at tRef
|
||||
const rx = samp(X, tRef);
|
||||
const rz = samp(Z, tRef);
|
||||
const ry = samp(Y, tRef);
|
||||
const c = Math.cos(-ry);
|
||||
const s = Math.sin(-ry);
|
||||
const pathAt = (t) => {
|
||||
const x = samp(X, t) - rx;
|
||||
const z = samp(Z, t) - rz;
|
||||
// rotate by -ry about y: (x, z) → (x c + z s, -x s + z c) with the three.js sense
|
||||
return {x: x * c + z * s, z: -x * s + z * c, yaw: samp(Y, t) - ry};
|
||||
};
|
||||
const toWorld = (p, lx, lz) => [p.x + lx * Math.cos(p.yaw) + lz * Math.sin(p.yaw), p.z - lx * Math.sin(p.yaw) + lz * Math.cos(p.yaw)];
|
||||
|
||||
// the step schedule: every crossing of a group's mark starts a swing for its four legs
|
||||
const swings = Array.from({length: 8}, () => []);
|
||||
for (let i = 1; i < N; i++) {
|
||||
const t = t0 + i / HZ;
|
||||
for (const [grp, off] of [
|
||||
[GA, 0],
|
||||
[GB, 0.5],
|
||||
]) {
|
||||
if (Math.floor(PH[i] - off) > Math.floor(PH[i - 1] - off) && PH[i] - off > 0) {
|
||||
for (const l of grp) {
|
||||
const S = swings[l];
|
||||
if (S.length && S[S.length - 1].t1 > t - 0.04) continue;
|
||||
S.push({t0: t, t1: t + SWING});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const start = Array.from({length: 8}, (_, l) => {
|
||||
const h = legHome(l);
|
||||
return toWorld(pathAt(t0), h[0], h[2]);
|
||||
});
|
||||
swings.forEach((S, l) => {
|
||||
let from = start[l];
|
||||
const h = legHome(l);
|
||||
for (const sw of S) {
|
||||
sw.from = from;
|
||||
sw.to = toWorld(pathAt(sw.t1 + 0.1), h[0], h[2]);
|
||||
from = sw.to;
|
||||
}
|
||||
});
|
||||
const footWorld = (l, t) => {
|
||||
let planted = start[l];
|
||||
for (const sw of swings[l]) {
|
||||
if (sw.t0 > t) break;
|
||||
if (t < sw.t1) {
|
||||
const q = (t - sw.t0) / (sw.t1 - sw.t0);
|
||||
const e = smoother((q - 0.04) / 0.9);
|
||||
const y = Math.pow(Math.sin(Math.PI * q), 1.1);
|
||||
return [sw.from[0] + (sw.to[0] - sw.from[0]) * e, FLOOR_Y + WHEEL_R + LIFT * y, sw.from[1] + (sw.to[1] - sw.from[1]) * e, y];
|
||||
}
|
||||
planted = sw.to;
|
||||
}
|
||||
return [planted[0], FLOOR_Y + WHEEL_R, planted[1], 0];
|
||||
};
|
||||
/** A foot in the body frame of the path at t, given the body's height y and its pitch and roll (radians). */
|
||||
const footLocal = (l, t, body) => {
|
||||
const p = pathAt(t);
|
||||
const f = footWorld(l, t);
|
||||
let x = f[0] - p.x;
|
||||
let y = f[1] - body.y;
|
||||
let z = f[2] - p.z;
|
||||
// undo yaw (rotation.y = yaw): R(-yaw) about y
|
||||
const cy = Math.cos(-p.yaw);
|
||||
const sy = Math.sin(-p.yaw);
|
||||
[x, z] = [x * cy + z * sy, -x * sy + z * cy];
|
||||
// undo roll about x, then pitch about z (the root's Euler order is YXZ: R = Ry Rx Rz)
|
||||
const cr = Math.cos(-body.roll);
|
||||
const sr = Math.sin(-body.roll);
|
||||
[y, z] = [y * cr - z * sr, y * sr + z * cr];
|
||||
const cp = Math.cos(-body.pitch);
|
||||
const sp = Math.sin(-body.pitch);
|
||||
[x, y] = [x * cp - y * sp, x * sp + y * cp];
|
||||
return [x, y, z];
|
||||
};
|
||||
const lifted = (l, t) => footWorld(l, t)[3];
|
||||
return {pathAt, footWorld, footLocal, lifted, rateAt: (t) => samp(RATE, t), phaseAt: (t) => samp(PH, t), velAt: at, swings};
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
// The construction drawing around the scorpion, copied from the bee's (robobee-shared/guides.js) with a centre and a
|
||||
// scale: hairline arcs and dashed circles in a few tilted planes, dots and small hollow markers riding on them, short
|
||||
// ticks. All in world space round the scorpion, so a camera orbit gives them depth. Lines are fat lines with a width
|
||||
// in device pixels; resize() keeps them hairline at any pixel ratio.
|
||||
import * as THREE from 'three';
|
||||
import {Line2} from 'three/addons/lines/Line2.js';
|
||||
import {LineGeometry} from 'three/addons/lines/LineGeometry.js';
|
||||
import {LineMaterial} from 'three/addons/lines/LineMaterial.js';
|
||||
import {rng} from '../kit/util.js';
|
||||
|
||||
const V3 = THREE.Vector3;
|
||||
const INK = '#8a8178';
|
||||
|
||||
export function buildGuides({centre = [0.05, 0.1, 0], seed = 5, scale = 1} = {}) {
|
||||
const R = rng(seed);
|
||||
const group = new THREE.Group();
|
||||
const lines = [];
|
||||
const C = new V3(...centre);
|
||||
// two unit vectors spanning the plane with normal n
|
||||
const basis = (n) => {
|
||||
const a = Math.abs(n.y) < 0.9 ? new V3(0, 1, 0) : new V3(1, 0, 0);
|
||||
const u = new V3().crossVectors(a, n).normalize();
|
||||
return [u, new V3().crossVectors(n, u)];
|
||||
};
|
||||
const circ = (c, r, n, a) => {
|
||||
const [u, v] = basis(n.clone().normalize());
|
||||
return c.clone().addScaledVector(u, Math.cos(a) * r).addScaledVector(v, Math.sin(a) * r);
|
||||
};
|
||||
const arc = (c, r, n, a0, a1, {dashed = false, width = 1, opacity = 0.5, dash = 0.045} = {}) => {
|
||||
const N = Math.max(24, Math.round(Math.abs(a1 - a0) * r * 60));
|
||||
const pts = [];
|
||||
for (let i = 0; i <= N; i++) {
|
||||
const p = circ(c, r, n, a0 + ((a1 - a0) * i) / N);
|
||||
pts.push(p.x, p.y, p.z);
|
||||
}
|
||||
const g = new LineGeometry();
|
||||
g.setPositions(pts);
|
||||
const m = new LineMaterial({color: INK, linewidth: width, transparent: true, opacity, dashed, dashSize: dash, gapSize: dash * 0.8, depthWrite: false, worldUnits: false});
|
||||
const l = new Line2(g, m);
|
||||
l.computeLineDistances();
|
||||
l.renderOrder = 4;
|
||||
group.add(l);
|
||||
lines.push({m, width, opacity});
|
||||
return l;
|
||||
};
|
||||
const seg = (a, b, opts = {}) => {
|
||||
const g = new LineGeometry();
|
||||
g.setPositions([a.x, a.y, a.z, b.x, b.y, b.z]);
|
||||
const m = new LineMaterial({color: INK, linewidth: opts.width ?? 1, transparent: true, opacity: opts.opacity ?? 0.45, dashed: !!opts.dashed, dashSize: 0.04, gapSize: 0.035, depthWrite: false});
|
||||
const l = new Line2(g, m);
|
||||
l.computeLineDistances();
|
||||
l.renderOrder = 4;
|
||||
group.add(l);
|
||||
lines.push({m, width: opts.width ?? 1, opacity: opts.opacity ?? 0.45});
|
||||
};
|
||||
|
||||
// the rings: [radius, normal, arcs, dashed, width, opacity]
|
||||
const RINGS = [
|
||||
[2.75, new V3(0.35, 0.25, 1), [[0.15, 1.9], [2.4, 3.5], [4.1, 5.6]], false, 1.0, 0.42],
|
||||
[2.05, new V3(0.1, 1, 0.3), [[0, Math.PI * 2]], true, 1.0, 0.45],
|
||||
[1.35, new V3(1, 0.15, 0.05), [[0.3, 2.6], [3.3, 5.5]], false, 1.1, 0.5],
|
||||
[3.45, new V3(0.55, 0.75, 0.35), [[0.6, 2.2], [3.6, 4.6]], false, 0.9, 0.32],
|
||||
[1.7, new V3(-0.4, 0.3, 1), [[0, Math.PI * 2]], true, 0.9, 0.36],
|
||||
[2.35, new V3(0.9, -0.2, 0.4), [[1.0, 2.9], [4.2, 5.9]], false, 0.9, 0.34],
|
||||
];
|
||||
for (const R of RINGS) R[0] *= scale;
|
||||
const onRing = [];
|
||||
for (const [r, n, arcs, dashed, w, o] of RINGS) {
|
||||
for (const [a0, a1] of arcs) arc(C, r, n, a0, a1, {dashed, width: w, opacity: o});
|
||||
onRing.push([r, n, arcs]);
|
||||
}
|
||||
// a small ring round the sensor head and one round the stinger, offset from the main centre
|
||||
arc(new V3(1.3, 0.2, 0.0), 0.55, new V3(0.75, 0.25, 0.6), 0, Math.PI * 2, {dashed: true, width: 0.9, opacity: 0.4, dash: 0.03});
|
||||
arc(new V3(-0.4, 1.7, 0), 0.8, new V3(-0.3, 0.2, 1), 0.4, 4.6, {width: 0.9, opacity: 0.38});
|
||||
|
||||
// dots and hollow markers riding on the rings, ticks across them
|
||||
const dots = [];
|
||||
const marks = new THREE.Group();
|
||||
group.add(marks);
|
||||
const dotGeo = new THREE.SphereGeometry(1, 10, 8);
|
||||
const dotMat = new THREE.MeshBasicMaterial({color: '#5d5751', transparent: true, opacity: 0.75, depthWrite: false});
|
||||
const ringGeo = new THREE.RingGeometry(0.62, 1, 28);
|
||||
const ringMat = new THREE.MeshBasicMaterial({color: '#6e675f', transparent: true, opacity: 0.7, depthWrite: false, side: THREE.DoubleSide});
|
||||
for (const [r, n, arcs] of onRing) {
|
||||
for (const [a0, a1] of arcs) {
|
||||
const k = Math.max(1, Math.round((a1 - a0) * 1.6));
|
||||
for (let i = 0; i < k; i++) {
|
||||
const a = a0 + (a1 - a0) * R();
|
||||
const p = circ(C, r, n, a);
|
||||
if (R() < 0.6) {
|
||||
const d = new THREE.Mesh(dotGeo, dotMat);
|
||||
d.position.copy(p);
|
||||
d.scale.setScalar(0.009 + R() * 0.012);
|
||||
d.renderOrder = 5;
|
||||
group.add(d);
|
||||
dots.push(d);
|
||||
} else {
|
||||
const m = new THREE.Mesh(ringGeo, ringMat);
|
||||
m.position.copy(p);
|
||||
m.scale.setScalar(0.022 + R() * 0.016);
|
||||
m.renderOrder = 5;
|
||||
marks.add(m);
|
||||
}
|
||||
// a short tick across the ring at some of them
|
||||
if (R() < 0.35) {
|
||||
const t = circ(C, r * 1.04, n, a);
|
||||
const b = circ(C, r * 0.96, n, a);
|
||||
seg(t, b, {width: 1, opacity: 0.5});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// a few straight dashed leaders out from the body
|
||||
for (const [a, b] of [
|
||||
[new V3(1.4, 0.3, 0.2), new V3(2.6, 1.2, 0.5)],
|
||||
[new V3(-0.8, 0.2, 0.4), new V3(-2.2, 0.0, 1.2)],
|
||||
[new V3(0.2, 0.6, -0.3), new V3(0.6, 2.2, -0.8)],
|
||||
]) {
|
||||
seg(a, b, {dashed: true, width: 0.9, opacity: 0.38});
|
||||
}
|
||||
|
||||
return {
|
||||
group,
|
||||
resize(w, h, pr) {
|
||||
for (const L of lines) {
|
||||
L.m.resolution.set(w, h);
|
||||
L.m.linewidth = L.width * pr;
|
||||
}
|
||||
},
|
||||
// ops.guides 0..1 fades the whole drawing
|
||||
update(camera, ops = {}) {
|
||||
const k = ops.guides ?? 1;
|
||||
group.userData.show = k > 0.001;
|
||||
group.visible = group.userData.show;
|
||||
for (const L of lines) L.m.opacity = Math.min(1, L.opacity * 1.1 * k);
|
||||
dotMat.opacity = 0.75 * k;
|
||||
ringMat.opacity = 0.7 * k;
|
||||
for (const m of marks.children) m.quaternion.copy(camera.quaternion);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// The spider's jump: a crouch, the push, a ballistic flight with the legs tucked, the landing and its absorb. Pure
|
||||
// functions of t, no three.js. J = {t0: the crouch starts, tl: lift-off, ta: touch-down, dist: the forward travel,
|
||||
// h: the apex over the standing height}. The forward travel rides on the gait's path as a velocity pulse (jumpKeys,
|
||||
// its integral is dist), so the gait re-plants the feet round the landing spot; jumpAt gives what goes on top of the
|
||||
// path: the body's height and pitch and the tuck the legs blend toward (spider.js legTuck).
|
||||
const smoother = (x) => {
|
||||
const u = Math.min(1, Math.max(0, x));
|
||||
return u * u * u * (u * (u * 6 - 15) + 10);
|
||||
};
|
||||
const ssw = (e, s, f) => smoother((e - s) / (f - s));
|
||||
// how far the body sinks into its legs before the push
|
||||
export const CROUCH = 0.17;
|
||||
// the absorb after touch-down
|
||||
export const LAND = 0.45;
|
||||
|
||||
/** Height offset, pitch (radians, nose up > 0), tuck 0..1 and whether the body is in the air, at t. */
|
||||
export function jumpAt(t, J) {
|
||||
const {t0, tl, ta, h} = J;
|
||||
if (t < t0 || t > ta + LAND) return {dy: 0, pitch: 0, tuck: 0, air: 0};
|
||||
if (t < tl) {
|
||||
// down and a little nose-down over most of the window, then the last 0.12 s straightens the legs fast
|
||||
const c = ssw(t, t0, tl - 0.12);
|
||||
const push = ssw(t, tl - 0.12, tl);
|
||||
return {dy: -CROUCH * c * (1 - push), pitch: -0.07 * c * (1 - push) + 0.16 * push, tuck: 0, air: 0};
|
||||
}
|
||||
if (t < ta) {
|
||||
const q = (t - tl) / (ta - tl);
|
||||
const tuck = ssw(q, 0.0, 0.28) * (1 - ssw(q, 0.7, 1.0));
|
||||
return {dy: 4 * h * q * (1 - q), pitch: 0.16 * (1 - 2 * q) - 0.04 * Math.sin(Math.PI * q), tuck, air: 1};
|
||||
}
|
||||
// the body sinks into the legs and comes back up
|
||||
const k = (t - ta) / LAND;
|
||||
const s = Math.sin(Math.PI * Math.min(1, k)) * (1 - 0.35 * k);
|
||||
return {dy: -0.13 * s, pitch: -0.08 * s, tuck: 0, air: 0};
|
||||
}
|
||||
|
||||
/** The jump's forward travel as gait velocity keys [t, speed, yawRate°/s]: a pulse over the flight whose integral is
|
||||
* J.dist (the gait eases between keys with the same smoother, so the area is half of peak x flight). */
|
||||
export const jumpKeys = (J) => [
|
||||
[J.tl, 0, 0],
|
||||
[(J.tl + J.ta) / 2, (2 * J.dist) / (J.ta - J.tl), 0],
|
||||
[J.ta, 0, 0],
|
||||
];
|
||||
@@ -0,0 +1,315 @@
|
||||
// The robotic scorpion's kitbash shop, copied from the bee's (robobee-shared/parts.js) with the stinger's orange
|
||||
// resin and a tapered tube added: the materials (gloss white shell, orange accent, graphite and black mechanism,
|
||||
// steel, the lens, clear glass and the bee's unused wing films) and the geometry every part is cut from. Everything is
|
||||
// built along +x and placed by the caller: sweepX turns a closed (x, r) profile round the x axis, whole or as an arc
|
||||
// with capped ends, which gives rings, collars, domes, shell plates and capsules from one function; gearGeo cuts a
|
||||
// toothed wheel with a bore; tube runs a cable along points.
|
||||
import * as THREE from 'three';
|
||||
import {RoundedBoxGeometry} from 'three/addons/geometries/RoundedBoxGeometry.js';
|
||||
import {mergeGeometries} from 'three/addons/utils/BufferGeometryUtils.js';
|
||||
|
||||
export const V3 = THREE.Vector3;
|
||||
export const D2R = Math.PI / 180;
|
||||
export const PAL = {white: '#f4f2ee', orange: '#ff5a1f', graphite: '#2f3238', black: '#111214', steel: '#cdd1d6'};
|
||||
|
||||
export function makeMaterials() {
|
||||
const phys = (o) => new THREE.MeshPhysicalMaterial(o);
|
||||
const std = (o) => new THREE.MeshStandardMaterial(o);
|
||||
return {
|
||||
// the white plastic: a soft base under a hard clear coat, so the softboxes sit on it as crisp bars
|
||||
shell: phys({color: PAL.white, roughness: 0.34, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.05}),
|
||||
// inside faces of the shells, a shade darker and matte
|
||||
shellIn: phys({color: '#dedad4', roughness: 0.6, metalness: 0, clearcoat: 0.2, clearcoatRoughness: 0.4, side: THREE.DoubleSide}),
|
||||
orange: phys({color: PAL.orange, roughness: 0.3, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.08}),
|
||||
// the orange panel at a wing tip: a film on the membrane, both faces, pulled forward so it never fights it
|
||||
orangeFilm: phys({color: PAL.orange, roughness: 0.32, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.08, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2}),
|
||||
graphite: std({color: PAL.graphite, roughness: 0.36, metalness: 0.72}),
|
||||
gunmetal: std({color: '#555a62', roughness: 0.28, metalness: 0.9}),
|
||||
black: phys({color: PAL.black, roughness: 0.3, metalness: 0.15, clearcoat: 0.8, clearcoatRoughness: 0.12}),
|
||||
rubber: std({color: '#1b1c1f', roughness: 0.7, metalness: 0}),
|
||||
steel: std({color: PAL.steel, roughness: 0.2, metalness: 1}),
|
||||
// the camera eye: a deep black inner element under a dark glass dome; its colour darkens only what shows
|
||||
// through it, the highlights stay at full strength
|
||||
lens: phys({color: '#020203', roughness: 0.05, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.02, envMapIntensity: 1.4}),
|
||||
lensGlass: phys({color: '#6f7277', roughness: 0, metalness: 0, transmission: 1, thickness: 0, ior: 1.5, clearcoat: 1, clearcoatRoughness: 0, specularIntensity: 1, envMapIntensity: 2.4}),
|
||||
amber: std({color: '#000000', emissive: '#ffa040', emissiveIntensity: 4.5}),
|
||||
// circuit boards in the thorax: a dark green-black laminate
|
||||
pcb: std({color: '#1b241f', roughness: 0.55, metalness: 0.1}),
|
||||
// the clear abdomen window: real transmission, so the mechanism inside refracts a touch
|
||||
glass: phys({color: '#ffffff', roughness: 0.0, metalness: 0, transmission: 1, thickness: 0, ior: 1.3, specularIntensity: 0.6, clearcoat: 0.5, clearcoatRoughness: 0.02}),
|
||||
// the wing film: a faint grey-white sheet; the veins and the rim carry the read
|
||||
membrane: phys({color: '#eef0f2', roughness: 0.38, metalness: 0, transparent: true, opacity: 0.3, depthWrite: false, side: THREE.DoubleSide, clearcoat: 1, clearcoatRoughness: 0.04, iridescence: 0.35, iridescenceIOR: 1.3}),
|
||||
// the wing rim: a pale clear-ish tube
|
||||
rim: phys({color: '#e4e7ea', roughness: 0.12, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.04, transparent: true, opacity: 0.55, depthWrite: false}),
|
||||
vein: std({color: '#4a4d53', roughness: 0.5, metalness: 0.2, transparent: true, opacity: 0.72}),
|
||||
veinCore: std({color: '#5a5d63', roughness: 0.5, metalness: 0.2}),
|
||||
led: std({color: '#000000', emissive: PAL.orange, emissiveIntensity: 1.4}),
|
||||
// the stinger's base and the claws' blade edges: a translucent orange resin with a hard coat
|
||||
orangeGlass: phys({color: '#ff6a24', roughness: 0.12, metalness: 0, transmission: 0.55, thickness: 0.2, ior: 1.45, attenuationColor: '#ff4a10', attenuationDistance: 0.25, clearcoat: 1, clearcoatRoughness: 0.03, transparent: true, opacity: 0.92}),
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ sweepX: a closed (x, r) profile turned round the x axis
|
||||
// profile: [[x, r], ...] closed loop, either winding. a0..a1: the arc, angle 0 at +y, 90° at +z. Profile corners
|
||||
// sharper than `smooth` degrees keep a hard edge; softer ones are shaded smooth. A partial arc gets capped ends.
|
||||
export function sweepX(profile, {a0 = 0, a1 = Math.PI * 2, segs = 64, smooth = 32} = {}) {
|
||||
let P = profile.map(([x, r]) => [x, Math.max(0, r)]);
|
||||
let area = 0;
|
||||
for (let i = 0; i < P.length; i++) {
|
||||
const [x0, r0] = P[i];
|
||||
const [x1, r1] = P[(i + 1) % P.length];
|
||||
area += x0 * r1 - x1 * r0;
|
||||
}
|
||||
if (area < 0) P = P.reverse();
|
||||
const n = P.length;
|
||||
// outward edge normals in the (x, r) plane
|
||||
const EN = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const [x0, r0] = P[i];
|
||||
const [x1, r1] = P[(i + 1) % n];
|
||||
const l = Math.hypot(x1 - x0, r1 - r0) || 1;
|
||||
EN.push([(r1 - r0) / l, -(x1 - x0) / l]);
|
||||
}
|
||||
const cosS = Math.cos(smooth * D2R);
|
||||
const vN = (i, e) => {
|
||||
// normal at vertex i as seen from edge e (e is i-1 or i)
|
||||
const other = e === i ? (i - 1 + n) % n : i;
|
||||
const a = EN[e];
|
||||
const b = EN[other];
|
||||
if (a[0] * b[0] + a[1] * b[1] < cosS) return a;
|
||||
const x = a[0] + b[0];
|
||||
const y = a[1] + b[1];
|
||||
const l = Math.hypot(x, y) || 1;
|
||||
return [x / l, y / l];
|
||||
};
|
||||
const full = Math.abs(a1 - a0) >= Math.PI * 2 - 1e-6;
|
||||
const pos = [];
|
||||
const nor = [];
|
||||
const idx = [];
|
||||
const cs = [];
|
||||
for (let j = 0; j <= segs; j++) {
|
||||
const th = a0 + ((a1 - a0) * j) / segs;
|
||||
cs.push([Math.cos(th), Math.sin(th)]);
|
||||
}
|
||||
for (let e = 0; e < n; e++) {
|
||||
const i0 = e;
|
||||
const i1 = (e + 1) % n;
|
||||
const [x0, r0] = P[i0];
|
||||
const [x1, r1] = P[i1];
|
||||
if (Math.hypot(x1 - x0, r1 - r0) < 1e-9) continue;
|
||||
const n0 = vN(i0, e);
|
||||
const n1 = vN(i1, e);
|
||||
const base = pos.length / 3;
|
||||
for (let j = 0; j <= segs; j++) {
|
||||
const [c, s] = cs[j];
|
||||
pos.push(x0, r0 * c, r0 * s, x1, r1 * c, r1 * s);
|
||||
nor.push(n0[0], n0[1] * c, n0[1] * s, n1[0], n1[1] * c, n1[1] * s);
|
||||
}
|
||||
for (let j = 0; j < segs; j++) {
|
||||
const a = base + j * 2;
|
||||
const b = a + 1;
|
||||
const c = a + 3;
|
||||
const d = a + 2;
|
||||
idx.push(a, b, c, a, c, d);
|
||||
}
|
||||
}
|
||||
if (!full) {
|
||||
const tri = THREE.ShapeUtils.triangulateShape(
|
||||
P.map(([x, r]) => new THREE.Vector2(x, r)),
|
||||
[],
|
||||
);
|
||||
for (const [th, flip] of [
|
||||
[a0, true],
|
||||
[a1, false],
|
||||
]) {
|
||||
const c = Math.cos(th);
|
||||
const s = Math.sin(th);
|
||||
// the cap's normal: -d/dθ at a0, +d/dθ at a1
|
||||
const nx = 0;
|
||||
const ny = flip ? s : -s;
|
||||
const nz = flip ? -c : c;
|
||||
const base = pos.length / 3;
|
||||
for (const [x, r] of P) {
|
||||
pos.push(x, r * c, r * s);
|
||||
nor.push(nx, ny, nz);
|
||||
}
|
||||
for (const t of tri) {
|
||||
if (flip) idx.push(base + t[0], base + t[2], base + t[1]);
|
||||
else idx.push(base + t[0], base + t[1], base + t[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
const g = new THREE.BufferGeometry();
|
||||
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
|
||||
g.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
|
||||
g.setIndex(idx);
|
||||
return g;
|
||||
}
|
||||
|
||||
// a rounded rectangle profile for a ring: x0..x1 wide, r0..r1 deep, corners rounded by `round`
|
||||
export function ringProfile(x0, x1, r0, r1, round = 0.01, steps = 3) {
|
||||
const rr = Math.min(round, (x1 - x0) / 2.01, (r1 - r0) / 2.01);
|
||||
const pts = [];
|
||||
const corner = (cx, cr, a0) => {
|
||||
for (let k = 0; k <= steps; k++) {
|
||||
const a = a0 + (k / steps) * (Math.PI / 2);
|
||||
pts.push([cx + Math.cos(a) * rr, cr + Math.sin(a) * rr]);
|
||||
}
|
||||
};
|
||||
corner(x1 - rr, r0 + rr, -Math.PI / 2);
|
||||
corner(x1 - rr, r1 - rr, 0);
|
||||
corner(x0 + rr, r1 - rr, Math.PI / 2);
|
||||
corner(x0 + rr, r0 + rr, Math.PI);
|
||||
return pts;
|
||||
}
|
||||
export const ring = (x0, x1, r0, r1, round, opts) => sweepX(ringProfile(x0, x1, r0, r1, round), opts);
|
||||
|
||||
// a thick spherical shell from polar angle p0 to p1 (0 = +x pole), outer radius R, wall t; the rims stay sharp so
|
||||
// the clear coat draws a crisp line along them
|
||||
export function domeProfile(R, t, p0, p1, steps = 24) {
|
||||
const out = [];
|
||||
const inn = [];
|
||||
for (let k = 0; k <= steps; k++) {
|
||||
const p = p0 + ((p1 - p0) * k) / steps;
|
||||
out.push([R * Math.cos(p), R * Math.sin(p)]);
|
||||
inn.push([(R - t) * Math.cos(p), (R - t) * Math.sin(p)]);
|
||||
}
|
||||
return [...out, ...inn.reverse()];
|
||||
}
|
||||
export const dome = (R, t, p0, p1, opts) => sweepX(domeProfile(R, t, p0, p1), opts);
|
||||
|
||||
// a solid of revolution from a radius function: r(u) for u in 0..1 along x0..x1, closed to the axis at both ends
|
||||
export function solidProfile(x0, x1, rFn, steps = 32) {
|
||||
const pts = [[x0, 0]];
|
||||
for (let k = 0; k <= steps; k++) {
|
||||
const u = k / steps;
|
||||
pts.push([x0 + (x1 - x0) * u, rFn(u)]);
|
||||
}
|
||||
pts.push([x1, 0]);
|
||||
return pts;
|
||||
}
|
||||
export const solid = (x0, x1, rFn, opts, steps) => sweepX(solidProfile(x0, x1, rFn, steps), opts);
|
||||
// a capsule-like rounded radius: r0 at the start, r1 at the end, ends rounded over `cap` of the length
|
||||
export const capsuleR = (r0, r1, cap = 0.12) => (u) => {
|
||||
const r = r0 + (r1 - r0) * u;
|
||||
const e = Math.min(u, 1 - u) / cap;
|
||||
return e >= 1 ? r : r * Math.sqrt(Math.max(0, 1 - (1 - e) * (1 - e)));
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------ gears, boxes, tubes
|
||||
// a spur gear around +z: `teeth` teeth between rRoot and rOut, `width` thick, a bore of holeR, lightening holes
|
||||
export function gearGeo(teeth, rOut, rRoot, width, holeR = 0, spokes = 0) {
|
||||
const sh = new THREE.Shape();
|
||||
for (let i = 0; i < teeth; i++) {
|
||||
const a0 = (i / teeth) * Math.PI * 2;
|
||||
const da = (Math.PI * 2) / teeth;
|
||||
const pts = [
|
||||
[rRoot, a0],
|
||||
[rRoot, a0 + da * 0.18],
|
||||
[rOut, a0 + da * 0.32],
|
||||
[rOut, a0 + da * 0.6],
|
||||
[rRoot, a0 + da * 0.74],
|
||||
];
|
||||
pts.forEach(([r, a], k) => (i === 0 && k === 0 ? sh.moveTo(r * Math.cos(a), r * Math.sin(a)) : sh.lineTo(r * Math.cos(a), r * Math.sin(a))));
|
||||
}
|
||||
sh.closePath();
|
||||
if (holeR) {
|
||||
const h = new THREE.Path();
|
||||
h.absarc(0, 0, holeR, 0, Math.PI * 2, true);
|
||||
sh.holes.push(h);
|
||||
}
|
||||
// round lightening holes between the bore and the rim
|
||||
if (spokes) {
|
||||
const rc = (holeR + rRoot) / 2;
|
||||
const rh = Math.min((rRoot - holeR) * 0.3, (Math.PI * rc) / spokes * 0.55);
|
||||
for (let k = 0; k < spokes; k++) {
|
||||
const a = (k / spokes) * Math.PI * 2;
|
||||
const h = new THREE.Path();
|
||||
h.absarc(Math.cos(a) * rc, Math.sin(a) * rc, rh, 0, Math.PI * 2, true);
|
||||
sh.holes.push(h);
|
||||
}
|
||||
}
|
||||
const bev = Math.min(width * 0.18, (rOut - rRoot) * 0.3);
|
||||
const g = new THREE.ExtrudeGeometry(sh, {depth: width - bev * 2, bevelEnabled: true, bevelThickness: bev, bevelSize: bev * 0.8, bevelSegments: 1, curveSegments: 10});
|
||||
g.translate(0, 0, -(width - bev * 2) / 2);
|
||||
return g;
|
||||
}
|
||||
// the same gear with its axis along +x
|
||||
export const gearX = (...a) => gearGeo(...a).rotateY(Math.PI / 2);
|
||||
|
||||
export const rbox = (w, h, d, r = 0.01) => new RoundedBoxGeometry(w, h, d, 3, Math.min(r, w / 2.01, h / 2.01, d / 2.01));
|
||||
export const cylX = (r0, r1, len, seg = 32) => new THREE.CylinderGeometry(r1, r0, len, seg).rotateZ(-Math.PI / 2);
|
||||
export const cylZ = (r0, r1, len, seg = 32) => new THREE.CylinderGeometry(r1, r0, len, seg).rotateX(Math.PI / 2);
|
||||
|
||||
/** A cable or rod through points (Vector3 or arrays), radius r. */
|
||||
export function tube(points, r, tubular = 64, radial = 10, closed = false) {
|
||||
const pts = points.map((p) => (p.isVector3 ? p : new V3(...p)));
|
||||
return new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts, closed, 'catmullrom', 0.5), tubular, r, radial, closed);
|
||||
}
|
||||
|
||||
/** A tube through points whose radius runs from r0 to r1 along its length (a stinger, a finger, a tapered link). */
|
||||
export function taperTube(points, r0, r1, tubular = 48, radial = 14, pow = 1) {
|
||||
const pts = points.map((p) => (p.isVector3 ? p : new V3(...p)));
|
||||
const curve = new THREE.CatmullRomCurve3(pts, false, 'catmullrom', 0.5);
|
||||
const g = new THREE.TubeGeometry(curve, tubular, 1, radial, false);
|
||||
const pos = g.attributes.position;
|
||||
const nor = g.attributes.normal;
|
||||
const c = new V3();
|
||||
for (let i = 0; i <= tubular; i++) {
|
||||
const u = i / tubular;
|
||||
const r = r1 + (r0 - r1) * Math.pow(1 - u, pow);
|
||||
curve.getPointAt(u, c);
|
||||
for (let j = 0; j <= radial; j++) {
|
||||
const k = i * (radial + 1) + j;
|
||||
pos.setXYZ(k, c.x + nor.getX(k) * r, c.y + nor.getY(k) * r, c.z + nor.getZ(k) * r);
|
||||
}
|
||||
}
|
||||
pos.needsUpdate = true;
|
||||
g.computeVertexNormals();
|
||||
return g;
|
||||
}
|
||||
|
||||
/** A coil spring along +x: radius R, wire r, `turns` over len. */
|
||||
export function coil(R, r, turns, len, seg = 240) {
|
||||
const pts = [];
|
||||
for (let i = 0; i <= seg; i++) {
|
||||
const u = i / seg;
|
||||
const a = u * turns * Math.PI * 2;
|
||||
pts.push(new V3(u * len, Math.cos(a) * R, Math.sin(a) * R));
|
||||
}
|
||||
return new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), seg, r, 8, false);
|
||||
}
|
||||
|
||||
export const merge = (geos) => mergeGeometries(geos.map((g) => (g.index ? g.toNonIndexed() : g)).map((g) => {
|
||||
// mergeGeometries wants identical attribute sets: keep position and normal only
|
||||
const o = new THREE.BufferGeometry();
|
||||
o.setAttribute('position', g.attributes.position);
|
||||
o.setAttribute('normal', g.attributes.normal);
|
||||
return o;
|
||||
}));
|
||||
|
||||
/** Put a mesh of geo/mat at (x, y, z) into parent; returns it. Every mesh casts and takes shadows. */
|
||||
export function put(parent, geo, mat, x = 0, y = 0, z = 0) {
|
||||
const m = new THREE.Mesh(geo, mat);
|
||||
m.position.set(x, y, z);
|
||||
m.castShadow = true;
|
||||
m.receiveShadow = true;
|
||||
parent.add(m);
|
||||
return m;
|
||||
}
|
||||
|
||||
/** Rotate an object so its local +x points along dir. */
|
||||
export function aimX(obj, dir) {
|
||||
obj.quaternion.setFromUnitVectors(new V3(1, 0, 0), dir.clone().normalize());
|
||||
return obj;
|
||||
}
|
||||
|
||||
/** Instances of one geometry at a list of matrices (casts and takes shadows). */
|
||||
export function instances(parent, geo, mat, mats) {
|
||||
const im = new THREE.InstancedMesh(geo, mat, mats.length);
|
||||
mats.forEach((m, i) => im.setMatrixAt(i, m));
|
||||
im.castShadow = true;
|
||||
im.receiveShadow = true;
|
||||
parent.add(im);
|
||||
return im;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Score for the THERAPHOS TH-8 simulator film (entry tarantula-film; the SALTICUS JS-8 score, robospider-sim), after the scorpion's (roboscorp-shared/
|
||||
score_sim.py): a bed for the whole film (D minor, 100 bpm, e-piano, bass, soft drums and a pad on the same changes)
|
||||
at one level, a quiet click on every button press, and short quiet accents on the spider's own moves: soft servo
|
||||
ticks under the steps, a tension rise in each crouch, a whoosh on each take-off and a thud on the first landing,
|
||||
thread ticks as the lenses unscrew and screw back, servo blips down the front leg, a lift of air as the canopy opens
|
||||
and the head's plates lift, two fang snaps, a whoosh into the explode and three clicks as it seats, and the one low
|
||||
impact of the film on the last landing.
|
||||
|
||||
python run_sfx.py sims/tarantula-shared/score.py
|
||||
|
||||
Every cue comes from the script in robospider-sim/timeline.json, with the offsets inside each act taken from tour.js
|
||||
(ACT, the two jumps J1 and J2, the walk keys, the explode out 0.2-1.8 s and home 0-1.0 s).
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
|
||||
from sfx.score_kit import airy, bed, chords, hz # noqa: E402
|
||||
from sfx.synth import blip, click, envelope, impact, pad, whoosh # noqa: E402
|
||||
|
||||
TIMELINE = os.environ.get("TL", "../tarantula-film/timeline.json")
|
||||
OUT = os.environ.get("OUT", os.path.join(os.environ.get("CUTAWAY_OUT", "cutaway-out"), "tarantula-score.wav"))
|
||||
TARGET_LUFS = -14.0
|
||||
SEED = 37
|
||||
|
||||
CHORDS = chords("Dm9:D3 F3 A3 C4 E4/D2", "A#maj7:A#2 D3 F3 A3/A#1", "Gm9:G2 A#2 D3 F3 A3/G1", "A7sus:A2 D3 E3 G3/A1")
|
||||
MOTIF = [(0.5, hz("A5")), (1.5, hz("F5")), (2.5, hz("E5"))]
|
||||
STRIDE = 2.7
|
||||
# the first jump, fixed in tour.js: crouch, lift-off, touch-down
|
||||
J1 = (1.5, 1.98, 2.55)
|
||||
|
||||
|
||||
def steps(mix, t0, t1, level=0.012):
|
||||
"""Soft servo ticks, two per stride (one per group of four feet landing), panned with the stepping side."""
|
||||
t = t0
|
||||
i = 0
|
||||
while t < t1:
|
||||
mix.put(t, click(1500 + 120 * (i % 3), 0.02), level, pan=-0.25 if i % 2 else 0.25)
|
||||
t += 0.5 / STRIDE
|
||||
i += 1
|
||||
|
||||
|
||||
def jump(mix, t0, tl, ta, last=False):
|
||||
"""A crouch that winds up, the take-off whoosh, the landing: a soft thud, or the film's one impact."""
|
||||
mix.put(t0, airy(tl - t0, 300, 1100, 0.8), 0.022)
|
||||
mix.put(tl - 0.04, whoosh(0.5, 600, 2800, peak=0.45), 0.045)
|
||||
for i in range(4):
|
||||
mix.put(tl - 0.1 + 0.02 * i, click(1800 + 200 * i, 0.015), 0.025, pan=-0.3 + 0.2 * i)
|
||||
if last:
|
||||
mix.put(ta, impact(1.2), 0.22)
|
||||
else:
|
||||
mix.put(ta, click(900, 0.05), 0.07)
|
||||
mix.put(ta + 0.005, blip(hz("D3"), 0.25, 0.08), 0.06)
|
||||
for i in range(3):
|
||||
mix.put(ta + 0.08 + 0.05 * i, click(2200 - 150 * i, 0.015), 0.025, pan=-0.2 + 0.2 * i)
|
||||
|
||||
|
||||
def snap(mix, t, level=0.045, pan=0.0):
|
||||
"""A fang snapping shut: a hard click with a short tonal knock under it."""
|
||||
mix.put(t, click(2600, 0.03), level, pan=pan)
|
||||
mix.put(t + 0.004, blip(hz("D5"), 0.12, 0.04), level * 0.35, pan=pan)
|
||||
|
||||
|
||||
def score(mix, tl):
|
||||
dur = tl["duration"]
|
||||
left, right, low, drums = bed(dur, 100, CHORDS, MOTIF, motif_voice="blip", kicks=(0, 2.5), snares=(1, 3), hats=8, swing=0.08, keys_vel=0.75, keys_lp=3800)
|
||||
mix.put_stereo(0, left, right, 0.13)
|
||||
mix.put(0, low, 0.13)
|
||||
mix.put(0, drums, 0.05)
|
||||
bar = 4 * 60 / 100
|
||||
changes = [(0.12 + b * bar, [f for f in CHORDS[b % len(CHORDS)][0][:4]]) for b in range(int(dur / bar) + 1)]
|
||||
pl, pr = pad(dur, changes, volume=envelope([(0, 0), (1.0, 1), (dur - 1.6, 1), (dur, 0)]), detune=0.8, tremolo=0.18, xfade=0.5)
|
||||
mix.put_stereo(0, pl, pr, 0.07)
|
||||
|
||||
acts = {e["act"]: e["t"] for e in tl["script"]}
|
||||
# the run-in and the first jump at the camera
|
||||
steps(mix, 0.0, 1.9)
|
||||
jump(mix, *J1)
|
||||
|
||||
for e in tl["script"]:
|
||||
t, act = e["t"], e["act"]
|
||||
mix.put(t, click(2400, 0.025), 0.055, pan=0.45)
|
||||
if act == "eyes":
|
||||
for i, dt in enumerate((0.35, 0.5, 0.65, 0.8, 0.95)):
|
||||
mix.put(t + dt, click(3300 - 180 * i, 0.016), 0.032, pan=0.1)
|
||||
mix.put(t + 0.9, blip(hz("A6"), 0.2, 0.06), 0.018)
|
||||
for i, dt in enumerate((1.95, 2.1, 2.25, 2.4)):
|
||||
mix.put(t + dt, click(2600 + 180 * i, 0.016), 0.028, pan=0.1)
|
||||
elif act == "leg":
|
||||
mix.put(t + 0.05, airy(0.5, 600, 1500, 0.5), 0.016, pan=0.35)
|
||||
for i, dt in enumerate((0.55, 0.75, 0.95, 1.15, 1.35)):
|
||||
mix.put(t + dt, blip(hz("D6") * 2 ** (i / 6), 0.18, 0.06), 0.02, pan=0.35)
|
||||
mix.put(t + 2.5, click(2000, 0.03), 0.05, pan=0.35)
|
||||
elif act == "abdomen":
|
||||
mix.put(t + 0.3, airy(1.1, 450, 1500, 0.6), 0.026, pan=-0.2)
|
||||
for i, dt in enumerate((0.7, 0.85, 1.0)):
|
||||
mix.put(t + dt, click(2800 - 200 * i, 0.018), 0.026, pan=-0.2)
|
||||
mix.put(t + 2.5, click(2100, 0.03), 0.055, pan=-0.2)
|
||||
elif act == "head":
|
||||
mix.put(t + 0.3, airy(1.0, 500, 1700, 0.6), 0.024)
|
||||
snap(mix, t + 0.95, 0.04, -0.15)
|
||||
snap(mix, t + 1.45, 0.04, 0.15)
|
||||
# the flared fangs snapping shut as the head closes
|
||||
snap(mix, t + 2.38, 0.05, 0.0)
|
||||
mix.put(t + 2.45, click(2100, 0.03), 0.05)
|
||||
elif act == "exploded":
|
||||
mix.put(t + 0.2, airy(1.4, 500, 2600, 0.7), 0.032, pan=-0.15)
|
||||
mix.put(t + 0.25, blip(hz("D6"), 0.3, 0.1), 0.025)
|
||||
elif act == "assemble":
|
||||
mix.put(t, airy(1.0, 2200, 600, 0.5), 0.02, pan=0.15)
|
||||
for i, dt in enumerate((0.6, 0.8, 1.0)):
|
||||
mix.put(t + dt, click(2000 + 300 * i, 0.03), 0.05, pan=-0.3 + 0.3 * i)
|
||||
mix.put(t + 1.15, whoosh(0.5, 800, 2200, peak=0.5), 0.022)
|
||||
elif act == "hero":
|
||||
steps(mix, t + 0.4, acts.get("jump", t + 3.0) + 0.4)
|
||||
elif act == "jump":
|
||||
jump(mix, t + 0.25, t + 0.72, t + 1.3, last=True)
|
||||
@@ -0,0 +1,100 @@
|
||||
// THERAPHOS TH-8, the approved tarantula film re-shot on the green page (entry tarantula-film). Everything that
|
||||
// moves comes from tour.js unchanged (the run-in, the gait, both jumps, every assembly, every camera, the timing); what
|
||||
// is new is only the look: green for orange on the spider and its glows, white paper with mint haze, and the green page
|
||||
// from ../green in place of the old console, the subject shifted by SHIFT into its 3D window.
|
||||
import {runSim} from '../kit/runtime.js';
|
||||
import {createConsole} from '../green/console.js';
|
||||
import {makeCursor, makeLabels, nice, ORANGE_TO, PAPER_GREEN, retint, SHIFT} from '../green/look.js';
|
||||
import {PAL} from './parts.js';
|
||||
import {buildSpider, FLOOR_Y} from './spider.js';
|
||||
import {createStage, PAPER} from './stage.js';
|
||||
import {makeTour, REACH} from './tour.js';
|
||||
|
||||
const D2R = Math.PI / 180;
|
||||
|
||||
Object.assign(PAL, {orange: ORANGE_TO});
|
||||
Object.assign(PAPER, PAPER_GREEN);
|
||||
|
||||
const ACTS = [['eyes', 'Optics'], ['leg', 'Front leg'], ['abdomen', 'Abdomen'], ['head', 'Head'], ['exploded', 'Teardown'], ['hero', 'Release'], ['jump', 'Jump']];
|
||||
const PAGE = {
|
||||
name: 'Theraphos',
|
||||
code: 'TH-8',
|
||||
title: 'Robotic Tarantula, Taken Apart',
|
||||
date: '2026-11-6',
|
||||
nav: [['overview', 'Overview'], ...ACTS],
|
||||
pills: ACTS,
|
||||
sub: {
|
||||
overview: ['8 legs · 32 joints', '2 main + 6 side optics'],
|
||||
eyes: ['Main optic Ø 46 mm', 'Iris: 10 blades, f/1.4'],
|
||||
leg: ['Coxa servo, yaw ±45°', 'Tibia piston, 60 mm'],
|
||||
abdomen: ['Glass cage, 5 bands', '20 lit coils'],
|
||||
head: ['Brow plate lifts 40 mm', 'Fangs flare 40°'],
|
||||
exploded: ['Every part apart', 'Turntable 360°'],
|
||||
hero: ['Back on 8 feet', 'Crouch armed'],
|
||||
jump: ['Jump at the lens', 'Legs tucked'],
|
||||
},
|
||||
cards: [{k: 'Gait', kind: 'wave', unit: 'Hz'}, {k: 'Body load', kind: 'bar', unit: '%'}, {k: 'Leg servos', kind: 'bars', n: 8}, {k: 'Battery', kind: 'bar', unit: '%'}],
|
||||
};
|
||||
const TEXT = {'MAIN OPTIC R': ['Main optic'], 'SIDE OPTIC': ['Side optics'], 'GLOW COILS': ['Lit coils'], 'KNEE RING': ['Knee ring', 'lit ring, 2.4 N·m'], 'CLAW TIP': ['Claw tip', 'lit, 14 mm']};
|
||||
const STATUS = {'RUN-IN': 'Running in', WALK: 'Walking', STANDING: 'Standing', CROUCH: 'Crouching', AIRBORNE: 'Airborne', LANDING: 'Landing', TEARDOWN: 'Teardown', REASSEMBLY: 'Reassembly', 'OPTICS OPEN': 'Optics open', 'LEG R1 APART': 'Front leg apart', 'LEG R1 LIFT': 'Front leg up', 'ABDOMEN OPEN': 'Abdomen open', 'HEAD OPEN': 'Head open'};
|
||||
|
||||
export function makeTarantulaGreen(TL) {
|
||||
const FILM = TL.film ?? TL.duration;
|
||||
const SPEED = TL.duration / FILM;
|
||||
const T = makeTour(TL);
|
||||
return async ({canvas, capture}) => {
|
||||
const app = document.getElementById('app');
|
||||
const st = createStage({canvas, floorY: FLOOR_Y, guides: {centre: [-0.3, 0.1, 0], scale: 1.3}});
|
||||
const sp = buildSpider();
|
||||
st.addBee(sp);
|
||||
retint(sp.root);
|
||||
sp.root.rotation.order = 'YXZ';
|
||||
const ui = createConsole(app, PAGE);
|
||||
const cursorAt = makeCursor(ui, T.SCRIPT);
|
||||
const labels = makeLabels(st, sp.anchors, TEXT);
|
||||
const fit = () => (app.style.transform = `scale(${Math.min(innerWidth / 1600, innerHeight / 900)})`);
|
||||
const resize = () => {
|
||||
fit();
|
||||
st.resize(1600, 900, capture ? devicePixelRatio || 1 : Math.min(devicePixelRatio || 1, 2));
|
||||
};
|
||||
resize();
|
||||
window.SP = {st, sp, T};
|
||||
return {
|
||||
resize,
|
||||
render(tf) {
|
||||
// a demo plays the scene's timeline a little faster: TL.film seconds of film for TL.duration of scene
|
||||
const t = tf * SPEED;
|
||||
const s = T.stateAt(t);
|
||||
const b = s.body;
|
||||
sp.root.position.set(b.x, b.y, b.z);
|
||||
sp.root.rotation.set(b.roll, b.yaw + s.turn * D2R, b.pitch);
|
||||
sp.root.updateMatrixWorld(true);
|
||||
sp.pose({explode: s.explode, spinT: s.spinT, spinA: s.spinA, t, sub: s.sub, feet: s.feet, tuck: s.tuck, palp: s.palp, reach: REACH});
|
||||
retint(sp.root);
|
||||
const c = s.cam;
|
||||
st.frame({...c, az: c.az * D2R, el: c.el * D2R, sx: (c.sx ?? 0) + SHIFT[0], sy: (c.sy ?? 0) + SHIFT[1]}, {guides: s.guides});
|
||||
const tel = T.telemetry(t, s);
|
||||
const v = s.view;
|
||||
const amp = tel.walking ? 0.85 : 0.12;
|
||||
const wave = [];
|
||||
for (let i = 0; i <= 90; i++) wave.push(amp * Math.sin(2 * Math.PI * Math.max(0.6, tel.freq) * (t - 1.2 + (i / 90) * 1.2)));
|
||||
const lift = Math.min(1, tel.lift);
|
||||
const bat = 0.861 - 0.0022 * t;
|
||||
ui.update({
|
||||
time: tf,
|
||||
dur: FILM,
|
||||
status: STATUS[tel.status] ?? nice(tel.status),
|
||||
cards: [{v: tel.freq.toFixed(1), wave}, {v: Math.round(lift * 100), bar: lift}, {bars: tel.servos}, {v: Math.round(bat * 100), bar: bat}],
|
||||
apart: Math.round(Math.max(s.open?.[v] ?? 0, s.explode) * 100),
|
||||
view: v === 'intro' ? 'overview' : v,
|
||||
callouts: labels(tel.labelSet),
|
||||
cursor: cursorAt(t),
|
||||
});
|
||||
return {};
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export const runTarantulaGreen = (TL, title = 'tarantula-film') =>
|
||||
runSim({duration: TL.film ?? TL.duration, fps: 60, theme: 'light', hud: {enabled: false, title, subtitle: ''}, director: {enabled: false}, watermark: ''}, makeTarantulaGreen(TL));
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,341 @@
|
||||
// The robotic spider's stage, copied from the scorpion v2's (roboscorp-shared/stage.js, itself the bee's) with an optional fov per frame: a near-white product studio. A warm
|
||||
// paper backdrop with no horizon, a soft shadow pooled on the floor under the scorpion (its silhouette seen from
|
||||
// below, blurred wide, plus a tighter pass for what stands on the floor), a softbox environment for the clear coat to
|
||||
// catch, a key with VSM self-shadows, a rim and a fill, GTAO kept off the backdrop and the clear parts, MSAA. The tone curve is linear up to 0.8 and rolls off
|
||||
// above, hue preserved; the backdrop writes the inverse of that curve, so the paper lands on its exact colour and the
|
||||
// floor shadow darkens it as drawn. frame(cam, ops) draws one frame; cam = {tx, ty, tz, az, el, d, sx, sy}.
|
||||
import * as THREE from 'three';
|
||||
import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';
|
||||
import {GTAOPass} from 'three/addons/postprocessing/GTAOPass.js';
|
||||
import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';
|
||||
import {FullScreenQuad, Pass} from 'three/addons/postprocessing/Pass.js';
|
||||
import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';
|
||||
import {buildGuides} from './guides.js';
|
||||
|
||||
const V3 = THREE.Vector3;
|
||||
// the paper: top, middle, the floor band (sRGB), and the shadow's tint
|
||||
export const PAPER = {top: '#fefcf8', mid: '#fcf9f3', low: '#f5efe7', shadow: '#c9bcae'};
|
||||
const KNEE = 0.8;
|
||||
THREE.ShaderChunk.tonemapping_pars_fragment = THREE.ShaderChunk.tonemapping_pars_fragment.replace(
|
||||
'vec3 CustomToneMapping( vec3 color ) { return color; }',
|
||||
`vec3 CustomToneMapping( vec3 color ) {
|
||||
color *= toneMappingExposure;
|
||||
float p = max( color.r, max( color.g, color.b ) );
|
||||
if ( p <= ${KNEE.toFixed(2)} ) return color;
|
||||
float np = ${KNEE.toFixed(2)} + ${(1 - KNEE).toFixed(2)} * ( 1.0 - exp( -( p - ${KNEE.toFixed(2)} ) / ${(1 - KNEE).toFixed(2)} ) );
|
||||
return color * ( np / p );
|
||||
}`,
|
||||
);
|
||||
export const BEE_LAYER = 1;
|
||||
// the scorpion is wider than the bee: the key's shadow box and the floor shadow's window grow with it
|
||||
const SPAN = 4.6;
|
||||
|
||||
const BACK_VERT = /* glsl */ `varying vec3 vW;
|
||||
void main(){
|
||||
#ifdef SCREEN
|
||||
vW = vec3(0.0); gl_Position = vec4(position.xy, 0.99999, 1.0);
|
||||
#else
|
||||
vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w;
|
||||
#endif
|
||||
}`;
|
||||
const BACK_FRAG = /* glsl */ `uniform vec3 uTop, uMid, uLow, uTint; uniform vec2 uRes;
|
||||
uniform sampler2D tSoft, tNear; uniform mat4 uVP; uniform float uSoft, uNear;
|
||||
varying vec3 vW;
|
||||
vec3 paper(float y){ return y > 0.42 ? mix(uMid, uTop, smoothstep(0.42, 1.0, y)) : mix(uLow, uMid, smoothstep(0.0, 0.42, y)); }
|
||||
// the inverse of the tone curve's shoulder: what to write so the output lands on c
|
||||
vec3 untone(vec3 c){
|
||||
float p = max(c.r, max(c.g, c.b));
|
||||
if (p <= ${KNEE.toFixed(2)}) return c;
|
||||
float pin = ${KNEE.toFixed(2)} - ${(1 - KNEE).toFixed(2)} * log(max(1e-4, 1.0 - (p - ${KNEE.toFixed(2)}) / ${(1 - KNEE).toFixed(2)}));
|
||||
return c * (pin / p);
|
||||
}
|
||||
float tap(sampler2D t, vec3 w){
|
||||
vec4 c = uVP * vec4(w, 1.0);
|
||||
vec2 uv = c.xy / c.w * 0.5 + 0.5;
|
||||
if (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0) return 0.0;
|
||||
vec2 e = smoothstep(0.0, 0.08, uv) * smoothstep(0.0, 0.08, 1.0 - uv);
|
||||
return texture2D(t, uv).r * e.x * e.y;
|
||||
}
|
||||
void main(){
|
||||
vec3 c = paper(gl_FragCoord.y / uRes.y);
|
||||
#ifndef SCREEN
|
||||
float s = clamp(tap(tSoft, vW) * uSoft + tap(tNear, vW) * uNear, 0.0, 1.0);
|
||||
c = mix(c, c * uTint, s);
|
||||
#endif
|
||||
gl_FragColor = vec4(untone(c), 1.0);
|
||||
}`;
|
||||
const QUAD_VERT = /* glsl */ `varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;
|
||||
const BLUR_FRAG = /* glsl */ `uniform sampler2D tSrc; uniform vec2 uDir; varying vec2 vUv;
|
||||
void main(){
|
||||
float w[5]; w[0] = 0.2270270270; w[1] = 0.1945945946; w[2] = 0.1216216216; w[3] = 0.0540540541; w[4] = 0.0162162162;
|
||||
vec4 c = texture2D(tSrc, vUv) * w[0];
|
||||
for (int i = 1; i < 5; i++) { c += texture2D(tSrc, vUv + uDir * float(i)) * w[i]; c += texture2D(tSrc, vUv - uDir * float(i)) * w[i]; }
|
||||
gl_FragColor = c;
|
||||
}`;
|
||||
// silhouette from below: everything counts, what hangs low counts more
|
||||
const SIL_VERT = /* glsl */ `varying float vH; uniform float uFloor; void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vH = w.y - uFloor; gl_Position = projectionMatrix * viewMatrix * w; }`;
|
||||
const SIL_FRAG = /* glsl */ `varying float vH; uniform float uFar, uBase; void main(){ float k = 1.0 - clamp(vH / uFar, 0.0, 1.0); gl_FragColor = vec4(uBase + (1.0 - uBase) * k * k, 0.0, 0.0, 1.0); }`;
|
||||
|
||||
export function createStage({canvas, floorY = -1.55, guides: guideOpts = {}}) {
|
||||
const renderer = new THREE.WebGLRenderer({canvas, antialias: false, preserveDrawingBuffer: true, powerPreference: 'high-performance'});
|
||||
renderer.toneMapping = THREE.CustomToneMapping;
|
||||
renderer.toneMappingExposure = 1.0;
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
renderer.shadowMap.enabled = true;
|
||||
renderer.shadowMap.type = THREE.VSMShadowMap;
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(30, 16 / 9, 0.05, 80);
|
||||
const composer = new EffectComposer(renderer, new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: 8}));
|
||||
composer.addPass(new RenderPass(scene, camera));
|
||||
const gtao = new GTAOPass(scene, camera, 4, 4);
|
||||
gtao.output = GTAOPass.OUTPUT.Default;
|
||||
gtao.blendIntensity = 1.0;
|
||||
gtao.updateGtaoMaterial({radius: 0.13, distanceExponent: 1.6, thickness: 0.9, scale: 1.0, samples: 16, distanceFallOff: 1.0, screenSpaceRadius: false});
|
||||
gtao.updatePdMaterial({lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 5, rings: 2, samples: 16});
|
||||
class Toggle extends Pass {
|
||||
constructor(fn) {
|
||||
super();
|
||||
this.needsSwap = false;
|
||||
this.fn = fn;
|
||||
}
|
||||
render() {
|
||||
this.fn();
|
||||
}
|
||||
}
|
||||
// the backdrop, the guides and every clear part stay out of the AO pass
|
||||
const skip = [];
|
||||
// extra: meshes skipped only while a mode asks (the shells under x-ray)
|
||||
let extra = [];
|
||||
const aoSkip = (on) => {
|
||||
for (const o of skip) o.visible = on && o.userData.show !== false;
|
||||
for (const o of extra) o.visible = on;
|
||||
};
|
||||
composer.addPass(new Toggle(() => aoSkip(false)));
|
||||
composer.addPass(gtao);
|
||||
composer.addPass(new Toggle(() => aoSkip(true)));
|
||||
composer.addPass(new OutputPass());
|
||||
|
||||
// ------------------------------------------------------------ the studio the clear coat reflects
|
||||
{
|
||||
const env = new THREE.Scene();
|
||||
env.background = new THREE.Color('#d8d4ce');
|
||||
const box = (w, h, pos, k, tint = [1, 0.985, 0.96]) => {
|
||||
const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({color: new THREE.Color(...tint).multiplyScalar(k), side: THREE.DoubleSide}));
|
||||
m.position.copy(pos);
|
||||
m.lookAt(0, 0, 0);
|
||||
env.add(m);
|
||||
};
|
||||
box(16, 10, new V3(-4, 16, 6), 3.2); // the big top box
|
||||
box(3, 16, new V3(-15, 4, 8), 2.6); // a tall strip, left front
|
||||
box(3, 16, new V3(14, 5, -6), 2.0, [0.96, 0.98, 1]); // the rim strip behind
|
||||
box(20, 3, new V3(2, 2, 16), 1.5); // a low card in front
|
||||
box(8, 8, new V3(10, 2, 12), 1.1); // fill, right front
|
||||
const g = new THREE.Mesh(new THREE.CircleGeometry(40, 32), new THREE.MeshBasicMaterial({color: '#e9e3da', side: THREE.DoubleSide}));
|
||||
g.rotation.x = -Math.PI / 2;
|
||||
g.position.y = -3;
|
||||
env.add(g);
|
||||
const pm = new THREE.PMREMGenerator(renderer);
|
||||
scene.environment = pm.fromScene(env, 0.025).texture;
|
||||
scene.environmentIntensity = 0.62;
|
||||
pm.dispose();
|
||||
}
|
||||
const KEY = new V3(-0.3, 0.86, 0.55).normalize();
|
||||
const key = new THREE.DirectionalLight('#fffaf3', 3.0);
|
||||
key.castShadow = true;
|
||||
Object.assign(key.shadow.camera, {left: -SPAN, right: SPAN, top: SPAN, bottom: -SPAN, near: 1, far: 18});
|
||||
key.shadow.mapSize.set(4096, 4096);
|
||||
key.shadow.radius = 6;
|
||||
key.shadow.blurSamples = 20;
|
||||
key.shadow.bias = -0.0005;
|
||||
key.shadow.normalBias = 0.01;
|
||||
scene.add(key, key.target);
|
||||
const rim = new THREE.DirectionalLight('#f2f6ff', 1.1);
|
||||
rim.position.set(3, 3, -5);
|
||||
scene.add(rim);
|
||||
const fill = new THREE.DirectionalLight('#fff6ec', 0.3);
|
||||
fill.position.set(4, -1, 5);
|
||||
scene.add(fill);
|
||||
scene.add(new THREE.HemisphereLight('#ffffff', '#d9cfc2', 0.32));
|
||||
|
||||
// ------------------------------------------------------------ backdrop: the paper behind, the floor with its shadow
|
||||
const lin = (hex) => new THREE.Color(hex);
|
||||
const backU = {
|
||||
uTop: {value: lin(PAPER.top)},
|
||||
uMid: {value: lin(PAPER.mid)},
|
||||
uLow: {value: lin(PAPER.low)},
|
||||
uTint: {value: lin(PAPER.shadow)},
|
||||
uRes: {value: new THREE.Vector2(1, 1)},
|
||||
tSoft: {value: null},
|
||||
tNear: {value: null},
|
||||
uVP: {value: new THREE.Matrix4()},
|
||||
uSoft: {value: 0.42},
|
||||
uNear: {value: 0.55},
|
||||
};
|
||||
const paper = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.ShaderMaterial({vertexShader: BACK_VERT, fragmentShader: BACK_FRAG, uniforms: backU, defines: {SCREEN: ''}, depthWrite: false, depthTest: false}));
|
||||
paper.frustumCulled = false;
|
||||
paper.renderOrder = -10;
|
||||
scene.add(paper);
|
||||
const floor = new THREE.Mesh(new THREE.PlaneGeometry(200, 200).rotateX(-Math.PI / 2), new THREE.ShaderMaterial({vertexShader: BACK_VERT, fragmentShader: BACK_FRAG, uniforms: backU, depthWrite: false}));
|
||||
floor.position.y = floorY;
|
||||
floor.renderOrder = -9;
|
||||
scene.add(floor);
|
||||
skip.push(paper, floor);
|
||||
|
||||
// the floor shadow: the bee from below into two targets, one blurred wide, one tight
|
||||
const SR = 512;
|
||||
const HALF = SPAN + 0.8;
|
||||
const mkRT = () => new THREE.WebGLRenderTarget(SR, SR, {type: THREE.HalfFloatType});
|
||||
const soft = [mkRT(), mkRT()];
|
||||
const near = [mkRT(), mkRT()];
|
||||
backU.tSoft.value = soft[0].texture;
|
||||
backU.tNear.value = near[0].texture;
|
||||
const shCam = new THREE.OrthographicCamera(-HALF, HALF, HALF, -HALF, 0, 6);
|
||||
shCam.up.set(0, 0, -1);
|
||||
shCam.layers.set(BEE_LAYER);
|
||||
const silU = {uFloor: {value: floorY}, uFar: {value: 1.6}, uBase: {value: 1.0}};
|
||||
const silMat = new THREE.ShaderMaterial({vertexShader: SIL_VERT, fragmentShader: SIL_FRAG, uniforms: silU, side: THREE.DoubleSide});
|
||||
const blurMat = new THREE.ShaderMaterial({vertexShader: QUAD_VERT, fragmentShader: BLUR_FRAG, uniforms: {tSrc: {value: null}, uDir: {value: new THREE.Vector2()}}, depthTest: false, depthWrite: false});
|
||||
const blurQuad = new FullScreenQuad(blurMat);
|
||||
const blur = ([a, b], px, passes) => {
|
||||
for (let i = 0; i < passes; i++) {
|
||||
blurMat.uniforms.tSrc.value = a.texture;
|
||||
blurMat.uniforms.uDir.value.set(px / SR, 0);
|
||||
renderer.setRenderTarget(b);
|
||||
blurQuad.render(renderer);
|
||||
blurMat.uniforms.tSrc.value = b.texture;
|
||||
blurMat.uniforms.uDir.value.set(0, px / SR);
|
||||
renderer.setRenderTarget(a);
|
||||
blurQuad.render(renderer);
|
||||
}
|
||||
};
|
||||
const black = new THREE.Color(0, 0, 0);
|
||||
const prevClear = new THREE.Color();
|
||||
const floorShadow = (c) => {
|
||||
shCam.position.set(c.x, floorY - 0.01, c.z);
|
||||
shCam.lookAt(c.x, floorY + 1, c.z);
|
||||
shCam.updateMatrixWorld();
|
||||
shCam.updateProjectionMatrix();
|
||||
renderer.getClearColor(prevClear);
|
||||
const prevA = renderer.getClearAlpha();
|
||||
const prevOv = scene.overrideMaterial;
|
||||
const prevSh = renderer.shadowMap.autoUpdate;
|
||||
renderer.shadowMap.autoUpdate = false;
|
||||
renderer.setClearColor(black, 1);
|
||||
scene.overrideMaterial = silMat;
|
||||
for (const [rt, base, far, px, passes] of [
|
||||
[soft, 1.0, 1.0, 3.2, 4],
|
||||
[near, 0.0, 1.5, 1.2, 2],
|
||||
]) {
|
||||
silU.uBase.value = base;
|
||||
silU.uFar.value = far;
|
||||
renderer.setRenderTarget(rt[0]);
|
||||
renderer.clear();
|
||||
renderer.render(scene, shCam);
|
||||
blur(rt, px, passes);
|
||||
}
|
||||
scene.overrideMaterial = prevOv;
|
||||
renderer.shadowMap.autoUpdate = prevSh;
|
||||
renderer.setRenderTarget(null);
|
||||
renderer.setClearColor(prevClear, prevA);
|
||||
backU.uVP.value.multiplyMatrices(shCam.projectionMatrix, shCam.matrixWorldInverse);
|
||||
};
|
||||
|
||||
// a dark studio for the camera lenses only: black all round with a few hard softboxes, so the glass reads deep
|
||||
// black with crisp highlights instead of mirroring the pale studio as a grey haze
|
||||
const lensEnv = (() => {
|
||||
const env = new THREE.Scene();
|
||||
env.background = new THREE.Color('#050506');
|
||||
const box = (w, h, dir, k) => {
|
||||
const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({color: new THREE.Color(1, 0.98, 0.95).multiplyScalar(k), side: THREE.DoubleSide}));
|
||||
m.position.copy(new V3(...dir).normalize().multiplyScalar(15));
|
||||
m.lookAt(0, 0, 0);
|
||||
env.add(m);
|
||||
};
|
||||
box(10, 6, [-0.2, 1, 0.2], 6); // overhead
|
||||
box(1.6, 12, [-0.85, 0.3, 0.45], 7); // a tall strip, left
|
||||
box(3.2, 2.2, [0.42, 0.62, 0.66], 9); // a small box above the camera: the hot spot on the dome
|
||||
box(1.2, 10, [0.75, 0.2, -0.6], 3); // a rim strip behind
|
||||
const pm = new THREE.PMREMGenerator(renderer);
|
||||
const tex = pm.fromScene(env, 0.01).texture;
|
||||
pm.dispose();
|
||||
return tex;
|
||||
})();
|
||||
|
||||
// ------------------------------------------------------------ the scorpion and the guides
|
||||
let bee = null;
|
||||
const addBee = (b) => {
|
||||
bee = b;
|
||||
scene.add(b.root);
|
||||
b.root.traverse((o) => {
|
||||
if (o.isMesh && !b.clear.includes(o)) o.layers.enable(BEE_LAYER);
|
||||
});
|
||||
skip.push(...b.clear);
|
||||
for (const m of [b.M.lens, b.M.lensGlass]) {
|
||||
if (!m) continue;
|
||||
m.envMap = lensEnv;
|
||||
m.needsUpdate = true;
|
||||
}
|
||||
};
|
||||
const guides = buildGuides(guideOpts);
|
||||
scene.add(guides.group);
|
||||
skip.push(guides.group);
|
||||
|
||||
const size = {w: 1920, h: 1080, pr: 1};
|
||||
const resize = (w, h, pr) => {
|
||||
Object.assign(size, {w, h, pr});
|
||||
renderer.setPixelRatio(pr);
|
||||
renderer.setSize(w, h, false);
|
||||
composer.setPixelRatio(pr);
|
||||
composer.setSize(w, h);
|
||||
camera.aspect = w / h;
|
||||
camera.updateProjectionMatrix();
|
||||
backU.uRes.value.set(Math.round(w * pr), Math.round(h * pr));
|
||||
guides.resize(Math.round(w * pr), Math.round(h * pr), pr);
|
||||
};
|
||||
// cam: target (tx, ty, tz), azimuth from +z toward +x, elevation, distance, screen shift sx/sy in CSS px, fov (30)
|
||||
const frame = (cam, ops = {}) => {
|
||||
const {tx, ty, tz, az, el, d} = cam;
|
||||
const fov = cam.fov ?? 30;
|
||||
if (camera.fov !== fov) {
|
||||
camera.fov = fov;
|
||||
camera.updateProjectionMatrix();
|
||||
}
|
||||
camera.position.set(tx + d * Math.cos(el) * Math.sin(az), ty + d * Math.sin(el), tz + d * Math.cos(el) * Math.cos(az));
|
||||
camera.lookAt(tx, ty, tz);
|
||||
camera.setViewOffset(size.w, size.h, -(cam.sx ?? 0), -(cam.sy ?? 0), size.w, size.h);
|
||||
camera.updateMatrixWorld();
|
||||
const c = bee ? bee.root.position : new V3();
|
||||
key.target.position.set(c.x + 0.1, c.y, c.z);
|
||||
key.position.copy(key.target.position).addScaledVector(KEY, 9);
|
||||
key.target.updateMatrixWorld();
|
||||
guides.update(camera, ops);
|
||||
floorShadow(c);
|
||||
composer.render();
|
||||
};
|
||||
const pv = new V3();
|
||||
/** World point to CSS px, or null behind the camera. Call after frame(). */
|
||||
const project = (p) => {
|
||||
pv.copy(p).project(camera);
|
||||
if (pv.z > 1) return null;
|
||||
return [(pv.x * 0.5 + 0.5) * size.w, (-pv.y * 0.5 + 0.5) * size.h];
|
||||
};
|
||||
const setAOSkip = (list) => {
|
||||
extra = list;
|
||||
};
|
||||
// a live page's quality knobs: MSAA samples, the AO pass, the key's shadow map
|
||||
const setQuality = ({samples, ao, shadow}) => {
|
||||
if (samples !== undefined) {
|
||||
for (const t of [composer.renderTarget1, composer.renderTarget2]) {
|
||||
t.samples = samples;
|
||||
t.dispose();
|
||||
}
|
||||
}
|
||||
if (ao !== undefined) gtao.enabled = ao;
|
||||
if (shadow !== undefined && shadow !== key.shadow.mapSize.x) {
|
||||
key.shadow.mapSize.set(shadow, shadow);
|
||||
key.shadow.map?.dispose();
|
||||
key.shadow.map = null;
|
||||
}
|
||||
};
|
||||
return {renderer, scene, camera, composer, gtao, key, resize, frame, addBee, size, floorY, project, setAOSkip, setQuality};
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
// The JS-8 simulator tour, after the scorpion's (roboscorp-shared/tour.js) under the camera rules of
|
||||
// 2026-10-31: frame 0 is already the low front 3/4 hero view with the spider big and running; every teardown is shot
|
||||
// from that hero side (within about ±35°, the eyes toward the camera, a little above, pushing in on the part); the
|
||||
// variety lives in the transitions, the explode's turntable and the final jump. The camera rides a smoothed copy of
|
||||
// the body's path, never the stride bob or the jump.
|
||||
// The film: the spider runs in, brakes, crouches and jumps at the camera; then the operator opens one assembly after
|
||||
// another: the main lenses unscrew and the side lenses swivel, the near front leg lifts and comes apart segment by
|
||||
// segment with its piston out of the glass, the abdomen's canopy swings open and the gears lift out spinning fast, the
|
||||
// head's plates lift and the fangs and palps work; then it explodes on a turntable, snaps back together, walks a few
|
||||
// steps and jumps at the camera again.
|
||||
// Script: the entry's timeline.json, {duration, script: [{t, act}]}; act is an assembly (eyes, leg, abdomen, head),
|
||||
// 'exploded', 'assemble', 'hero' (the walk) or 'jump' (the final jump). Everything is a pure function of film time t.
|
||||
import * as THREE from 'three';
|
||||
import {VIEWPORT} from './console.js';
|
||||
import {buildGait, STRIDE_HZ} from './gait.js';
|
||||
import {CROUCH, jumpAt, jumpKeys} from './jump.js';
|
||||
import {FLOOR_Y, LEG_NAMES} from './spider.js';
|
||||
|
||||
const smoother = (x) => {
|
||||
const u = Math.min(1, Math.max(0, x));
|
||||
return u * u * u * (u * (u * 6 - 15) + 10);
|
||||
};
|
||||
const ss = (a, b, t) => smoother((t - a) / (b - a));
|
||||
const lerp = (a, b, k) => a + (b - a) * k;
|
||||
const D2R = Math.PI / 180;
|
||||
// a fast in, eased out pulse: 0 before a, up to 1 at b, back to 0 by c
|
||||
const pulse = (a, b, c, t) => ss(a, b, t) * (1 - ss(b, c, t));
|
||||
// millimetres per scene unit, for the readouts
|
||||
const MM = 220;
|
||||
export const REACH = 0.7;
|
||||
|
||||
export const ASSEMBLIES = ['hero', 'eyes', 'leg', 'abdomen', 'head', 'jump'];
|
||||
export const ASSEMBLY_LABEL = {hero: 'HERO', eyes: 'OPTICS', leg: 'LEG R1', abdomen: 'ABDOMEN', head: 'HEAD', jump: 'JUMP'};
|
||||
export const DISPLAY2 = ['labels', 'exploded', 'turntable', 'trace'];
|
||||
export const DISPLAY2_LABEL = {labels: 'LABELS', exploded: 'EXPLODED', turntable: 'TURNTABLE', trace: 'GAIT TRACE'};
|
||||
const BUTTON = {eyes: 'eyes', leg: 'leg', abdomen: 'abdomen', head: 'head', exploded: 'exploded', assemble: 'exploded', hero: 'hero', jump: 'jump'};
|
||||
|
||||
// each act's own clock (seconds after its click): when its parts open and when they close
|
||||
const ACT = {
|
||||
eyes: {open: [0.3, 1.3], close: [1.95, 2.45]},
|
||||
leg: {open: [0.5, 1.45], close: [2.05, 2.5]},
|
||||
abdomen: {open: [0.3, 1.35], close: [2.0, 2.5]},
|
||||
head: {open: [0.3, 1.3], close: [1.95, 2.45]},
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------ cameras: [az, el, d, tx, ty, tz, sx, sy, fov] in the
|
||||
// frame of the smoothed body path (az from the spider's right toward its face: 90 is straight at the face, the hero
|
||||
// side is about 66), u = seconds into the view
|
||||
const H = 66;
|
||||
export const CAMS = {
|
||||
intro: (u) => {
|
||||
const k = ss(0, 3.2, u);
|
||||
return [lerp(H + 8, H - 4, k), lerp(10, 8, k), lerp(7.6, 6.8, k), lerp(-0.2, 0.4, k), lerp(0.0, -0.06, k), 0.0, 0, -14, 36];
|
||||
},
|
||||
eyes: (u) => [lerp(H + 4, H + 12, ss(0, 2.6, u)), lerp(12, 8, ss(0, 2.6, u)), lerp(6.0, 5.3, ss(0, 1.8, u)), 0.62, 0.04, 0.0, 0, -14, 36],
|
||||
leg: (u) => [lerp(H - 16, H - 26, ss(0, 2.6, u)), lerp(16, 12, ss(0, 2.6, u)), lerp(6.6, 6.0, ss(0, 1.8, u)), 0.8, 0.06, 0.56, 0, -14, 36],
|
||||
abdomen: (u) => [lerp(H - 4, H - 14, ss(0, 2.6, u)), lerp(36, 31, ss(0, 2.6, u)), lerp(8.2, 7.6, ss(0, 1.8, u)), -0.7, 0.4, 0.0, 0, -14, 36],
|
||||
head: (u) => [lerp(H + 22, H + 14, ss(0, 2.6, u)), lerp(18, 14, ss(0, 2.6, u)), lerp(6.5, 5.9, ss(0, 1.8, u)), 0.45, 0.08, 0.0, 0, -14, 36],
|
||||
exploded: (u) => [H + 10 * u, lerp(16, 22, ss(0, 2.0, u)), lerp(11.0, 12.2, ss(0, 1.6, u)), -0.25, 0.3, 0.0, 0, -14, 36],
|
||||
hero: (u) => [lerp(H - 30, H + 26, ss(0, 3.0, u)), lerp(14, 7, ss(0, 3.0, u)), lerp(8.4, 7.2, ss(0, 3.0, u)), 0.3, -0.04, 0.0, 0, -14, 36],
|
||||
jump: (u) => [lerp(H + 24, H + 18, ss(0, 3.0, u)), lerp(7, 5, ss(0, 1.6, u)), lerp(7.4, 6.9, ss(0, 1.2, u)) - 0.25 * ss(1.4, 3.3, u), 0.5, lerp(-0.04, 0.02, ss(0.4, 1.8, u)), 0.0, 0, -14, 36],
|
||||
};
|
||||
|
||||
export function makeTour(TL) {
|
||||
const SCRIPT = [...TL.script].sort((a, b) => a.t - b.t);
|
||||
const DURATION = TL.duration;
|
||||
const EVENTS = SCRIPT.map((e) => e.t);
|
||||
const at = (act) => SCRIPT.filter((e) => e.act === act).map((e) => e.t);
|
||||
const T_EXP = at('exploded')[0] ?? 999;
|
||||
const T_ASM = at('assemble')[0] ?? 999;
|
||||
const T_HERO = at('hero')[0] ?? 999;
|
||||
const T_JUMP = at('jump')[0] ?? 999;
|
||||
const T_LEG = at('leg')[0] ?? 999;
|
||||
// the two jumps: at the camera out of the run-in, and the last one
|
||||
const J1 = {t0: 1.5, tl: 1.98, ta: 2.55, dist: 1.1, h: 0.52};
|
||||
const J2 = {t0: T_JUMP + 0.25, tl: T_JUMP + 0.72, ta: T_JUMP + 1.3, dist: 1.35, h: 0.6};
|
||||
const jumpBoth = (t) => {
|
||||
const a = jumpAt(t, J1);
|
||||
const b = jumpAt(t, J2);
|
||||
return {dy: a.dy + b.dy, pitch: a.pitch + b.pitch, tuck: Math.max(a.tuck, b.tuck), air: Math.max(a.air, b.air)};
|
||||
};
|
||||
const openOf = (act, t) => {
|
||||
let v = 0;
|
||||
for (const t0 of at(act)) {
|
||||
const A = ACT[act];
|
||||
v = Math.max(v, ss(t0 + A.open[0], t0 + A.open[1], t) * (1 - ss(t0 + A.close[0], t0 + A.close[1], t)));
|
||||
}
|
||||
return v;
|
||||
};
|
||||
const explodeAt = (t) => ss(T_EXP + 0.2, T_EXP + 1.8, t) * (1 - ss(T_ASM, T_ASM + 1.0, t));
|
||||
// the turntable: one full turn from the explode to just after the spider is whole again, eased at both ends
|
||||
const TT = [T_EXP + 0.2, T_ASM + 1.3];
|
||||
const turnAt = (t) => {
|
||||
const [a, b] = TT;
|
||||
if (t <= a) return 0;
|
||||
const R = 0.6;
|
||||
const span = b - a;
|
||||
const v = 360 / (span - R);
|
||||
const x = Math.min(t, b) - a;
|
||||
if (x < R) return (v * x * x) / (2 * R);
|
||||
if (x < span - R) return v * (x - R / 2);
|
||||
const y = x - (span - R);
|
||||
return v * (span - 1.5 * R) + v * y - (v * y * y) / (2 * R);
|
||||
};
|
||||
const activity = (t) => Math.max(...Object.keys(ACT).map((a) => openOf(a, t)), explodeAt(t));
|
||||
// the busy clocks: every gear turns on spinT, six times faster while an assembly is open; the abdomen's own gears
|
||||
// on spinA, five times faster again while the canopy is up
|
||||
const DT = 1 / 240;
|
||||
const SPIN = [0];
|
||||
const SPINA = [0];
|
||||
for (let i = 1; i * DT <= DURATION + 1; i++) {
|
||||
const tm = (i - 0.5) * DT;
|
||||
const r = 1 + 5 * activity(tm);
|
||||
SPIN.push(SPIN[i - 1] + r * DT);
|
||||
SPINA.push(SPINA[i - 1] + (r + 5 * openOf('abdomen', tm)) * DT);
|
||||
}
|
||||
const look = (A, t) => {
|
||||
const u = Math.max(0, Math.min(A.length - 2, t / DT));
|
||||
const i = Math.floor(u);
|
||||
return A[i] + (A[i + 1] - A[i]) * (u - i);
|
||||
};
|
||||
const spinAt = (t) => (t < 0 ? t : look(SPIN, t));
|
||||
const spinAAt = (t) => (t < 0 ? t : look(SPINA, t));
|
||||
|
||||
// the walk: the run-in on a gentle curve to a stop, the first jump's travel, still through the acts, a short walk
|
||||
// on a curve after the reassembly, a stop, the last jump's travel
|
||||
const gait = buildGait({
|
||||
duration: DURATION + 0.5,
|
||||
tRef: 1.42,
|
||||
keys: [
|
||||
[-1.5, 1.05, 12],
|
||||
[0.7, 1.0, 9],
|
||||
[1.42, 0, 0],
|
||||
...jumpKeys(J1),
|
||||
[T_HERO + 0.3, 0, 0],
|
||||
[T_HERO + 0.8, 0.62, -16],
|
||||
[T_JUMP - 0.55, 0.55, -16],
|
||||
[T_JUMP - 0.05, 0, 0],
|
||||
...jumpKeys(J2),
|
||||
],
|
||||
});
|
||||
// the camera's path: the body's path low-passed (gaussian, sigma 0.4 s), so the camera follows the spider without
|
||||
// picking up the jump's dash or the stride
|
||||
const CHZ = 60;
|
||||
const C0 = -1.5;
|
||||
const CN = Math.ceil((DURATION + 1 - C0) * CHZ);
|
||||
const raw = Array.from({length: CN}, (_, i) => gait.pathAt(C0 + i / CHZ));
|
||||
const SIG = 0.4 * CHZ;
|
||||
const KR = Math.ceil(3 * SIG);
|
||||
const KW = Array.from({length: 2 * KR + 1}, (_, j) => Math.exp(-0.5 * Math.pow((j - KR) / SIG, 2)));
|
||||
const CX = new Float64Array(CN);
|
||||
const CZ = new Float64Array(CN);
|
||||
const CY = new Float64Array(CN);
|
||||
for (let i = 0; i < CN; i++) {
|
||||
let sx = 0;
|
||||
let sz = 0;
|
||||
let sy = 0;
|
||||
let sw = 0;
|
||||
for (let j = -KR; j <= KR; j++) {
|
||||
const p = raw[Math.max(0, Math.min(CN - 1, i + j))];
|
||||
const w = KW[j + KR];
|
||||
sx += p.x * w;
|
||||
sz += p.z * w;
|
||||
sy += p.yaw * w;
|
||||
sw += w;
|
||||
}
|
||||
CX[i] = sx / sw;
|
||||
CZ[i] = sz / sw;
|
||||
CY[i] = sy / sw;
|
||||
}
|
||||
const camPath = (t) => {
|
||||
const u = Math.max(0, Math.min(CN - 1.000001, (t - C0) * CHZ));
|
||||
const i = Math.floor(u);
|
||||
const f = u - i;
|
||||
return {x: CX[i] + (CX[i + 1] - CX[i]) * f, z: CZ[i] + (CZ[i + 1] - CZ[i]) * f, yaw: CY[i] + (CY[i + 1] - CY[i]) * f};
|
||||
};
|
||||
|
||||
// the near front leg (R1): lifted off the floor and held up in front before it comes apart
|
||||
const legLiftAt = (t) => {
|
||||
let v = 0;
|
||||
for (const t0 of at('leg')) v = Math.max(v, ss(t0 + 0.05, t0 + 0.45, t) * (1 - ss(t0 + 2.2, t0 + 2.65, t)));
|
||||
return v;
|
||||
};
|
||||
// the body: the path, the jumps, a bob with the stride, a slow breath, a lean off the lifted leg
|
||||
const bodyAt = (t) => {
|
||||
const p = gait.pathAt(t);
|
||||
const rate = gait.rateAt(t) / STRIDE_HZ;
|
||||
const ph = gait.phaseAt(t);
|
||||
const [, w] = gait.velAt(t);
|
||||
const j = jumpBoth(t);
|
||||
const run = Math.min(1, rate) * (1 - j.air);
|
||||
let y = j.dy + 0.014 * Math.sin(ph * Math.PI * 4) * run + 0.006 * Math.sin(t * 1.7);
|
||||
let roll = -w * 0.001 + 0.01 * Math.sin(ph * Math.PI * 2) * run;
|
||||
const pitch = j.pitch + 0.008 * Math.sin(t * 1.3 + 1);
|
||||
const kl = legLiftAt(t);
|
||||
roll -= 0.05 * kl;
|
||||
y += 0.02 * kl;
|
||||
return {x: p.x, z: p.z, y, yaw: p.yaw, roll, pitch, rate, jump: j};
|
||||
};
|
||||
const feetAt = (t, b) => {
|
||||
const F = [];
|
||||
for (let l = 0; l < 8; l++) {
|
||||
const f = gait.footLocal(l, t, b);
|
||||
if (l === 4) {
|
||||
const k = legLiftAt(t);
|
||||
f[0] -= 0.3 * k;
|
||||
f[1] += 0.62 * k;
|
||||
f[2] -= 0.12 * k;
|
||||
}
|
||||
F.push(f);
|
||||
}
|
||||
return F;
|
||||
};
|
||||
// the palps: up in front of the face for the jumps and the head act, otherwise hanging and twitching
|
||||
const palpAt = (t, j) => 0.35 + 0.55 * j.tuck + 0.35 * pulse(J1.t0, J1.tl, J1.ta + 0.3, t) + 0.35 * pulse(J2.t0, J2.tl, J2.ta + 0.3, t) + 0.5 * pulse(J2.ta + 0.35, J2.ta + 0.8, J2.ta + 1.8, t);
|
||||
// the close: after the last landing the main lenses focus on the camera (their rings run out a little and back)
|
||||
const focusAt = (t) => 0.38 * pulse(J2.ta + 0.4, J2.ta + 0.85, J2.ta + 1.75, t);
|
||||
|
||||
// the camera: each act's view, blended over 0.9 s with a short dolly out, on the smoothed path
|
||||
const VIEWS = [{t: -1, key: 'intro'}, ...SCRIPT.map((e) => ({t: e.t, key: e.act === 'assemble' ? 'exploded' : e.act}))];
|
||||
const viewIdx = (t) => {
|
||||
let i = 0;
|
||||
while (i < VIEWS.length - 1 && VIEWS[i + 1].t <= t) i++;
|
||||
return i;
|
||||
};
|
||||
const camFn = (V, t) => CAMS[V.key](t - (V.key === 'intro' ? 0 : V.t));
|
||||
// the follow time: the camera follows the smoothed path, except into a jump, where its follow eases to a stop
|
||||
// just before take-off (the speed falls from 1 to 0 over a..b), so the spider leaps toward a camera that holds
|
||||
const ease = (t, a, b) => {
|
||||
if (t <= a) return t;
|
||||
const u = Math.min(1, (t - a) / (b - a));
|
||||
return a + (b - a) * (u - (u * u) / 2);
|
||||
};
|
||||
const followT = (V, t) => (V.key === 'intro' ? ease(t, 0.8, 1.95) : V.key === 'jump' ? ease(t, J2.t0 - 0.6, J2.tl) : t);
|
||||
// a view's camera in the world: its framing turned with the path's heading and put on the path
|
||||
const world = (V, t) => {
|
||||
const o = camFn(V, t);
|
||||
const p = camPath(followT(V, t));
|
||||
const cy = Math.cos(p.yaw);
|
||||
const sy = Math.sin(p.yaw);
|
||||
return [o[0] + p.yaw / D2R, o[1], o[2], p.x + o[3] * cy + o[5] * sy, o[4], p.z - o[3] * sy + o[5] * cy, o[6], o[7], o[8]];
|
||||
};
|
||||
// each view blended from the last one over 0.9 s in world space, with a short dolly out
|
||||
const camAt = (t) => {
|
||||
const i = viewIdx(t);
|
||||
let o = world(VIEWS[i], t);
|
||||
if (VIEWS[i].key === 'exploded' && i > 0 && VIEWS[i - 1].key === 'exploded') o = world(VIEWS[i - 1], t);
|
||||
else if (i > 0) {
|
||||
const k = ss(VIEWS[i].t, VIEWS[i].t + 0.9, t);
|
||||
if (k < 1) {
|
||||
const a = world(VIEWS[i - 1], t);
|
||||
const dAz = ((((o[0] - a[0]) % 360) + 540) % 360) - 180;
|
||||
const b = o.map((v, n) => lerp(a[n], v, k));
|
||||
b[0] = a[0] + dAz * k;
|
||||
b[2] += 0.6 * Math.sin(Math.PI * k);
|
||||
o = b;
|
||||
}
|
||||
}
|
||||
return {az: o[0], el: o[1], d: o[2], tx: o[3], ty: o[4], tz: o[5], sx: o[6], sy: o[7], fov: o[8]};
|
||||
};
|
||||
const actAt = (t) => VIEWS[viewIdx(t)].key;
|
||||
|
||||
const stateAt = (t) => {
|
||||
const ex = explodeAt(t);
|
||||
const open = Object.fromEntries(Object.keys(ACT).map((a) => [a, openOf(a, t)]));
|
||||
const body = bodyAt(t);
|
||||
return {
|
||||
t,
|
||||
spinT: spinAt(t),
|
||||
spinA: spinAAt(t),
|
||||
explode: ex,
|
||||
sub: {eyes: Math.max(open.eyes, focusAt(t)), leg: open.leg, abdomen: open.abdomen, head: open.head},
|
||||
body,
|
||||
feet: feetAt(t, body),
|
||||
tuck: body.jump.tuck,
|
||||
palp: palpAt(t, body.jump),
|
||||
open,
|
||||
cam: camAt(t),
|
||||
view: actAt(t),
|
||||
guides: 0.35 + 0.65 * Math.min(1, ex * 2.5 + activity(t)),
|
||||
turn: turnAt(t),
|
||||
};
|
||||
};
|
||||
|
||||
// labels: on while an act's parts are moving apart and while they hang open, gone before they close
|
||||
const LABELS = {
|
||||
eyes: [['lens', 'MAIN OPTIC R', 'Ø 46 MM · 9 ELEMENTS'], ['iris', 'IRIS', '10 BLADES · F/1.4'], ['eyeGlass', 'DOME GLASS', 'SAPPHIRE · AR COAT'], ['ale', 'SIDE OPTIC', '6 SECONDARY · SWIVEL']],
|
||||
leg: [['hipR1', 'COXA SERVO', 'YAW ±45°'], ['femR1', 'FEMUR PLATES', 'RIVETED · 52 BRISTLES'], ['kneeR1', 'KNEE RING', 'GLOW RING · 2.4 N·M'], ['pistonR1', 'TIBIA PISTON', 'PLATED · 60 MM'], ['footR1', 'CLAW TIP', 'GLOW · 14 MM']],
|
||||
abdomen: [['canopy', 'GLASS CAGE', '5 BANDS · HINGED'], ['gears', 'FLANK GEARS', '7 PER SIDE · 5× SPEED'], ['core', 'GLOW COILS', '20 COILS · 5× SPEED']],
|
||||
head: [['visor', 'BROW PLATE', 'LIFT 40 MM'], ['channel', 'SPINE CHANNEL', '8 GEARS'], ['face', 'EYE PLATE', '8 LENSES'], ['chel', 'FANG', 'FLARE 40° · GLOW TIP'], ['jaw', 'JAW BLOCK', '4 LINES · 2 GEARS']],
|
||||
exploded: [['lens', 'OPTICS', '2 + 6 LENSES'], ['core', 'GLOW COILS', 'SPINNING FREE'], ['canopy', 'CAGE', 'GLASS · 5 BANDS'], ['kneeR1', 'LEG RINGS', '8 × 4 JOINTS']],
|
||||
};
|
||||
const labelAt = (t, s) => {
|
||||
const v = s.view;
|
||||
if (ACT[v]) {
|
||||
const t0 = at(v).filter((x) => x <= t).pop();
|
||||
const A = ACT[v];
|
||||
return {set: LABELS[v], o: ss(t0 + A.open[0] + 0.1, t0 + A.open[0] + 0.45, t) * (1 - ss(t0 + A.close[0] - 0.25, t0 + A.close[0], t))};
|
||||
}
|
||||
if (v === 'exploded') return {set: LABELS.exploded, o: ss(T_EXP + 0.4, T_EXP + 0.8, t) * (1 - ss(T_EXP + 2.3, T_EXP + 2.6, t))};
|
||||
return {set: [], o: 0};
|
||||
};
|
||||
|
||||
// the optics: the iris opens wide for the eye act, stops down for the jumps; the focus range follows the camera
|
||||
const irisAt = (t) => {
|
||||
const j = jumpBoth(t);
|
||||
return Math.max(0.05, Math.min(1, 0.35 + 0.6 * Math.max(openOf('eyes', t), focusAt(t)) - 0.25 * j.air + 0.06 * Math.sin(t * 2.1)));
|
||||
};
|
||||
const telemetry = (t, s) => {
|
||||
const b = s.body;
|
||||
const j = b.jump;
|
||||
const ex = s.explode > 0.04;
|
||||
const walking = b.rate > 0.05;
|
||||
// the step diagram: stance and swing spans of every leg over the last 1.6 s, as fractions of the window
|
||||
const W0 = t - 1.6;
|
||||
const steps = [0, 1, 2, 3, 4, 5, 6, 7].map((l) => {
|
||||
const row = [];
|
||||
let x = W0;
|
||||
for (const sw of gait.swings[l]) {
|
||||
if (sw.t1 < W0) continue;
|
||||
if (sw.t0 > t) break;
|
||||
const a = Math.max(W0, sw.t0);
|
||||
const c = Math.min(t, sw.t1);
|
||||
if (a > x) row.push([(x - W0) / 1.6, (a - W0) / 1.6, false]);
|
||||
row.push([(a - W0) / 1.6, (c - W0) / 1.6, true]);
|
||||
x = c;
|
||||
}
|
||||
if (x < t) row.push([(x - W0) / 1.6, 1, false]);
|
||||
return row;
|
||||
});
|
||||
const legOpen = s.open.leg > 0.08;
|
||||
const free = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => ex || (i === 4 && legOpen));
|
||||
const lifts = [0, 1, 2, 3, 4, 5, 6, 7].map((l) => gait.lifted(l, t));
|
||||
const nLift = lifts.reduce((a, v) => a + v, 0);
|
||||
// the crouch loads every knee, the flight unloads them
|
||||
const crouch = Math.max(0, -j.dy) / CROUCH;
|
||||
const servos = lifts.map((v, i) => (free[i] ? 0 : Math.max(0.04, Math.min(1, (j.air ? 0.1 : (v > 0.05 ? 0.16 : 0.34 + (0.22 * nLift) / 4) + 0.55 * crouch) + [0.06, 0.1, 0.04, 0.0, 0.08, 0.02, 0.09, 0.05][i] + 0.04 * Math.sin(t * 6 + i) - (i === 4 ? 0.3 * legLiftAt(t) : 0)))));
|
||||
const v = s.view;
|
||||
const opening = ACT[v] ? s.open[v] : 0;
|
||||
const NAME = {eyes: 'OPTICS OPEN', leg: 'LEG R1 APART', abdomen: 'ABDOMEN OPEN', head: 'HEAD OPEN'};
|
||||
let status = 'STANDING';
|
||||
let kind = 'ok';
|
||||
const jumpState = j.air ? 'AIRBORNE' : (t > J1.t0 && t < J1.tl) || (t > J2.t0 && t < J2.tl) ? 'CROUCH' : (t > J1.ta && t < J1.ta + 0.45) || (t > J2.ta && t < J2.ta + 0.45) ? 'LANDING' : null;
|
||||
if (walking && !jumpState) status = t < 3 ? 'RUN-IN' : 'WALK';
|
||||
if (ACT[v] && opening > 0.05) [status, kind] = [NAME[v], 'warn'];
|
||||
if (v === 'leg' && legLiftAt(t) > 0.05 && opening <= 0.05) status = 'LEG R1 LIFT';
|
||||
if (v === 'exploded') [status, kind] = t < T_ASM ? ['TEARDOWN', 'warn'] : s.explode > 0.04 ? ['REASSEMBLY', 'warn'] : ['STANDING', 'ok'];
|
||||
if (jumpState) [status, kind] = [jumpState, 'warn'];
|
||||
const ROW = {eyes: 0, head: 1, abdomen: 2, jump: 3, leg: 4};
|
||||
const sub = (i) => {
|
||||
if (ex) return ['warn', 'DETACHED'];
|
||||
if (ROW[v] === i && opening > 0.05) return ['warn', i === 4 ? 'DETACHED' : 'OPEN'];
|
||||
if (i === 3) return j.air ? ['warn', 'AIRBORNE'] : jumpState === 'CROUCH' ? ['warn', 'ARMED'] : ['ok', 'READY'];
|
||||
if (i === 4) return walking ? ['ok', 'STEPPING'] : ['ok', 'HOLDING'];
|
||||
if (i === 5) return s.open.head > 0.05 ? ['warn', 'ACTIVE'] : ['ok', 'FOLDED'];
|
||||
if (i === 0) return ['ok', 'TRACKING'];
|
||||
return ['ok', 'SEALED'];
|
||||
};
|
||||
const last = SCRIPT.filter((e) => e.t <= t).pop();
|
||||
const say = (e) => (e.act === 'exploded' ? 'EXPLODED ON' : e.act === 'assemble' ? 'EXPLODED OFF · REASSEMBLE' : e.act === 'hero' ? 'HERO · WALK' : e.act === 'jump' ? 'JUMP · ARMED' : `ISOLATE ${ASSEMBLY_LABEL[e.act]}`);
|
||||
const labels = labelAt(t, s);
|
||||
// the jump readouts: the height over the stance (negative in the crouch), the last flight's airtime, the launch
|
||||
// speed, the tuck
|
||||
const Jl = t >= J2.t0 ? J2 : J1;
|
||||
const air = j.air ? t - Jl.tl : t >= Jl.ta ? Jl.ta - Jl.tl : 0;
|
||||
const launch = (2 * Jl.dist) / (Jl.ta - Jl.tl) * (MM / 1000) + 0.0;
|
||||
const iris = irisAt(t);
|
||||
const trace = [];
|
||||
for (let i = 0; i <= 40; i++) trace.push(irisAt(t - 2 + (i / 40) * 2));
|
||||
const [vv] = gait.velAt(t);
|
||||
return {
|
||||
time: t,
|
||||
dur: DURATION,
|
||||
lift: 0.18 + 0.45 * b.rate + 0.4 * crouch + 0.35 * j.air + 0.15 * activity(t),
|
||||
status,
|
||||
statusKind: kind,
|
||||
freq: gait.rateAt(t) * (1 - j.air),
|
||||
speed: Math.abs(vv) * MM,
|
||||
steps,
|
||||
pattern: j.air ? 'BALLISTIC · TUCKED' : walking ? 'ALT TETRAPOD' : 'STANCE · 8 FEET',
|
||||
duty: walking && !j.air ? 0.54 : j.air ? 0 : 1,
|
||||
jumpH: j.dy * MM,
|
||||
jumpK: Math.max(0, Math.min(1, (j.dy + CROUCH) / (J2.h + CROUCH))),
|
||||
airtime: air,
|
||||
launch: t >= Jl.tl ? launch : 0,
|
||||
tuck: j.tuck,
|
||||
servos,
|
||||
legsFree: ex,
|
||||
legFreeEach: free,
|
||||
walking,
|
||||
iris,
|
||||
fstop: 1.4 / Math.sqrt(Math.max(0.05, iris)) ,
|
||||
irisTrace: trace,
|
||||
lensOpen: [iris * (0.96 + 0.04 * Math.sin(t * 3)), iris],
|
||||
opticsOpen: s.open.eyes > 0.05,
|
||||
opticsMode: s.open.eyes > 0.05 ? 'OPEN' : j.air || jumpState === 'CROUCH' ? 'LOCK' : walking ? 'TRACK' : 'SCAN',
|
||||
range: s.cam.d * MM,
|
||||
view: v === 'intro' ? 'hero' : v === 'exploded' ? null : v,
|
||||
display: {labels: labels.o > 0.5, exploded: t >= T_EXP && t < T_ASM, turntable: s.turn > 0 && t < TT[1], trace: walking},
|
||||
subs: [0, 1, 2, 3, 4, 5].map(sub),
|
||||
focus: jumpState ? 3 : ROW[v] ?? (v === 'exploded' ? 2 : -1),
|
||||
events: EVENTS,
|
||||
next: `${EVENTS.length} OPERATOR ACTIONS`,
|
||||
log: last ? `OPERATOR · ${say(last)}` : 'INBOUND · RUN-IN · 8 LEGS',
|
||||
mode: status,
|
||||
modeSub: j.air
|
||||
? `${Math.round(j.dy * MM)} MM UP · TUCK ${Math.round(j.tuck * 100)}%`
|
||||
: status === 'CROUCH'
|
||||
? `${Math.round(-j.dy * MM)} MM DOWN · KNEES LOADED`
|
||||
: status === 'RUN-IN' || status === 'WALK'
|
||||
? `${(Math.abs(vv) * MM).toFixed(0)} MM/S · YAW ${((((b.yaw / D2R) % 360) + 360) % 360).toFixed(0)}°`
|
||||
: status === 'TEARDOWN' || status === 'REASSEMBLY'
|
||||
? `TURNTABLE ${Math.round(s.turn)}° · ${Math.round(s.explode * 100)}% APART`
|
||||
: ACT[v] && opening > 0.05
|
||||
? `${ASSEMBLY_LABEL[v]} · ${Math.round(opening * 100)}% APART`
|
||||
: `8 FEET DOWN · ${((0 - FLOOR_Y) * MM).toFixed(0)} MM CLEARANCE`,
|
||||
viewNote: `ISOLATE · ${v === 'intro' || v === 'hero' || v === 'jump' ? 'HERO' : v === 'exploded' ? 'ALL' : ASSEMBLY_LABEL[v]}`,
|
||||
labelSet: labels,
|
||||
legNames: LEG_NAMES,
|
||||
};
|
||||
};
|
||||
|
||||
return {SCRIPT, DURATION, stateAt, telemetry, camAt, gait};
|
||||
}
|
||||
|
||||
/** Labels in two columns at the viewport's edges, from a set of anchors (as the bee's makeLabels2). */
|
||||
export function makeLabels(st, sc) {
|
||||
const p = new THREE.Vector3();
|
||||
return ({set, o}) => {
|
||||
if (o < 0.02) return [];
|
||||
const pts = [];
|
||||
for (const [key, name, sub] of set) {
|
||||
const A = sc.anchors[key];
|
||||
if (!A) continue;
|
||||
A.obj.updateWorldMatrix(true, false);
|
||||
const at = st.project(A.obj.localToWorld(p.copy(A.at)));
|
||||
if (at && at[0] > VIEWPORT.x0 + 30 && at[0] < VIEWPORT.x1 - 30 && at[1] > VIEWPORT.y0 + 40 && at[1] < VIEWPORT.y1 - 70) pts.push({name, sub, at});
|
||||
}
|
||||
const mid = (VIEWPORT.x0 + VIEWPORT.x1) / 2;
|
||||
const out = [];
|
||||
const stack = (col, x, w) => {
|
||||
let y = Math.max(VIEWPORT.y0 + 48, Math.min(col.length ? col[0].at[1] - 10 : 0, VIEWPORT.y1 - 110 - 34 * col.length));
|
||||
for (const c of col) {
|
||||
y = Math.max(y, Math.min(VIEWPORT.y1 - 110, c.at[1] - 10));
|
||||
out.push({name: c.name, sub: c.sub, at: c.at, label: [x, y], w, o});
|
||||
y += 34;
|
||||
}
|
||||
};
|
||||
stack(pts.filter((x) => x.at[0] < mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x0 + 16, 168);
|
||||
stack(pts.filter((x) => x.at[0] >= mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x1 - 160, 150);
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ the operator's pointer, on the act buttons (the bee's)
|
||||
const GUTTER_X = 1262;
|
||||
export function makeCursor(ui, SCRIPT) {
|
||||
// Timeline actions without a visible button still run; the pointer skips them.
|
||||
const EV = SCRIPT.filter((e) => e.t > 0).map((e) => ({t: e.t, spot: ui.spots[BUTTON[e.act]]})).filter((e) => e.spot);
|
||||
if (!EV.length) return () => ({x: -1, y: 0, press: false, ring: 0, ringX: 0, ringY: 0});
|
||||
const WP = [[0, GUTTER_X, EV[0].spot[1] + 60]];
|
||||
let [px, py, pt] = [GUTTER_X, EV[0].spot[1] + 60, 0];
|
||||
EV.forEach((e, n) => {
|
||||
const [x, y] = e.spot;
|
||||
const travel = Math.min(0.7, 0.3 + Math.hypot(x - px, y - py) / 900);
|
||||
const arrive = e.t - 0.1;
|
||||
if (arrive - travel - pt > 1.4) {
|
||||
const rest = [GUTTER_X, Math.max(170, Math.min(720, y + 40))];
|
||||
WP.push([pt + 0.7, ...rest]);
|
||||
WP.push([arrive - travel, ...rest]);
|
||||
} else WP.push([Math.max(pt + 0.01, arrive - travel), px, py]);
|
||||
WP.push([arrive, x, y], [e.t + 0.18, x, y]);
|
||||
[px, py, pt] = [x, y, e.t + 0.18];
|
||||
const next = EV[n + 1];
|
||||
if (!next || next.t - 0.1 - 0.7 - pt > 0.8) {
|
||||
[px, py, pt] = [GUTTER_X, y + 12, pt + 0.55];
|
||||
WP.push([pt, px, py]);
|
||||
}
|
||||
});
|
||||
WP.push([pt + 0.9, GUTTER_X, Math.min(720, py + 50)]);
|
||||
return (t) => {
|
||||
let i = 0;
|
||||
while (i < WP.length - 2 && t > WP[i + 1][0]) i++;
|
||||
const [t0, x0, y0] = WP[i];
|
||||
const [t1, x1, y1] = WP[i + 1];
|
||||
const k = ss(t0, t1, t);
|
||||
const len = Math.hypot(x1 - x0, y1 - y0);
|
||||
const bow = Math.sin(Math.PI * k) * Math.min(22, len * 0.07);
|
||||
let press = false;
|
||||
let ring = 0;
|
||||
let rx = 0;
|
||||
let ry = 0;
|
||||
for (const e of EV) {
|
||||
if (t >= e.t - 0.07 && t < e.t + 0.09) press = true;
|
||||
if (t >= e.t && t < e.t + 0.55) {
|
||||
ring = 1 - (t - e.t) / 0.55;
|
||||
[rx, ry] = e.spot;
|
||||
}
|
||||
}
|
||||
return {x: x0 + (x1 - x0) * k + (len ? (-(y1 - y0) / len) * bow : 0), y: y0 + (y1 - y0) * k + (len ? ((x1 - x0) / len) * bow : 0), press, ring, ringX: rx, ringY: ry};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// VESPION VX-9, the 10-second demo for the article (2026-11-06), green: a dive in from above, the wing pulled out and
|
||||
// turned over, the explode in slow motion, a climb straight out of the top of the frame. Tour: ../wasp-shared/tour_10.js.
|
||||
import {runWaspGreen} from '../wasp-shared/sim_green.js';
|
||||
import {make10Tour} from '../wasp-shared/tour_10.js';
|
||||
import TL from './timeline.json';
|
||||
|
||||
runWaspGreen(TL, 'wasp-demo', {tour: make10Tour});
|
||||
@@ -0,0 +1 @@
|
||||
{"duration": 10.0, "script": [{"t": 1.5, "act": "wing"}, {"t": 3.8, "act": "exploded"}, {"t": 6.6, "act": "assemble"}, {"t": 7.8, "act": "hero"}]}
|
||||
@@ -0,0 +1,7 @@
|
||||
// VESPION VX-9 on the green page, made 2026-11-06: the approved wasp film (wasp-film) with its movement, cameras,
|
||||
// timing and sound untouched, re-shot in green on the model-launch page. Code: ../wasp-shared/sim_green.js and
|
||||
// ../green (console.js, look.js).
|
||||
import {runWaspGreen} from '../wasp-shared/sim_green.js';
|
||||
import TL from './timeline.json';
|
||||
|
||||
runWaspGreen(TL);
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"duration": 24.0,
|
||||
"script": [
|
||||
{"t": 3.0, "act": "optics"},
|
||||
{"t": 5.7, "act": "wing"},
|
||||
{"t": 8.5, "act": "leg"},
|
||||
{"t": 11.0, "act": "thorax"},
|
||||
{"t": 13.6, "act": "abdomen"},
|
||||
{"t": 16.1, "act": "exploded"},
|
||||
{"t": 19.3, "act": "assemble"},
|
||||
{"t": 20.5, "act": "hero"}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,359 @@
|
||||
// The Mellis HB-7 console, laid out at 1600 x 900 after the Cessna console and the reference app recordings: the
|
||||
// orange HB-7 badge and title with the sim status cells, the wing beat with its live stroke chart, power, the six leg
|
||||
// servos, flight telemetry with an attitude ball, the views, the display toggles, the subsystem registry, the flight
|
||||
// log with the operator's actions on its timeline, the flight-mode word in the viewport, the labels with leaders into
|
||||
// the bee and the operator's pointer. Panels are light paper over the near-white studio; the bee's orange is the one
|
||||
// accent. update(s) redraws every live part from the frame's state; the film and a live page share it.
|
||||
export const C = {ink: '#24211d', mute: '#9a8f82', faint: '#e0d7ca', line: '#ece5da', panel: 'rgba(253,251,247,.95)', or: '#ff5a1f', green: '#2fa36b', track: '#efe8de'};
|
||||
export const VIEWS = ['hero', 'front', 'side', 'wing', 'legs'];
|
||||
export const VIEW_LABEL = {hero: 'HERO', front: 'FRONT', side: 'SIDE', wing: 'WING', legs: 'LEGS'};
|
||||
export const DISPLAY = ['labels', 'xray', 'exploded', 'blur', 'orbit'];
|
||||
export const DISPLAY_LABEL = {labels: 'LABELS', xray: 'X-RAY', exploded: 'EXPLODED', blur: 'MOTION BLUR', orbit: 'ORBIT'};
|
||||
// the viewport: the 3D shows between the side columns, above the flight log
|
||||
export const VIEWPORT = {x0: 330, x1: 1270, y0: 108, y1: 744};
|
||||
const CSS = `
|
||||
#app{font-family:Inter,system-ui,sans-serif;color:${C.ink};-webkit-font-smoothing:antialiased;font-variant-numeric:tabular-nums}
|
||||
.ui{position:absolute;inset:0;pointer-events:none}
|
||||
.mo{font-family:'JetBrains Mono',ui-monospace,monospace}
|
||||
.cp{position:absolute;background:${C.panel};border:1px solid ${C.line};border-radius:6px;box-shadow:0 2px 10px rgba(120,90,50,.07)}
|
||||
.ph{position:absolute;display:flex;align-items:center;gap:9px;font:700 10.5px 'JetBrains Mono',monospace;letter-spacing:1.8px}
|
||||
.ph i{display:block;width:3px;height:13px;background:${C.or}}
|
||||
.pn{position:absolute;font:500 9.5px 'JetBrains Mono',monospace;color:${C.mute};letter-spacing:1px}
|
||||
.sm{font:500 9px 'JetBrains Mono',monospace;letter-spacing:1.6px;color:${C.mute};text-transform:uppercase;white-space:nowrap}
|
||||
.v{font:600 11px 'JetBrains Mono',monospace;color:${C.ink};white-space:nowrap}
|
||||
.bt{position:absolute;height:23px;padding:0 10px;display:flex;align-items:center;justify-content:center;border:1px solid ${C.faint};border-radius:4px;background:#fffdf9;font:700 9.4px 'JetBrains Mono',monospace;letter-spacing:1.3px;color:${C.ink};white-space:nowrap;box-sizing:border-box}
|
||||
.call{position:absolute;white-space:nowrap;padding:3px 6px 3px 5px;margin:-3px 0 0 -5px;background:rgba(253,251,247,.86);border-radius:3px}
|
||||
.call b{display:flex;align-items:center;gap:6px;font:700 9.4px 'JetBrains Mono',monospace;letter-spacing:1.3px;color:${C.ink}}
|
||||
.call b i{display:block;width:6px;height:6px;background:${C.or}}
|
||||
.call span{display:block;font:500 7.8px 'JetBrains Mono',monospace;letter-spacing:1.2px;color:${C.mute};margin-top:2px}
|
||||
.chip{position:absolute;height:15px;padding:0 6px;border-radius:3px;font:700 7.6px 'JetBrains Mono',monospace;letter-spacing:1.1px;display:flex;align-items:center;white-space:nowrap}
|
||||
.cur{position:absolute;left:0;top:0;z-index:50;filter:drop-shadow(0 1px 2px rgba(0,0,0,.3))}
|
||||
.ring{position:absolute;width:34px;height:34px;margin:-17px 0 0 -17px;border-radius:50%;border:1.5px solid ${C.or};opacity:0;z-index:49}
|
||||
`;
|
||||
const el = (h) => {
|
||||
const d = document.createElement('div');
|
||||
d.innerHTML = h.trim();
|
||||
return d.firstElementChild;
|
||||
};
|
||||
const SUBS = [
|
||||
['OPTIC HEAD', '2 × 18 MM LENS · AMBER IR'],
|
||||
['NECK BEARING', '10-SEGMENT COLLAR'],
|
||||
['THORAX DRIVE', '3 GEARS · 11 ACTUATORS'],
|
||||
['WING ROOTS', '4 HINGES · 7.5 HZ CRANK'],
|
||||
['LEG SERVOS', '6 LEGS × 3 JOINTS'],
|
||||
['ABDOMEN BANDS', '5 SEGMENTS · GLASS STING'],
|
||||
];
|
||||
const LEGS = ['L1', 'L2', 'L3', 'R1', 'R2', 'R3'];
|
||||
|
||||
// opts (all optional, the first film's console when absent): views / viewLabel / viewsTitle / viewRows for the view
|
||||
// panel (the second film puts its assemblies there, in two rows), display / displayLabel for the toggles; the panels
|
||||
// below move down to make room and the subsystem rows close up.
|
||||
export function createConsole(app, opts = {}) {
|
||||
const views = opts.views ?? VIEWS;
|
||||
const viewLabel = opts.viewLabel ?? VIEW_LABEL;
|
||||
const display = opts.display ?? DISPLAY;
|
||||
const displayLabel = opts.displayLabel ?? DISPLAY_LABEL;
|
||||
const viewRows = opts.viewRows ?? 1;
|
||||
const style = document.createElement('style');
|
||||
style.textContent = CSS;
|
||||
document.head.appendChild(style);
|
||||
const ui = el(`<div class="ui"></div>`);
|
||||
app.appendChild(ui);
|
||||
const add = (h) => {
|
||||
const n = el(h);
|
||||
ui.appendChild(n);
|
||||
return n;
|
||||
};
|
||||
const panel = (x, y, w, h, title, n) => {
|
||||
add(`<div class="cp" style="left:${x}px;top:${y}px;width:${w}px;height:${h}px"></div>`);
|
||||
add(`<div class="ph" style="left:${x + 14}px;top:${y + 13}px"><i></i>${title}</div>`);
|
||||
add(`<div class="pn" style="right:${1600 - x - w + 14}px;top:${y + 15}px">${n}</div>`);
|
||||
};
|
||||
const hr = (x, y, w) => add(`<div style="position:absolute;left:${x}px;top:${y}px;width:${w}px;height:1px;background:${C.line}"></div>`);
|
||||
const L = {x: 24, w: 290};
|
||||
const R = {x: 1286, w: 290};
|
||||
|
||||
// ------------------------------------------------------------ header: badge, title, the lift bar, the status cells
|
||||
add(`<div style="position:absolute;left:0;top:0;width:160px;height:88px;background:${C.or}"></div>`);
|
||||
add(`<svg style="position:absolute;left:24px;top:24px" width="44" height="40" viewBox="0 0 44 40"><g fill="none" stroke="#fff" stroke-width="2.2"><path d="M22 3l9 5.2v10.4l-9 5.2-9-5.2V8.2z"/><path d="M13 14C7 6 1 9 2 14s7 5 11 2M31 14c6-8 12-5 11 0s-7 5-11 2"/><path d="M18 26l-3 10M26 26l3 10M22 24v12"/></g></svg>`);
|
||||
add(`<div class="mo" style="position:absolute;left:80px;top:34px;color:#fff;font-size:16px;font-weight:600;letter-spacing:3px">VX-9</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:182px;top:20px;letter-spacing:2.4px">ROBOTIC WASP · MICRO AIR VEHICLE</div>`);
|
||||
add(`<div style="position:absolute;left:181px;top:35px;font-size:33px;font-weight:700;letter-spacing:-.6px;line-height:1">Vespion VX-9 <span style="color:${C.or};font-weight:400">/</span></div>`);
|
||||
add(`<div class="mo" style="position:absolute;left:182px;top:74px;font-size:11.2px;letter-spacing:2.2px;color:#6d6357">FLAPPING-WING DRONE / FIELD SIMULATOR</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:700px;top:22px">LIFT LOAD</div>`);
|
||||
const liftPct = add(`<div class="mo" style="position:absolute;right:${1600 - 1040}px;top:21px;font-size:10px;font-weight:700"></div>`);
|
||||
const liftCells = [];
|
||||
for (let i = 0; i < 40; i++) liftCells.push(add(`<div style="position:absolute;left:${700 + i * 8.5}px;top:38px;width:6px;height:13px;border-radius:1px;background:${C.track}"></div>`));
|
||||
add(`<div class="sm" style="position:absolute;left:700px;top:57px;font-size:7.6px">IDLE</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:852px;top:57px;font-size:7.6px">HOVER</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:1010px;top:57px;font-size:7.6px">MAX</div>`);
|
||||
const cells = [
|
||||
['SIM ID', 'HB7-0412'],
|
||||
['RUNTIME', ''],
|
||||
['STATUS', ''],
|
||||
['OPERATOR', 'LAB 3 · R.K.'],
|
||||
];
|
||||
const cellV = cells.map(([k, v], i) => {
|
||||
const x = 1086 + i * 118;
|
||||
if (i) add(`<div style="position:absolute;left:${x - 12}px;top:20px;width:1px;height:44px;background:${C.faint}"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:${x}px;top:22px">${k}</div>`);
|
||||
return add(`<div class="mo" style="position:absolute;left:${x}px;top:40px;font-size:12px;font-weight:600;letter-spacing:.4px">${v}</div>`);
|
||||
});
|
||||
{
|
||||
let h = '';
|
||||
for (let r = 0; r < 2; r++) for (let c = 0; c < 14; c++) h += `<path d="M${c * 25 + 4} ${r * 22}v8M${c * 25} ${r * 22 + 4}h8" stroke="${C.or}" stroke-width="1.1" opacity=".55"/>`;
|
||||
add(`<svg style="position:absolute;left:640px;top:84px" width="352" height="34">${h}</svg>`);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 01 wing beat
|
||||
panel(L.x, 108, L.w, 226, 'WING BEAT', '01');
|
||||
const fq = add(`<div style="position:absolute;left:38px;top:140px;font-size:34px;font-weight:700;letter-spacing:-1px;line-height:1"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:39px;top:178px">STROKE FREQUENCY</div>`);
|
||||
const amp = add(`<div style="position:absolute;right:${1600 - 300}px;top:146px;font-size:22px;font-weight:700;line-height:1"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;right:${1600 - 300}px;top:178px">AMPLITUDE</div>`);
|
||||
const chart = add(`<svg style="position:absolute;left:38px;top:198px" width="262" height="96"></svg>`);
|
||||
hr(38, 302, 262);
|
||||
add(`<div class="sm" style="position:absolute;left:38px;top:312px">PLAYBACK</div>`);
|
||||
const pb = add(`<div class="v" style="position:absolute;left:104px;top:310px"></div>`);
|
||||
const shutter = add(`<div class="sm" style="position:absolute;right:${1600 - 300}px;top:312px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ 02 power
|
||||
panel(L.x, 346, L.w, 148, 'POWER', '02');
|
||||
const batt = add(`<div style="position:absolute;left:38px;top:378px;font-size:28px;font-weight:700;letter-spacing:-.8px;line-height:1"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:39px;top:410px">BATTERY</div>`);
|
||||
const battCells = [];
|
||||
for (let i = 0; i < 10; i++) battCells.push(add(`<div style="position:absolute;left:${150 + i * 15}px;top:383px;width:11px;height:20px;border-radius:2px;background:${C.track}"></div>`));
|
||||
hr(38, 428, 262);
|
||||
const pw = [['DRAW', 444], ['CELL', 444], ['MOTOR', 444]].map(([k], i) => {
|
||||
const x = 38 + i * 90;
|
||||
add(`<div class="sm" style="position:absolute;left:${x}px;top:440px">${k}</div>`);
|
||||
return add(`<div class="v" style="position:absolute;left:${x}px;top:458px;font-size:13px"></div>`);
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 03 leg servos
|
||||
panel(L.x, 506, L.w, 238, 'LEG SERVOS', '03');
|
||||
const legState = add(`<div class="chip" style="right:${1600 - 300}px;top:536px"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:38px;top:540px">LOAD PER LEG · KNEE TORQUE</div>`);
|
||||
const servo = LEGS.map((n, i) => {
|
||||
const y = 566 + i * 27;
|
||||
add(`<div class="mo" style="position:absolute;left:38px;top:${y}px;font-size:10px;font-weight:700">${n}</div>`);
|
||||
add(`<div style="position:absolute;left:66px;top:${y + 4}px;width:178px;height:6px;background:${C.track};border-radius:3px"></div>`);
|
||||
const f = add(`<div style="position:absolute;left:66px;top:${y + 4}px;height:6px;background:${C.ink};border-radius:3px"></div>`);
|
||||
const v = add(`<div class="v" style="position:absolute;right:${1600 - 300}px;top:${y - 1}px"></div>`);
|
||||
return {f, v};
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 04 flight
|
||||
panel(R.x, 108, R.w, 196, 'FLIGHT', '04');
|
||||
const ball = add(`<svg style="position:absolute;left:1300px;top:142px" width="96" height="96"></svg>`);
|
||||
const fl = [['ALT AGL', 0], ['V/S', 1], ['PITCH', 2], ['ROLL', 3]].map(([k], i) => {
|
||||
const y = 142 + i * 24;
|
||||
add(`<div class="sm" style="position:absolute;left:1412px;top:${y + 2}px">${k}</div>`);
|
||||
return add(`<div class="v" style="position:absolute;right:${1600 - 1562}px;top:${y}px"></div>`);
|
||||
});
|
||||
hr(1300, 252, 262);
|
||||
add(`<div class="sm" style="position:absolute;left:1300px;top:264px">HOLD</div>`);
|
||||
const hold = add(`<div class="v" style="position:absolute;left:1350px;top:262px"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:1440px;top:264px">AIRSPEED</div>`);
|
||||
const air = add(`<div class="v" style="position:absolute;right:${1600 - 1562}px;top:262px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ 05 views, 06 display
|
||||
const btn = {};
|
||||
const btnRow = (keys, labels, x0, y, wmax = 262, pad = 22) => {
|
||||
let x = x0;
|
||||
let yy = y;
|
||||
for (const k of keys) {
|
||||
const w = Math.round(labels[k].length * 7.1 + pad);
|
||||
if (x + w > x0 + wmax) {
|
||||
x = x0;
|
||||
yy += 30;
|
||||
}
|
||||
btn[k] = add(`<div class="bt" style="left:${x}px;top:${yy}px;width:${w}px">${labels[k]}</div>`);
|
||||
x += w + 6;
|
||||
}
|
||||
};
|
||||
const viewsH = 50 + 30 * viewRows;
|
||||
panel(R.x, 316, R.w, viewsH, opts.viewsTitle ?? 'VIEWS', '05');
|
||||
btnRow(views, viewLabel, 1300, 353, 262, 16);
|
||||
const dispY = 316 + viewsH + 12;
|
||||
panel(R.x, dispY, R.w, 110, 'DISPLAY', '06');
|
||||
btnRow(display, displayLabel, 1300, dispY + 37);
|
||||
const subY = dispY + 122;
|
||||
const subStep = Math.min(29, (744 - subY - 40) / 6);
|
||||
|
||||
// ------------------------------------------------------------ 07 subsystems
|
||||
panel(R.x, subY, R.w, 744 - subY, 'SUBSYSTEMS', '07');
|
||||
const subs = SUBS.map(([n, d], i) => {
|
||||
const y = subY + 34 + i * subStep;
|
||||
const bar = add(`<div style="position:absolute;left:1296px;top:${y}px;width:2px;height:22px;background:transparent"></div>`);
|
||||
add(`<div class="mo" style="position:absolute;left:1304px;top:${y + 1}px;font-size:9px;color:${C.mute}">0${i + 1}</div>`);
|
||||
const name = add(`<div class="mo" style="position:absolute;left:1328px;top:${y}px;font-size:9.4px;font-weight:700;letter-spacing:1.2px">${n}</div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:1328px;top:${y + 13}px;font-size:7.6px">${d}</div>`);
|
||||
const chip = add(`<div class="chip" style="right:${1600 - 1562}px;top:${y + 3}px"></div>`);
|
||||
return {bar, name, chip};
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 08 flight log
|
||||
panel(330, 760, 940, 98, 'FLIGHT LOG', '08');
|
||||
add(`<div class="bt" style="left:346px;top:796px;width:44px;height:44px;border-radius:50%;border:none;background:${C.or};color:#fff;font-size:14px">❚❚</div>`);
|
||||
const logMode = add(`<div class="mo" style="position:absolute;left:406px;width:780px;top:790px;text-align:center;font-size:9.6px;font-weight:700;letter-spacing:1.6px;color:${C.or}"></div>`);
|
||||
add(`<div class="sm" style="position:absolute;left:406px;top:791px">TAKE-OFF</div>`);
|
||||
add(`<div class="sm" style="position:absolute;right:${1600 - 1250}px;top:791px">LAND</div>`);
|
||||
const TLB = {x: 408, w: 840};
|
||||
add(`<div style="position:absolute;left:${TLB.x}px;top:818px;width:${TLB.w}px;height:3px;background:${C.track};border-radius:2px"></div>`);
|
||||
const tlFill = add(`<div style="position:absolute;left:${TLB.x}px;top:818px;height:3px;background:${C.or};border-radius:2px"></div>`);
|
||||
const tlTicks = add(`<div style="position:absolute;inset:0"></div>`);
|
||||
const tlKnob = add(`<div style="position:absolute;top:812px;width:15px;height:15px;margin-left:-7.5px;border-radius:50%;background:#fff;border:2px solid ${C.or};box-sizing:border-box"></div>`);
|
||||
const tlTime = add(`<div class="mo" style="position:absolute;left:406px;top:834px;font-size:9.6px;color:${C.mute};letter-spacing:1px"></div>`);
|
||||
const tlNext = add(`<div class="sm" style="position:absolute;right:${1600 - 1250}px;top:836px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ viewport notes: model, the view, the flight mode
|
||||
add(`<div class="sm" style="position:absolute;left:346px;top:122px;letter-spacing:2px">MODEL VX-9 · REV A</div>`);
|
||||
const viewNote = add(`<div class="sm" style="position:absolute;right:${1600 - 1254}px;top:122px;letter-spacing:2px"></div>`);
|
||||
add(`<svg style="position:absolute;left:346px;top:140px" width="60" height="60"><path d="M0 60V0h60" fill="none" stroke="${C.or}" stroke-width="1" stroke-dasharray="3 3" opacity=".6"/></svg>`);
|
||||
add(`<svg style="position:absolute;left:1194px;top:680px" width="60" height="60"><path d="M60 0v60H0" fill="none" stroke="${C.or}" stroke-width="1" stroke-dasharray="3 3" opacity=".6"/></svg>`);
|
||||
add(`<div class="sm" style="position:absolute;left:346px;top:666px">FLIGHT MODE</div>`);
|
||||
const mode = add(`<div style="position:absolute;left:345px;top:680px;font-size:30px;font-weight:700;letter-spacing:-.4px;line-height:1;color:${C.or}"></div>`);
|
||||
const modeSub = add(`<div class="sm" style="position:absolute;left:346px;top:716px"></div>`);
|
||||
|
||||
// ------------------------------------------------------------ footer
|
||||
add(`<div class="sm" style="position:absolute;left:27px;top:878px;letter-spacing:2.2px">FIELD SIMULATOR · PROCEDURAL MODEL · 6 LEGS · 4 WINGS · 2 OPTICS</div>`);
|
||||
add(`<div class="sm" style="position:absolute;right:28px;top:878px;letter-spacing:2.2px">VESPION ROBOTICS · INTERCEPT LAB <span style="color:${C.or}">//////</span></div>`);
|
||||
|
||||
// ------------------------------------------------------------ labels, the pointer
|
||||
const callSvg = add(`<svg style="position:absolute;inset:0;overflow:visible" width="1600" height="900"></svg>`);
|
||||
const callG = add(`<div style="position:absolute;inset:0"></div>`);
|
||||
const ring = add(`<div class="ring"></div>`);
|
||||
const cur = add(`<div class="cur"><svg width="22" height="22" viewBox="0 0 34 34"><path d="M4 3 L30 13.5 L17.5 17.5 L13.5 30 Z" fill="#111" stroke="#fff" stroke-width="2.2" stroke-linejoin="round"/></svg></div>`);
|
||||
const centre = (n) => {
|
||||
const r = n.getBoundingClientRect();
|
||||
return [r.left + r.width / 2, r.top + r.height / 2];
|
||||
};
|
||||
const spots = Object.fromEntries(Object.entries(btn).map(([k, n]) => [k, centre(n)]));
|
||||
const pointer = (c) => {
|
||||
cur.style.display = c.x < 0 ? 'none' : 'block';
|
||||
cur.style.transform = `translate(${(c.x - 3).toFixed(2)}px, ${(c.y - 2).toFixed(2)}px) scale(${c.press ? 0.88 : 1})`;
|
||||
ring.style.left = `${c.ringX}px`;
|
||||
ring.style.top = `${c.ringY}px`;
|
||||
ring.style.opacity = String(c.ring * 0.85);
|
||||
ring.style.transform = `scale(${(0.35 + 0.9 * (1 - c.ring)).toFixed(3)})`;
|
||||
};
|
||||
const clock = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(Math.floor(s) % 60).padStart(2, '0')}`;
|
||||
const chipStyle = (n, kind, text) => {
|
||||
const k = {ok: [C.green, '#fff'], warn: [C.or, '#fff'], idle: [C.track, C.mute]}[kind];
|
||||
n.style.background = k[0];
|
||||
n.style.color = k[1];
|
||||
n.textContent = text;
|
||||
};
|
||||
let tickKey = '';
|
||||
|
||||
return {
|
||||
spots,
|
||||
btn,
|
||||
root: ui,
|
||||
TLB,
|
||||
update(s) {
|
||||
// header
|
||||
const lift = Math.round(s.lift * 40);
|
||||
liftCells.forEach((c, i) => (c.style.background = i < lift ? (i > 30 ? C.or : C.ink) : C.track));
|
||||
liftPct.textContent = `${Math.round(s.lift * 100)}%`;
|
||||
cellV[1].textContent = `00:00:${String(Math.floor(s.time)).padStart(2, '0')}`;
|
||||
cellV[2].innerHTML = `<span style="color:${s.statusKind === 'ok' ? C.green : C.or}">●</span> ${s.status}`;
|
||||
// wing beat: the frequency, the amplitude, the stroke of the near forewing (orange) and hindwing (grey) over the
|
||||
// last 1.2 s, with the now marker on the right
|
||||
fq.innerHTML = `${s.freq.toFixed(1)}<span style="font-size:14px;font-weight:600;color:${C.mute}"> HZ</span>`;
|
||||
amp.textContent = `±${Math.round(s.amp)}°`;
|
||||
{
|
||||
const W = 262;
|
||||
const H = 96;
|
||||
const Y = (a) => H / 2 - (a / 40) * (H / 2 - 8);
|
||||
let g = `<line x1="0" x2="${W}" y1="${H / 2}" y2="${H / 2}" stroke="${C.faint}" stroke-width="1"/>`;
|
||||
for (const a of [-32, 32]) g += `<line x1="0" x2="${W}" y1="${Y(a)}" y2="${Y(a)}" stroke="${C.line}" stroke-width="1" stroke-dasharray="2 3"/><text x="${W - 2}" y="${Y(a) - 3}" text-anchor="end" font-size="7" fill="${C.mute}" font-family="JetBrains Mono">${a > 0 ? '+' : ''}${a}°</text>`;
|
||||
const path = (k) => s.stroke.map((p, i) => `${i ? 'L' : 'M'}${((i / (s.stroke.length - 1)) * (W - 10)).toFixed(1)} ${Y(p[k]).toFixed(1)}`).join('');
|
||||
g += `<path d="${path(1)}" fill="none" stroke="${C.mute}" stroke-width="1" opacity=".7"/><path d="${path(0)}" fill="none" stroke="${C.or}" stroke-width="1.6"/>`;
|
||||
const last = s.stroke[s.stroke.length - 1];
|
||||
g += `<line x1="${W - 10}" x2="${W - 10}" y1="4" y2="${H - 4}" stroke="${C.ink}" stroke-width=".8" stroke-dasharray="2 2"/><circle cx="${W - 10}" cy="${Y(last[0]).toFixed(1)}" r="3.4" fill="${C.or}"/>`;
|
||||
g += `<text x="0" y="${H - 1}" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">−1.2 S</text><text x="${W - 14}" y="${H - 1}" text-anchor="end" font-size="7" fill="${C.mute}" font-family="JetBrains Mono" letter-spacing="1">NOW</text>`;
|
||||
chart.innerHTML = g;
|
||||
}
|
||||
pb.textContent = `${s.playback.toFixed(1)}×`;
|
||||
shutter.textContent = s.blur > 0.5 ? 'SHUTTER 1/60' : 'HI-SPEED 1/2000';
|
||||
// power
|
||||
batt.innerHTML = `${Math.round(s.battery * 100)}<span style="font-size:13px;color:${C.mute}">%</span>`;
|
||||
const bc = Math.round(s.battery * 10);
|
||||
battCells.forEach((c, i) => (c.style.background = i < bc ? (i < 2 ? C.or : C.green) : C.track));
|
||||
pw[0].textContent = `${s.power.toFixed(1)} W`;
|
||||
pw[1].textContent = `${s.volt.toFixed(2)} V`;
|
||||
pw[2].textContent = `${s.motorT.toFixed(0)} °C`;
|
||||
// leg servos
|
||||
chipStyle(legState, s.legsFree ? 'warn' : 'ok', s.legsFree ? 'DETACHED' : 'HOLDING');
|
||||
servo.forEach((b, i) => {
|
||||
const v = s.servos[i];
|
||||
b.f.style.width = `${(v * 178).toFixed(1)}px`;
|
||||
const free = s.legFreeEach ? s.legFreeEach[i] : s.legsFree;
|
||||
b.f.style.background = v > 0.6 ? C.or : C.ink;
|
||||
b.v.textContent = free ? 'DETACHED' : `${Math.round(v * 100)}%`;
|
||||
b.v.style.color = free ? C.or : C.ink;
|
||||
b.v.style.fontSize = free ? '8.6px' : '11px';
|
||||
});
|
||||
// flight: the attitude ball (the horizon tilts with roll and slides with pitch) and the numbers
|
||||
{
|
||||
const r = 44;
|
||||
const off = s.pitch * 2.2;
|
||||
ball.innerHTML = `<defs><clipPath id="bc"><circle cx="48" cy="48" r="${r}"/></clipPath></defs><circle cx="48" cy="48" r="${r}" fill="#fbf8f3" stroke="${C.faint}"/><g clip-path="url(#bc)"><g transform="rotate(${(-s.roll).toFixed(2)} 48 48) translate(0 ${off.toFixed(2)})"><rect x="-20" y="48" width="136" height="70" fill="${C.track}"/><line x1="-20" x2="116" y1="48" y2="48" stroke="${C.ink}" stroke-width="1"/>${[-20, -10, 10, 20].map((p) => `<line x1="${48 - (Math.abs(p) > 10 ? 12 : 7)}" x2="${48 + (Math.abs(p) > 10 ? 12 : 7)}" y1="${48 - p * 2.2}" y2="${48 - p * 2.2}" stroke="${C.mute}" stroke-width=".8"/>`).join('')}</g></g><path d="M26 48h14l4 5 4-5h22" fill="none" stroke="${C.or}" stroke-width="2"/><circle cx="48" cy="48" r="2" fill="${C.or}"/>`;
|
||||
fl[0].textContent = s.airborne ? `${s.alt.toFixed(1)} MM` : '—';
|
||||
fl[1].textContent = s.airborne ? `${s.vs >= 0 ? '+' : '−'}${Math.abs(s.vs).toFixed(1)} MM/S` : '—';
|
||||
fl[2].textContent = `${s.pitch >= 0 ? '+' : '−'}${Math.abs(s.pitch).toFixed(2)}°`;
|
||||
fl[3].textContent = `${s.roll >= 0 ? '+' : '−'}${Math.abs(s.roll).toFixed(2)}°`;
|
||||
hold.textContent = s.airborne ? 'POSITION' : 'OFF';
|
||||
air.textContent = `${s.airspeed.toFixed(2)} M/S`;
|
||||
}
|
||||
// views, display
|
||||
const onBtn = (k, on) => {
|
||||
btn[k].style.background = on ? C.or : '#fffdf9';
|
||||
btn[k].style.color = on ? '#fff' : C.ink;
|
||||
btn[k].style.borderColor = on ? C.or : C.faint;
|
||||
};
|
||||
for (const k of views) onBtn(k, s.view === k);
|
||||
for (const k of display) onBtn(k, !!s.display[k]);
|
||||
// subsystems: a status chip each, the row the current view looks at marked
|
||||
subs.forEach((r, i) => {
|
||||
const [kind, text] = s.subs[i];
|
||||
chipStyle(r.chip, kind, text);
|
||||
r.bar.style.background = s.focus === i ? C.or : 'transparent';
|
||||
r.name.style.color = s.focus === i ? C.or : C.ink;
|
||||
});
|
||||
// flight log: the film's progress, a tick for every press, the mode
|
||||
const kx = TLB.x + (s.time / s.dur) * TLB.w;
|
||||
tlFill.style.width = `${(kx - TLB.x).toFixed(1)}px`;
|
||||
tlKnob.style.left = `${kx.toFixed(1)}px`;
|
||||
const key = s.events.length;
|
||||
if (key !== tickKey) {
|
||||
tickKey = key;
|
||||
tlTicks.innerHTML = s.events.map((e) => `<div style="position:absolute;left:${(TLB.x + (e / s.dur) * TLB.w - 1).toFixed(1)}px;top:813px;width:2px;height:13px;background:${C.ink};opacity:.35"></div>`).join('');
|
||||
}
|
||||
tlTime.textContent = `${clock(s.time)} / ${clock(s.dur)}`;
|
||||
tlNext.textContent = s.next;
|
||||
logMode.textContent = s.log;
|
||||
viewNote.textContent = s.viewNote ?? `VIEW · ${viewLabel[s.view]}${s.display.orbit ? ' · ORBIT' : ''}`;
|
||||
mode.textContent = s.mode;
|
||||
modeSub.textContent = s.modeSub;
|
||||
// labels: an orange square, the name, the note, a thin leader to the part
|
||||
let lh = '';
|
||||
let ch = '';
|
||||
for (const c of s.callouts) {
|
||||
if (c.o < 0.02 || !c.at) continue;
|
||||
const [ax, ay] = c.at;
|
||||
const [lx, ly] = c.label;
|
||||
const right = lx > ax;
|
||||
const ex = right ? lx - 6 : lx + c.w + 6;
|
||||
lh += `<polyline points="${ax.toFixed(1)},${ay.toFixed(1)} ${ex.toFixed(1)},${(ly + 6).toFixed(1)}" fill="none" stroke="${C.or}" stroke-width=".9" opacity="${c.o.toFixed(2)}"/><circle cx="${ax.toFixed(1)}" cy="${ay.toFixed(1)}" r="2.4" fill="${C.or}" opacity="${c.o.toFixed(2)}"/>`;
|
||||
ch += `<div class="call" style="left:${lx.toFixed(1)}px;top:${(ly - 1).toFixed(1)}px;opacity:${c.o.toFixed(2)}"><b><i></i>${c.name}</b><span>${c.sub}</span></div>`;
|
||||
}
|
||||
callSvg.innerHTML = lh;
|
||||
callG.innerHTML = ch;
|
||||
pointer(s.cursor);
|
||||
},
|
||||
pointer,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// The construction drawing around the bee: hairline arcs and dashed circles in a few tilted planes, dots and small
|
||||
// hollow markers riding on them, short ticks. All in world space round the bee, so a camera orbit gives them depth.
|
||||
// Lines are fat lines with a width in device pixels; resize() keeps them hairline at any pixel ratio.
|
||||
import * as THREE from 'three';
|
||||
import {Line2} from 'three/addons/lines/Line2.js';
|
||||
import {LineGeometry} from 'three/addons/lines/LineGeometry.js';
|
||||
import {LineMaterial} from 'three/addons/lines/LineMaterial.js';
|
||||
import {rng} from '../kit/util.js';
|
||||
|
||||
const V3 = THREE.Vector3;
|
||||
const INK = '#8a8178';
|
||||
|
||||
export function buildGuides({centre = [0.05, 0.1, 0], seed = 5} = {}) {
|
||||
const R = rng(seed);
|
||||
const group = new THREE.Group();
|
||||
const lines = [];
|
||||
const C = new V3(...centre);
|
||||
// two unit vectors spanning the plane with normal n
|
||||
const basis = (n) => {
|
||||
const a = Math.abs(n.y) < 0.9 ? new V3(0, 1, 0) : new V3(1, 0, 0);
|
||||
const u = new V3().crossVectors(a, n).normalize();
|
||||
return [u, new V3().crossVectors(n, u)];
|
||||
};
|
||||
const circ = (c, r, n, a) => {
|
||||
const [u, v] = basis(n.clone().normalize());
|
||||
return c.clone().addScaledVector(u, Math.cos(a) * r).addScaledVector(v, Math.sin(a) * r);
|
||||
};
|
||||
const arc = (c, r, n, a0, a1, {dashed = false, width = 1, opacity = 0.5, dash = 0.045} = {}) => {
|
||||
const N = Math.max(24, Math.round(Math.abs(a1 - a0) * r * 60));
|
||||
const pts = [];
|
||||
for (let i = 0; i <= N; i++) {
|
||||
const p = circ(c, r, n, a0 + ((a1 - a0) * i) / N);
|
||||
pts.push(p.x, p.y, p.z);
|
||||
}
|
||||
const g = new LineGeometry();
|
||||
g.setPositions(pts);
|
||||
const m = new LineMaterial({color: INK, linewidth: width, transparent: true, opacity, dashed, dashSize: dash, gapSize: dash * 0.8, depthWrite: false, worldUnits: false});
|
||||
const l = new Line2(g, m);
|
||||
l.computeLineDistances();
|
||||
l.renderOrder = 4;
|
||||
group.add(l);
|
||||
lines.push({m, width, opacity});
|
||||
return l;
|
||||
};
|
||||
const seg = (a, b, opts = {}) => {
|
||||
const g = new LineGeometry();
|
||||
g.setPositions([a.x, a.y, a.z, b.x, b.y, b.z]);
|
||||
const m = new LineMaterial({color: INK, linewidth: opts.width ?? 1, transparent: true, opacity: opts.opacity ?? 0.45, dashed: !!opts.dashed, dashSize: 0.04, gapSize: 0.035, depthWrite: false});
|
||||
const l = new Line2(g, m);
|
||||
l.computeLineDistances();
|
||||
l.renderOrder = 4;
|
||||
group.add(l);
|
||||
lines.push({m, width: opts.width ?? 1, opacity: opts.opacity ?? 0.45});
|
||||
};
|
||||
|
||||
// the rings: [radius, normal, arcs, dashed, width, opacity]
|
||||
const RINGS = [
|
||||
[2.75, new V3(0.35, 0.25, 1), [[0.15, 1.9], [2.4, 3.5], [4.1, 5.6]], false, 1.0, 0.42],
|
||||
[2.05, new V3(0.1, 1, 0.3), [[0, Math.PI * 2]], true, 1.0, 0.45],
|
||||
[1.35, new V3(1, 0.15, 0.05), [[0.3, 2.6], [3.3, 5.5]], false, 1.1, 0.5],
|
||||
[3.45, new V3(0.55, 0.75, 0.35), [[0.6, 2.2], [3.6, 4.6]], false, 0.9, 0.32],
|
||||
[1.7, new V3(-0.4, 0.3, 1), [[0, Math.PI * 2]], true, 0.9, 0.36],
|
||||
[2.35, new V3(0.9, -0.2, 0.4), [[1.0, 2.9], [4.2, 5.9]], false, 0.9, 0.34],
|
||||
];
|
||||
const onRing = [];
|
||||
for (const [r, n, arcs, dashed, w, o] of RINGS) {
|
||||
for (const [a0, a1] of arcs) arc(C, r, n, a0, a1, {dashed, width: w, opacity: o});
|
||||
onRing.push([r, n, arcs]);
|
||||
}
|
||||
// a small ring round the eye and one round the tail, offset from the main centre
|
||||
arc(new V3(1.2, 0.14, 0.1), 0.62, new V3(0.55, 0.05, 0.85), 0, Math.PI * 2, {dashed: true, width: 0.9, opacity: 0.4, dash: 0.03});
|
||||
arc(new V3(-1.15, -0.25, 0), 0.75, new V3(-0.9, -0.3, 0.3), 0.4, 4.6, {width: 0.9, opacity: 0.38});
|
||||
|
||||
// dots and hollow markers riding on the rings, ticks across them
|
||||
const dots = [];
|
||||
const marks = new THREE.Group();
|
||||
group.add(marks);
|
||||
const dotGeo = new THREE.SphereGeometry(1, 10, 8);
|
||||
const dotMat = new THREE.MeshBasicMaterial({color: '#5d5751', transparent: true, opacity: 0.75, depthWrite: false});
|
||||
const ringGeo = new THREE.RingGeometry(0.62, 1, 28);
|
||||
const ringMat = new THREE.MeshBasicMaterial({color: '#6e675f', transparent: true, opacity: 0.7, depthWrite: false, side: THREE.DoubleSide});
|
||||
for (const [r, n, arcs] of onRing) {
|
||||
for (const [a0, a1] of arcs) {
|
||||
const k = Math.max(1, Math.round((a1 - a0) * 1.6));
|
||||
for (let i = 0; i < k; i++) {
|
||||
const a = a0 + (a1 - a0) * R();
|
||||
const p = circ(C, r, n, a);
|
||||
if (R() < 0.6) {
|
||||
const d = new THREE.Mesh(dotGeo, dotMat);
|
||||
d.position.copy(p);
|
||||
d.scale.setScalar(0.009 + R() * 0.012);
|
||||
d.renderOrder = 5;
|
||||
group.add(d);
|
||||
dots.push(d);
|
||||
} else {
|
||||
const m = new THREE.Mesh(ringGeo, ringMat);
|
||||
m.position.copy(p);
|
||||
m.scale.setScalar(0.022 + R() * 0.016);
|
||||
m.renderOrder = 5;
|
||||
marks.add(m);
|
||||
}
|
||||
// a short tick across the ring at some of them
|
||||
if (R() < 0.35) {
|
||||
const t = circ(C, r * 1.04, n, a);
|
||||
const b = circ(C, r * 0.96, n, a);
|
||||
seg(t, b, {width: 1, opacity: 0.5});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// a few straight dashed leaders out from the body
|
||||
for (const [a, b] of [
|
||||
[new V3(0.9, 0.55, 0.2), new V3(1.9, 1.6, 0.4)],
|
||||
[new V3(-0.6, -0.4, 0.3), new V3(-1.9, -1.1, 0.9)],
|
||||
[new V3(0.2, 0.5, -0.3), new V3(0.6, 1.9, -0.8)],
|
||||
]) {
|
||||
seg(a, b, {dashed: true, width: 0.9, opacity: 0.38});
|
||||
}
|
||||
|
||||
return {
|
||||
group,
|
||||
resize(w, h, pr) {
|
||||
for (const L of lines) {
|
||||
L.m.resolution.set(w, h);
|
||||
L.m.linewidth = L.width * pr;
|
||||
}
|
||||
},
|
||||
// ops.guides 0..1 fades the whole drawing
|
||||
update(camera, ops = {}) {
|
||||
const k = ops.guides ?? 1;
|
||||
group.userData.show = k > 0.001;
|
||||
group.visible = group.userData.show;
|
||||
for (const L of lines) L.m.opacity = Math.min(1, L.opacity * 1.1 * k);
|
||||
dotMat.opacity = 0.75 * k;
|
||||
ringMat.opacity = 0.7 * k;
|
||||
for (const m of marks.children) m.quaternion.copy(camera.quaternion);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
// The robotic bee's kitbash shop: the materials (gloss white shell, orange accent, graphite and black mechanism,
|
||||
// steel, the lens, the clear abdomen and the wing membrane) and the geometry every part is cut from. Everything is
|
||||
// built along +x and placed by the caller: sweepX turns a closed (x, r) profile round the x axis, whole or as an arc
|
||||
// with capped ends, which gives rings, collars, domes, shell plates and capsules from one function; gearGeo cuts a
|
||||
// toothed wheel with a bore; tube runs a cable along points.
|
||||
import * as THREE from 'three';
|
||||
import {RoundedBoxGeometry} from 'three/addons/geometries/RoundedBoxGeometry.js';
|
||||
import {mergeGeometries} from 'three/addons/utils/BufferGeometryUtils.js';
|
||||
|
||||
export const V3 = THREE.Vector3;
|
||||
export const D2R = Math.PI / 180;
|
||||
export const PAL = {white: '#f4f2ee', orange: '#ff5a1f', graphite: '#2f3238', black: '#111214', steel: '#cdd1d6'};
|
||||
|
||||
export function makeMaterials() {
|
||||
const phys = (o) => new THREE.MeshPhysicalMaterial(o);
|
||||
const std = (o) => new THREE.MeshStandardMaterial(o);
|
||||
return {
|
||||
// the white plastic: a soft base under a hard clear coat, so the softboxes sit on it as crisp bars
|
||||
shell: phys({color: PAL.white, roughness: 0.34, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.05}),
|
||||
// inside faces of the shells, a shade darker and matte
|
||||
shellIn: phys({color: '#dedad4', roughness: 0.6, metalness: 0, clearcoat: 0.2, clearcoatRoughness: 0.4, side: THREE.DoubleSide}),
|
||||
orange: phys({color: PAL.orange, roughness: 0.3, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.08}),
|
||||
// the orange panel at a wing tip: a film on the membrane, both faces, pulled forward so it never fights it
|
||||
orangeFilm: phys({color: PAL.orange, roughness: 0.32, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.08, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2}),
|
||||
graphite: std({color: PAL.graphite, roughness: 0.36, metalness: 0.72}),
|
||||
gunmetal: std({color: '#555a62', roughness: 0.28, metalness: 0.9}),
|
||||
black: phys({color: PAL.black, roughness: 0.3, metalness: 0.15, clearcoat: 0.8, clearcoatRoughness: 0.12}),
|
||||
rubber: std({color: '#1b1c1f', roughness: 0.7, metalness: 0}),
|
||||
steel: std({color: PAL.steel, roughness: 0.2, metalness: 1}),
|
||||
// the camera eye: a deep black inner element under a dark glass dome; its colour darkens only what shows
|
||||
// through it, the highlights stay at full strength
|
||||
lens: phys({color: '#020203', roughness: 0.05, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.02, envMapIntensity: 1.4}),
|
||||
lensGlass: phys({color: '#6f7277', roughness: 0, metalness: 0, transmission: 1, thickness: 0, ior: 1.5, clearcoat: 1, clearcoatRoughness: 0, specularIntensity: 1, envMapIntensity: 2.4}),
|
||||
amber: std({color: '#000000', emissive: '#ffa040', emissiveIntensity: 4.5}),
|
||||
// circuit boards in the thorax: a dark green-black laminate
|
||||
pcb: std({color: '#1b241f', roughness: 0.55, metalness: 0.1}),
|
||||
// the clear abdomen window: real transmission, so the mechanism inside refracts a touch
|
||||
glass: phys({color: '#ffffff', roughness: 0.0, metalness: 0, transmission: 1, thickness: 0, ior: 1.3, specularIntensity: 0.6, clearcoat: 0.5, clearcoatRoughness: 0.02}),
|
||||
// the wing film: a faint grey-white sheet; the veins and the rim carry the read
|
||||
membrane: phys({color: '#eef0f2', roughness: 0.38, metalness: 0, transparent: true, opacity: 0.3, depthWrite: false, side: THREE.DoubleSide, clearcoat: 1, clearcoatRoughness: 0.04, iridescence: 0.35, iridescenceIOR: 1.3}),
|
||||
// the wing rim: a pale clear-ish tube
|
||||
rim: phys({color: '#e4e7ea', roughness: 0.12, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.04, transparent: true, opacity: 0.55, depthWrite: false}),
|
||||
vein: std({color: '#4a4d53', roughness: 0.5, metalness: 0.2, transparent: true, opacity: 0.72}),
|
||||
veinCore: std({color: '#5a5d63', roughness: 0.5, metalness: 0.2}),
|
||||
led: std({color: '#000000', emissive: PAL.orange, emissiveIntensity: 1.4}),
|
||||
// the wasp: the orange light inside the waist rings, the abdomen gaps and the sting, a touch hotter than led
|
||||
glow: std({color: '#000000', emissive: '#ff6a1c', emissiveIntensity: 1.9}),
|
||||
// the sting: clear glass tinted toward amber, the glow core shows through it
|
||||
// a faint amber tint in the glass itself
|
||||
sting: phys({color: '#fff0e2', roughness: 0.04, metalness: 0, transmission: 1, thickness: 0.035, ior: 1.3, attenuationColor: '#ffb27a', attenuationDistance: 1.4, specularIntensity: 1, clearcoat: 1, clearcoatRoughness: 0.02, envMapIntensity: 1.8}),
|
||||
// the sting's rim: a fresnel edge in warm amber over the glass, strongest where the surface turns from the eye
|
||||
stingRim: new THREE.ShaderMaterial({
|
||||
transparent: true,
|
||||
depthWrite: false,
|
||||
uniforms: {uColor: {value: new THREE.Color('#7c5236')}, uK: {value: 0.85}},
|
||||
vertexShader: 'varying vec3 vN; varying vec3 vV; void main(){ vec4 mv = modelViewMatrix * vec4(position, 1.0); vN = normalize(normalMatrix * normal); vV = normalize(-mv.xyz); gl_Position = projectionMatrix * mv; }',
|
||||
fragmentShader: 'uniform vec3 uColor; uniform float uK; varying vec3 vN; varying vec3 vV; void main(){ float f = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 2.0); gl_FragColor = vec4(uColor, f * uK); }',
|
||||
}),
|
||||
stingCore: std({color: '#000000', emissive: '#ff7424', emissiveIntensity: 2.0}),
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ sweepX: a closed (x, r) profile turned round the x axis
|
||||
// profile: [[x, r], ...] closed loop, either winding. a0..a1: the arc, angle 0 at +y, 90° at +z. Profile corners
|
||||
// sharper than `smooth` degrees keep a hard edge; softer ones are shaded smooth. A partial arc gets capped ends.
|
||||
export function sweepX(profile, {a0 = 0, a1 = Math.PI * 2, segs = 64, smooth = 32} = {}) {
|
||||
let P = profile.map(([x, r]) => [x, Math.max(0, r)]);
|
||||
let area = 0;
|
||||
for (let i = 0; i < P.length; i++) {
|
||||
const [x0, r0] = P[i];
|
||||
const [x1, r1] = P[(i + 1) % P.length];
|
||||
area += x0 * r1 - x1 * r0;
|
||||
}
|
||||
if (area < 0) P = P.reverse();
|
||||
const n = P.length;
|
||||
// outward edge normals in the (x, r) plane
|
||||
const EN = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const [x0, r0] = P[i];
|
||||
const [x1, r1] = P[(i + 1) % n];
|
||||
const l = Math.hypot(x1 - x0, r1 - r0) || 1;
|
||||
EN.push([(r1 - r0) / l, -(x1 - x0) / l]);
|
||||
}
|
||||
const cosS = Math.cos(smooth * D2R);
|
||||
const vN = (i, e) => {
|
||||
// normal at vertex i as seen from edge e (e is i-1 or i)
|
||||
const other = e === i ? (i - 1 + n) % n : i;
|
||||
const a = EN[e];
|
||||
const b = EN[other];
|
||||
if (a[0] * b[0] + a[1] * b[1] < cosS) return a;
|
||||
const x = a[0] + b[0];
|
||||
const y = a[1] + b[1];
|
||||
const l = Math.hypot(x, y) || 1;
|
||||
return [x / l, y / l];
|
||||
};
|
||||
const full = Math.abs(a1 - a0) >= Math.PI * 2 - 1e-6;
|
||||
const pos = [];
|
||||
const nor = [];
|
||||
const idx = [];
|
||||
const cs = [];
|
||||
for (let j = 0; j <= segs; j++) {
|
||||
const th = a0 + ((a1 - a0) * j) / segs;
|
||||
cs.push([Math.cos(th), Math.sin(th)]);
|
||||
}
|
||||
for (let e = 0; e < n; e++) {
|
||||
const i0 = e;
|
||||
const i1 = (e + 1) % n;
|
||||
const [x0, r0] = P[i0];
|
||||
const [x1, r1] = P[i1];
|
||||
if (Math.hypot(x1 - x0, r1 - r0) < 1e-9) continue;
|
||||
const n0 = vN(i0, e);
|
||||
const n1 = vN(i1, e);
|
||||
const base = pos.length / 3;
|
||||
for (let j = 0; j <= segs; j++) {
|
||||
const [c, s] = cs[j];
|
||||
pos.push(x0, r0 * c, r0 * s, x1, r1 * c, r1 * s);
|
||||
nor.push(n0[0], n0[1] * c, n0[1] * s, n1[0], n1[1] * c, n1[1] * s);
|
||||
}
|
||||
for (let j = 0; j < segs; j++) {
|
||||
const a = base + j * 2;
|
||||
const b = a + 1;
|
||||
const c = a + 3;
|
||||
const d = a + 2;
|
||||
idx.push(a, b, c, a, c, d);
|
||||
}
|
||||
}
|
||||
if (!full) {
|
||||
const tri = THREE.ShapeUtils.triangulateShape(
|
||||
P.map(([x, r]) => new THREE.Vector2(x, r)),
|
||||
[],
|
||||
);
|
||||
for (const [th, flip] of [
|
||||
[a0, true],
|
||||
[a1, false],
|
||||
]) {
|
||||
const c = Math.cos(th);
|
||||
const s = Math.sin(th);
|
||||
// the cap's normal: -d/dθ at a0, +d/dθ at a1
|
||||
const nx = 0;
|
||||
const ny = flip ? s : -s;
|
||||
const nz = flip ? -c : c;
|
||||
const base = pos.length / 3;
|
||||
for (const [x, r] of P) {
|
||||
pos.push(x, r * c, r * s);
|
||||
nor.push(nx, ny, nz);
|
||||
}
|
||||
for (const t of tri) {
|
||||
if (flip) idx.push(base + t[0], base + t[2], base + t[1]);
|
||||
else idx.push(base + t[0], base + t[1], base + t[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
const g = new THREE.BufferGeometry();
|
||||
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
|
||||
g.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
|
||||
g.setIndex(idx);
|
||||
return g;
|
||||
}
|
||||
|
||||
// a rounded rectangle profile for a ring: x0..x1 wide, r0..r1 deep, corners rounded by `round`
|
||||
export function ringProfile(x0, x1, r0, r1, round = 0.01, steps = 3) {
|
||||
const rr = Math.min(round, (x1 - x0) / 2.01, (r1 - r0) / 2.01);
|
||||
const pts = [];
|
||||
const corner = (cx, cr, a0) => {
|
||||
for (let k = 0; k <= steps; k++) {
|
||||
const a = a0 + (k / steps) * (Math.PI / 2);
|
||||
pts.push([cx + Math.cos(a) * rr, cr + Math.sin(a) * rr]);
|
||||
}
|
||||
};
|
||||
corner(x1 - rr, r0 + rr, -Math.PI / 2);
|
||||
corner(x1 - rr, r1 - rr, 0);
|
||||
corner(x0 + rr, r1 - rr, Math.PI / 2);
|
||||
corner(x0 + rr, r0 + rr, Math.PI);
|
||||
return pts;
|
||||
}
|
||||
export const ring = (x0, x1, r0, r1, round, opts) => sweepX(ringProfile(x0, x1, r0, r1, round), opts);
|
||||
|
||||
// a thick spherical shell from polar angle p0 to p1 (0 = +x pole), outer radius R, wall t; the rims stay sharp so
|
||||
// the clear coat draws a crisp line along them
|
||||
export function domeProfile(R, t, p0, p1, steps = 24) {
|
||||
const out = [];
|
||||
const inn = [];
|
||||
for (let k = 0; k <= steps; k++) {
|
||||
const p = p0 + ((p1 - p0) * k) / steps;
|
||||
out.push([R * Math.cos(p), R * Math.sin(p)]);
|
||||
inn.push([(R - t) * Math.cos(p), (R - t) * Math.sin(p)]);
|
||||
}
|
||||
return [...out, ...inn.reverse()];
|
||||
}
|
||||
export const dome = (R, t, p0, p1, opts) => sweepX(domeProfile(R, t, p0, p1), opts);
|
||||
|
||||
// a solid of revolution from a radius function: r(u) for u in 0..1 along x0..x1, closed to the axis at both ends
|
||||
export function solidProfile(x0, x1, rFn, steps = 32) {
|
||||
const pts = [[x0, 0]];
|
||||
for (let k = 0; k <= steps; k++) {
|
||||
const u = k / steps;
|
||||
pts.push([x0 + (x1 - x0) * u, rFn(u)]);
|
||||
}
|
||||
pts.push([x1, 0]);
|
||||
return pts;
|
||||
}
|
||||
export const solid = (x0, x1, rFn, opts, steps) => sweepX(solidProfile(x0, x1, rFn, steps), opts);
|
||||
// a capsule-like rounded radius: r0 at the start, r1 at the end, ends rounded over `cap` of the length
|
||||
export const capsuleR = (r0, r1, cap = 0.12) => (u) => {
|
||||
const r = r0 + (r1 - r0) * u;
|
||||
const e = Math.min(u, 1 - u) / cap;
|
||||
return e >= 1 ? r : r * Math.sqrt(Math.max(0, 1 - (1 - e) * (1 - e)));
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------ gears, boxes, tubes
|
||||
// a spur gear around +z: `teeth` teeth between rRoot and rOut, `width` thick, a bore of holeR, lightening holes
|
||||
export function gearGeo(teeth, rOut, rRoot, width, holeR = 0, spokes = 0) {
|
||||
const sh = new THREE.Shape();
|
||||
for (let i = 0; i < teeth; i++) {
|
||||
const a0 = (i / teeth) * Math.PI * 2;
|
||||
const da = (Math.PI * 2) / teeth;
|
||||
const pts = [
|
||||
[rRoot, a0],
|
||||
[rRoot, a0 + da * 0.18],
|
||||
[rOut, a0 + da * 0.32],
|
||||
[rOut, a0 + da * 0.6],
|
||||
[rRoot, a0 + da * 0.74],
|
||||
];
|
||||
pts.forEach(([r, a], k) => (i === 0 && k === 0 ? sh.moveTo(r * Math.cos(a), r * Math.sin(a)) : sh.lineTo(r * Math.cos(a), r * Math.sin(a))));
|
||||
}
|
||||
sh.closePath();
|
||||
if (holeR) {
|
||||
const h = new THREE.Path();
|
||||
h.absarc(0, 0, holeR, 0, Math.PI * 2, true);
|
||||
sh.holes.push(h);
|
||||
}
|
||||
// round lightening holes between the bore and the rim
|
||||
if (spokes) {
|
||||
const rc = (holeR + rRoot) / 2;
|
||||
const rh = Math.min((rRoot - holeR) * 0.3, (Math.PI * rc) / spokes * 0.55);
|
||||
for (let k = 0; k < spokes; k++) {
|
||||
const a = (k / spokes) * Math.PI * 2;
|
||||
const h = new THREE.Path();
|
||||
h.absarc(Math.cos(a) * rc, Math.sin(a) * rc, rh, 0, Math.PI * 2, true);
|
||||
sh.holes.push(h);
|
||||
}
|
||||
}
|
||||
const bev = Math.min(width * 0.18, (rOut - rRoot) * 0.3);
|
||||
const g = new THREE.ExtrudeGeometry(sh, {depth: width - bev * 2, bevelEnabled: true, bevelThickness: bev, bevelSize: bev * 0.8, bevelSegments: 1, curveSegments: 10});
|
||||
g.translate(0, 0, -(width - bev * 2) / 2);
|
||||
return g;
|
||||
}
|
||||
// the same gear with its axis along +x
|
||||
export const gearX = (...a) => gearGeo(...a).rotateY(Math.PI / 2);
|
||||
|
||||
export const rbox = (w, h, d, r = 0.01) => new RoundedBoxGeometry(w, h, d, 3, Math.min(r, w / 2.01, h / 2.01, d / 2.01));
|
||||
export const cylX = (r0, r1, len, seg = 32) => new THREE.CylinderGeometry(r1, r0, len, seg).rotateZ(-Math.PI / 2);
|
||||
export const cylZ = (r0, r1, len, seg = 32) => new THREE.CylinderGeometry(r1, r0, len, seg).rotateX(Math.PI / 2);
|
||||
|
||||
/** A cable or rod through points (Vector3 or arrays), radius r. */
|
||||
export function tube(points, r, tubular = 64, radial = 10, closed = false) {
|
||||
const pts = points.map((p) => (p.isVector3 ? p : new V3(...p)));
|
||||
return new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts, closed, 'catmullrom', 0.5), tubular, r, radial, closed);
|
||||
}
|
||||
|
||||
/** A coil spring along +x: radius R, wire r, `turns` over len. */
|
||||
export function coil(R, r, turns, len, seg = 240) {
|
||||
const pts = [];
|
||||
for (let i = 0; i <= seg; i++) {
|
||||
const u = i / seg;
|
||||
const a = u * turns * Math.PI * 2;
|
||||
pts.push(new V3(u * len, Math.cos(a) * R, Math.sin(a) * R));
|
||||
}
|
||||
return new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), seg, r, 8, false);
|
||||
}
|
||||
|
||||
export const merge = (geos) => mergeGeometries(geos.map((g) => (g.index ? g.toNonIndexed() : g)).map((g) => {
|
||||
// mergeGeometries wants identical attribute sets: keep position and normal only
|
||||
const o = new THREE.BufferGeometry();
|
||||
o.setAttribute('position', g.attributes.position);
|
||||
o.setAttribute('normal', g.attributes.normal);
|
||||
return o;
|
||||
}));
|
||||
|
||||
/** Put a mesh of geo/mat at (x, y, z) into parent; returns it. Every mesh casts and takes shadows. */
|
||||
export function put(parent, geo, mat, x = 0, y = 0, z = 0) {
|
||||
const m = new THREE.Mesh(geo, mat);
|
||||
m.position.set(x, y, z);
|
||||
m.castShadow = true;
|
||||
m.receiveShadow = true;
|
||||
parent.add(m);
|
||||
return m;
|
||||
}
|
||||
|
||||
/** Rotate an object so its local +x points along dir. */
|
||||
export function aimX(obj, dir) {
|
||||
obj.quaternion.setFromUnitVectors(new V3(1, 0, 0), dir.clone().normalize());
|
||||
return obj;
|
||||
}
|
||||
|
||||
/** Instances of one geometry at a list of matrices (casts and takes shadows). */
|
||||
export function instances(parent, geo, mat, mats) {
|
||||
const im = new THREE.InstancedMesh(geo, mat, mats.length);
|
||||
mats.forEach((m, i) => im.setMatrixAt(i, m));
|
||||
im.castShadow = true;
|
||||
im.receiveShadow = true;
|
||||
parent.add(im);
|
||||
return im;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Score for the VESPION VX-9 wasp film (entry wasp-film), the bee's second-cut score with one more cue (the sting
|
||||
sliding out in the abdomen act). The bee's notes: Score for the MELLIS HB-7 simulator film, second cut (entry robobee-sim2): the same bed as the other bee films (D minor,
|
||||
96 bpm, e-piano, bass, soft drums and a pad on the same changes) at one level the whole way, a quiet click on every
|
||||
button press, and for every act short quiet accents on its own moves: thread ticks as the lens unscrews and screws
|
||||
back, a swish as the wing pulls out and turns over and a snap as it seats, servo ticks down the leg, a lift of air as
|
||||
the thorax and the abdomen open and a click as they close, a whoosh into the explode and three clicks as the bee seats
|
||||
again, and a rising air as it banks away. No drones.
|
||||
|
||||
python run_sfx.py sims/wasp-shared/score.py
|
||||
|
||||
Every cue comes from the script in robobee-sim2/timeline.json, with the offsets inside each act taken from tour_v2.js
|
||||
(ACT, the explode out 0.2-1.8 s and home 0-1.0 s, the departure 1.0 s after HERO).
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
|
||||
from sfx.score_kit import airy, bed, chords, hz # noqa: E402
|
||||
from sfx.synth import blip, click, envelope, pad # noqa: E402
|
||||
|
||||
TIMELINE = os.environ.get("TL", "../wasp-film/timeline.json")
|
||||
OUT = os.environ.get("OUT", os.path.join(os.environ.get("CUTAWAY_OUT", "cutaway-out"), "wasp-score.wav"))
|
||||
TARGET_LUFS = -14.0
|
||||
SEED = 29
|
||||
|
||||
CHORDS = chords("Dm9:D3 F3 A3 C4 E4/D2", "Bbmaj7:Bb2 D3 F3 A3/Bb1", "Gm9:G2 Bb2 D3 F3 A3/G1", "A7sus:A2 D3 E3 G3/A1")
|
||||
MOTIF = [(0.5, hz("A5")), (1.5, hz("F5")), (2.5, hz("E5"))]
|
||||
|
||||
|
||||
def score(mix, tl):
|
||||
dur = tl["duration"]
|
||||
left, right, low, drums = bed(dur, 96, CHORDS, MOTIF, motif_voice="blip", kicks=(0, 2.5), snares=(1, 3), hats=8, swing=0.08, keys_vel=0.75, keys_lp=3800)
|
||||
mix.put_stereo(0, left, right, 0.13)
|
||||
mix.put(0, low, 0.13)
|
||||
mix.put(0, drums, 0.05)
|
||||
bar = 4 * 60 / 96
|
||||
changes = [(0.12 + b * bar, [f for f in CHORDS[b % len(CHORDS)][0][:4]]) for b in range(int(dur / bar) + 1)]
|
||||
pl, pr = pad(dur, changes, volume=envelope([(0, 0), (1.0, 1), (dur - 1.6, 1), (dur, 0)]), detune=0.8, tremolo=0.18, xfade=0.5)
|
||||
mix.put_stereo(0, pl, pr, 0.07)
|
||||
# the fly-in: one air that follows the bank
|
||||
mix.put(0.0, airy(2.4, 700, 1800, 0.6), 0.02, pan=-0.3)
|
||||
|
||||
for e in tl["script"]:
|
||||
t, act = e["t"], e["act"]
|
||||
mix.put(t, click(2400, 0.025), 0.055, pan=0.45)
|
||||
if act == "optics":
|
||||
for i, dt in enumerate((0.4, 0.62, 0.84, 1.06)):
|
||||
mix.put(t + dt, click(3200 - 200 * i, 0.018), 0.035, pan=0.2)
|
||||
for i, dt in enumerate((2.2, 2.36, 2.52)):
|
||||
mix.put(t + dt, click(2600 + 200 * i, 0.018), 0.03, pan=0.2)
|
||||
elif act == "wing":
|
||||
mix.put(t + 0.45, airy(0.8, 600, 2200, 0.6), 0.025, pan=-0.3)
|
||||
mix.put(t + 0.9, airy(1.4, 900, 1500, 0.5), 0.016, pan=-0.2)
|
||||
mix.put(t + 2.68, click(1800, 0.03), 0.06, pan=-0.2)
|
||||
elif act == "leg":
|
||||
for i, dt in enumerate((0.38, 0.6, 0.82, 1.04)):
|
||||
mix.put(t + dt, blip(hz("D6") * 2 ** (i / 6), 0.18, 0.06), 0.02, pan=0.1)
|
||||
mix.put(t + 2.55, click(2000, 0.03), 0.05)
|
||||
elif act in ("thorax", "abdomen"):
|
||||
mix.put(t + 0.3, airy(1.0, 500, 1600, 0.6), 0.024)
|
||||
mix.put(t + (2.6 if act == "thorax" else 2.45), click(2100, 0.03), 0.055)
|
||||
if act == "abdomen":
|
||||
# the sting slides out of its collar and back
|
||||
mix.put(t + 1.05, blip(hz("A5"), 0.22, 0.07), 0.018, pan=-0.2)
|
||||
mix.put(t + 1.5, click(2900, 0.02), 0.035, pan=-0.2)
|
||||
mix.put(t + 2.15, click(2500, 0.02), 0.03, pan=-0.2)
|
||||
elif act == "exploded":
|
||||
mix.put(t + 0.2, airy(1.4, 500, 2600, 0.7), 0.032, pan=-0.15)
|
||||
mix.put(t + 0.25, blip(hz("D6"), 0.3, 0.1), 0.025)
|
||||
elif act == "assemble":
|
||||
mix.put(t, airy(1.0, 2200, 600, 0.5), 0.02, pan=0.15)
|
||||
for i, dt in enumerate((0.6, 0.8, 1.0)):
|
||||
mix.put(t + dt, click(2000 + 300 * i, 0.03), 0.05, pan=-0.3 + 0.3 * i)
|
||||
mix.put(t + 0.9, airy(0.6, 400, 1300, 0.6), 0.016)
|
||||
elif act == "hero":
|
||||
mix.put(t + 1.0, airy(2.0, 500, 2400, 0.7), 0.03, pan=0.4)
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Score for the MELLIS HB-7 18-second film (entry wasp-demo, tour_10.js): the bee films' bed in D minor (Dm9, Bbmaj7,
|
||||
Gm9, A7sus at 96 bpm: e-piano, bass, soft drums and a pad) at one level the whole way, a quiet click on every button
|
||||
press, and short quiet accents on each act's own moves: a falling air for the dive in from the left, thread ticks as
|
||||
the lens unscrews and screws back, a swish as the wing leaves its hinge and another as it turns over and a snap as it
|
||||
seats, a lift of air and a few gear ticks as the thorax and the abdomen open and a click as they close, a whoosh into
|
||||
the explode with a long falling air and one low note under the 0.4x speed ramp and slow glass ticks as the parts drift
|
||||
apart, three clicks as the bee seats again, and a rising air that swells as the bee darts at the lens and passes to
|
||||
its right. No drones.
|
||||
|
||||
python run_sfx.py sims/wasp-shared/score_demo.py
|
||||
|
||||
Every cue comes from wasp-demo/timeline.json. The offsets inside each act are tour_10.js's, in SCENE seconds, and go
|
||||
through the same speed-ramp warp (RAMP, anchored on EXPLODED) back to film time.
|
||||
"""
|
||||
|
||||
import bisect
|
||||
import os
|
||||
|
||||
|
||||
|
||||
from sfx.score_kit import airy, bed, chords, hz # noqa: E402
|
||||
from sfx.synth import blip, click, envelope, pad # noqa: E402
|
||||
|
||||
TIMELINE = os.environ.get("TL", "../wasp-demo/timeline.json")
|
||||
OUT = os.environ.get("OUT", os.path.join(os.environ.get("CUTAWAY_OUT", "cutaway-out"), "wasp-demo-score.wav"))
|
||||
TARGET_LUFS = -14.0
|
||||
SEED = 53
|
||||
|
||||
CHORDS = chords("Dm9:D3 F3 A3 C4 E4/D2", "Bbmaj7:Bb2 D3 F3 A3/Bb1", "Gm9:G2 Bb2 D3 F3 A3/G1", "A7sus:A2 D3 E3 G3/A1")
|
||||
MOTIF = [(0.5, hz("A5")), (1.5, hz("F5")), (2.5, hz("E5"))]
|
||||
# tour_10.js: the ramp in film seconds after the EXPLODED click, and the dart's start after HERO (scene seconds)
|
||||
RAMP_A, RAMP_B, RAMP_LOW = (0.35, 0.55), (1.9, 2.1), 0.4
|
||||
DEP = 0.75
|
||||
|
||||
|
||||
def _smoother(x):
|
||||
u = min(1.0, max(0.0, x))
|
||||
return u * u * u * (u * (u * 6 - 15) + 10)
|
||||
|
||||
|
||||
def make_warp(t_ramp, dur):
|
||||
"""film time -> scene time and back, the same integral as tour_10.js makeWarp"""
|
||||
dt = 1 / 480
|
||||
n = int((dur + 2) / dt)
|
||||
ts = [i * dt for i in range(n + 1)]
|
||||
tau = [0.0]
|
||||
for i in range(1, n + 1):
|
||||
mid = ts[i] - dt / 2
|
||||
bump = _smoother((mid - t_ramp - RAMP_A[0]) / (RAMP_A[1] - RAMP_A[0])) * (1 - _smoother((mid - t_ramp - RAMP_B[0]) / (RAMP_B[1] - RAMP_B[0])))
|
||||
tau.append(tau[-1] + (1 - (1 - RAMP_LOW) * bump) * dt)
|
||||
|
||||
def interp(x, xs, ys):
|
||||
if x <= xs[0]:
|
||||
return ys[0]
|
||||
if x >= xs[-1]:
|
||||
return ys[-1]
|
||||
j = bisect.bisect_right(xs, x) - 1
|
||||
k = (x - xs[j]) / (xs[j + 1] - xs[j])
|
||||
return ys[j] + (ys[j + 1] - ys[j]) * k
|
||||
|
||||
return (lambda x: interp(x, ts, tau)), (lambda y: interp(y, tau, ts))
|
||||
|
||||
|
||||
def score(mix, tl):
|
||||
dur = tl["duration"]
|
||||
t_exp = next((e["t"] for e in tl["script"] if e["act"] == "exploded"), 999.0)
|
||||
tau_at, film_at = make_warp(t_exp, dur)
|
||||
|
||||
left, right, low, drums = bed(dur, 96, CHORDS, MOTIF, motif_voice="blip", kicks=(0, 2.5), snares=(1, 3), hats=8, swing=0.08, keys_vel=0.75, keys_lp=3800)
|
||||
mix.put_stereo(0, left, right, 0.13)
|
||||
mix.put(0, low, 0.13)
|
||||
mix.put(0, drums, 0.05)
|
||||
bar = 4 * 60 / 96
|
||||
changes = [(0.12 + b * bar, [f for f in CHORDS[b % len(CHORDS)][0][:4]]) for b in range(int(dur / bar) + 1)]
|
||||
pl, pr = pad(dur, changes, volume=envelope([(0, 0), (1.0, 1), (dur - 1.4, 1), (dur, 0)]), detune=0.8, tremolo=0.18, xfade=0.5)
|
||||
mix.put_stereo(0, pl, pr, 0.07)
|
||||
# the dive in from high on the left
|
||||
mix.put(0.0, airy(1.6, 2200, 700, 0.6), 0.024, pan=-0.35)
|
||||
|
||||
for e in tl["script"]:
|
||||
t, act = e["t"], e["act"]
|
||||
k0 = tau_at(t)
|
||||
|
||||
def at(dt, t0=k0):
|
||||
"""an offset in scene seconds after the click, in film time"""
|
||||
return film_at(t0 + dt)
|
||||
|
||||
mix.put(t, click(2400, 0.025), 0.055, pan=0.45)
|
||||
if act == "optics":
|
||||
for i, dt in enumerate((0.3, 0.48, 0.66, 0.84)):
|
||||
mix.put(at(dt), click(3200 - 200 * i, 0.018), 0.035, pan=0.2)
|
||||
for i, dt in enumerate((1.58, 1.71, 1.84)):
|
||||
mix.put(at(dt), click(2600 + 200 * i, 0.018), 0.03, pan=0.2)
|
||||
elif act == "wing":
|
||||
mix.put(at(0.2), airy(0.6, 600, 2200, 0.6), 0.025, pan=-0.3)
|
||||
mix.put(at(0.5), airy(0.95, 900, 1500, 0.5), 0.016, pan=-0.2)
|
||||
mix.put(at(1.92), click(1800, 0.03), 0.06, pan=-0.2)
|
||||
elif act in ("thorax", "abdomen"):
|
||||
mix.put(at(0.25), airy(0.8, 500, 1600, 0.6), 0.024)
|
||||
for i in range(4):
|
||||
mix.put(at(0.55 + 0.11 * i), click(3300 + 140 * i, 0.012), 0.02, pan=0.1 - 0.1 * i)
|
||||
mix.put(at(1.9 if act == "thorax" else 1.95), click(2100, 0.03), 0.055)
|
||||
elif act == "exploded":
|
||||
mix.put(at(0.2), airy(1.0, 500, 2600, 0.7), 0.032, pan=-0.15)
|
||||
mix.put(at(0.25), blip(hz("D6"), 0.3, 0.1), 0.024)
|
||||
# the ramp: a long falling air under the slowed parts, one low note as time stretches, slow glass ticks
|
||||
mix.put(t + RAMP_A[0], airy(RAMP_B[1] - RAMP_A[0] + 0.3, 1800, 450, 0.5), 0.022, pan=-0.1)
|
||||
mix.put(t + RAMP_A[1], blip(hz("D4"), 1.1, 0.5), 0.015)
|
||||
for i in range(6):
|
||||
mix.put(t + RAMP_A[1] + 0.22 * i, click(3600 - 150 * i, 0.012), 0.018, pan=0.4 - 0.16 * i)
|
||||
elif act == "assemble":
|
||||
mix.put(t, airy(0.8, 2200, 600, 0.5), 0.02, pan=-0.15)
|
||||
for i, dt in enumerate((0.45, 0.6, 0.75)):
|
||||
mix.put(at(dt), click(2000 + 300 * i, 0.03), 0.05, pan=0.3 - 0.3 * i)
|
||||
mix.put(at(0.7), airy(0.5, 400, 1300, 0.6), 0.016)
|
||||
elif act == "hero":
|
||||
mix.put(at(0.1), airy(0.7, 900, 1600, 0.5), 0.012, pan=-0.1)
|
||||
# the dart: a rising air that swells to the pass by the lens and swings right with it
|
||||
d0 = at(DEP)
|
||||
n = max(0.4, dur - d0)
|
||||
mix.put(d0, airy(n, 400, 3000, 0.7), 0.032, pan=0.15)
|
||||
mix.put(d0 + n * 0.7, airy(n * 0.3, 2600, 1200, 0.6), 0.03, pan=0.6)
|
||||
@@ -0,0 +1,121 @@
|
||||
// VESPION VX-9, the approved wasp film re-shot on the green page (entry wasp-film). Everything that moves comes
|
||||
// from this folder's tour_v2.js unchanged (the wasp, its flight, every assembly, every camera, the timing); what is new
|
||||
// is only the look: green for orange on the wasp, white paper with mint haze, and the green page from ../green instead
|
||||
// of the old console. The subject shifts by green/look.js SHIFT so it sits in the green page's 3D window.
|
||||
import {runSim} from '../kit/runtime.js';
|
||||
import {createConsole} from '../green/console.js';
|
||||
import {makeCursor, makeLabels, ORANGE_TO, PAPER_GREEN, retint, SHIFT} from '../green/look.js';
|
||||
import {buildBee} from './bee.js';
|
||||
import {PAL} from './parts.js';
|
||||
import {createStage, PAPER} from './stage.js';
|
||||
import {FLOOR_Y} from './tour.js';
|
||||
import {makeTour2, REACH} from './tour_v2.js';
|
||||
|
||||
const D2R = Math.PI / 180;
|
||||
|
||||
Object.assign(PAL, {orange: ORANGE_TO});
|
||||
Object.assign(PAPER, PAPER_GREEN);
|
||||
|
||||
const PAGE = {
|
||||
name: 'Vespion',
|
||||
code: 'VX-9',
|
||||
title: 'Robotic Wasp, Taken Apart',
|
||||
date: '2026-11-6',
|
||||
nav: [['overview', 'Overview'], ['optics', 'Optics'], ['wing', 'Wings'], ['leg', 'Legs'], ['thorax', 'Thorax'], ['abdomen', 'Abdomen'], ['exploded', 'Teardown'], ['hero', 'Release']],
|
||||
pills: [['optics', 'Optics'], ['wing', 'Wings'], ['leg', 'Legs'], ['thorax', 'Thorax'], ['abdomen', 'Abdomen'], ['exploded', 'Teardown'], ['hero', 'Release']],
|
||||
sub: {
|
||||
overview: ['Wingspan 2 × 180 mm', '6 legs · 2 camera eyes'],
|
||||
optics: ['Iris: 10 blades', 'Glass Ø 40 mm'],
|
||||
wing: ['Frosted film, 0.1 mm', 'Hinge: quick release'],
|
||||
leg: ['2 servos per leg', 'Foot: twin hooks'],
|
||||
thorax: ['3 spur gears', 'Flight CPU + IMU'],
|
||||
abdomen: ['5 telescoping bands', 'Glass stinger'],
|
||||
exploded: ['Every part apart', 'Turntable 330°'],
|
||||
hero: ['Wings to 7.5 Hz', 'Banking out'],
|
||||
},
|
||||
};
|
||||
// tour_v2's capital labels in the page's voice
|
||||
const TEXT = {
|
||||
'OUTER GLASS': ['Front glass', 'Ø 40 mm, AR coated'],
|
||||
'INNER ELEMENT': ['Inner element', 'Ø 15 mm'],
|
||||
IRIS: ['Iris', '10 blades, opens 3×'],
|
||||
'LENS BARREL': ['Lens barrel', 'threaded, 4 rings'],
|
||||
'WING MEMBRANE': ['Wing film', '0.1 mm, frosted'],
|
||||
'WING HINGE': ['Wing hinge', 'quick release'],
|
||||
'HINDWING HINGE': ['Hindwing hinge', 'phase +40°'],
|
||||
'HIP SERVO': ['Hip servo', 'yaw + lift'],
|
||||
'KNEE SERVO': ['Knee servo', '0.4 N·m'],
|
||||
'FOOT CLAW': ['Foot claw', 'twin hooks'],
|
||||
'SADDLE PLATE': ['Saddle plate', 'polymer shell'],
|
||||
'DRIVE GEAR STACK': ['Drive gears', '3 spur gears'],
|
||||
'ACTUATOR RING': ['Actuator ring', '11 pistons'],
|
||||
'CONTROL BOARDS': ['Flight boards', 'CPU + IMU'],
|
||||
'WAIST STALK': ['Waist stalk', '5 lit beads'],
|
||||
'SHELL BAND': ['Shell band', 'telescoping'],
|
||||
'BAND 4': ['Band 4', '5 riveted segments'],
|
||||
STINGER: ['Stinger', 'glass, extends 30 mm'],
|
||||
'OPTIC HEAD': ['Optic head', '2 lenses'],
|
||||
'NECK BEARING': ['Neck bearing', '10 segments'],
|
||||
'DRIVE GEARS': ['Drive gears', 'spinning free'],
|
||||
'ABDOMEN BANDS': ['Abdomen bands', '5 segments'],
|
||||
};
|
||||
const STATUS = {DIVING: 'Diving in', 'SLOW-MO': 'Slow motion', 'CLIMB-OUT': 'Climbing out', BANKING: 'Banking in', HOVER: 'Hovering', TEARDOWN: 'Teardown', REASSEMBLY: 'Reassembly', DEPARTING: 'Departing', 'OPTICS OPEN': 'Optics open', 'WING OFF': 'Wing off', 'LEG L2 OPEN': 'Leg open', 'THORAX OPEN': 'Thorax open', 'ABDOMEN OPEN': 'Abdomen open'};
|
||||
|
||||
export function makeWaspGreen(TL, {tour = makeTour2} = {}) {
|
||||
const T = tour(TL);
|
||||
return async ({canvas, capture}) => {
|
||||
const app = document.getElementById('app');
|
||||
const st = createStage({canvas, floorY: FLOOR_Y});
|
||||
const bee = buildBee();
|
||||
st.addBee(bee);
|
||||
retint(bee.root);
|
||||
bee.root.rotation.order = 'YXZ';
|
||||
const ui = createConsole(app, PAGE);
|
||||
const cursorAt = makeCursor(ui, T.SCRIPT);
|
||||
const labels = makeLabels(st, bee.anchors, TEXT);
|
||||
const fit = () => {
|
||||
const k = Math.min(innerWidth / 1600, innerHeight / 900);
|
||||
app.style.transform = `scale(${k})`;
|
||||
};
|
||||
const resize = () => {
|
||||
fit();
|
||||
st.resize(1600, 900, capture ? devicePixelRatio || 1 : Math.min(devicePixelRatio || 1, 2));
|
||||
};
|
||||
resize();
|
||||
window.WASP = {st, bee, T};
|
||||
return {
|
||||
resize,
|
||||
render(t) {
|
||||
const s = T.stateAt(t);
|
||||
bee.pose({explode: s.explode, flap: s.flap, flapAmp: s.amp, display: s.display, t: s.spinT, spinT: s.spinT, blur: 1, reach: REACH, sub: s.sub, eye: s.eye, wingOut: s.wingOut, wingFlip: s.wingFlip, legK: s.legK, stingK: s.stingK});
|
||||
retint(bee.root);
|
||||
const f = s.flight;
|
||||
bee.root.position.copy(f.pos);
|
||||
bee.root.rotation.set(f.roll * D2R, f.yaw * D2R, f.pitch * D2R);
|
||||
const c = s.cam;
|
||||
st.frame({...c, az: c.az * D2R, el: c.el * D2R, sx: c.sx + SHIFT[0], sy: c.sy + SHIFT[1]}, {guides: s.guides});
|
||||
const tel = T.telemetry(t, s);
|
||||
const v = s.view;
|
||||
const opening = Math.max(s.open?.[v] ?? 0, v === 'wing' ? s.wingOut : 0);
|
||||
ui.update({
|
||||
time: t,
|
||||
dur: TL.duration,
|
||||
status: STATUS[tel.status] ?? tel.status,
|
||||
freq: tel.freq,
|
||||
stroke: tel.stroke.map((p) => p[0]),
|
||||
lift: tel.lift,
|
||||
battery: tel.battery,
|
||||
servos: tel.servos,
|
||||
apart: Math.round(Math.max(opening, s.explode) * 100),
|
||||
view: v === 'intro' ? 'overview' : v,
|
||||
callouts: labels(tel.labelSet),
|
||||
cursor: cursorAt(t),
|
||||
});
|
||||
return {};
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export const runWaspGreen = (TL, title = 'wasp-film', opts = {}) =>
|
||||
runSim({duration: TL.duration, fps: 60, theme: 'light', hud: {enabled: false, title, subtitle: ''}, director: {enabled: false}, watermark: ''}, makeWaspGreen(TL, opts));
|
||||
@@ -0,0 +1,344 @@
|
||||
// The robotic bee's stage: a near-white product studio. A warm paper backdrop with no horizon, a soft shadow pooled
|
||||
// on the floor under the bee (the bee's silhouette seen from below, blurred wide, plus a tighter pass for what hangs
|
||||
// close to the floor), a softbox environment for the clear coat to catch, a key with VSM self-shadows, a rim and a
|
||||
// fill, GTAO kept off the backdrop and the clear parts, MSAA. The tone curve is linear up to 0.8 and rolls off
|
||||
// above, hue preserved; the backdrop writes the inverse of that curve, so the paper lands on its exact colour and the
|
||||
// floor shadow darkens it as drawn. frame(cam, ops) draws one frame; cam = {tx, ty, tz, az, el, d, sx, sy}.
|
||||
import * as THREE from 'three';
|
||||
import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';
|
||||
import {GTAOPass} from 'three/addons/postprocessing/GTAOPass.js';
|
||||
import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';
|
||||
import {FullScreenQuad, Pass} from 'three/addons/postprocessing/Pass.js';
|
||||
import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';
|
||||
import {buildGuides} from './guides.js';
|
||||
|
||||
const V3 = THREE.Vector3;
|
||||
// the paper: top, middle, the floor band (sRGB), and the shadow's tint
|
||||
export const PAPER = {top: '#fefcf8', mid: '#fcf9f3', low: '#f5efe7', shadow: '#c9bcae'};
|
||||
const KNEE = 0.8;
|
||||
THREE.ShaderChunk.tonemapping_pars_fragment = THREE.ShaderChunk.tonemapping_pars_fragment.replace(
|
||||
'vec3 CustomToneMapping( vec3 color ) { return color; }',
|
||||
`vec3 CustomToneMapping( vec3 color ) {
|
||||
color *= toneMappingExposure;
|
||||
float p = max( color.r, max( color.g, color.b ) );
|
||||
if ( p <= ${KNEE.toFixed(2)} ) return color;
|
||||
float np = ${KNEE.toFixed(2)} + ${(1 - KNEE).toFixed(2)} * ( 1.0 - exp( -( p - ${KNEE.toFixed(2)} ) / ${(1 - KNEE).toFixed(2)} ) );
|
||||
return color * ( np / p );
|
||||
}`,
|
||||
);
|
||||
export const BEE_LAYER = 1;
|
||||
|
||||
const BACK_VERT = /* glsl */ `varying vec3 vW;
|
||||
void main(){
|
||||
#ifdef SCREEN
|
||||
vW = vec3(0.0); gl_Position = vec4(position.xy, 0.99999, 1.0);
|
||||
#else
|
||||
vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w;
|
||||
#endif
|
||||
}`;
|
||||
const BACK_FRAG = /* glsl */ `uniform vec3 uTop, uMid, uLow, uTint; uniform vec2 uRes;
|
||||
uniform sampler2D tSoft, tNear; uniform mat4 uVP; uniform float uSoft, uNear;
|
||||
varying vec3 vW;
|
||||
vec3 paper(float y){ return y > 0.42 ? mix(uMid, uTop, smoothstep(0.42, 1.0, y)) : mix(uLow, uMid, smoothstep(0.0, 0.42, y)); }
|
||||
// the inverse of the tone curve's shoulder: what to write so the output lands on c
|
||||
vec3 untone(vec3 c){
|
||||
float p = max(c.r, max(c.g, c.b));
|
||||
if (p <= ${KNEE.toFixed(2)}) return c;
|
||||
float pin = ${KNEE.toFixed(2)} - ${(1 - KNEE).toFixed(2)} * log(max(1e-4, 1.0 - (p - ${KNEE.toFixed(2)}) / ${(1 - KNEE).toFixed(2)}));
|
||||
return c * (pin / p);
|
||||
}
|
||||
float tap(sampler2D t, vec3 w){
|
||||
vec4 c = uVP * vec4(w, 1.0);
|
||||
vec2 uv = c.xy / c.w * 0.5 + 0.5;
|
||||
if (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0) return 0.0;
|
||||
vec2 e = smoothstep(0.0, 0.08, uv) * smoothstep(0.0, 0.08, 1.0 - uv);
|
||||
return texture2D(t, uv).r * e.x * e.y;
|
||||
}
|
||||
void main(){
|
||||
vec3 c = paper(gl_FragCoord.y / uRes.y);
|
||||
#ifndef SCREEN
|
||||
float s = clamp(tap(tSoft, vW) * uSoft + tap(tNear, vW) * uNear, 0.0, 1.0);
|
||||
c = mix(c, c * uTint, s);
|
||||
#endif
|
||||
gl_FragColor = vec4(untone(c), 1.0);
|
||||
}`;
|
||||
const QUAD_VERT = /* glsl */ `varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;
|
||||
const BLUR_FRAG = /* glsl */ `uniform sampler2D tSrc; uniform vec2 uDir; varying vec2 vUv;
|
||||
void main(){
|
||||
float w[5]; w[0] = 0.2270270270; w[1] = 0.1945945946; w[2] = 0.1216216216; w[3] = 0.0540540541; w[4] = 0.0162162162;
|
||||
vec4 c = texture2D(tSrc, vUv) * w[0];
|
||||
for (int i = 1; i < 5; i++) { c += texture2D(tSrc, vUv + uDir * float(i)) * w[i]; c += texture2D(tSrc, vUv - uDir * float(i)) * w[i]; }
|
||||
gl_FragColor = c;
|
||||
}`;
|
||||
// silhouette from below: everything counts, what hangs low counts more
|
||||
const SIL_VERT = /* glsl */ `varying float vH; uniform float uFloor; void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vH = w.y - uFloor; gl_Position = projectionMatrix * viewMatrix * w; }`;
|
||||
const SIL_FRAG = /* glsl */ `varying float vH; uniform float uFar, uBase; void main(){ float k = 1.0 - clamp(vH / uFar, 0.0, 1.0); gl_FragColor = vec4(uBase + (1.0 - uBase) * k * k, 0.0, 0.0, 1.0); }`;
|
||||
|
||||
export function createStage({canvas, floorY = -1.55}) {
|
||||
const renderer = new THREE.WebGLRenderer({canvas, antialias: false, preserveDrawingBuffer: true, powerPreference: 'high-performance'});
|
||||
renderer.toneMapping = THREE.CustomToneMapping;
|
||||
renderer.toneMappingExposure = 1.0;
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
renderer.shadowMap.enabled = true;
|
||||
renderer.shadowMap.type = THREE.VSMShadowMap;
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(30, 16 / 9, 0.05, 80);
|
||||
const composer = new EffectComposer(renderer, new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: 8}));
|
||||
composer.addPass(new RenderPass(scene, camera));
|
||||
const gtao = new GTAOPass(scene, camera, 4, 4);
|
||||
gtao.output = GTAOPass.OUTPUT.Default;
|
||||
gtao.blendIntensity = 1.0;
|
||||
gtao.updateGtaoMaterial({radius: 0.13, distanceExponent: 1.6, thickness: 0.9, scale: 1.0, samples: 16, distanceFallOff: 1.0, screenSpaceRadius: false});
|
||||
gtao.updatePdMaterial({lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 5, rings: 2, samples: 16});
|
||||
class Toggle extends Pass {
|
||||
constructor(fn) {
|
||||
super();
|
||||
this.needsSwap = false;
|
||||
this.fn = fn;
|
||||
}
|
||||
render() {
|
||||
this.fn();
|
||||
}
|
||||
}
|
||||
// the backdrop, the guides and every clear part stay out of the AO pass
|
||||
const skip = [];
|
||||
// extra: meshes skipped only while a mode asks (the shells under x-ray)
|
||||
let extra = [];
|
||||
const aoSkip = (on) => {
|
||||
for (const o of skip) o.visible = on && o.userData.show !== false;
|
||||
for (const o of extra) o.visible = on;
|
||||
};
|
||||
composer.addPass(new Toggle(() => aoSkip(false)));
|
||||
composer.addPass(gtao);
|
||||
composer.addPass(new Toggle(() => aoSkip(true)));
|
||||
composer.addPass(new OutputPass());
|
||||
|
||||
// ------------------------------------------------------------ the studio the clear coat reflects
|
||||
{
|
||||
const env = new THREE.Scene();
|
||||
env.background = new THREE.Color('#d8d4ce');
|
||||
const box = (w, h, pos, k, tint = [1, 0.985, 0.96]) => {
|
||||
const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({color: new THREE.Color(...tint).multiplyScalar(k), side: THREE.DoubleSide}));
|
||||
m.position.copy(pos);
|
||||
m.lookAt(0, 0, 0);
|
||||
env.add(m);
|
||||
};
|
||||
box(16, 10, new V3(-4, 16, 6), 3.2); // the big top box
|
||||
box(3, 16, new V3(-15, 4, 8), 2.6); // a tall strip, left front
|
||||
box(3, 16, new V3(14, 5, -6), 2.0, [0.96, 0.98, 1]); // the rim strip behind
|
||||
box(20, 3, new V3(2, 2, 16), 1.5); // a low card in front
|
||||
box(8, 8, new V3(10, 2, 12), 1.1); // fill, right front
|
||||
const g = new THREE.Mesh(new THREE.CircleGeometry(40, 32), new THREE.MeshBasicMaterial({color: '#e9e3da', side: THREE.DoubleSide}));
|
||||
g.rotation.x = -Math.PI / 2;
|
||||
g.position.y = -3;
|
||||
env.add(g);
|
||||
const pm = new THREE.PMREMGenerator(renderer);
|
||||
scene.environment = pm.fromScene(env, 0.025).texture;
|
||||
scene.environmentIntensity = 0.62;
|
||||
pm.dispose();
|
||||
}
|
||||
const KEY = new V3(-0.3, 0.86, 0.55).normalize();
|
||||
const key = new THREE.DirectionalLight('#fffaf3', 3.0);
|
||||
key.castShadow = true;
|
||||
Object.assign(key.shadow.camera, {left: -3.4, right: 3.4, top: 3.4, bottom: -3.4, near: 1, far: 16});
|
||||
key.shadow.mapSize.set(4096, 4096);
|
||||
key.shadow.radius = 6;
|
||||
key.shadow.blurSamples = 20;
|
||||
key.shadow.bias = -0.0005;
|
||||
key.shadow.normalBias = 0.01;
|
||||
scene.add(key, key.target);
|
||||
const rim = new THREE.DirectionalLight('#f2f6ff', 1.1);
|
||||
rim.position.set(3, 3, -5);
|
||||
scene.add(rim);
|
||||
const fill = new THREE.DirectionalLight('#fff6ec', 0.3);
|
||||
fill.position.set(4, -1, 5);
|
||||
scene.add(fill);
|
||||
scene.add(new THREE.HemisphereLight('#ffffff', '#d9cfc2', 0.32));
|
||||
|
||||
// ------------------------------------------------------------ backdrop: the paper behind, the floor with its shadow
|
||||
const lin = (hex) => new THREE.Color(hex);
|
||||
const backU = {
|
||||
uTop: {value: lin(PAPER.top)},
|
||||
uMid: {value: lin(PAPER.mid)},
|
||||
uLow: {value: lin(PAPER.low)},
|
||||
uTint: {value: lin(PAPER.shadow)},
|
||||
uRes: {value: new THREE.Vector2(1, 1)},
|
||||
tSoft: {value: null},
|
||||
tNear: {value: null},
|
||||
uVP: {value: new THREE.Matrix4()},
|
||||
uSoft: {value: 0.42},
|
||||
uNear: {value: 0.55},
|
||||
};
|
||||
const paper = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.ShaderMaterial({vertexShader: BACK_VERT, fragmentShader: BACK_FRAG, uniforms: backU, defines: {SCREEN: ''}, depthWrite: false, depthTest: false}));
|
||||
paper.frustumCulled = false;
|
||||
paper.renderOrder = -10;
|
||||
scene.add(paper);
|
||||
const floor = new THREE.Mesh(new THREE.PlaneGeometry(200, 200).rotateX(-Math.PI / 2), new THREE.ShaderMaterial({vertexShader: BACK_VERT, fragmentShader: BACK_FRAG, uniforms: backU, depthWrite: false}));
|
||||
floor.position.y = floorY;
|
||||
floor.renderOrder = -9;
|
||||
scene.add(floor);
|
||||
skip.push(paper, floor);
|
||||
|
||||
// the floor shadow: the bee from below into two targets, one blurred wide, one tight
|
||||
const SR = 512;
|
||||
const HALF = 4.2;
|
||||
const mkRT = () => new THREE.WebGLRenderTarget(SR, SR, {type: THREE.HalfFloatType});
|
||||
const soft = [mkRT(), mkRT()];
|
||||
const near = [mkRT(), mkRT()];
|
||||
backU.tSoft.value = soft[0].texture;
|
||||
backU.tNear.value = near[0].texture;
|
||||
const shCam = new THREE.OrthographicCamera(-HALF, HALF, HALF, -HALF, 0, 6);
|
||||
shCam.up.set(0, 0, -1);
|
||||
shCam.layers.set(BEE_LAYER);
|
||||
const silU = {uFloor: {value: floorY}, uFar: {value: 1.6}, uBase: {value: 1.0}};
|
||||
const silMat = new THREE.ShaderMaterial({vertexShader: SIL_VERT, fragmentShader: SIL_FRAG, uniforms: silU, side: THREE.DoubleSide});
|
||||
const blurMat = new THREE.ShaderMaterial({vertexShader: QUAD_VERT, fragmentShader: BLUR_FRAG, uniforms: {tSrc: {value: null}, uDir: {value: new THREE.Vector2()}}, depthTest: false, depthWrite: false});
|
||||
const blurQuad = new FullScreenQuad(blurMat);
|
||||
const blur = ([a, b], px, passes) => {
|
||||
for (let i = 0; i < passes; i++) {
|
||||
blurMat.uniforms.tSrc.value = a.texture;
|
||||
blurMat.uniforms.uDir.value.set(px / SR, 0);
|
||||
renderer.setRenderTarget(b);
|
||||
blurQuad.render(renderer);
|
||||
blurMat.uniforms.tSrc.value = b.texture;
|
||||
blurMat.uniforms.uDir.value.set(0, px / SR);
|
||||
renderer.setRenderTarget(a);
|
||||
blurQuad.render(renderer);
|
||||
}
|
||||
};
|
||||
const black = new THREE.Color(0, 0, 0);
|
||||
const prevClear = new THREE.Color();
|
||||
// floor: 'full' (a wide pass and a tight one), 'one' (the wide pass only), 'half' / 'quarter' (that, every 2nd / 4th
|
||||
// frame)
|
||||
let floorMode = 'full';
|
||||
let floorTick = 0;
|
||||
const floorShadow = (c) => {
|
||||
if ((floorMode === 'half' && floorTick++ % 2) || (floorMode === 'quarter' && floorTick++ % 4)) return;
|
||||
shCam.position.set(c.x, floorY - 0.01, c.z);
|
||||
shCam.lookAt(c.x, floorY + 1, c.z);
|
||||
shCam.updateMatrixWorld();
|
||||
shCam.updateProjectionMatrix();
|
||||
renderer.getClearColor(prevClear);
|
||||
const prevA = renderer.getClearAlpha();
|
||||
const prevOv = scene.overrideMaterial;
|
||||
const prevSh = renderer.shadowMap.autoUpdate;
|
||||
renderer.shadowMap.autoUpdate = false;
|
||||
renderer.setClearColor(black, 1);
|
||||
scene.overrideMaterial = silMat;
|
||||
const passes = floorMode === 'full' ? [
|
||||
[soft, 1.0, 1.0, 3.2, 4],
|
||||
[near, 0.0, 1.5, 1.2, 2],
|
||||
] : [[soft, 1.0, 1.0, 3.2, 3]];
|
||||
backU.uNear.value = floorMode === 'full' ? 0.55 : 0;
|
||||
for (const [rt, base, far, px, passes2] of passes) {
|
||||
silU.uBase.value = base;
|
||||
silU.uFar.value = far;
|
||||
renderer.setRenderTarget(rt[0]);
|
||||
renderer.clear();
|
||||
renderer.render(scene, shCam);
|
||||
blur(rt, px, passes2);
|
||||
}
|
||||
scene.overrideMaterial = prevOv;
|
||||
renderer.shadowMap.autoUpdate = prevSh;
|
||||
renderer.setRenderTarget(null);
|
||||
renderer.setClearColor(prevClear, prevA);
|
||||
backU.uVP.value.multiplyMatrices(shCam.projectionMatrix, shCam.matrixWorldInverse);
|
||||
};
|
||||
|
||||
// a dark studio for the camera lenses only: black all round with a few hard softboxes, so the glass reads deep
|
||||
// black with crisp highlights instead of mirroring the pale studio as a grey haze
|
||||
const lensEnv = (() => {
|
||||
const env = new THREE.Scene();
|
||||
env.background = new THREE.Color('#050506');
|
||||
const box = (w, h, dir, k) => {
|
||||
const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({color: new THREE.Color(1, 0.98, 0.95).multiplyScalar(k), side: THREE.DoubleSide}));
|
||||
m.position.copy(new V3(...dir).normalize().multiplyScalar(15));
|
||||
m.lookAt(0, 0, 0);
|
||||
env.add(m);
|
||||
};
|
||||
box(10, 6, [-0.2, 1, 0.2], 6); // overhead
|
||||
box(1.6, 12, [-0.85, 0.3, 0.45], 7); // a tall strip, left
|
||||
box(3.2, 2.2, [0.42, 0.62, 0.66], 9); // a small box above the camera: the hot spot on the dome
|
||||
box(1.2, 10, [0.75, 0.2, -0.6], 3); // a rim strip behind
|
||||
const pm = new THREE.PMREMGenerator(renderer);
|
||||
const tex = pm.fromScene(env, 0.01).texture;
|
||||
pm.dispose();
|
||||
return tex;
|
||||
})();
|
||||
|
||||
// ------------------------------------------------------------ the bee and the guides
|
||||
let bee = null;
|
||||
const addBee = (b) => {
|
||||
bee = b;
|
||||
scene.add(b.root);
|
||||
b.root.traverse((o) => {
|
||||
if (o.isMesh && !b.clear.includes(o)) o.layers.enable(BEE_LAYER);
|
||||
});
|
||||
skip.push(...b.clear);
|
||||
for (const m of [b.M.lens, b.M.lensGlass]) {
|
||||
if (!m) continue;
|
||||
m.envMap = lensEnv;
|
||||
m.needsUpdate = true;
|
||||
}
|
||||
};
|
||||
const guides = buildGuides();
|
||||
scene.add(guides.group);
|
||||
skip.push(guides.group);
|
||||
|
||||
const size = {w: 1920, h: 1080, pr: 1};
|
||||
const resize = (w, h, pr) => {
|
||||
Object.assign(size, {w, h, pr});
|
||||
renderer.setPixelRatio(pr);
|
||||
renderer.setSize(w, h, false);
|
||||
composer.setPixelRatio(pr);
|
||||
composer.setSize(w, h);
|
||||
camera.aspect = w / h;
|
||||
camera.updateProjectionMatrix();
|
||||
backU.uRes.value.set(Math.round(w * pr), Math.round(h * pr));
|
||||
guides.resize(Math.round(w * pr), Math.round(h * pr), pr);
|
||||
};
|
||||
// cam: target (tx, ty, tz), azimuth from +z toward +x, elevation, distance, screen shift sx/sy in CSS px
|
||||
const frame = (cam, ops = {}) => {
|
||||
const {tx, ty, tz, az, el, d} = cam;
|
||||
camera.position.set(tx + d * Math.cos(el) * Math.sin(az), ty + d * Math.sin(el), tz + d * Math.cos(el) * Math.cos(az));
|
||||
camera.lookAt(tx, ty, tz);
|
||||
camera.setViewOffset(size.w, size.h, -(cam.sx ?? 0), -(cam.sy ?? 0), size.w, size.h);
|
||||
camera.updateMatrixWorld();
|
||||
const c = bee ? bee.root.position : new V3();
|
||||
key.target.position.set(c.x + 0.1, c.y, c.z);
|
||||
key.position.copy(key.target.position).addScaledVector(KEY, 8);
|
||||
key.target.updateMatrixWorld();
|
||||
guides.update(camera, ops);
|
||||
floorShadow(c);
|
||||
composer.render();
|
||||
};
|
||||
const pv = new V3();
|
||||
/** World point to CSS px, or null behind the camera. Call after frame(). */
|
||||
const project = (p) => {
|
||||
pv.copy(p).project(camera);
|
||||
if (pv.z > 1) return null;
|
||||
return [(pv.x * 0.5 + 0.5) * size.w, (-pv.y * 0.5 + 0.5) * size.h];
|
||||
};
|
||||
const setAOSkip = (list) => {
|
||||
extra = list;
|
||||
};
|
||||
// a live page's quality knobs: MSAA samples, the AO pass, the key's shadow map
|
||||
const setQuality = ({samples, ao, shadow, floor, self, blur}) => {
|
||||
if (blur !== undefined) key.shadow.blurSamples = blur;
|
||||
if (floor !== undefined) floorMode = floor;
|
||||
if (self !== undefined) key.castShadow = self;
|
||||
if (samples !== undefined) {
|
||||
for (const t of [composer.renderTarget1, composer.renderTarget2]) {
|
||||
t.samples = samples;
|
||||
t.dispose();
|
||||
}
|
||||
}
|
||||
if (ao !== undefined) gtao.enabled = ao;
|
||||
if (shadow !== undefined && shadow !== key.shadow.mapSize.x) {
|
||||
key.shadow.mapSize.set(shadow, shadow);
|
||||
key.shadow.map?.dispose();
|
||||
key.shadow.map = null;
|
||||
}
|
||||
};
|
||||
return {renderer, scene, camera, composer, gtao, key, resize, frame, addBee, size, floorY, project, setAOSkip, setQuality};
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
// The HB-7 simulator tour: everything the console film needs from one script (the entry's timeline.json, {duration,
|
||||
// script: [{t, view | display, cam?}]}) as pure functions of film time t. The display toggles and their eased weights,
|
||||
// the motion they drive (the motor winding down before the explode, the reassembly, the wings spinning up, the
|
||||
// high-speed camera slowing playback to 0.2× when MOTION BLUR goes off), the cameras for the five views, the telemetry
|
||||
// the console shows (all read off the same motion, so the numbers agree with the picture), the labels and the
|
||||
// operator's pointer. The film (sim.js) and a later live page share it, the way cessna-shared/live.js reuses film.js.
|
||||
import * as THREE from 'three';
|
||||
import {DISPLAY, VIEWPORT} from './console.js';
|
||||
|
||||
const smoother = (x) => {
|
||||
const u = Math.min(1, Math.max(0, x));
|
||||
return u * u * u * (u * (u * 6 - 15) + 10);
|
||||
};
|
||||
const ss = (a, b, t) => smoother((t - a) / (b - a));
|
||||
const lerp = (a, b, k) => a + (b - a) * k;
|
||||
|
||||
export const FLAP_HZ = 7.5;
|
||||
export const AMP = 32;
|
||||
export const REACH = 0.6;
|
||||
// bee units to millimetres (the body is 3 units, a 240 mm drone) and the floor under it
|
||||
const MM = 80;
|
||||
export const FLOOR_Y = -1.85;
|
||||
|
||||
// ------------------------------------------------------------ cameras (u = seconds since the view came on)
|
||||
// [az, el, d, tx, ty, tz, sx, sy]; the viewport sits a little above the canvas centre, hence sy
|
||||
export const VIEW_FN = {
|
||||
'hero:intro': (u) => {
|
||||
// from frame 0: an orbit round the front quarter and a push-in, the whole bee big the whole way
|
||||
const k = ss(-0.6, 3.6, u);
|
||||
return [lerp(82, 30, k), lerp(4, 11, k), lerp(9.4, 6.8, k), 0.1, -0.24, 0.25, -30, -14];
|
||||
},
|
||||
hero: (u) => [32 + 2.2 * u, 10, 7.6, -0.1, -0.28, 0.3, -40, -14],
|
||||
'hero:end': (u) => [24 + 2.6 * u, 8, 7.3, -0.05, -0.26, 0.28, -30, -14],
|
||||
front: (u) => [86 + 2 * u, 12, 7.8, 0.35, -0.28, 0.0, 0, -14],
|
||||
side: (u) => [3 + 2 * u, 7, 8.8, -0.2, -0.3, 0.0, 0, -14],
|
||||
// the near forewing from ahead and above: it spans the viewport, its face shows and its stroke sweeps up and down
|
||||
wing: (u) => [70 - 1.2 * u, 36, 6.6, 0.05, 0.22, 1.0, 0, -14],
|
||||
legs: (u) => [40 + 2 * u, 5, 6.8, 0.3, -0.62, 0.3, 0, -14],
|
||||
};
|
||||
const EASE = {labels: 0.5, xray: 0.8, exploded: 1.8, blur: 0.6, orbit: 1.4};
|
||||
const button = (key) => key.split(':')[0];
|
||||
|
||||
/** Everything from one tour. */
|
||||
export function makeTour(TL) {
|
||||
const SCRIPT = [...TL.script].sort((a, b) => a.t - b.t);
|
||||
const DURATION = TL.duration;
|
||||
const EVENTS = SCRIPT.filter((e) => e.t > 0).map((e) => e.t);
|
||||
const displayAt = (t) => {
|
||||
const out = Object.fromEntries(DISPLAY.map((k) => [k, 0]));
|
||||
for (const e of SCRIPT) if (e.display && e.t <= t) out[e.display] = out[e.display] ? 0 : 1;
|
||||
return out;
|
||||
};
|
||||
const lastFlip = (key, t) => SCRIPT.filter((e) => e.display === key && e.t <= t).pop()?.t ?? -99;
|
||||
const eased = (key, t) => {
|
||||
const on = displayAt(t)[key];
|
||||
const k = ss(lastFlip(key, t), lastFlip(key, t) + EASE[key], t);
|
||||
return on ? k : 1 - k;
|
||||
};
|
||||
// the motor and the teardown: EXPLODED on winds the beat down over 0.7 s, then the parts travel out over 1.8 s;
|
||||
// off brings them home over 1.8 s, then the beat spins back up over 0.7 s
|
||||
const motion = (t) => {
|
||||
const on = displayAt(t).exploded;
|
||||
const t0 = lastFlip('exploded', t);
|
||||
if (on) return {explode: ss(t0 + 0.5, t0 + 2.3, t), amp: AMP * (1 - ss(t0, t0 + 0.7, t))};
|
||||
if (t0 < -90) return {explode: 0, amp: AMP};
|
||||
return {explode: 1 - ss(t0, t0 + 1.8, t), amp: AMP * ss(t0 + 1.7, t0 + 2.4, t)};
|
||||
};
|
||||
// playback: 1× with the motion blur on, 0.2× (a high-speed capture) with it off; the bee's own clock integrates it,
|
||||
// and so does the energy the wings draw
|
||||
const rate = (t) => 1 - 0.8 * (1 - eased('blur', t));
|
||||
const DT = 1 / 240;
|
||||
const SIM = [0];
|
||||
const FLY = [0];
|
||||
for (let i = 1; i * DT <= DURATION + 1; i++) {
|
||||
const t = (i - 0.5) * DT;
|
||||
SIM.push(SIM[i - 1] + rate(t) * DT);
|
||||
FLY.push(FLY[i - 1] + (motion(t).amp / AMP) * rate(t) * DT);
|
||||
}
|
||||
const look = (A, t) => {
|
||||
const u = Math.max(0, Math.min(A.length - 2, t / DT));
|
||||
const i = Math.floor(u);
|
||||
return A[i] + (A[i + 1] - A[i]) * (u - i);
|
||||
};
|
||||
// before the film starts the bee was already flying at 1×
|
||||
const simT = (t) => (t < 0 ? t : look(SIM, t));
|
||||
const flyT = (t) => (t < 0 ? 0 : look(FLY, t));
|
||||
|
||||
// cameras: each view blends from the one before over 1.6 s; the explode pulls the camera back so the parts stay in
|
||||
// the viewport; the orbit's turn rate ramps in
|
||||
const VIEWS = SCRIPT.filter((e) => e.view).map((e) => ({t: e.t, key: e.cam ? `${e.view}:${e.cam}` : e.view}));
|
||||
// the orbit: on, it ramps into a steady 16°/s; off, it keeps the turn made so far and coasts to a stop
|
||||
const orbitTurn = (t) => {
|
||||
const f = lastFlip('orbit', t);
|
||||
if (f < -90) return 0;
|
||||
const R = EASE.orbit;
|
||||
const turned = (x) => 16 * (x < R ? (x * x) / (2 * R) : x - R / 2);
|
||||
if (displayAt(t).orbit) return turned(t - f);
|
||||
const on = SCRIPT.filter((e) => e.display === 'orbit' && e.t < f).pop();
|
||||
if (!on) return 0;
|
||||
const c = Math.min(t - f, R);
|
||||
return turned(f - on.t) + 16 * c * (1 - c / (2 * R));
|
||||
};
|
||||
const viewIdx = (t) => {
|
||||
let i = 0;
|
||||
while (i < VIEWS.length - 1 && VIEWS[i + 1].t <= t) i++;
|
||||
return i;
|
||||
};
|
||||
const blendCam = (a, b, k) => {
|
||||
const o = b.map((v, i) => lerp(a[i], v, k));
|
||||
const dAz = ((b[0] - a[0] + 540) % 360) - 180;
|
||||
o[0] = a[0] + dAz * k;
|
||||
const swing = Math.min(1, Math.abs(dAz) / 90);
|
||||
// every move dollies out a little on the way, so between two close views the bee never passes cut by the panels
|
||||
o[2] += Math.max(0, Math.max(a[2], b[2]) + 0.5 * swing + 1.4 - o[2]) * Math.sin(Math.PI * k);
|
||||
return o;
|
||||
};
|
||||
const camAt = (t) => {
|
||||
const i = viewIdx(t);
|
||||
const V = VIEWS[i];
|
||||
let o = VIEW_FN[V.key](t - V.t);
|
||||
if (i > 0) {
|
||||
const k = ss(V.t, V.t + 1.6, t);
|
||||
if (k < 1) o = blendCam(VIEW_FN[VIEWS[i - 1].key](t - VIEWS[i - 1].t), o, k);
|
||||
}
|
||||
const ex = motion(t).explode;
|
||||
o = [...o];
|
||||
o[2] *= 1 + 0.62 * ex;
|
||||
o[4] += 0.15 * ex;
|
||||
o[1] += 6 * ex;
|
||||
// the orbit's turn; once it is off, the next view blends it away
|
||||
let az = orbitTurn(t);
|
||||
if (!displayAt(t).orbit && V.t > lastFlip('orbit', t)) az *= 1 - ss(V.t, V.t + 1.6, t);
|
||||
o[0] += az;
|
||||
return {az: o[0], el: o[1], d: o[2], tx: o[3], ty: o[4], tz: o[5], sx: o[6], sy: o[7]};
|
||||
};
|
||||
const viewAt = (t) => {
|
||||
const V = VIEWS[viewIdx(t)];
|
||||
return [V.t, button(V.key)];
|
||||
};
|
||||
// labels wait 0.9 s into a view before they come in; on a view change the old ones fade out over 0.3 s
|
||||
const labelGate = (t) => {
|
||||
const i = viewIdx(t);
|
||||
const V = VIEWS[i];
|
||||
const g = ss(V.t + 0.9, V.t + 1.5, t);
|
||||
const prev = i > 0 ? ss(VIEWS[i - 1].t + 0.9, VIEWS[i - 1].t + 1.5, V.t) * (1 - ss(V.t, V.t + 0.3, t)) : 0;
|
||||
return Math.min(1, g + prev);
|
||||
};
|
||||
|
||||
/** The bee's state at film time t: pose parameters, hover, x-ray, guides, camera. */
|
||||
const stateAt = (t) => {
|
||||
const m = motion(t);
|
||||
const T = simT(t);
|
||||
const calm = 1 - Math.min(1, m.explode * 2.5);
|
||||
return {
|
||||
t,
|
||||
simT: T,
|
||||
explode: m.explode,
|
||||
amp: m.amp,
|
||||
flap: Math.PI * 2 * FLAP_HZ * T,
|
||||
display: 1 - m.amp / AMP,
|
||||
blur: eased('blur', t),
|
||||
rate: rate(t),
|
||||
xray: eased('xray', t),
|
||||
hover: {y: 0.05 * Math.sin(T * 2.6) * calm, pitch: 0.025 * Math.sin(T * 1.9 + 0.6) * calm, roll: 0.03 * Math.sin(T * 1.3 + 1.1) * calm, calm},
|
||||
guides: 0.45 + 0.55 * Math.max(Math.min(1, m.explode * 2.5), eased('xray', t)),
|
||||
cam: camAt(t),
|
||||
view: viewAt(t)[1],
|
||||
displays: displayAt(t),
|
||||
labels: eased('labels', t) * labelGate(t),
|
||||
};
|
||||
};
|
||||
|
||||
/** What the console shows at t, read off the same motion as the picture. */
|
||||
const telemetry = (t, s) => {
|
||||
const T = s.simT;
|
||||
const D = s.displays;
|
||||
// the stroke angle of the near forewing and hindwing over the last 1.2 s of film time
|
||||
const stroke = [];
|
||||
for (let i = 0; i <= 90; i++) {
|
||||
const tt = t - 1.2 + (i / 90) * 1.2;
|
||||
const a = motion(tt).amp;
|
||||
const ph = Math.PI * 2 * FLAP_HZ * simT(tt);
|
||||
stroke.push([a * Math.sin(ph), a * Math.sin(ph + 0.7)]);
|
||||
}
|
||||
const beat = ss(0.5, 6, s.amp);
|
||||
const fly = flyT(t);
|
||||
const power = 4.2 + 31 * Math.pow(s.amp / AMP, 1.5) * (1 + 0.04 * Math.sin(s.flap)) + 1.1 * s.hover.calm;
|
||||
const ex = s.explode > 0.04;
|
||||
// leg loads follow the hover: the legs take more as the bee decelerates at the bottom of each bob
|
||||
const acc = -Math.sin(T * 2.6);
|
||||
const servos = [0.44, 0.58, 0.49, 0.4, 0.53, 0.46].map((b, i) => (ex ? 0 : Math.max(0, Math.min(1, b * (1 + 0.32 * acc * (i % 3 === 1 ? 1.2 : 1)) + 0.03 * Math.sin(T * 7 + i)))));
|
||||
const reassembling = !D.exploded && s.explode > 0.04;
|
||||
const [status, statusKind] = D.exploded ? ['TEARDOWN', 'warn'] : reassembling ? ['REASSEMBLY', 'warn'] : s.blur < 0.5 ? ['HI-SPEED', 'warn'] : ['HOVER', 'ok'];
|
||||
const modeSub = D.exploded
|
||||
? `EXPLODED VIEW · ${Math.round(s.explode * 100)}% · 128 PARTS`
|
||||
: reassembling
|
||||
? 'PARTS SEATING · MOTOR ARMED'
|
||||
: s.blur < 0.5
|
||||
? 'CAPTURE 2000 FPS · 0.2× PLAYBACK'
|
||||
: `STATION KEEPING · ${((s.hover.y - FLOOR_Y) * MM).toFixed(0)} MM AGL`;
|
||||
const last = SCRIPT.filter((e) => e.t > 0 && e.t <= t).pop();
|
||||
const say = (e) => (e.view ? `VIEW → ${button(e.view).toUpperCase()}` : `${e.display === 'blur' ? 'MOTION BLUR' : e.display === 'xray' ? 'X-RAY' : e.display.toUpperCase()} ${displayAt(e.t + 0.001)[e.display] ? 'ON' : 'OFF'}`);
|
||||
const sub = (i) => {
|
||||
if (ex && i !== 3) return ['warn', 'DETACHED'];
|
||||
if (i === 0) return ['ok', 'TRACKING'];
|
||||
if (i === 1) return ['ok', 'LOCKED'];
|
||||
if (i === 2) return s.xray > 0.5 ? ['warn', 'EXPOSED'] : s.amp > 1 ? ['ok', 'RUNNING'] : ['idle', 'STOPPED'];
|
||||
if (i === 3) return ex ? ['warn', 'DETACHED'] : s.blur < 0.5 ? ['warn', 'HI-SPEED'] : s.amp > 1 ? ['ok', `${FLAP_HZ} HZ`] : ['idle', 'PARKED'];
|
||||
if (i === 4) return ['ok', 'HOLDING'];
|
||||
return s.xray > 0.5 ? ['warn', 'EXPOSED'] : ['ok', 'SEALED'];
|
||||
};
|
||||
const focus = s.view === 'wing' ? 3 : s.view === 'legs' ? 4 : s.view === 'front' ? 0 : s.xray > 0.5 ? 2 : -1;
|
||||
return {
|
||||
time: t,
|
||||
dur: DURATION,
|
||||
lift: Math.max(0, (s.amp / AMP) * (0.68 + 0.02 * Math.sin(s.flap))),
|
||||
status,
|
||||
statusKind,
|
||||
freq: FLAP_HZ * beat,
|
||||
amp: s.amp,
|
||||
stroke,
|
||||
playback: s.rate,
|
||||
blur: s.blur,
|
||||
battery: 0.842 - 0.0024 * fly,
|
||||
power,
|
||||
volt: 3.92 - 0.006 * power,
|
||||
motorT: 34 + 7 * Math.min(1, fly / 20) + 0.08 * power,
|
||||
servos,
|
||||
legsFree: ex,
|
||||
airborne: !ex,
|
||||
alt: (s.hover.y - FLOOR_Y) * MM,
|
||||
vs: MM * 0.05 * 2.6 * Math.cos(T * 2.6) * s.hover.calm * s.rate,
|
||||
pitch: (s.hover.pitch * 180) / Math.PI,
|
||||
roll: (s.hover.roll * 180) / Math.PI,
|
||||
airspeed: Math.abs(MM * 0.05 * 2.6 * Math.cos(T * 2.6) * s.hover.calm * s.rate) / 1000 + 0.004 * s.hover.calm,
|
||||
view: s.view,
|
||||
display: D,
|
||||
subs: [0, 1, 2, 3, 4, 5].map(sub),
|
||||
focus,
|
||||
events: EVENTS,
|
||||
next: `${EVENTS.length} OPERATOR ACTIONS`,
|
||||
log: last ? `OPERATOR · ${say(last)}` : 'AUTO-HOVER · STATION KEEPING',
|
||||
mode: status,
|
||||
modeSub,
|
||||
};
|
||||
};
|
||||
|
||||
return {SCRIPT, DURATION, EVENTS, displayAt, eased, motion, simT, camAt, viewAt, stateAt, telemetry};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ labels
|
||||
const V3 = THREE.Vector3;
|
||||
const GENERAL = [
|
||||
['lens', 'OPTIC LENS', '18 MM · AMBER IR PUPIL'],
|
||||
['antenna', 'ANTENNA', 'AIRFLOW + SCENT SENSOR'],
|
||||
['collar', 'NECK BEARING', '10-SEGMENT COLLAR'],
|
||||
['hinge', 'WING HINGE', '7.5 HZ CRANK · ±32°'],
|
||||
['gears', 'DRIVE GEAR STACK', '3 SPUR GEARS'],
|
||||
['core', 'CONTROL BOARDS', 'FLIGHT CPU · IMU'],
|
||||
['pad', 'SHOULDER PAD', 'POLYMER SHELL'],
|
||||
['knee2', 'LEG SERVO', 'KNEE · 0.4 N·M'],
|
||||
['capsule', 'ABDOMEN CAPSULE', 'GEAR TRAIN · SPRING'],
|
||||
['sting', 'POLLEN PROBE', 'RETRACTABLE TIP'],
|
||||
];
|
||||
const LEGSET = [
|
||||
['hip1', 'HIP SERVO', 'YAW + LIFT'],
|
||||
['knee1', 'KNEE SERVO L1', '0.4 N·M'],
|
||||
['knee2', 'KNEE SERVO L2', '0.4 N·M'],
|
||||
['knee3', 'KNEE SERVO L3', '0.4 N·M'],
|
||||
['foot', 'FOOT WHEEL', 'GRIP PAD'],
|
||||
['pad', 'SHOULDER PAD', 'POLYMER SHELL'],
|
||||
['core', 'CONTROL BOARDS', 'SERVO DRIVERS'],
|
||||
];
|
||||
const WINGSET = [
|
||||
['hinge', 'WING HINGE', '7.5 HZ CRANK · ±32°'],
|
||||
['wing', 'WING MEMBRANE', 'FROSTED FILM · 0.1 MM'],
|
||||
['hinge2', 'HINDWING HINGE', 'PHASE +40°'],
|
||||
['antenna', 'ANTENNA', 'AIRFLOW + SCENT SENSOR'],
|
||||
['gears', 'DRIVE GEAR STACK', '3 SPUR GEARS'],
|
||||
];
|
||||
/** Labels for a view, in two columns at the viewport's edges, stacked by height so no two touch. */
|
||||
export function makeLabels(st, bee) {
|
||||
const p = new V3();
|
||||
return (view, o) => {
|
||||
if (o < 0.02) return [];
|
||||
const set = view === 'legs' ? LEGSET : view === 'wing' ? WINGSET : GENERAL;
|
||||
const pts = [];
|
||||
for (const [key, name, sub] of set) {
|
||||
const A = bee.anchors[key];
|
||||
if (!A) continue;
|
||||
A.obj.updateWorldMatrix(true, false);
|
||||
const at = st.project(A.obj.localToWorld(p.copy(A.at)));
|
||||
if (at && at[0] > VIEWPORT.x0 + 30 && at[0] < VIEWPORT.x1 - 30 && at[1] > VIEWPORT.y0 + 40 && at[1] < VIEWPORT.y1 - 70) pts.push({name, sub, at});
|
||||
}
|
||||
const mid = (VIEWPORT.x0 + VIEWPORT.x1) / 2;
|
||||
const Lc = pts.filter((x) => x.at[0] < mid).sort((a, b) => a.at[1] - b.at[1]);
|
||||
const Rc = pts.filter((x) => x.at[0] >= mid).sort((a, b) => a.at[1] - b.at[1]);
|
||||
const out = [];
|
||||
const stack = (col, x, w) => {
|
||||
let y = VIEWPORT.y0 + 48;
|
||||
// start low enough that the column ends above the flight-mode word
|
||||
y = Math.max(y, Math.min(col.length ? col[0].at[1] - 10 : y, VIEWPORT.y1 - 110 - 34 * col.length));
|
||||
for (const c of col) {
|
||||
y = Math.max(y, Math.min(VIEWPORT.y1 - 110, c.at[1] - 10));
|
||||
out.push({name: c.name, sub: c.sub, at: c.at, label: [x, y], w, o});
|
||||
y += 34;
|
||||
}
|
||||
};
|
||||
stack(Lc, VIEWPORT.x0 + 16, 168);
|
||||
stack(Rc, VIEWPORT.x1 - 160, 150);
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ the operator's pointer (after cessna-shared/film_v2.js)
|
||||
// It reaches each button 0.1 s before the press, leaves 0.2 s after, travels in an eased bow, and between distant
|
||||
// presses waits in the gutter left of the right-hand panels, never over the bee.
|
||||
const GUTTER_X = 1262;
|
||||
export function makeCursor(ui, SCRIPT) {
|
||||
const EV = SCRIPT.filter((e) => e.t > 0).map((e) => ({t: e.t, spot: ui.spots[e.view ?? e.display]}));
|
||||
const first = EV[0].spot;
|
||||
const WP = [[0, GUTTER_X, first[1] + 60]];
|
||||
let [px, py, pt] = [GUTTER_X, first[1] + 60, 0];
|
||||
EV.forEach((e, n) => {
|
||||
const [x, y] = e.spot;
|
||||
const travel = Math.min(0.75, 0.32 + Math.hypot(x - px, y - py) / 900);
|
||||
const arrive = e.t - 0.1;
|
||||
if (arrive - travel - pt > 1.6) {
|
||||
const rest = [GUTTER_X, Math.max(170, Math.min(720, y + 40))];
|
||||
WP.push([pt + 0.75, ...rest]);
|
||||
WP.push([arrive - travel, ...rest]);
|
||||
} else WP.push([Math.max(pt + 0.01, arrive - travel), px, py]);
|
||||
WP.push([arrive, x, y], [e.t + 0.2, x, y]);
|
||||
[px, py, pt] = [x, y, e.t + 0.2];
|
||||
const next = EV[n + 1];
|
||||
if (!next || next.t - 0.1 - 0.75 - pt > 0.9) {
|
||||
[px, py, pt] = [GUTTER_X, y + 12, pt + 0.6];
|
||||
WP.push([pt, px, py]);
|
||||
}
|
||||
});
|
||||
WP.push([pt + 0.9, GUTTER_X, Math.min(720, py + 50)]);
|
||||
return (t) => {
|
||||
let i = 0;
|
||||
while (i < WP.length - 2 && t > WP[i + 1][0]) i++;
|
||||
const [t0, x0, y0] = WP[i];
|
||||
const [t1, x1, y1] = WP[i + 1];
|
||||
const k = ss(t0, t1, t);
|
||||
const len = Math.hypot(x1 - x0, y1 - y0);
|
||||
const bow = Math.sin(Math.PI * k) * Math.min(22, len * 0.07);
|
||||
let press = false;
|
||||
let ring = 0;
|
||||
let rx = 0;
|
||||
let ry = 0;
|
||||
for (const e of EV) {
|
||||
if (t >= e.t - 0.07 && t < e.t + 0.09) press = true;
|
||||
if (t >= e.t && t < e.t + 0.55) {
|
||||
ring = 1 - (t - e.t) / 0.55;
|
||||
[rx, ry] = e.spot;
|
||||
}
|
||||
}
|
||||
return {x: x0 + (x1 - x0) * k + (len ? (-(y1 - y0) / len) * bow : 0), y: y0 + (y1 - y0) * k + (len ? ((x1 - x0) / len) * bow : 0), press, ring, ringX: rx, ringY: ry};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
// The Vespion VX-9 wasp's 10-second demo (entry wasp-demo), made 2026-11-06 for the article: the bee's 18-second
|
||||
// film (robobee-shared/tour_18.js) carried onto the wasp (its tour_v2.js differences: the sting, the abdomen camera's
|
||||
// target, the labels) and cut down to one assembly. What it runs:
|
||||
// - the opening: the wasp dives in from high on the left, banking, and flares nose-up as it brakes;
|
||||
// - one assembly, the WING: pulled out of its hinge and turned over in the air;
|
||||
// - the explode in slow motion (0.4x while the parts leave), the camera passing low under them, a full 360 deg
|
||||
// turntable and a push-in for the reassembly;
|
||||
// - the exit: the wasp turns a little toward the lens, noses up and climbs straight out of the top of the frame.
|
||||
// The speed ramp is a warp of film time t into scene time tau (tauAt), so everything stays a pure function of t.
|
||||
import * as THREE from 'three';
|
||||
import {FLOOR_Y} from './tour.js';
|
||||
import {AMP, ASSEMBLY_LABEL, FLAP_HZ} from './tour_v2.js';
|
||||
|
||||
const smoother = (x) => {
|
||||
const u = Math.min(1, Math.max(0, x));
|
||||
return u * u * u * (u * (u * 6 - 15) + 10);
|
||||
};
|
||||
const ss = (a, b, t) => smoother((t - a) / (b - a));
|
||||
const lerp = (a, b, k) => a + (b - a) * k;
|
||||
const bump = (a, b, c, d, t) => ss(a, b, t) * (1 - ss(c, d, t));
|
||||
const D2R = Math.PI / 180;
|
||||
const MM = 80;
|
||||
const S = 1.15;
|
||||
|
||||
// each act's own clock in scene seconds after its click, a beat every 2.2 s
|
||||
export const ACT_R = {
|
||||
optics: {open: [0.25, 1.05], close: [1.55, 1.9], stop: false},
|
||||
wing: {open: [0.2, 0.75], close: [1.6, 1.95], stop: true},
|
||||
thorax: {open: [0.25, 1.0], close: [1.5, 1.9], stop: true},
|
||||
abdomen: {open: [0.25, 1.0], close: [1.55, 1.95], stop: true},
|
||||
};
|
||||
// the pulled wing turns over once while it hangs out of its hinge
|
||||
export const WING_FLIP = [0.45, 1.45];
|
||||
// the ramp in film seconds after the EXPLODED click: down to 0.4x as the parts start to leave, held while they drift
|
||||
// apart, back up as the turntable takes over
|
||||
export const RAMP = {a: [0.35, 0.55], b: [1.9, 2.1], low: 0.4};
|
||||
// the climb starts this long after HERO (scene seconds)
|
||||
export const DEP = 0.75;
|
||||
// the hero camera, low on the front-right so the climb reads against the paper above
|
||||
const HERO_AZ = 32;
|
||||
const HERO_EL = 4;
|
||||
const HERO_D = 7.8;
|
||||
|
||||
export function makeWarp(tRamp, dur) {
|
||||
const rate = (t) => 1 - (1 - RAMP.low) * bump(tRamp + RAMP.a[0], tRamp + RAMP.a[1], tRamp + RAMP.b[0], tRamp + RAMP.b[1], t);
|
||||
const DT = 1 / 480;
|
||||
const TAU = [0];
|
||||
for (let i = 1; i * DT <= dur + 2; i++) TAU.push(TAU[i - 1] + rate((i - 0.5) * DT) * DT);
|
||||
const tauAt = (t) => {
|
||||
if (t <= 0) return t;
|
||||
const u = Math.min(TAU.length - 2, t / DT);
|
||||
const i = Math.floor(u);
|
||||
return TAU[i] + (TAU[i + 1] - TAU[i]) * (u - i);
|
||||
};
|
||||
return {rate, tauAt};
|
||||
}
|
||||
|
||||
export function make10Tour(TL) {
|
||||
const SCRIPT = [...TL.script].sort((a, b) => a.t - b.t);
|
||||
const DURATION = TL.duration;
|
||||
const EVENTS = SCRIPT.map((e) => e.t);
|
||||
const tfOf = (act) => (SCRIPT.find((e) => e.act === act) ?? {t: 999}).t;
|
||||
const tfExp = tfOf('exploded');
|
||||
const tfAsm = tfOf('assemble');
|
||||
const {rate, tauAt} = makeWarp(tfExp, DURATION);
|
||||
const AT = {};
|
||||
for (const e of SCRIPT) (AT[e.act] ??= []).push(tauAt(e.t));
|
||||
const at = (act) => AT[act] ?? [];
|
||||
const T_EXP = at('exploded')[0] ?? 999;
|
||||
const T_ASM = at('assemble')[0] ?? 999;
|
||||
const T_END = at('hero')[0] ?? 999;
|
||||
const T_FIRST = Math.min(...Object.keys(ACT_R).flatMap((a) => at(a)), 999);
|
||||
|
||||
const openOf = (act, x) => {
|
||||
let v = 0;
|
||||
for (const t0 of at(act)) {
|
||||
const A2 = ACT_R[act];
|
||||
v = Math.max(v, bump(t0 + A2.open[0], t0 + A2.open[1], t0 + A2.close[0], t0 + A2.close[1], x));
|
||||
}
|
||||
return v;
|
||||
};
|
||||
const explodeAt = (x) => ss(T_EXP + 0.2, T_EXP + 1.5, x) * (1 - ss(T_ASM, T_ASM + 0.8, x));
|
||||
// the turntable: a full +360 deg from the explode to just after the bee is whole again
|
||||
const TT = [T_EXP + 0.2, T_ASM + 1.2];
|
||||
const turnAt = (x) => {
|
||||
const [a, b] = TT;
|
||||
if (x <= a) return 0;
|
||||
const R = 0.5;
|
||||
const span = b - a;
|
||||
const v = 360 / (span - R);
|
||||
const y0 = Math.min(x, b) - a;
|
||||
if (y0 < R) return (v * y0 * y0) / (2 * R);
|
||||
if (y0 < span - R) return v * (y0 - R / 2);
|
||||
const y = y0 - (span - R);
|
||||
return v * (span - 1.5 * R) + v * y - (v * y * y) / (2 * R);
|
||||
};
|
||||
// the wings park for the acts that need still wings and for the explode; when the next act parks them too they stay
|
||||
// parked across the cut instead of spinning up for a moment between
|
||||
const STOPS = [];
|
||||
SCRIPT.forEach((e, n) => {
|
||||
const A2 = ACT_R[e.act];
|
||||
if (!A2?.stop) return;
|
||||
const t0 = tauAt(e.t);
|
||||
const nx = SCRIPT[n + 1];
|
||||
const hold = nx && (ACT_R[nx.act]?.stop || nx.act === 'exploded') ? tauAt(nx.t) - t0 + 0.4 : A2.close[1];
|
||||
STOPS.push([t0, t0 + 0.35, t0 + hold, t0 + hold + 0.45]);
|
||||
});
|
||||
STOPS.push([T_EXP, T_EXP + 0.4, T_ASM + 0.7, T_ASM + 1.2]);
|
||||
const stopAt = (x) => Math.max(0, ...STOPS.map((w) => bump(w[0], w[1], w[2], w[3], x)));
|
||||
const activity = (x) => Math.max(...Object.keys(ACT_R).map((a) => openOf(a, x)), explodeAt(x));
|
||||
const DT = 1 / 240;
|
||||
const SPIN = [0];
|
||||
for (let i = 1; i * DT <= DURATION + 1; i++) SPIN.push(SPIN[i - 1] + (1 + 5 * activity((i - 0.5) * DT)) * DT);
|
||||
const look = (A2, x) => {
|
||||
const u = Math.max(0, Math.min(A2.length - 2, x / DT));
|
||||
const i = Math.floor(u);
|
||||
return A2[i] + (A2[i + 1] - A2[i]) * (u - i);
|
||||
};
|
||||
const spinAt = (x) => (x < 0 ? x : look(SPIN, x));
|
||||
|
||||
// the bee: dives in from high on the left banking, flares nose-up and hovers through the teardowns, turns on the
|
||||
// explode turntable, turns a little toward the lens on HERO and climbs out of the top of the frame
|
||||
const flightAt = (x) => {
|
||||
const kIn = ss(-0.9, 1.6, x);
|
||||
const ex = explodeAt(x);
|
||||
const calm = 1 - Math.min(1, ex * 2.5);
|
||||
const path = new THREE.Vector3(lerp(-0.8 * S, 0, kIn), lerp(1.0 * S, 0, kIn), lerp(0.45 * S, 0, kIn));
|
||||
let yaw = lerp(-24, 0, kIn);
|
||||
let roll = 28 * Math.sin(Math.PI * Math.min(1, kIn * 1.05)) - 7 * Math.sin(2 * Math.PI * kIn) * kIn + 1.7 * Math.sin(x * 1.3 + 1.1) * calm;
|
||||
let pitch = -16 * (1 - kIn) + 10 * Math.sin(Math.PI * ss(0.55, 1.0, kIn)) + 1.4 * Math.sin(x * 1.9 + 0.6) * calm;
|
||||
yaw += turnAt(x);
|
||||
// HERO: the wasp turns a little toward the lens and lifts its nose, then climbs straight up out of the frame,
|
||||
// pitching up into the climb with one roll
|
||||
const kH = ss(T_END, T_END + 0.8, x);
|
||||
yaw -= 22 * kH;
|
||||
pitch += 8 * kH;
|
||||
roll += 10 * Math.sin(Math.PI * kH);
|
||||
if (x > T_END + DEP) {
|
||||
const u = x - T_END - DEP;
|
||||
const k = ss(0, 0.6, u);
|
||||
pitch += 24 * k;
|
||||
roll -= 12 * Math.sin(Math.PI * ss(0, 1.3, u));
|
||||
path.y += 0.7 * u + 1.8 * u * u;
|
||||
path.x += 0.3 * u * u;
|
||||
}
|
||||
const pos = path.clone().add(new THREE.Vector3(0, 0.05 * Math.sin(x * 2.6) * calm, 0));
|
||||
return {pos, path, yaw, roll, pitch, calm};
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------ cameras: [az, el, d, tx, ty, tz, sx, sy]
|
||||
// az from the right flank (0) toward the face (90); the hero side is about 20-40. The teardown targets and drift
|
||||
// rates are the second cut's.
|
||||
const macro = (act, u, depth = 0.12) => {
|
||||
const A2 = ACT_R[act];
|
||||
return 1 - depth * bump(A2.open[1] - 0.35, A2.open[1] + 0.1, A2.close[0] - 0.1, A2.close[1], u);
|
||||
};
|
||||
const push = (a, b, u, end = 1.9) => lerp(a, b, ss(0, end, u));
|
||||
const EXP_SPAN_F = tfAsm - tfExp;
|
||||
const CAM = {
|
||||
// the dive: the camera comes down from above with the bee, pushing in
|
||||
intro: (u) => {
|
||||
const k = ss(0, 2.0, u);
|
||||
return [lerp(46, 34, k), lerp(22, 10, k), lerp(7.9, 7.4, k), 0.0, -0.2, 0.25, -20, -14];
|
||||
},
|
||||
// the lens from the face side, so the barrel unscrews sideways across the frame
|
||||
optics: (u) => [90 - 9 * u, 6, push(4.9, 4.3, u) * macro('optics', u, 0.07), 1.22, 0.12, 0.45, 0, -14],
|
||||
// the wing from the hero side, rising with it as it leaves the hinge and turns over
|
||||
wing: (u) => {
|
||||
const k = ss(0, 1.9, u);
|
||||
return [38 + 9 * k, lerp(12, 22, k), push(8.8, 7.8, u), -0.5, 0.95, 1.25, 0, -14];
|
||||
},
|
||||
// the thorax from high over the near flank
|
||||
thorax: (u) => [6 + 10 * u, 34, push(6.9, 6.0, u) * macro('thorax', u), 0.0, 0.32, 0.05, 0, -14],
|
||||
// the abdomen from behind the near flank as it telescopes out
|
||||
abdomen: (u) => [-32 + 10 * u, 14, push(6.8, 5.9, u) * macro('abdomen', u, 0.08), -2.45, -0.95, 0.1, 0, -14],
|
||||
// the explode, on FILM time (u = film seconds since the click): while the ramp holds the parts at 0.4x the camera
|
||||
// keeps its own speed and swings round low under them looking up, then rises over the turntable and pushes in for
|
||||
// the reassembly
|
||||
exploded: (u) => {
|
||||
const arc = ss(0.45, 2.0, u);
|
||||
const rise = ss(1.9, 2.9, u);
|
||||
const near = ss(EXP_SPAN_F - 0.3, EXP_SPAN_F + 0.9, u);
|
||||
return [24 + 32 * arc - 14 * rise, lerp(10, -2, arc) + 20 * rise, lerp(11.4, 12.0, arc) - 3.6 * near, 0.0, lerp(-0.15, 0.05, arc) * (1 - rise) - 0.15 * rise, 0.0, -10, -14];
|
||||
},
|
||||
// HERO: low on the front-right, holding still while the wasp turns and climbs out
|
||||
hero: (u) => {
|
||||
const k = ss(0, 0.9, u);
|
||||
return [lerp(42, HERO_AZ, k), lerp(18, HERO_EL, k), lerp(8.4, HERO_D, k), 0.0, -0.15, 0.25, -14, -14];
|
||||
},
|
||||
};
|
||||
|
||||
const VIEWS = [{t: -1, tf: -1, key: 'intro'}, ...SCRIPT.map((e) => ({t: tauAt(e.t), tf: e.t, key: e.act === 'assemble' ? 'exploded' : e.act}))];
|
||||
const viewIdx = (x) => {
|
||||
let i = 0;
|
||||
while (i < VIEWS.length - 1 && VIEWS[i + 1].t <= x) i++;
|
||||
return i;
|
||||
};
|
||||
// ASSEMBLE runs on the EXPLODED view's clock, so both read as one continuous shot (and HERO blends out of it)
|
||||
const resolve = (i) => (VIEWS[i].key === 'exploded' && i > 0 && VIEWS[i - 1].key === 'exploded' ? VIEWS[i - 1] : VIEWS[i]);
|
||||
const camFn = (V, x, t) => CAM[V.key](V.key === 'intro' ? x : V.key === 'exploded' ? t - V.tf : x - V.t);
|
||||
const camAt = (x, t) => {
|
||||
const i = viewIdx(x);
|
||||
let o = camFn(resolve(i), x, t);
|
||||
if (i > 0 && resolve(i) === VIEWS[i]) {
|
||||
const k = ss(VIEWS[i].t, VIEWS[i].t + 0.7, x);
|
||||
if (k < 1) {
|
||||
const a = camFn(resolve(i - 1), x, t);
|
||||
const dAz = ((o[0] - a[0] + 540) % 360) - 180;
|
||||
const b = o.map((v, j) => lerp(a[j], v, k));
|
||||
b[0] = a[0] + dAz * k;
|
||||
b[2] += 0.5 * Math.sin(Math.PI * k);
|
||||
o = b;
|
||||
}
|
||||
}
|
||||
const f = flightAt(x);
|
||||
// the camera follows the wasp's path, and on the climb lets go sideways and follows the rise a third of the way
|
||||
const kOut = ss(T_END + DEP - 0.2, T_END + DEP + 0.5, x);
|
||||
const kIn = 1 - ss(0.2, 1.9, x);
|
||||
const tr = (0.85 - 0.3 * kIn) * (1 - kOut);
|
||||
const trY = (0.85 - 0.35 * kIn) * (1 - 0.65 * kOut);
|
||||
return {az: o[0], el: o[1], d: o[2], tx: o[3] + f.path.x * tr, ty: o[4] + f.path.y * trY, tz: o[5] + f.path.z * tr, sx: o[6], sy: o[7]};
|
||||
};
|
||||
const actAt = (x) => VIEWS[viewIdx(x)].key;
|
||||
|
||||
const stateAt = (t) => {
|
||||
const x = tauAt(t);
|
||||
const ex = explodeAt(x);
|
||||
const amp = AMP * (1 - stopAt(x));
|
||||
const f = flightAt(x);
|
||||
const open = Object.fromEntries(Object.keys(ACT_R).map((a) => [a, openOf(a, x)]));
|
||||
let wingFlip = 0;
|
||||
for (const t0 of at('wing')) wingFlip = Math.max(wingFlip, ss(t0 + WING_FLIP[0], t0 + WING_FLIP[1], x));
|
||||
if (wingFlip >= 1) wingFlip = 0;
|
||||
// the sting: out of its collar once the abdomen hangs open, back in before it closes
|
||||
let stingK = 0;
|
||||
for (const t0 of at('abdomen')) stingK = Math.max(stingK, ss(t0 + 0.75, t0 + 1.15, x) * (1 - ss(t0 + 1.4, t0 + 1.6, x)));
|
||||
return {
|
||||
t,
|
||||
tau: x,
|
||||
rate: rate(t),
|
||||
spinT: spinAt(x),
|
||||
explode: ex,
|
||||
amp,
|
||||
flap: Math.PI * 2 * FLAP_HZ * x,
|
||||
display: 1 - amp / AMP,
|
||||
blur: 1,
|
||||
sub: {thorax: open.thorax, abdomen: open.abdomen},
|
||||
eye: open.optics,
|
||||
wingOut: open.wing,
|
||||
wingFlip,
|
||||
stingK,
|
||||
legK: 0,
|
||||
open,
|
||||
flight: f,
|
||||
cam: camAt(x, t),
|
||||
view: actAt(x),
|
||||
guides: 0.45 + 0.55 * Math.min(1, ex * 2.5 + activity(x)),
|
||||
turn: turnAt(x),
|
||||
};
|
||||
};
|
||||
|
||||
// labels: on while the act's parts are moving apart and while they hang open, gone before they close
|
||||
const LABELS = {
|
||||
optics: [['eyeGlass', 'OUTER GLASS', 'Ø 40 MM · AR COATED'], ['eyeInner', 'INNER ELEMENT', 'Ø 15 MM'], ['iris', 'IRIS', '10 BLADES · OPENS 3×'], ['barrel', 'LENS BARREL', 'THREADED · 4 RINGS']],
|
||||
wing: [['wing', 'WING MEMBRANE', 'FROSTED FILM · 0.1 MM'], ['hinge', 'WING HINGE', 'QUICK RELEASE'], ['hinge2', 'HINDWING HINGE', 'PHASE +40°']],
|
||||
thorax: [['plate', 'SADDLE PLATE', 'POLYMER SHELL'], ['gears', 'DRIVE GEAR STACK', '3 SPUR GEARS'], ['act', 'ACTUATOR RING', '11 PISTONS'], ['core', 'CONTROL BOARDS', 'FLIGHT CPU · IMU']],
|
||||
abdomen: [['waist', 'WAIST STALK', '5 BEADS · LIT RINGS'], ['s1', 'SHELL BAND', 'TELESCOPING'], ['capsule', 'BAND 4', 'RIVETED · 5 SEGMENTS'], ['sting', 'STINGER', 'GLASS · EXTENDS 30 MM']],
|
||||
exploded: [['lens', 'OPTIC HEAD', '2 × LENS'], ['collar', 'NECK BEARING', '10 SEGMENTS'], ['gears', 'DRIVE GEARS', 'SPINNING FREE'], ['capsule', 'ABDOMEN BANDS', '5 SEGMENTS'], ['hinge', 'WING HINGE', 'QUICK RELEASE']],
|
||||
};
|
||||
const labelAt = (x, s) => {
|
||||
const v = s.view;
|
||||
if (ACT_R[v]) {
|
||||
const t0 = at(v).filter((y) => y <= x).pop();
|
||||
const A2 = ACT_R[v];
|
||||
return {set: LABELS[v], o: bump(t0 + A2.open[0] + 0.1, t0 + A2.open[0] + 0.4, t0 + A2.close[0] - 0.25, t0 + A2.close[0], x)};
|
||||
}
|
||||
if (v === 'exploded') return {set: LABELS.exploded, o: bump(T_EXP + 0.4, T_EXP + 0.8, T_EXP + 1.6, T_EXP + 1.9, x)};
|
||||
return {set: [], o: 0};
|
||||
};
|
||||
|
||||
const telemetry = (t, s) => {
|
||||
const x = s.tau;
|
||||
const f = s.flight;
|
||||
const stroke = [];
|
||||
for (let i = 0; i <= 90; i++) {
|
||||
const tt = x - 1.2 + (i / 90) * 1.2;
|
||||
const a = AMP * (1 - stopAt(tt));
|
||||
const ph = Math.PI * 2 * FLAP_HZ * tt;
|
||||
stroke.push([a * Math.sin(ph), a * Math.sin(ph + 0.7)]);
|
||||
}
|
||||
const ex = s.explode > 0.04;
|
||||
const acc = -Math.sin(x * 2.6);
|
||||
const free = [0, 1, 2, 3, 4, 5].map(() => ex);
|
||||
const servos = [0.44, 0.58, 0.49, 0.4, 0.53, 0.46].map((b, i) => (free[i] ? 0 : Math.max(0, Math.min(1, b * (1 + 0.32 * acc) + 0.12 * Math.abs(f.roll) / 30 + 0.03 * Math.sin(x * 7 + i)))));
|
||||
const v = s.view;
|
||||
const opening = ACT_R[v] ? s.open[v] : 0;
|
||||
const NAME = {optics: 'OPTICS OPEN', wing: 'WING OFF', thorax: 'THORAX OPEN', abdomen: 'ABDOMEN OPEN'};
|
||||
const dartU = x - T_END - DEP;
|
||||
const darting = dartU > 0;
|
||||
let status = 'HOVER';
|
||||
let kind = 'ok';
|
||||
if (x < T_FIRST) status = 'DIVING';
|
||||
if (ACT_R[v] && opening > 0.05) [status, kind] = [NAME[v], 'warn'];
|
||||
if (v === 'exploded') [status, kind] = s.rate < 0.9 ? ['SLOW-MO', 'warn'] : x < T_ASM ? ['TEARDOWN', 'warn'] : s.explode > 0.04 ? ['REASSEMBLY', 'warn'] : ['HOVER', 'ok'];
|
||||
if (darting) status = 'CLIMB-OUT';
|
||||
const ROW = {optics: 0, thorax: 2, wing: 3, leg: 4, abdomen: 5};
|
||||
const sub = (i) => {
|
||||
if (ex) return ['warn', 'DETACHED'];
|
||||
if (ROW[v] === i && opening > 0.05) return ['warn', i === 3 ? 'DETACHED' : 'OPEN'];
|
||||
if (i === 3) return s.amp > 1 ? ['ok', `${FLAP_HZ} HZ`] : ['idle', 'PARKED'];
|
||||
if (i === 2) return s.amp > 1 ? ['ok', 'RUNNING'] : ['idle', 'STOPPED'];
|
||||
return ['ok', ['TRACKING', 'LOCKED', '', '', 'HOLDING', 'SEALED'][i]];
|
||||
};
|
||||
const last = SCRIPT.filter((e) => e.t <= t).pop();
|
||||
const say = (e) => (e.act === 'exploded' ? 'EXPLODED ON' : e.act === 'assemble' ? 'EXPLODED OFF · REASSEMBLE' : e.act === 'hero' ? 'HERO · CLIMB-OUT' : `ISOLATE ${ASSEMBLY_LABEL[e.act]}`);
|
||||
const sp = darting ? 0.4 + 1.2 * (1.2 + 3 * dartU) : f.pos.length() > 0.05 ? 0.4 + 0.2 * Math.abs(Math.sin(x)) : 0.004;
|
||||
const labels = labelAt(x, s);
|
||||
return {
|
||||
time: t,
|
||||
dur: DURATION,
|
||||
lift: Math.max(0, (s.amp / AMP) * (0.68 + 0.02 * Math.sin(s.flap)) + 0.12 * Math.abs(f.roll) / 30),
|
||||
status,
|
||||
statusKind: kind,
|
||||
freq: FLAP_HZ * ss(0.5, 6, s.amp),
|
||||
amp: s.amp,
|
||||
stroke,
|
||||
playback: s.rate,
|
||||
blur: 1,
|
||||
battery: 0.842 - 0.0022 * t,
|
||||
power: 4.2 + 31 * Math.pow(s.amp / AMP, 1.5) * (1 + 0.04 * Math.sin(s.flap)) + 3 * Math.abs(f.roll) / 30 + (darting ? 9 * ss(0, 0.5, dartU) : 0),
|
||||
volt: 3.92 - 0.006 * 36,
|
||||
motorT: 34 + 0.35 * t,
|
||||
servos,
|
||||
legsFree: ex,
|
||||
legFreeEach: free,
|
||||
airborne: true,
|
||||
alt: (f.pos.y - FLOOR_Y) * MM,
|
||||
vs: x < T_FIRST ? -MM * S * (ss(-0.9, 1.6, x + 0.05) - ss(-0.9, 1.6, x - 0.05)) * 10 : MM * 0.05 * 2.6 * Math.cos(x * 2.6) * f.calm,
|
||||
pitch: f.pitch,
|
||||
roll: f.roll,
|
||||
airspeed: sp,
|
||||
view: v === 'intro' ? 'hero' : v === 'exploded' ? null : v,
|
||||
display: {labels: labels.o > 0.5, exploded: x >= T_EXP && x < T_ASM, blur: s.amp > 3, turntable: s.turn > 0.5 && x < TT[1]},
|
||||
subs: [0, 1, 2, 3, 4, 5].map(sub),
|
||||
focus: ROW[v] ?? (v === 'exploded' ? 1 : -1),
|
||||
events: EVENTS,
|
||||
next: `${EVENTS.length} OPERATOR ACTIONS`,
|
||||
log: last ? `OPERATOR · ${say(last)}` : 'INBOUND · DIVING · BANK LEFT',
|
||||
mode: status,
|
||||
modeSub:
|
||||
status === 'DIVING'
|
||||
? `BANK ${f.roll.toFixed(0)}° · DIVING IN`
|
||||
: status === 'SLOW-MO'
|
||||
? `PLAYBACK ${s.rate.toFixed(2)}× · ${Math.round(s.explode * 100)}% APART`
|
||||
: status === 'TEARDOWN' || status === 'REASSEMBLY'
|
||||
? `TURNTABLE ${Math.round(s.turn)}° CW · ${Math.round(s.explode * 100)}% APART`
|
||||
: status === 'CLIMB-OUT'
|
||||
? `CLIMBING · ${sp.toFixed(1)} M/S`
|
||||
: ACT_R[v]
|
||||
? `${ASSEMBLY_LABEL[v]} · ${Math.round(opening * 100)}% APART`
|
||||
: `STATION KEEPING · ${((f.pos.y - FLOOR_Y) * MM).toFixed(0)} MM AGL`,
|
||||
viewNote: `ISOLATE · ${v === 'intro' || v === 'hero' ? 'HERO' : v === 'exploded' ? 'ALL' : ASSEMBLY_LABEL[v]}`,
|
||||
labelSet: labels,
|
||||
};
|
||||
};
|
||||
|
||||
return {SCRIPT, DURATION, stateAt, telemetry, camAt, flightAt, tauAt};
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
// The VX-9 wasp's tour: the bee's (robobee-shared/tour_v2.js) 1:1, the stinger sliding out at the end of the abdomen act.
|
||||
// The HB-7 simulator tour, second cut: the bee itself does something big every 2-3 s. It flies in and banks through a
|
||||
// turn, then the operator opens one assembly after another, each with the camera pushed in on it: the lens unscrews
|
||||
// along its axis and the iris opens, a wing pulls out of its hinge and turns over in the air, a leg comes apart
|
||||
// segment by segment with its servos spinning, the thorax shells lift off over spinning gears, the abdomen telescopes
|
||||
// apart; then the whole bee explodes on a 330° turntable with its parts spinning, snaps back together while it still
|
||||
// turns, spins its wings up and banks away out of frame. Labels show only while parts move.
|
||||
// Script: the entry's timeline.json, {duration, script: [{t, act}]}; act is an assembly (optics, wing, leg, thorax,
|
||||
// abdomen), 'exploded', 'assemble' or 'hero' (the departure). Everything is a pure function of film time t.
|
||||
import * as THREE from 'three';
|
||||
import {VIEWPORT} from './console.js';
|
||||
import {FLOOR_Y} from './tour.js';
|
||||
|
||||
const smoother = (x) => {
|
||||
const u = Math.min(1, Math.max(0, x));
|
||||
return u * u * u * (u * (u * 6 - 15) + 10);
|
||||
};
|
||||
const ss = (a, b, t) => smoother((t - a) / (b - a));
|
||||
const lerp = (a, b, k) => a + (b - a) * k;
|
||||
const D2R = Math.PI / 180;
|
||||
const MM = 80;
|
||||
export const FLAP_HZ = 7.5;
|
||||
export const AMP = 32;
|
||||
export const REACH = 0.62;
|
||||
|
||||
export const ASSEMBLIES = ['hero', 'optics', 'wing', 'leg', 'thorax', 'abdomen'];
|
||||
export const ASSEMBLY_LABEL = {hero: 'HERO', optics: 'OPTICS', wing: 'WING', leg: 'LEG L2', thorax: 'THORAX', abdomen: 'ABDOMEN'};
|
||||
export const DISPLAY2 = ['labels', 'exploded', 'blur', 'turntable'];
|
||||
export const DISPLAY2_LABEL = {labels: 'LABELS', exploded: 'EXPLODED', blur: 'MOTION BLUR', turntable: 'TURNTABLE'};
|
||||
// the button each act presses
|
||||
const BUTTON = {optics: 'optics', wing: 'wing', leg: 'leg', thorax: 'thorax', abdomen: 'abdomen', exploded: 'exploded', assemble: 'exploded', hero: 'hero'};
|
||||
|
||||
// each act's own clock (seconds after its click): when it opens, when it closes, whether the wings stop for it
|
||||
const ACT = {
|
||||
optics: {open: [0.35, 1.5], close: [2.2, 2.65], stop: false},
|
||||
wing: {open: [0.45, 1.25], close: [2.35, 2.7], stop: true},
|
||||
leg: {open: [0.35, 1.45], close: [2.15, 2.55], stop: false},
|
||||
thorax: {open: [0.3, 1.4], close: [2.1, 2.6], stop: true},
|
||||
abdomen: {open: [0.3, 1.3], close: [2.0, 2.45], stop: true},
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------ cameras: [az, el, d, tx, ty, tz, sx, sy], u = seconds on
|
||||
export const CAM2 = {
|
||||
intro: (u) => {
|
||||
const k = ss(0, 3.0, u);
|
||||
return [lerp(150, 34, k), lerp(15, 9, k), lerp(8.6, 7.3, k), 0.0, -0.25, 0.25, -30, -14];
|
||||
},
|
||||
optics: (u) => [88 - 8 * u, 6, lerp(4.9, 4.2, ss(0, 1.6, u)), 1.22, 0.12, 0.45, 0, -14],
|
||||
wing: (u) => [40 + 6 * u, 18, lerp(8.6, 7.6, ss(0, 1.6, u)), -0.5, 0.95, 1.25, 0, -14],
|
||||
leg: (u) => [14 + 9 * u, 6, lerp(6.6, 5.8, ss(0, 1.6, u)), 0.1, -0.8, 0.45, 0, -14],
|
||||
thorax: (u) => [8 + 10 * u, 34, lerp(6.8, 6.0, ss(0, 1.6, u)), 0.0, 0.32, 0.05, 0, -14],
|
||||
abdomen: (u) => [-30 + 9 * u, 14, lerp(6.6, 5.8, ss(0, 1.6, u)), -2.45, -0.95, 0.1, 0, -14],
|
||||
exploded: (u) => [34 + 5 * u, 18, 11.6, 0.0, -0.15, 0.0, -20, -14],
|
||||
hero: (u) => [18 + 14 * u, 9, 6.8, 0.0, -0.22, 0.25, -30, -14],
|
||||
};
|
||||
|
||||
export function makeTour2(TL) {
|
||||
const SCRIPT = [...TL.script].sort((a, b) => a.t - b.t);
|
||||
const DURATION = TL.duration;
|
||||
const EVENTS = SCRIPT.map((e) => e.t);
|
||||
const AT = {};
|
||||
for (const e of SCRIPT) (AT[e.act] ??= []).push(e.t);
|
||||
const at = (act) => AT[act] ?? [];
|
||||
const T_EXP = at('exploded')[0] ?? 999;
|
||||
const T_ASM = at('assemble')[0] ?? 999;
|
||||
const T_END = at('hero')[0] ?? 999;
|
||||
// an assembly's opening, 0..1, from its act's clock
|
||||
const openOf = (act, t) => {
|
||||
let v = 0;
|
||||
for (const t0 of at(act)) {
|
||||
const A = ACT[act];
|
||||
v = Math.max(v, ss(t0 + A.open[0], t0 + A.open[1], t) * (1 - ss(t0 + A.close[0], t0 + A.close[1], t)));
|
||||
}
|
||||
return v;
|
||||
};
|
||||
// the full explode: out 0.2-1.8 s after EXPLODED, home 0-1.0 s after it goes off (fast, it snaps)
|
||||
const explodeAt = (t) => ss(T_EXP + 0.2, T_EXP + 1.8, t) * (1 - ss(T_ASM, T_ASM + 1.0, t));
|
||||
// the turntable: 330° from the explode to just after the bee is whole again, steady in the middle
|
||||
const TT = [T_EXP + 0.2, T_ASM + 1.5];
|
||||
const turnAt = (t) => {
|
||||
const [a, b] = TT;
|
||||
if (t <= a) return 0;
|
||||
const R = 0.6;
|
||||
const span = b - a;
|
||||
const v = 330 / (span - R);
|
||||
const x = Math.min(t, b) - a;
|
||||
// a trapezoid of speed: ramp up over R, steady, ramp down over R
|
||||
if (x < R) return (v * x * x) / (2 * R);
|
||||
if (x < span - R) return v * (x - R / 2);
|
||||
const y = x - (span - R);
|
||||
return v * (span - 1.5 * R) + v * y - (v * y * y) / (2 * R);
|
||||
};
|
||||
// the wings stop for the acts that need still wings and for the explode, and spin back up after
|
||||
const stopAt = (t) => {
|
||||
let v = 0;
|
||||
for (const act of Object.keys(ACT)) {
|
||||
if (!ACT[act].stop) continue;
|
||||
for (const t0 of at(act)) v = Math.max(v, ss(t0, t0 + 0.45, t) * (1 - ss(t0 + ACT[act].close[1], t0 + ACT[act].close[1] + 0.5, t)));
|
||||
}
|
||||
return Math.max(v, ss(T_EXP, T_EXP + 0.45, t) * (1 - ss(T_ASM + 0.9, T_ASM + 1.5, t)));
|
||||
};
|
||||
// the busy clock the gears and loose parts turn on: they run five times faster while something is open
|
||||
const activity = (t) => Math.max(...Object.keys(ACT).map((a) => openOf(a, t)), explodeAt(t));
|
||||
const DT = 1 / 240;
|
||||
const SPIN = [0];
|
||||
for (let i = 1; i * DT <= DURATION + 1; i++) SPIN.push(SPIN[i - 1] + (1 + 5 * activity((i - 0.5) * DT)) * DT);
|
||||
const look = (A, t) => {
|
||||
const u = Math.max(0, Math.min(A.length - 2, t / DT));
|
||||
const i = Math.floor(u);
|
||||
return A[i] + (A[i + 1] - A[i]) * (u - i);
|
||||
};
|
||||
const spinAt = (t) => (t < 0 ? t : look(SPIN, t));
|
||||
|
||||
// the flight: in from behind-left banking through a turn, the hover, the turntable, the departure banking away
|
||||
const flightAt = (t) => {
|
||||
const kIn = ss(-0.3, 2.6, t);
|
||||
const ex = explodeAt(t);
|
||||
const calm = 1 - Math.min(1, ex * 2.5);
|
||||
const pos = new THREE.Vector3(lerp(-2.6, 0, kIn), lerp(0.6, 0, kIn) + 0.05 * Math.sin(t * 2.6) * calm, lerp(-3.2, 0, kIn));
|
||||
let yaw = lerp(-80, 0, kIn) + 14 * Math.sin(Math.PI * kIn);
|
||||
let roll = 30 * Math.sin(Math.PI * Math.min(1, kIn * 1.05)) + 1.7 * Math.sin(t * 1.3 + 1.1) * calm;
|
||||
let pitch = -6 * Math.sin(Math.PI * kIn) + 1.4 * Math.sin(t * 1.9 + 0.6) * calm;
|
||||
yaw += turnAt(t);
|
||||
if (t > T_END + 1.0) {
|
||||
const u = t - T_END - 1.0;
|
||||
const k = ss(0, 1.0, u);
|
||||
yaw += 38 * k;
|
||||
roll -= 30 * k;
|
||||
pitch += 8 * k;
|
||||
const h = new THREE.Vector3(Math.cos(yaw * D2R), 0, -Math.sin(yaw * D2R));
|
||||
pos.addScaledVector(h, 1.6 * u * u).add(new THREE.Vector3(0, 0.45 * u * u, 0));
|
||||
}
|
||||
return {pos, yaw, roll, pitch, calm};
|
||||
};
|
||||
|
||||
// the camera: each act's view, blended over 0.8 s with a short dolly out, tracking the bee as it flies
|
||||
const VIEWS = [{t: -1, key: 'intro'}, ...SCRIPT.map((e) => ({t: e.t, key: e.act === 'assemble' ? 'exploded' : e.act}))];
|
||||
const viewIdx = (t) => {
|
||||
let i = 0;
|
||||
while (i < VIEWS.length - 1 && VIEWS[i + 1].t <= t) i++;
|
||||
return i;
|
||||
};
|
||||
const camFn = (V, t) => CAM2[V.key](t - (V.key === 'intro' ? 0 : V.t));
|
||||
const camAt = (t) => {
|
||||
const i = viewIdx(t);
|
||||
let o = camFn(VIEWS[i], t);
|
||||
// the reassembly keeps the explode's camera running from where it was
|
||||
if (VIEWS[i].key === 'exploded' && i > 0 && VIEWS[i - 1].key === 'exploded') o = camFn(VIEWS[i - 1], t);
|
||||
else if (i > 0) {
|
||||
const k = ss(VIEWS[i].t, VIEWS[i].t + 0.85, t);
|
||||
if (k < 1) {
|
||||
const a = camFn(VIEWS[i - 1], t);
|
||||
const dAz = ((o[0] - a[0] + 540) % 360) - 180;
|
||||
const b = o.map((v, j) => lerp(a[j], v, k));
|
||||
b[0] = a[0] + dAz * k;
|
||||
b[2] += 0.7 * Math.sin(Math.PI * k);
|
||||
o = b;
|
||||
}
|
||||
}
|
||||
// the camera follows the bee in, and lets it go on the way out
|
||||
const f = flightAt(t);
|
||||
const track = 0.85 - 0.5 * ss(T_END + 1.0, T_END + 2.0, t);
|
||||
return {az: o[0], el: o[1], d: o[2], tx: o[3] + f.pos.x * track, ty: o[4] + f.pos.y * track, tz: o[5] + f.pos.z * track, sx: o[6], sy: o[7]};
|
||||
};
|
||||
const actAt = (t) => {
|
||||
const i = viewIdx(t);
|
||||
return VIEWS[i].key;
|
||||
};
|
||||
|
||||
const stateAt = (t) => {
|
||||
const ex = explodeAt(t);
|
||||
const amp = AMP * (1 - stopAt(t));
|
||||
const f = flightAt(t);
|
||||
const open = Object.fromEntries(Object.keys(ACT).map((a) => [a, openOf(a, t)]));
|
||||
// the wing's own clock: out, one full turn over, back in fast
|
||||
let wingOut = 0;
|
||||
let wingFlip = 0;
|
||||
for (const t0 of at('wing')) {
|
||||
const A = ACT.wing;
|
||||
wingOut = Math.max(wingOut, ss(t0 + A.open[0], t0 + A.open[1], t) * (1 - ss(t0 + A.close[0], t0 + A.close[1], t)));
|
||||
wingFlip = Math.max(wingFlip, ss(t0 + 0.9, t0 + 2.3, t));
|
||||
}
|
||||
if (wingFlip >= 1) wingFlip = 0;
|
||||
// the sting: out of its collar once the abdomen hangs open, back in before it closes
|
||||
let stingK = 0;
|
||||
for (const t0 of at('abdomen')) stingK = Math.max(stingK, ss(t0 + 1.05, t0 + 1.55, t) * (1 - ss(t0 + 1.9, t0 + 2.2, t)));
|
||||
const view = actAt(t);
|
||||
return {
|
||||
t,
|
||||
spinT: spinAt(t),
|
||||
explode: ex,
|
||||
amp,
|
||||
flap: Math.PI * 2 * FLAP_HZ * t,
|
||||
display: 1 - amp / AMP,
|
||||
blur: 1,
|
||||
sub: {thorax: open.thorax, abdomen: open.abdomen},
|
||||
eye: open.optics,
|
||||
wingOut,
|
||||
wingFlip,
|
||||
legK: open.leg,
|
||||
stingK,
|
||||
open,
|
||||
flight: f,
|
||||
cam: camAt(t),
|
||||
view,
|
||||
guides: 0.45 + 0.55 * Math.min(1, ex * 2.5 + activity(t)),
|
||||
turn: turnAt(t),
|
||||
};
|
||||
};
|
||||
|
||||
// labels: on while the act's parts are moving apart and while they hang open, gone before they close
|
||||
const LABELS = {
|
||||
optics: [['eyeGlass', 'OUTER GLASS', 'Ø 40 MM · AR COATED'], ['eyeInner', 'INNER ELEMENT', 'Ø 15 MM'], ['iris', 'IRIS', '10 BLADES · OPENS 3×'], ['barrel', 'LENS BARREL', 'THREADED · 4 RINGS']],
|
||||
wing: [['wing', 'WING MEMBRANE', 'FROSTED FILM · 0.1 MM'], ['hinge', 'WING HINGE', 'QUICK RELEASE'], ['hinge2', 'HINDWING HINGE', 'PHASE +40°']],
|
||||
leg: [['hip2', 'HIP SERVO', 'YAW + LIFT'], ['knee2', 'KNEE SERVO', '0.4 N·M'], ['foot', 'FOOT CLAW', 'TWIN HOOKS']],
|
||||
thorax: [['plate', 'SADDLE PLATE', 'POLYMER SHELL'], ['gears', 'DRIVE GEAR STACK', '3 SPUR GEARS'], ['act', 'ACTUATOR RING', '11 PISTONS'], ['core', 'CONTROL BOARDS', 'FLIGHT CPU · IMU']],
|
||||
abdomen: [['waist', 'WAIST STALK', '5 BEADS · LIT RINGS'], ['s1', 'SHELL BAND', 'TELESCOPING'], ['capsule', 'BAND 4', 'RIVETED · 5 SEGMENTS'], ['sting', 'STINGER', 'GLASS · EXTENDS 30 MM']],
|
||||
exploded: [['lens', 'OPTIC HEAD', '2 × LENS'], ['collar', 'NECK BEARING', '10 SEGMENTS'], ['gears', 'DRIVE GEARS', 'SPINNING FREE'], ['capsule', 'ABDOMEN BANDS', '5 SEGMENTS'], ['hinge', 'WING HINGE', 'QUICK RELEASE']],
|
||||
};
|
||||
const labelAt = (t, s) => {
|
||||
const v = s.view;
|
||||
if (ACT[v]) {
|
||||
const t0 = at(v).filter((x) => x <= t).pop();
|
||||
const A = ACT[v];
|
||||
return {set: LABELS[v], o: ss(t0 + A.open[0] + 0.1, t0 + A.open[0] + 0.45, t) * (1 - ss(t0 + A.close[0] - 0.25, t0 + A.close[0], t))};
|
||||
}
|
||||
if (v === 'exploded') return {set: LABELS.exploded, o: ss(T_EXP + 0.4, T_EXP + 0.8, t) * (1 - ss(T_EXP + 2.3, T_EXP + 2.6, t))};
|
||||
return {set: [], o: 0};
|
||||
};
|
||||
|
||||
const telemetry = (t, s) => {
|
||||
const f = s.flight;
|
||||
const stroke = [];
|
||||
for (let i = 0; i <= 90; i++) {
|
||||
const tt = t - 1.2 + (i / 90) * 1.2;
|
||||
const a = AMP * (1 - stopAt(tt));
|
||||
const ph = Math.PI * 2 * FLAP_HZ * tt;
|
||||
stroke.push([a * Math.sin(ph), a * Math.sin(ph + 0.7)]);
|
||||
}
|
||||
const ex = s.explode > 0.04;
|
||||
const acc = -Math.sin(t * 2.6);
|
||||
const free = [0, 1, 2, 3, 4, 5].map((i) => ex || (i === 1 && s.legK > 0.08));
|
||||
const servos = [0.44, 0.58, 0.49, 0.4, 0.53, 0.46].map((b, i) => (free[i] ? 0 : Math.max(0, Math.min(1, b * (1 + 0.32 * acc) + 0.12 * Math.abs(f.roll) / 30 + 0.03 * Math.sin(t * 7 + i)))));
|
||||
const v = s.view;
|
||||
const opening = ACT[v] ? s.open[v] : 0;
|
||||
const NAME = {optics: 'OPTICS OPEN', wing: 'WING OFF', leg: 'LEG L2 OPEN', thorax: 'THORAX OPEN', abdomen: 'ABDOMEN OPEN'};
|
||||
let status = 'HOVER';
|
||||
let kind = 'ok';
|
||||
if (t < 2.6) status = 'BANKING';
|
||||
if (ACT[v] && (opening > 0.05 || (v === 'wing' && s.wingOut > 0.05))) [status, kind] = [NAME[v], 'warn'];
|
||||
if (v === 'exploded') [status, kind] = t < T_ASM ? ['TEARDOWN', 'warn'] : s.explode > 0.04 ? ['REASSEMBLY', 'warn'] : ['HOVER', 'ok'];
|
||||
if (t > T_END + 1.0) status = 'DEPARTING';
|
||||
const ROW = {optics: 0, thorax: 2, wing: 3, leg: 4, abdomen: 5};
|
||||
const sub = (i) => {
|
||||
if (ex) return ['warn', 'DETACHED'];
|
||||
if (ROW[v] === i && (opening > 0.05 || (v === 'wing' && s.wingOut > 0.05))) return ['warn', i === 3 ? 'DETACHED' : 'OPEN'];
|
||||
if (i === 3) return s.amp > 1 ? ['ok', `${FLAP_HZ} HZ`] : ['idle', 'PARKED'];
|
||||
if (i === 2) return s.amp > 1 ? ['ok', 'RUNNING'] : ['idle', 'STOPPED'];
|
||||
return ['ok', ['TRACKING', 'LOCKED', '', '', 'HOLDING', 'SEALED'][i]];
|
||||
};
|
||||
const last = SCRIPT.filter((e) => e.t <= t).pop();
|
||||
const say = (e) => (e.act === 'exploded' ? 'EXPLODED ON' : e.act === 'assemble' ? 'EXPLODED OFF · REASSEMBLE' : e.act === 'hero' ? 'HERO · RELEASE' : `ISOLATE ${ASSEMBLY_LABEL[e.act]}`);
|
||||
const sp = f.pos.length() > 0.05 ? 0.4 + 0.2 * Math.abs(Math.sin(t)) : 0.004;
|
||||
const labels = labelAt(t, s);
|
||||
return {
|
||||
time: t,
|
||||
dur: DURATION,
|
||||
lift: Math.max(0, (s.amp / AMP) * (0.68 + 0.02 * Math.sin(s.flap)) + 0.12 * Math.abs(f.roll) / 30),
|
||||
status,
|
||||
statusKind: kind,
|
||||
freq: FLAP_HZ * ss(0.5, 6, s.amp),
|
||||
amp: s.amp,
|
||||
stroke,
|
||||
playback: 1,
|
||||
blur: 1,
|
||||
battery: 0.842 - 0.0022 * t,
|
||||
power: 4.2 + 31 * Math.pow(s.amp / AMP, 1.5) * (1 + 0.04 * Math.sin(s.flap)) + 3 * Math.abs(f.roll) / 30,
|
||||
volt: 3.92 - 0.006 * 36,
|
||||
motorT: 34 + 0.35 * t,
|
||||
servos,
|
||||
legsFree: ex,
|
||||
legFreeEach: free,
|
||||
airborne: true,
|
||||
alt: (f.pos.y - FLOOR_Y) * MM,
|
||||
vs: MM * 0.05 * 2.6 * Math.cos(t * 2.6) * f.calm,
|
||||
pitch: f.pitch,
|
||||
roll: f.roll,
|
||||
airspeed: sp,
|
||||
view: v === 'intro' ? 'hero' : v === 'exploded' ? null : v,
|
||||
display: {labels: labels.o > 0.5, exploded: t >= T_EXP && t < T_ASM, blur: s.amp > 3, turntable: s.turn > 0 && t < TT[1]},
|
||||
subs: [0, 1, 2, 3, 4, 5].map(sub),
|
||||
focus: ROW[v] ?? (v === 'exploded' ? 1 : -1),
|
||||
events: EVENTS,
|
||||
next: `${EVENTS.length} OPERATOR ACTIONS`,
|
||||
log: last ? `OPERATOR · ${say(last)}` : 'INBOUND · BANKING LEFT',
|
||||
mode: status,
|
||||
modeSub:
|
||||
status === 'BANKING'
|
||||
? `ROLL ${f.roll.toFixed(0)}° · INBOUND`
|
||||
: status === 'TEARDOWN' || status === 'REASSEMBLY'
|
||||
? `TURNTABLE ${Math.round(s.turn)}° · ${Math.round(s.explode * 100)}% APART`
|
||||
: status === 'DEPARTING'
|
||||
? `BANK ${f.roll.toFixed(0)}° · RELEASED`
|
||||
: ACT[v]
|
||||
? `${ASSEMBLY_LABEL[v]} · ${Math.round(Math.max(opening, s.wingOut) * 100)}% APART`
|
||||
: `STATION KEEPING · ${((f.pos.y - FLOOR_Y) * MM).toFixed(0)} MM AGL`,
|
||||
viewNote: `ISOLATE · ${v === 'intro' || v === 'hero' ? 'HERO' : v === 'exploded' ? 'ALL' : ASSEMBLY_LABEL[v]}`,
|
||||
labelSet: labels,
|
||||
};
|
||||
};
|
||||
|
||||
return {SCRIPT, DURATION, stateAt, telemetry, camAt};
|
||||
}
|
||||
|
||||
/** Labels in two columns at the viewport's edges, as the first cut, from a set of anchors. */
|
||||
export function makeLabels2(st, bee) {
|
||||
const p = new THREE.Vector3();
|
||||
return ({set, o}) => {
|
||||
if (o < 0.02) return [];
|
||||
const pts = [];
|
||||
for (const [key, name, sub] of set) {
|
||||
const A = bee.anchors[key];
|
||||
if (!A) continue;
|
||||
A.obj.updateWorldMatrix(true, false);
|
||||
const at = st.project(A.obj.localToWorld(p.copy(A.at)));
|
||||
if (at && at[0] > VIEWPORT.x0 + 30 && at[0] < VIEWPORT.x1 - 30 && at[1] > VIEWPORT.y0 + 40 && at[1] < VIEWPORT.y1 - 70) pts.push({name, sub, at});
|
||||
}
|
||||
const mid = (VIEWPORT.x0 + VIEWPORT.x1) / 2;
|
||||
const out = [];
|
||||
const stack = (col, x, w) => {
|
||||
let y = Math.max(VIEWPORT.y0 + 48, Math.min(col.length ? col[0].at[1] - 10 : 0, VIEWPORT.y1 - 110 - 34 * col.length));
|
||||
for (const c of col) {
|
||||
y = Math.max(y, Math.min(VIEWPORT.y1 - 110, c.at[1] - 10));
|
||||
out.push({name: c.name, sub: c.sub, at: c.at, label: [x, y], w, o});
|
||||
y += 34;
|
||||
}
|
||||
};
|
||||
stack(pts.filter((x) => x.at[0] < mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x0 + 16, 168);
|
||||
stack(pts.filter((x) => x.at[0] >= mid).sort((a, b) => a.at[1] - b.at[1]), VIEWPORT.x1 - 160, 150);
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ the operator's pointer, on the act buttons
|
||||
const GUTTER_X = 1262;
|
||||
export function makeCursor2(ui, SCRIPT) {
|
||||
const EV = SCRIPT.filter((e) => e.t > 0).map((e) => ({t: e.t, spot: ui.spots[BUTTON[e.act]]}));
|
||||
const WP = [[0, GUTTER_X, EV[0].spot[1] + 60]];
|
||||
let [px, py, pt] = [GUTTER_X, EV[0].spot[1] + 60, 0];
|
||||
EV.forEach((e, n) => {
|
||||
const [x, y] = e.spot;
|
||||
const travel = Math.min(0.7, 0.3 + Math.hypot(x - px, y - py) / 900);
|
||||
const arrive = e.t - 0.1;
|
||||
if (arrive - travel - pt > 1.4) {
|
||||
const rest = [GUTTER_X, Math.max(170, Math.min(720, y + 40))];
|
||||
WP.push([pt + 0.7, ...rest]);
|
||||
WP.push([arrive - travel, ...rest]);
|
||||
} else WP.push([Math.max(pt + 0.01, arrive - travel), px, py]);
|
||||
WP.push([arrive, x, y], [e.t + 0.18, x, y]);
|
||||
[px, py, pt] = [x, y, e.t + 0.18];
|
||||
const next = EV[n + 1];
|
||||
if (!next || next.t - 0.1 - 0.7 - pt > 0.8) {
|
||||
[px, py, pt] = [GUTTER_X, y + 12, pt + 0.55];
|
||||
WP.push([pt, px, py]);
|
||||
}
|
||||
});
|
||||
WP.push([pt + 0.9, GUTTER_X, Math.min(720, py + 50)]);
|
||||
return (t) => {
|
||||
let i = 0;
|
||||
while (i < WP.length - 2 && t > WP[i + 1][0]) i++;
|
||||
const [t0, x0, y0] = WP[i];
|
||||
const [t1, x1, y1] = WP[i + 1];
|
||||
const k = ss(t0, t1, t);
|
||||
const len = Math.hypot(x1 - x0, y1 - y0);
|
||||
const bow = Math.sin(Math.PI * k) * Math.min(22, len * 0.07);
|
||||
let press = false;
|
||||
let ring = 0;
|
||||
let rx = 0;
|
||||
let ry = 0;
|
||||
for (const e of EV) {
|
||||
if (t >= e.t - 0.07 && t < e.t + 0.09) press = true;
|
||||
if (t >= e.t && t < e.t + 0.55) {
|
||||
ring = 1 - (t - e.t) / 0.55;
|
||||
[rx, ry] = e.spot;
|
||||
}
|
||||
}
|
||||
return {x: x0 + (x1 - x0) * k + (len ? (-(y1 - y0) / len) * bow : 0), y: y0 + (y1 - y0) * k + (len ? ((x1 - x0) / len) * bow : 0), press, ring, ringX: rx, ringY: ry};
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user