donut-orbit.html 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
  6. <title>NOUS · pretext</title>
  7. <link rel="preconnect" href="https://fonts.googleapis.com">
  8. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  9. <link href="https://fonts.googleapis.com/css2?family=Geist+Mono:wght@400;500&display=block" rel="stylesheet">
  10. <style>
  11. :root { color-scheme: dark; }
  12. :root {
  13. --background: color-mix(in srgb, #041C1C 100%, transparent);
  14. --background-base: #041C1C;
  15. --background-alpha: 1;
  16. --background-blend: difference;
  17. --midground: color-mix(in srgb, #ffe6cb 100%, transparent);
  18. --midground-base: #ffe6cb;
  19. --midground-alpha: 1;
  20. --foreground: color-mix(in srgb, #ffffff 0%, transparent);
  21. --foreground-base: #ffffff;
  22. --foreground-alpha: 0;
  23. --foreground-blend: difference;
  24. }
  25. html, body {
  26. margin: 0;
  27. width: 100%;
  28. min-height: 100vh;
  29. overflow: hidden;
  30. background: #000;
  31. }
  32. /* literally center the composition in 100vh */
  33. body {
  34. display: flex;
  35. align-items: center;
  36. justify-content: center;
  37. }
  38. #stage {
  39. position: relative;
  40. z-index: 2;
  41. width: min(1240px, 100vw);
  42. height: min(720px, 100vh);
  43. cursor: grab;
  44. overflow: visible;
  45. }
  46. #stage:active { cursor: grabbing; }
  47. #c,
  48. #orbCanvas {
  49. display: block;
  50. position: absolute;
  51. left: calc((100vw - min(1240px, 100vw)) / -2);
  52. top: calc((100vh - min(720px, 100vh)) / -2);
  53. width: 100vw;
  54. height: 100vh;
  55. pointer-events: none;
  56. }
  57. #c { z-index: 3; }
  58. #orbCanvas {
  59. z-index: 4;
  60. opacity: 1;
  61. }
  62. #noiseCanvas {
  63. display: block;
  64. position: absolute;
  65. inset: 0;
  66. width: 100%;
  67. height: 100%;
  68. pointer-events: none;
  69. }
  70. #textLayer {
  71. position: absolute;
  72. inset: 0;
  73. z-index: 2;
  74. color: var(--midground-base);
  75. font: 400 10px/15px "Geist Mono", "JetBrains Mono", "SF Mono", SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  76. pointer-events: auto;
  77. user-select: text;
  78. -webkit-user-select: text;
  79. }
  80. #textLayer *::selection {
  81. background: var(--selection-bg, var(--midground));
  82. color: var(--background-base);
  83. }
  84. .flow-line {
  85. position: absolute;
  86. height: 20px;
  87. white-space: pre;
  88. overflow: visible;
  89. color: var(--midground-base);
  90. }
  91. #annotationLayer {
  92. position: absolute;
  93. inset: 0;
  94. z-index: 4;
  95. pointer-events: none;
  96. overflow: visible;
  97. }
  98. .annot {
  99. position: absolute;
  100. pointer-events: none;
  101. will-change: opacity, transform;
  102. }
  103. .tok-keyword { color: color-mix(in srgb, var(--midground-base) 54%, #ff174d); }
  104. .tok-string { color: color-mix(in srgb, var(--midground-base) 52%, #ff6b3d); }
  105. .tok-comment { color: color-mix(in srgb, var(--midground-base) 42%, #7f1d1d); }
  106. .tok-number { color: color-mix(in srgb, var(--midground-base) 50%, #ff2a6d); }
  107. .tok-const { color: color-mix(in srgb, var(--midground-base) 48%, #ff003c); }
  108. .layer { position: fixed; inset: 0; pointer-events: none; }
  109. .bg-lens { z-index: 1; background-color: var(--background); mix-blend-mode: var(--background-blend); }
  110. .vignette { z-index: 99; background: radial-gradient(ellipse at 0% 0%, rgba(255,189,56,0) 60%, rgba(255,189,56,0.35) 100%); mix-blend-mode: lighten; opacity: 0.22; }
  111. .fg-lens { z-index: 100; background-color: var(--foreground); mix-blend-mode: var(--foreground-blend); }
  112. .noise {
  113. z-index: 101;
  114. mix-blend-mode: difference;
  115. }
  116. #noiseCanvas {
  117. width: 100%;
  118. height: 100%;
  119. display: block;
  120. }
  121. .terminal-cursor {
  122. position: absolute;
  123. width: 0.6em;
  124. height: 1em;
  125. background: #fff;
  126. z-index: 6;
  127. pointer-events: none;
  128. mix-blend-mode: difference;
  129. animation: term-blink 1s steps(1, end) infinite;
  130. }
  131. @keyframes term-blink {
  132. 0%, 60% { opacity: 1; }
  133. 60.01%, 100% { opacity: 0; }
  134. }
  135. .cursor-anchor {
  136. display: inline-block;
  137. width: 0;
  138. height: 1em;
  139. vertical-align: text-top;
  140. pointer-events: none;
  141. }
  142. @font-face {
  143. font-family: "Mondwest";
  144. src: url("https://esm.sh/@nous-research/ui@0.4.0/dist/fonts/Mondwest-Regular.woff2") format("woff2");
  145. font-weight: 400; font-style: normal; font-display: block;
  146. }
  147. @font-face {
  148. font-family: "Geist Mono";
  149. src: url("https://cdn.jsdelivr.net/npm/@fontsource/geist-mono@5.2.5/files/geist-mono-latin-400-normal.woff2") format("woff2");
  150. font-weight: 400; font-style: normal; font-display: block;
  151. }
  152. @font-face {
  153. font-family: "JetBrains Mono";
  154. src: url("https://cdn.jsdelivr.net/npm/@fontsource/jetbrains-mono@5.2.5/files/jetbrains-mono-latin-400-normal.woff2") format("woff2");
  155. font-weight: 400; font-style: normal; font-display: block;
  156. }
  157. .font-primer { position: fixed; left: -9999px; top: -9999px; font: 400 26px "Mondwest", serif; }
  158. </style>
  159. </head>
  160. <body>
  161. <div id="stage"><div id="textLayer" aria-label="self-learning source stream"></div><div id="terminalCursor" class="terminal-cursor" hidden></div><canvas id="c"></canvas><canvas id="orbCanvas"></canvas></div>
  162. <div class="layer bg-lens"></div>
  163. <div class="layer vignette"></div>
  164. <div class="layer fg-lens"></div>
  165. <div class="layer noise"><canvas id="noiseCanvas"></canvas></div>
  166. <div class="font-primer" aria-hidden="true">Aa Mondwest priming glyphs 0123456789</div>
  167. <script type="module">
  168. import {
  169. prepareWithSegments,
  170. layoutNextLineRange,
  171. materializeLineRange,
  172. } from "https://esm.sh/@chenglou/pretext@0.0.6";
  173. import gsap from "https://esm.sh/gsap@3.12.5";
  174. import GUI from "https://esm.sh/lil-gui@0.19.2";
  175. const SELF_LEARNING_SOURCE = String.raw`
  176. type ToolId=u16; type FeatureId=u32; type W=f32;
  177. struct Obs{tool:ToolId,reward:f32,lat:u32,feat:&'static[FeatureId],tok:u16}
  178. struct Belief{prior:W,conf:W,last:u64,uses:u32}
  179. #[inline] fn sig(x:f32)->f32{1.0/(1.0+(-x).exp())}
  180. #[inline] fn decay(now:u64,last:u64)->f32{1.0-((now-last)as f32/900.0).min(1.0)*0.22}
  181. #[inline] fn clamp8(x:f32)->f32{x.clamp(-8.0,8.0)}
  182. fn score(theta:&[W],b:&[Belief],o:&Obs)->f32{
  183. let sparse=o.feat.iter().fold(0.0,|a,id|a+theta[*id as usize]);
  184. let belief=b[o.tool as usize].prior*b[o.tool as usize].conf.max(0.15);
  185. sparse+belief-(o.lat as f32*0.00072)-(o.tok as f32*0.00009)
  186. }
  187. fn update(theta:&mut[W],b:&mut[Belief],o:&Obs,now:u64,eta:f32){
  188. let p=sig(score(theta,b,o));
  189. let e=(o.reward-p).clamp(-1.0,1.0);
  190. let step=eta*e/(o.feat.len().max(1)as f32).sqrt();
  191. for id in o.feat{
  192. let w=&mut theta[*id as usize];
  193. *w=clamp8(*w+step-0.0003*w.signum());
  194. }
  195. let slot=&mut b[o.tool as usize];
  196. let d=decay(now,slot.last);
  197. let r=(o.reward-o.lat as f32*0.00035).clamp(-1.0,1.0);
  198. slot.prior=slot.prior*d+r*0.14+e*0.06;
  199. slot.conf=(slot.conf*0.93+r.abs()*0.07).min(1.0);
  200. slot.uses=slot.uses.saturating_add(1);
  201. slot.last=now;
  202. }
  203. fn consolidate(trace:&[Obs],theta:&mut[W],b:&mut[Belief],now:u64){
  204. let eta=0.042/(1.0+(trace.len()as f32*0.003));
  205. let mut credit=1.0;
  206. for o in trace.iter().rev(){
  207. update(theta,b,o,now,eta*credit);
  208. credit*=0.985;
  209. }
  210. }
  211. fn choose<'a>(theta:&[W],b:&[Belief],xs:&'a[Obs],temp:f32)->&'a Obs{
  212. xs.iter().max_by(|a,bx|{
  213. let sa=score(theta,b,a)/temp.max(0.05);
  214. let sb=score(theta,b,bx)/temp.max(0.05);
  215. sa.partial_cmp(&sb).unwrap()
  216. }).unwrap()
  217. }
  218. `;
  219. const CODE_CHUNK = SELF_LEARNING_SOURCE
  220. .trim()
  221. .replace(/\t/g, " ")
  222. .replace(/\n{3,}/g, "\n\n");
  223. const STREAM_REPEAT_COUNT = 6;
  224. const streamCorpus = Array.from({ length: STREAM_REPEAT_COUNT }, () => CODE_CHUNK).join("\n\n");
  225. const stage = document.getElementById("stage");
  226. const textLayer = document.getElementById("textLayer");
  227. const canvas = document.getElementById("c");
  228. const orbCanvas = document.getElementById("orbCanvas");
  229. const ctx = canvas.getContext("2d", { alpha: true });
  230. const orbCtx = orbCanvas.getContext("2d", { alpha: true });
  231. let W = 0, H = 0, DPR = 1;
  232. let canvasLeft = 0, canvasTop = 0, canvasW = 0, canvasH = 0;
  233. let BODY_FONT = '400 10px "Geist Mono", "JetBrains Mono", "SF Mono", SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';
  234. let BODY_LINE_H = 15;
  235. let ASCII_FONT = '8px monospace';
  236. let CELL_W = 4.8;
  237. let CELL_H = 8;
  238. const CHARS = ' ·:;+=░▒▓█';
  239. const EMPTY = 0;
  240. const CHARS_LAST = CHARS.length - 1;
  241. const LOGO = ['N', 'O', 'U', 'S'].map((letter, i) => ({
  242. letter,
  243. rows: [
  244. i === 0
  245. ? '██░░░██,██░░░██,███░░██,█░██░██,█░░████,█░░░███,██░░░██,██░░░██,██░░░██'
  246. : i === 1
  247. ? '░█████░,██░░░██,██░░░██,██░░░██,██░░░██,██░░░██,██░░░██,██░░░██,░█████░'
  248. : i === 2
  249. ? '██░░░██,██░░░██,██░░░██,██░░░██,██░░░██,██░░░██,██░░░██,██░░░██,░█████░'
  250. : '░█████░,██░░░██,██░░░░░,░████░░,░░░░██░,░░░░░██,██░░░██,██░░░██,░█████░'
  251. ][0].split(',')
  252. }));
  253. function hash(x, y) {
  254. const n = Math.sin(x * 127.1 + y * 311.7) * 43758.5453;
  255. return n - Math.floor(n);
  256. }
  257. function charAt(t) {
  258. return CHARS[Math.min(CHARS.length - 1, Math.max(0, Math.floor(t * CHARS.length)))];
  259. }
  260. function gridDist(v, step) {
  261. return Math.abs(v / step - Math.round(v / step)) * step;
  262. }
  263. function rot(a, b, angle) {
  264. const c = Math.cos(angle), s = Math.sin(angle);
  265. return [a * c - b * s, a * s + b * c];
  266. }
  267. function hexToRGB(h) {
  268. const v = parseInt(h.slice(1), 16);
  269. return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
  270. }
  271. let fontsReady = false;
  272. let bodyPrepared = null;
  273. function rebuildLayouts() {
  274. bodyPrepared = prepareWithSegments(streamCorpus, BODY_FONT, { whiteSpace: "pre-wrap" });
  275. }
  276. const LENS_0 = { bgBlend: "difference", bgColor: "#041C1C", bgOpacity: 1, mgColor: "#ffe6cb", mgOpacity: 1, fgBlend: "difference", fgColor: "#FFFFFF", fgOpacity: 0 };
  277. const LENS_5I = { bgBlend: "multiply", bgColor: "#ffffff", bgOpacity: 1, mgColor: "#fffff5", mgOpacity: 1, fgBlend: "difference", fgColor: "#041a1f", fgOpacity: 1 };
  278. const LENS = { current: null, mgBase: null, depthColors: null };
  279. function colorMix(color, alpha) { return `color-mix(in srgb, ${color} ${Math.round(alpha * 100)}%, transparent)`; }
  280. function precomputeDepthColors(mgColor) {
  281. const [r, g, b] = hexToRGB(mgColor);
  282. return Array.from({ length: 64 }, (_, i) => {
  283. const depth = i / 63;
  284. const m = 0.4 + depth * 0.6;
  285. return `rgba(${(r * m) | 0},${(g * m) | 0},${(b * m) | 0},${depth})`;
  286. });
  287. }
  288. function applyLens(preset) {
  289. LENS.current = preset;
  290. LENS.mgBase = preset.mgColor;
  291. LENS.depthColors = precomputeDepthColors(preset.mgColor);
  292. const s = document.documentElement.style;
  293. for (const [name, color, alpha] of [["foreground", preset.fgColor, preset.fgOpacity], ["midground", preset.mgColor, preset.mgOpacity], ["background", preset.bgColor, preset.bgOpacity]]) {
  294. s.setProperty(`--${name}`, colorMix(color, alpha));
  295. s.setProperty(`--${name}-base`, color);
  296. s.setProperty(`--${name}-alpha`, `${alpha}`);
  297. }
  298. s.setProperty("--background-blend", preset.bgBlend);
  299. s.setProperty("--foreground-blend", preset.fgBlend);
  300. }
  301. applyLens(LENS_0);
  302. addEventListener("keydown", e => { if (e.key === "x" || e.key === "X") applyLens(LENS.current === LENS_0 ? LENS_5I : LENS_0); });
  303. const SELECTION_COLORS = [
  304. "oklch(85% 0.12 330)",
  305. "oklch(85% 0.12 300)",
  306. "oklch(85% 0.12 270)",
  307. "oklch(85% 0.12 230)",
  308. "oklch(85% 0.12 180)",
  309. "oklch(85% 0.12 150)",
  310. "oklch(85% 0.12 120)",
  311. "oklch(85% 0.12 90)",
  312. "oklch(85% 0.12 60)",
  313. "oklch(85% 0.12 30)",
  314. "oklch(88% 0.10 80)",
  315. ];
  316. let selectionIdx = 0;
  317. function cycleSelectionColor() {
  318. requestAnimationFrame(() => {
  319. document.documentElement.style.setProperty("--selection-bg", SELECTION_COLORS[(selectionIdx = (selectionIdx + 1) % SELECTION_COLORS.length)]);
  320. });
  321. }
  322. document.addEventListener("selectstart", cycleSelectionColor);
  323. addEventListener("keydown", e => {
  324. if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "a") {
  325. cycleSelectionColor();
  326. e.preventDefault();
  327. const selection = getSelection();
  328. const range = document.createRange();
  329. range.selectNodeContents(textLayer);
  330. selection.removeAllRanges();
  331. selection.addRange(range);
  332. }
  333. });
  334. let asciiMask, asciiChar, asciiGlyph, orbMask, orbChar, orbGlyph, obstacleRows, intervals;
  335. let cols = 0, rows = 0;
  336. let canvasCols = 0, canvasRows = 0;
  337. let lastFrameTime = 0;
  338. const drawnLines = { x: [], y: [], w: [], text: [], count: 0 };
  339. let lineNodes = [];
  340. let terminalAnchorEl = null;
  341. let terminalLineEl = null;
  342. let orbShapeControl = null;
  343. let autoCubeCall = null;
  344. let lastTextSignature = "";
  345. const ORB = {
  346. panX: 0, panY: 0,
  347. orbitX: -1.42, orbitY: 0,
  348. radius: 0.135,
  349. zoom: 3,
  350. cubeScale: 1.8,
  351. autoSpin: 0.18,
  352. lat: 19,
  353. lon: 30,
  354. wire: 0.2,
  355. shape: "sphere",
  356. shapeMix: 0,
  357. drag: null,
  358. positioned: false,
  359. staged: false,
  360. };
  361. const SCENE = {
  362. orbBuildDuration: 1.45,
  363. };
  364. let nousStartTime = null;
  365. const AUTO_CUBE_AFTER_NOUS_RESOLVE = 0.0;
  366. function setOrbShape(shape, { reveal = false, syncControl = true } = {}) {
  367. ORB.shape = shape;
  368. if (syncControl) {
  369. ctrls.orbShape = shape;
  370. orbShapeControl?.updateDisplay();
  371. }
  372. if (reveal) {
  373. gsap.killTweensOf(orbCanvas);
  374. orbCanvas.style.opacity = "1";
  375. }
  376. gsap.killTweensOf(ORB, "shapeMix");
  377. gsap.to(ORB, {
  378. shapeMix: shape === "cube" ? 1 : 0,
  379. duration: Math.max(0.01, ctrls.shapeMorphDuration ?? 0.65),
  380. ease: "power2.inOut",
  381. onUpdate: () => { lastTextSignature = ""; },
  382. });
  383. lastTextSignature = "";
  384. }
  385. function sceneTimeNow() {
  386. return (typeof performance !== "undefined" ? performance.now() : Date.now()) * 0.001 - sceneEpoch;
  387. }
  388. function armNous(atTime = sceneTimeNow()) {
  389. if (nousStartTime !== null) return;
  390. const startAt = Math.max(0, atTime);
  391. nousStartTime = startAt;
  392. const delay = Math.max(0, startAt - sceneTimeNow()) + Math.max(0, ctrls.orbContainNous ?? 1.0);
  393. gsap.killTweensOf(orbCanvas);
  394. gsap.to(orbCanvas, {
  395. opacity: 0,
  396. duration: Math.max(0.05, ctrls.orbFadeDuration ?? 0.7),
  397. delay,
  398. ease: "power2.out",
  399. });
  400. autoCubeCall?.kill();
  401. const nousResolveAt = startAt + (LOGO.length - 1) * 0.4 + 1.0;
  402. const cubeAt = nousResolveAt + AUTO_CUBE_AFTER_NOUS_RESOLVE;
  403. autoCubeCall = gsap.delayedCall(Math.max(0, cubeAt - sceneTimeNow()), () => {
  404. setOrbShape("cube", { reveal: true, syncControl: false });
  405. });
  406. }
  407. function orbBuildStartTime() {
  408. return Math.max(0, ctrls.orbLead ?? 0);
  409. }
  410. function codeTypingStartTime() {
  411. return Math.max(0, orbBuildStartTime() + SCENE.orbBuildDuration * 0.62 - 0.3);
  412. }
  413. function logoCenterPan() {
  414. const aspect = cols / rows / 2;
  415. const h = 0.38;
  416. const w = h * 2.6 * 0.55;
  417. const halfStageX = (w / 2 / aspect) * W;
  418. const centerX = W * 0.5;
  419. const centerY = H * 0.5;
  420. return {
  421. panX: centerX / W - 0.5,
  422. panY: centerY / H - 0.5,
  423. left: centerX - halfStageX,
  424. right: centerX + halfStageX,
  425. };
  426. }
  427. function startSceneTimeline() {
  428. if (ORB.staged || !cols || !rows || !W || !H) return;
  429. ORB.staged = true;
  430. const now = sceneTimeNow();
  431. const startAt = Math.max(0, orbBuildStartTime() + SCENE.orbBuildDuration * 0.72 - now);
  432. gsap.timeline({ delay: startAt })
  433. .to(ORB, {
  434. orbitX: 0.55,
  435. orbitY: `+=${Math.PI * 1.85}`,
  436. duration: 2.4,
  437. ease: "power3.inOut",
  438. onUpdate: () => { lastTextSignature = ""; },
  439. }, "<")
  440. .to(ORB, {
  441. radius: 0.125,
  442. duration: 2.4,
  443. ease: "power3.inOut",
  444. onUpdate: () => { lastTextSignature = ""; },
  445. }, "<")
  446. .to(ORB, {
  447. wire: ctrls.orbWireLow,
  448. duration: ctrls.wireDropDuration,
  449. ease: "power2.inOut",
  450. onUpdate: () => { lastTextSignature = ""; },
  451. onComplete: () => {
  452. armNous(sceneTimeNow() + Math.max(0, ctrls.nousAfterWire));
  453. },
  454. });
  455. }
  456. function resize() {
  457. const r = stage.getBoundingClientRect();
  458. W = Math.max(1, Math.floor(r.width));
  459. H = Math.max(1, Math.floor(r.height));
  460. canvasLeft = r.left;
  461. canvasTop = r.top;
  462. canvasW = Math.max(1, window.innerWidth);
  463. canvasH = Math.max(1, window.innerHeight);
  464. DPR = Math.min(window.devicePixelRatio || 1, 2);
  465. canvas.width = Math.floor(canvasW * DPR);
  466. canvas.height = Math.floor(canvasH * DPR);
  467. orbCanvas.width = Math.floor(canvasW * DPR);
  468. orbCanvas.height = Math.floor(canvasH * DPR);
  469. ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
  470. orbCtx.setTransform(DPR, 0, 0, DPR, 0, 0);
  471. ctx.font = ASCII_FONT;
  472. orbCtx.font = ASCII_FONT;
  473. CELL_W = ctx.measureText("M").width || CELL_W;
  474. cols = Math.ceil(W / CELL_W);
  475. rows = Math.ceil(H / CELL_H);
  476. canvasCols = Math.ceil(canvasW / CELL_W);
  477. canvasRows = Math.ceil(canvasH / CELL_H);
  478. asciiMask = new Uint8Array(canvasCols * canvasRows);
  479. asciiChar = new Uint8Array(canvasCols * canvasRows);
  480. asciiGlyph = new Array(canvasCols * canvasRows);
  481. orbMask = new Uint8Array(canvasCols * canvasRows);
  482. orbChar = new Uint8Array(canvasCols * canvasRows);
  483. orbGlyph = new Array(canvasCols * canvasRows);
  484. obstacleRows = Array.from({ length: rows }, () => []);
  485. intervals = new Float32Array(64);
  486. if (!ORB.positioned && W > 100 && H > 100) {
  487. ORB.panX = 0;
  488. ORB.panY = 0;
  489. ORB.positioned = true;
  490. }
  491. startSceneTimeline();
  492. }
  493. addEventListener("resize", () => { lastTextSignature = ""; resize(); });
  494. function orbCenter() {
  495. const rNorm = ORB.radius * ORB.zoom;
  496. return {
  497. x: (0.5 + ORB.panX) * W,
  498. y: (0.5 + ORB.panY) * H,
  499. canvasX: (0.5 + ORB.panX) * W + canvasLeft,
  500. canvasY: (0.5 + ORB.panY) * H + canvasTop,
  501. r: rNorm * H,
  502. rNorm,
  503. };
  504. }
  505. stage.addEventListener("pointerdown", e => {
  506. const rect = stage.getBoundingClientRect();
  507. const center = orbCenter();
  508. const hitScale = ORB.shape === "cube" ? ORB.cubeScale : 1;
  509. const dx = e.clientX - rect.left - center.x;
  510. const dy = e.clientY - rect.top - center.y;
  511. if (Math.hypot(dx, dy) > center.r * 1.35 * hitScale) return;
  512. e.preventDefault();
  513. stage.setPointerCapture(e.pointerId);
  514. ORB.drag = {
  515. id: e.pointerId,
  516. mode: (e.ctrlKey || e.metaKey) ? "rotate" : "move",
  517. dx,
  518. dy,
  519. lastX: e.clientX,
  520. lastY: e.clientY,
  521. };
  522. });
  523. stage.addEventListener("pointermove", e => {
  524. if (!ORB.drag || ORB.drag.id !== e.pointerId) return;
  525. if (ORB.drag.mode === "rotate" || e.ctrlKey || e.metaKey) {
  526. const deltaX = e.clientX - ORB.drag.lastX;
  527. const deltaY = e.clientY - ORB.drag.lastY;
  528. ORB.orbitY += (deltaX / Math.max(1, W)) * Math.PI * 2;
  529. ORB.orbitX = Math.max(-1.5, Math.min(1.5, ORB.orbitX + (deltaY / Math.max(1, H)) * 4));
  530. ORB.drag.mode = "rotate";
  531. ORB.drag.lastX = e.clientX;
  532. ORB.drag.lastY = e.clientY;
  533. return;
  534. }
  535. const rect = stage.getBoundingClientRect();
  536. const cx = e.clientX - rect.left - ORB.drag.dx;
  537. const cy = e.clientY - rect.top - ORB.drag.dy;
  538. ORB.panX = cx / W - 0.5;
  539. ORB.panY = cy / H - 0.5;
  540. lastTextSignature = "";
  541. });
  542. stage.addEventListener("wheel", e => {
  543. const rect = stage.getBoundingClientRect();
  544. const center = orbCenter();
  545. const hitScale = ORB.shape === "cube" ? ORB.cubeScale : 1;
  546. const dx = e.clientX - rect.left - center.x;
  547. const dy = e.clientY - rect.top - center.y;
  548. if (Math.hypot(dx, dy) > center.r * 1.5 * hitScale) return;
  549. e.preventDefault();
  550. ORB.zoom *= Math.exp(-e.deltaY * 0.0012);
  551. ORB.zoom = Math.max(0.25, Math.min(12, ORB.zoom));
  552. lastTextSignature = "";
  553. }, { passive: false });
  554. stage.addEventListener("pointerup", e => {
  555. if (ORB.drag?.id === e.pointerId) ORB.drag = null;
  556. });
  557. stage.addEventListener("pointercancel", e => {
  558. if (ORB.drag?.id === e.pointerId) ORB.drag = null;
  559. });
  560. stage.addEventListener("dblclick", e => {
  561. const rect = stage.getBoundingClientRect();
  562. const center = orbCenter();
  563. const hitScale = ORB.shape === "cube" ? ORB.cubeScale : 1;
  564. const dx = e.clientX - rect.left - center.x;
  565. const dy = e.clientY - rect.top - center.y;
  566. if (Math.hypot(dx, dy) > center.r * 1.45 * hitScale) return;
  567. e.preventDefault();
  568. setOrbShape(ORB.shape === "sphere" ? "cube" : "sphere", { reveal: true });
  569. });
  570. function rasterizeNOUS(time) {
  571. asciiMask.fill(0);
  572. asciiGlyph.fill("");
  573. for (const r of obstacleRows) r.length = 0;
  574. // NOUS uses the same cell-shader/reveal language as bb-ascii's source logo.
  575. if (nousStartTime === null || time < nousStartTime) {
  576. mergeObstacleRows();
  577. return;
  578. }
  579. const t = Math.max(0, time - nousStartTime);
  580. const aspect = cols / rows / 2;
  581. const h = 0.38;
  582. const baseW = h * 2.6 * 0.55;
  583. const letterWidth = 7;
  584. const baseLetterPitch = 7.6;
  585. const letterGap = Math.max(0, ctrls.nousLetterSpacing ?? 0);
  586. const letterAdvance = baseLetterPitch + letterGap;
  587. const baseLogoUnits = LOGO.length * baseLetterPitch - 0.6;
  588. const logoUnits = LOGO.length * baseLetterPitch + (LOGO.length - 1) * letterGap - 0.6;
  589. const w = baseW * (logoUnits / baseLogoUnits);
  590. const nousRowMin = new Float32Array(rows);
  591. const nousRowMax = new Float32Array(rows);
  592. nousRowMin.fill(Infinity);
  593. nousRowMax.fill(-Infinity);
  594. for (let y = 0; y < rows; y++) {
  595. const ny = y / rows - 0.5;
  596. if (Math.abs(ny) > h / 2) continue;
  597. for (let x = 0; x < cols; x++) {
  598. const nx = (x / cols - 0.5) * aspect;
  599. if (Math.abs(nx) > w / 2) continue;
  600. const lx = (nx + w / 2) / w;
  601. const ly = (ny + h / 2) / h;
  602. const tx = lx * logoUnits;
  603. const idx = Math.floor(tx / letterAdvance);
  604. const cx = Math.floor(tx - idx * letterAdvance);
  605. const cy = Math.floor(ly * 9);
  606. if (idx < 0 || idx >= LOGO.length || cx >= letterWidth) continue;
  607. const { letter, rows: glyphRows } = LOGO[idx];
  608. const row = glyphRows[cy];
  609. if (!row || cx >= row.length || row[cx] !== '█') continue;
  610. const localT = Math.max(0, t - idx * 0.4);
  611. const phase1 = Math.min(1, localT);
  612. const phase2 = Math.min(1, Math.max(0, localT - 1));
  613. const reveal = phase1 * 1.5 - hash(cx, cy + idx * 10) * 0.5;
  614. if (phase1 < 1 && reveal <= 0) continue;
  615. const morph = phase2 + hash(cx, cy) * 0.3;
  616. const ch = phase1 < 1
  617. ? (reveal >= 1 ? letter : charAt(reveal))
  618. : charAt(morph);
  619. const drawC = Math.floor((canvasLeft + x * CELL_W + CELL_W * 0.5) / CELL_W);
  620. const drawR = Math.floor((canvasTop + y * CELL_H + CELL_H * 0.5) / CELL_H);
  621. let cellIdx = -1;
  622. if (drawR >= 0 && drawR < canvasRows && drawC >= 0 && drawC < canvasCols) {
  623. cellIdx = drawR * canvasCols + drawC;
  624. asciiMask[cellIdx] = 1;
  625. asciiChar[cellIdx] = Math.max(0, CHARS.indexOf(ch));
  626. if (CHARS.indexOf(ch) < 0) asciiGlyph[cellIdx] = ch;
  627. }
  628. const x0 = x * CELL_W;
  629. const x1 = x0 + CELL_W;
  630. if (x0 < nousRowMin[y]) nousRowMin[y] = x0;
  631. if (x1 > nousRowMax[y]) nousRowMax[y] = x1;
  632. // bb-ascii turns late morph cells into solid dark cell backgrounds. In
  633. // this transparent/lensed canvas, a full-block char carries that punch.
  634. if (cellIdx >= 0 && phase1 >= 1 && morph > 0.8) asciiChar[cellIdx] = CHARS.length - 1;
  635. }
  636. }
  637. // Slightly dilate/smooth the measured NOUS silhouette so surrounding text
  638. // does not visually "kiss" sharp letter corners (notably on the S).
  639. const smoothMin = new Float32Array(rows);
  640. const smoothMax = new Float32Array(rows);
  641. smoothMin.fill(Infinity);
  642. smoothMax.fill(-Infinity);
  643. for (let y = 0; y < rows; y++) {
  644. if (!Number.isFinite(nousRowMin[y])) continue;
  645. for (let oy = -1; oy <= 1; oy++) {
  646. const yy = y + oy;
  647. if (yy < 0 || yy >= rows) continue;
  648. if (!Number.isFinite(nousRowMin[yy])) continue;
  649. if (nousRowMin[yy] < smoothMin[y]) smoothMin[y] = nousRowMin[yy];
  650. if (nousRowMax[yy] > smoothMax[y]) smoothMax[y] = nousRowMax[yy];
  651. }
  652. }
  653. const pad = Math.max(4, CELL_W * 1.25);
  654. const bleedRows = 2;
  655. for (let y = 0; y < rows; y++) {
  656. if (!Number.isFinite(smoothMin[y])) continue;
  657. for (let oy = -bleedRows; oy <= bleedRows; oy++) {
  658. const row = y + oy;
  659. if (row < 0 || row >= rows) continue;
  660. const bleedPad = pad + Math.abs(oy) * CELL_W * 0.28;
  661. obstacleRows[row].push([
  662. Math.max(0, smoothMin[y] - bleedPad),
  663. Math.min(W, smoothMax[y] + bleedPad),
  664. ]);
  665. }
  666. }
  667. mergeObstacleRows();
  668. }
  669. function mergeObstacleRows() {
  670. for (const spans of obstacleRows) {
  671. if (spans.length < 2) continue;
  672. spans.sort((a, b) => a[0] - b[0]);
  673. let w = 0;
  674. for (let i = 1; i < spans.length; i++) {
  675. const last = spans[w], cur = spans[i];
  676. if (cur[0] <= last[1] + CELL_W * 3.1) last[1] = Math.max(last[1], cur[1]);
  677. else spans[++w] = cur;
  678. }
  679. spans.length = w + 1;
  680. }
  681. }
  682. const CUBE_VERTS = [
  683. [-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1],
  684. [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1],
  685. ];
  686. const CUBE_EDGES = [
  687. [0, 1], [1, 2], [2, 3], [3, 0],
  688. [4, 5], [5, 6], [6, 7], [7, 4],
  689. [0, 4], [1, 5], [2, 6], [3, 7],
  690. ];
  691. function projectCubeVerts(center, radiusPx, orbitX, orbitY, scale = 1) {
  692. const camZ = 3.3;
  693. const projScale = radiusPx * 1.34 * scale;
  694. return CUBE_VERTS.map(([vx, vy, vz]) => {
  695. const [rx, ry, rz] = rotateOrbVec(vx, vy, vz, orbitX, orbitY);
  696. const inv = 1 / (camZ + rz);
  697. return {
  698. x: center.canvasX + rx * projScale * inv,
  699. y: center.canvasY + ry * projScale * inv,
  700. d: (rz + 1) * 0.5,
  701. };
  702. });
  703. }
  704. function convexHull(points) {
  705. if (points.length <= 2) return points.slice();
  706. const pts = points
  707. .map(p => ({ x: p.x, y: p.y }))
  708. .sort((a, b) => (a.x - b.x) || (a.y - b.y));
  709. const cross = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
  710. const lower = [];
  711. for (const p of pts) {
  712. while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();
  713. lower.push(p);
  714. }
  715. const upper = [];
  716. for (let i = pts.length - 1; i >= 0; i--) {
  717. const p = pts[i];
  718. while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();
  719. upper.push(p);
  720. }
  721. lower.pop();
  722. upper.pop();
  723. return lower.concat(upper);
  724. }
  725. function makeEmptySpanRows() {
  726. return Array.from({ length: rows }, () => ({ left: Infinity, right: -Infinity }));
  727. }
  728. function addSpan(spanRows, row, left, right) {
  729. if (row < 0 || row >= rows || right <= left) return;
  730. if (left < spanRows[row].left) spanRows[row].left = left;
  731. if (right > spanRows[row].right) spanRows[row].right = right;
  732. }
  733. function collectCubeObstacleRows(center, radiusPx, orbitX, orbitY, obstacleScale) {
  734. const spanRows = makeEmptySpanRows();
  735. if (obstacleScale <= 0.0001) return spanRows;
  736. const projected = projectCubeVerts(center, radiusPx, orbitX, orbitY, ORB.cubeScale * obstacleScale)
  737. .map(p => ({ x: p.x - canvasLeft, y: p.y - canvasTop }));
  738. const hull = convexHull(projected);
  739. if (hull.length < 3) return spanRows;
  740. let yMin = Infinity;
  741. let yMax = -Infinity;
  742. for (const p of hull) {
  743. if (p.y < yMin) yMin = p.y;
  744. if (p.y > yMax) yMax = p.y;
  745. }
  746. const r0 = Math.max(0, Math.floor((yMin - CELL_H) / CELL_H));
  747. const r1 = Math.min(rows - 1, Math.ceil((yMax + CELL_H) / CELL_H));
  748. const pad = Math.max(4, CELL_W * 1.6);
  749. for (let row = r0; row <= r1; row++) {
  750. const scanY = row * CELL_H + CELL_H * 0.5;
  751. const xs = [];
  752. for (let i = 0; i < hull.length; i++) {
  753. const a = hull[i];
  754. const b = hull[(i + 1) % hull.length];
  755. const y0 = a.y;
  756. const y1 = b.y;
  757. if ((y0 <= scanY && scanY < y1) || (y1 <= scanY && scanY < y0)) {
  758. const t = (scanY - y0) / (y1 - y0);
  759. xs.push(a.x + (b.x - a.x) * t);
  760. }
  761. }
  762. if (xs.length < 2) continue;
  763. xs.sort((a, b) => a - b);
  764. for (let i = 0; i + 1 < xs.length; i += 2) {
  765. const left = Math.max(0, xs[i] - pad);
  766. const right = Math.min(W, xs[i + 1] + pad);
  767. if (right - left > CELL_W) addSpan(spanRows, row, left, right);
  768. }
  769. }
  770. return spanRows;
  771. }
  772. function collectSphereObstacleRows(center, radiusNorm, obstacleScale, rPad) {
  773. const spanRows = makeEmptySpanRows();
  774. const obstacleRadiusNorm = radiusNorm * obstacleScale;
  775. const obstaclePadNorm = (rPad / H) * obstacleScale;
  776. if (obstacleRadiusNorm <= 0.0001) return spanRows;
  777. const radiusPx = radiusNorm * H;
  778. const rMin = Math.floor((center.canvasY - radiusPx - rPad) / CELL_H);
  779. const rMax = Math.ceil((center.canvasY + radiusPx + rPad) / CELL_H);
  780. for (let r = rMin; r <= rMax; r++) {
  781. const y = r * CELL_H + CELL_H * 0.5;
  782. const stageY = y - canvasTop;
  783. const pyForObstacle = stageY / H - 0.5 - ORB.panY;
  784. if (Math.abs(pyForObstacle) > obstacleRadiusNorm + obstaclePadNorm) continue;
  785. const halfNorm = Math.sqrt(Math.max(0, (obstacleRadiusNorm + obstaclePadNorm) ** 2 - pyForObstacle * pyForObstacle));
  786. const halfPx = halfNorm * H;
  787. const stageRow = Math.floor(stageY / CELL_H);
  788. addSpan(spanRows, stageRow, center.x - halfPx, center.x + halfPx);
  789. }
  790. return spanRows;
  791. }
  792. function pushMorphedObstacleRows(sphereRows, cubeRows, mix) {
  793. const centerX = W * (0.5 + ORB.panX);
  794. for (let row = 0; row < rows; row++) {
  795. const sphereValid = Number.isFinite(sphereRows[row].left);
  796. const cubeValid = Number.isFinite(cubeRows[row].left);
  797. if (!sphereValid && !cubeValid) continue;
  798. const sLeft = sphereValid ? sphereRows[row].left : centerX;
  799. const sRight = sphereValid ? sphereRows[row].right : centerX;
  800. const cLeft = cubeValid ? cubeRows[row].left : centerX;
  801. const cRight = cubeValid ? cubeRows[row].right : centerX;
  802. const left = sLeft + (cLeft - sLeft) * mix;
  803. const right = sRight + (cRight - sRight) * mix;
  804. if (right - left > CELL_W) obstacleRows[row].push([Math.max(0, left), Math.min(W, right)]);
  805. }
  806. }
  807. function rotateOrbVec(vx, vy, vz, orbitX, orbitY) {
  808. let a = rot(vy, vz, orbitX); vy = a[0]; vz = a[1];
  809. a = rot(vx, vz, orbitY); vx = a[0]; vz = a[1];
  810. return [vx, vy, vz];
  811. }
  812. function rasterizeCubeWire(center, radiusPx, buildPhase, orbitX, orbitY, weight = 1) {
  813. const unit = Math.max(1, Math.min(CELL_W, CELL_H));
  814. const wirePx = Math.max(1, ORB.wire * radiusPx * 0.17);
  815. const brush = Math.max(0, Math.ceil((wirePx - unit * 0.45) / unit));
  816. const projected = projectCubeVerts(center, radiusPx, orbitX, orbitY, ORB.cubeScale);
  817. for (let ei = 0; ei < CUBE_EDGES.length; ei++) {
  818. const [a, b] = CUBE_EDGES[ei];
  819. const p0 = projected[a];
  820. const p1 = projected[b];
  821. const dx = p1.x - p0.x;
  822. const dy = p1.y - p0.y;
  823. const len = Math.hypot(dx, dy);
  824. const steps = Math.max(2, Math.ceil(len / Math.max(1, unit * 0.45)));
  825. for (let s = 0; s <= steps; s++) {
  826. const t = s / steps;
  827. const px = p0.x + dx * t;
  828. const py = p0.y + dy * t;
  829. const depth = p0.d + (p1.d - p0.d) * t;
  830. const c = Math.floor(px / CELL_W);
  831. const r = Math.floor(py / CELL_H);
  832. for (let oy = -brush; oy <= brush; oy++) {
  833. for (let ox = -brush; ox <= brush; ox++) {
  834. if (brush > 0 && ox * ox + oy * oy > brush * brush + 0.25) continue;
  835. const cc = c + ox;
  836. const rr = r + oy;
  837. if (rr < 0 || rr >= canvasRows || cc < 0 || cc >= canvasCols) continue;
  838. const reveal = buildPhase * 1.45 - hash(cc + ei * 13, rr + ei * 17) * 0.5;
  839. if (buildPhase < 1 && reveal <= 0) continue;
  840. const idx = rr * canvasCols + cc;
  841. const val = buildPhase < 1
  842. ? Math.min(CHARS_LAST, Math.floor(reveal * CHARS_LAST))
  843. : Math.min(CHARS_LAST, Math.floor((0.45 + depth * 0.55) * CHARS_LAST));
  844. const weightedVal = Math.min(CHARS_LAST, Math.floor(val * weight));
  845. if (weightedVal <= 0) continue;
  846. orbMask[idx] = 1;
  847. orbGlyph[idx] = "";
  848. if (weightedVal > orbChar[idx]) orbChar[idx] = weightedVal;
  849. }
  850. }
  851. }
  852. }
  853. }
  854. function rasterizeOrb(time) {
  855. orbMask.fill(0);
  856. orbChar.fill(0);
  857. orbGlyph.fill("");
  858. const buildStart = orbBuildStartTime();
  859. if (time < buildStart) return;
  860. const shapeMix = Math.max(0, Math.min(1, ORB.shapeMix ?? (ORB.shape === "cube" ? 1 : 0)));
  861. const sphereWeight = 1 - shapeMix;
  862. const cubeWeight = shapeMix;
  863. const sphereOrbitX = ORB.orbitX;
  864. const sphereOrbitY = ORB.orbitY + time * ORB.autoSpin;
  865. const cubeOrbitX = ORB.orbitX + time * ORB.autoSpin * 0.72;
  866. const cubeOrbitY = ORB.orbitY + time * ORB.autoSpin * 1.35;
  867. const latStep = Math.PI / ORB.lat;
  868. const lonStep = (Math.PI * 2) / ORB.lon;
  869. const rPad = 15.5;
  870. const center = orbCenter();
  871. const radiusPx = center.r;
  872. const radiusNorm = center.rNorm;
  873. const buildPhase = Math.min(1, Math.max(0, (time - buildStart) / SCENE.orbBuildDuration));
  874. const spacePhase = Math.min(1, Math.max(0, (time - buildStart) / Math.max(0.001, ctrls.orbSpaceDuration)));
  875. const spaceGrow = Math.pow(spacePhase, Math.max(0.01, ctrls.orbSpaceEase));
  876. const spaceStart = Math.max(0, Math.min(1, ctrls.orbSpaceStart));
  877. const obstacleScale = spaceStart + (1 - spaceStart) * spaceGrow;
  878. const rMin = Math.floor((center.canvasY - radiusPx - rPad) / CELL_H);
  879. const rMax = Math.ceil((center.canvasY + radiusPx + rPad) / CELL_H);
  880. const sphereObstacleRows = collectSphereObstacleRows(center, radiusNorm, obstacleScale, rPad);
  881. const cubeObstacleRows = collectCubeObstacleRows(center, radiusPx, cubeOrbitX, cubeOrbitY, obstacleScale);
  882. pushMorphedObstacleRows(sphereObstacleRows, cubeObstacleRows, shapeMix);
  883. if (cubeWeight > 0.001) {
  884. rasterizeCubeWire(center, radiusPx, buildPhase, cubeOrbitX, cubeOrbitY, cubeWeight);
  885. }
  886. if (sphereWeight <= 0.001) {
  887. mergeObstacleRows();
  888. return;
  889. }
  890. const cMin = Math.floor((center.canvasX - radiusPx - rPad) / CELL_W);
  891. const cMax = Math.ceil((center.canvasX + radiusPx + rPad) / CELL_W);
  892. for (let r = rMin; r <= rMax; r++) {
  893. const y = r * CELL_H + CELL_H * 0.5;
  894. const stageY = y - canvasTop;
  895. for (let c = cMin; c <= cMax; c++) {
  896. // Direct port of bb-ascii/app/nous/sphere/page.tsx:
  897. // px uses width/height normalization, py is row-normalized, then both
  898. // are offset by pan. This is what makes the sphere circular on screen.
  899. const stageX = c * CELL_W + CELL_W * 0.5 - canvasLeft;
  900. const px = (stageX / W - 0.5 - ORB.panX) * (W / H);
  901. const py = stageY / H - 0.5 - ORB.panY;
  902. const d2 = px * px + py * py;
  903. if (d2 > radiusNorm * radiusNorm) continue;
  904. const pz = Math.sqrt(radiusNorm * radiusNorm - d2);
  905. const depth = (pz / radiusNorm) * 0.5 + 0.5;
  906. let sx = px / radiusNorm, sy = py / radiusNorm, sz = pz / radiusNorm;
  907. let a = rot(sy, sz, sphereOrbitX); sy = a[0]; sz = a[1];
  908. a = rot(sx, sz, sphereOrbitY); sx = a[0]; sz = a[1];
  909. const latD = gridDist(Math.asin(Math.max(-1, Math.min(1, sy))) + Math.PI / 2, latStep);
  910. const lonD = gridDist(Math.atan2(sz, sx) + Math.PI, lonStep);
  911. const wire = ORB.wire * (0.3 + depth * 0.7);
  912. const minD = Math.min(latD, lonD);
  913. if (minD > wire) continue;
  914. const edge = 1 - minD / wire;
  915. if (r >= 0 && r < canvasRows && c >= 0 && c < canvasCols) {
  916. const reveal = buildPhase * 1.5 - hash(c, r) * 0.5;
  917. if (buildPhase < 1 && reveal <= 0) continue;
  918. const idx = r * canvasCols + c;
  919. const val = buildPhase < 1
  920. ? Math.min(CHARS_LAST, Math.floor(reveal * CHARS_LAST))
  921. : Math.min(CHARS_LAST, Math.floor(edge * (0.4 + depth * 0.6) * CHARS.length));
  922. const weightedVal = Math.min(CHARS_LAST, Math.floor(val * sphereWeight));
  923. if (weightedVal <= 0) continue;
  924. orbMask[idx] = 1;
  925. orbGlyph[idx] = "";
  926. if (weightedVal > orbChar[idx]) orbChar[idx] = weightedVal;
  927. }
  928. }
  929. }
  930. mergeObstacleRows();
  931. }
  932. let typedChars = 0;
  933. let typedPrepared = null;
  934. let typedDirty = true;
  935. let typedBudget = 0;
  936. function tickTyping(time, dt) {
  937. if (!bodyPrepared) return;
  938. if (time < codeTypingStartTime()) return;
  939. const cps = Math.max(1, ctrls.typeSpeed ?? 42);
  940. typedBudget += dt * cps;
  941. const steps = Math.min(240, Math.floor(typedBudget));
  942. if (steps > 0) {
  943. typedBudget -= steps;
  944. typedChars = Math.min(streamCorpus.length, typedChars + steps);
  945. typedDirty = true;
  946. }
  947. }
  948. function getTypedPrepared() {
  949. if (!typedDirty && typedPrepared) return typedPrepared;
  950. const cap = Math.max(0, Math.floor(typedChars));
  951. const visible = streamCorpus.slice(0, cap);
  952. typedPrepared = prepareWithSegments(visible, BODY_FONT, { whiteSpace: "pre-wrap" });
  953. typedDirty = false;
  954. return typedPrepared;
  955. }
  956. function layoutParagraphs() {
  957. drawnLines.count = 0;
  958. if (typedChars <= 0) return;
  959. const prepared = getTypedPrepared();
  960. ctx.font = BODY_FONT;
  961. const MARGIN_X = Math.max(32, Math.min(72, W * 0.06));
  962. const MIN_LINE_W = 120;
  963. const yStart = Math.max(32, H * 0.08);
  964. const yEnd = H - 32;
  965. let cursor = { segmentIndex: 0, graphemeIndex: 0 };
  966. for (let y = yStart; y < yEnd; y += BODY_LINE_H) {
  967. const row = Math.max(0, Math.min(rows - 1, Math.floor(y / CELL_H)));
  968. const spans = obstacleRows[row] || [];
  969. let n = 0;
  970. let x = MARGIN_X;
  971. for (const [a, b] of spans) {
  972. const left = Math.max(MARGIN_X, a);
  973. const right = Math.min(W - MARGIN_X, b);
  974. if (left - x >= MIN_LINE_W) { intervals[n++] = x; intervals[n++] = left - 10; }
  975. x = Math.max(x, right + 10);
  976. }
  977. if (W - MARGIN_X - x >= MIN_LINE_W) { intervals[n++] = x; intervals[n++] = W - MARGIN_X; }
  978. if (!n) { intervals[n++] = MARGIN_X; intervals[n++] = W - MARGIN_X; }
  979. for (let k = 0; k < n; k += 2) {
  980. const ix0 = intervals[k], ix1 = intervals[k + 1];
  981. const range = layoutNextLineRange(prepared, cursor, ix1 - ix0);
  982. if (!range) return;
  983. const line = materializeLineRange(prepared, range);
  984. const i = drawnLines.count++;
  985. drawnLines.x[i] = ix0;
  986. drawnLines.y[i] = y;
  987. drawnLines.w[i] = ix1 - ix0;
  988. drawnLines.text[i] = line.text;
  989. cursor = range.end;
  990. }
  991. }
  992. }
  993. function escapeHTML(text) {
  994. return text
  995. .replaceAll("&", "&amp;")
  996. .replaceAll("<", "&lt;")
  997. .replaceAll(">", "&gt;");
  998. }
  999. function highlightSource(text) {
  1000. const token = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\/\/[^\n]*|\b(?:as|break|const|else|enum|false|fn|for|if|impl|in|let|match|mut|pub|return|self|static|struct|true|type|use|where|while)\b|\b[A-Z_]{2,}\b|\b\d+(?:\.\d+)?\b)/g;
  1001. let out = "";
  1002. let last = 0;
  1003. for (const match of text.matchAll(token)) {
  1004. const value = match[0];
  1005. out += escapeHTML(text.slice(last, match.index));
  1006. const cls = value.startsWith("#")
  1007. ? "tok-comment"
  1008. : value.startsWith('"') || value.startsWith("'")
  1009. ? "tok-string"
  1010. : /^\d/.test(value)
  1011. ? "tok-number"
  1012. : /^[A-Z_]{2,}$/.test(value)
  1013. ? "tok-const"
  1014. : "tok-keyword";
  1015. out += `<span class="${cls}">${escapeHTML(value)}</span>`;
  1016. last = match.index + value.length;
  1017. }
  1018. out += escapeHTML(text.slice(last));
  1019. return out;
  1020. }
  1021. function renderTextLayer() {
  1022. const parts = [LENS.mgBase, drawnLines.count];
  1023. for (let i = 0; i < drawnLines.count; i++) {
  1024. parts.push(drawnLines.x[i] | 0, drawnLines.y[i] | 0, drawnLines.w[i] | 0, drawnLines.text[i]);
  1025. }
  1026. const signature = parts.join("|");
  1027. if (signature === lastTextSignature) return;
  1028. lastTextSignature = signature;
  1029. ctx.font = BODY_FONT;
  1030. textLayer.style.color = LENS.mgBase;
  1031. textLayer.style.setProperty("--midground-base", LENS.mgBase);
  1032. while (lineNodes.length < drawnLines.count) {
  1033. const el = document.createElement("div");
  1034. el.className = "flow-line";
  1035. textLayer.appendChild(el);
  1036. lineNodes.push(el);
  1037. }
  1038. terminalAnchorEl = null;
  1039. terminalLineEl = null;
  1040. for (let i = 0; i < lineNodes.length; i++) {
  1041. const el = lineNodes[i];
  1042. if (i >= drawnLines.count) {
  1043. el.hidden = true;
  1044. continue;
  1045. }
  1046. const text = drawnLines.text[i];
  1047. const isTail = i === drawnLines.count - 1;
  1048. el.hidden = false;
  1049. el.innerHTML = isTail
  1050. ? `${highlightSource(text)}<span class="cursor-anchor" aria-hidden="true"></span>`
  1051. : highlightSource(text);
  1052. el.style.left = `${drawnLines.x[i]}px`;
  1053. el.style.top = `${drawnLines.y[i] - BODY_LINE_H + 4}px`;
  1054. el.style.width = `${drawnLines.w[i]}px`;
  1055. el.style.textAlign = "left";
  1056. el.style.wordSpacing = "0px";
  1057. if (isTail) {
  1058. terminalAnchorEl = el.querySelector(".cursor-anchor");
  1059. terminalLineEl = el;
  1060. }
  1061. }
  1062. }
  1063. let sceneEpoch = 0;
  1064. function restartScene() {
  1065. gsap.killTweensOf(ORB);
  1066. gsap.killTweensOf(orbCanvas);
  1067. autoCubeCall?.kill();
  1068. autoCubeCall = null;
  1069. ORB.panX = 0;
  1070. ORB.panY = 0;
  1071. ORB.zoom = ctrls.orbZoom;
  1072. ORB.cubeScale = ctrls.cubeScale;
  1073. ORB.shape = ctrls.orbShape;
  1074. ORB.shapeMix = ctrls.orbShape === "cube" ? 1 : 0;
  1075. ORB.orbitX = -1.42;
  1076. ORB.orbitY = 0;
  1077. ORB.wire = ctrls.orbWire;
  1078. orbCanvas.style.opacity = "1";
  1079. ORB.staged = false;
  1080. ORB.positioned = true;
  1081. typedChars = 0;
  1082. typedBudget = 0;
  1083. typedPrepared = null;
  1084. typedDirty = true;
  1085. nousStartTime = null;
  1086. sceneEpoch = (typeof performance !== "undefined" ? performance.now() : Date.now()) * 0.001;
  1087. lastTextSignature = "";
  1088. startSceneTimeline();
  1089. }
  1090. function applyFontSizes() {
  1091. const bodyPx = ctrls.bodyFontSize;
  1092. const asciiPx = ctrls.asciiFontSize;
  1093. BODY_FONT = `400 ${bodyPx}px "JetBrains Mono", "SF Mono", SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`;
  1094. BODY_LINE_H = Math.round(bodyPx * 1.45);
  1095. ASCII_FONT = `${asciiPx}px monospace`;
  1096. CELL_H = asciiPx;
  1097. textLayer.style.font = `400 ${bodyPx}px/${BODY_LINE_H}px "JetBrains Mono", "SF Mono", SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`;
  1098. rebuildLayouts();
  1099. typedPrepared = null;
  1100. typedDirty = true;
  1101. resize();
  1102. lastTextSignature = "";
  1103. }
  1104. function applyColors() {
  1105. if (!LENS.current) return;
  1106. LENS.current.bgColor = ctrls.bgColor;
  1107. LENS.current.mgColor = ctrls.mgColor;
  1108. LENS.current.fgColor = ctrls.fgColor;
  1109. applyLens(LENS.current);
  1110. lastTextSignature = "";
  1111. }
  1112. const ctrls = {
  1113. bodyFontSize: 10,
  1114. asciiFontSize: 8,
  1115. autoSpin: 0.18,
  1116. orbShape: "sphere",
  1117. shapeMorphDuration: 0.65,
  1118. cubeScale: 1.8,
  1119. orbLead: 0.35,
  1120. orbZoom: 3,
  1121. orbRadius: 0.135,
  1122. orbWire: 0.2,
  1123. orbSpaceStart: 0.82,
  1124. orbSpaceDuration: 0.7,
  1125. orbSpaceEase: 1.1,
  1126. orbWireLow: 0.01,
  1127. wireDropDuration: 1.2,
  1128. orbFadeDuration: 0.85,
  1129. orbContainNous: 1.0,
  1130. nousAfterWire: 0,
  1131. nousLetterSpacing: 2.7,
  1132. typeSpeed: 816,
  1133. bgColor: "#041C1C",
  1134. mgColor: "#ffe6cb",
  1135. fgColor: "#FFFFFF",
  1136. noiseEnabled: true,
  1137. noiseColor: "#eaeaea",
  1138. noiseDensity: 0.11,
  1139. noiseOpacity: 0.25,
  1140. noiseSize: 1,
  1141. noiseBlend: "difference",
  1142. restart: () => restartScene(),
  1143. };
  1144. const DEV_MODE = new URLSearchParams(window.location.search).has("dev");
  1145. if (DEV_MODE) {
  1146. const gui = new GUI({ title: "controls" });
  1147. gui.add(ctrls, "bodyFontSize", 10, 22, 1).name("body font").onChange(applyFontSizes);
  1148. gui.add(ctrls, "asciiFontSize", 8, 20, 1).name("ascii font").onChange(applyFontSizes);
  1149. gui.add(ctrls, "autoSpin", 0, 0.6, 0.01).name("auto-spin").onChange(v => { ORB.autoSpin = v; });
  1150. orbShapeControl = gui.add(ctrls, "orbShape", ["sphere", "cube"]).name("orb shape").onChange(v => {
  1151. setOrbShape(v);
  1152. });
  1153. gui.add(ctrls, "shapeMorphDuration", 0.05, 2, 0.01).name("shape morph (s)");
  1154. gui.add(ctrls, "orbLead", 0, 6, 0.05).name("orb start (s)").onFinishChange(() => restartScene());
  1155. gui.add(ctrls, "orbZoom", 0.25, 12, 0.01).name("orb zoom").onChange(v => { ORB.zoom = v; });
  1156. gui.add(ctrls, "cubeScale", 0.8, 3.5, 0.01).name("cube scale").onChange(v => { ORB.cubeScale = v; });
  1157. gui.add(ctrls, "orbRadius", 0.08, 0.4, 0.005).name("orb radius").onChange(v => { ORB.radius = v; });
  1158. gui.add(ctrls, "orbSpaceStart", 0.4, 1, 0.01).name("space start");
  1159. gui.add(ctrls, "orbSpaceDuration", 0.2, 4, 0.05).name("space grow (s)");
  1160. gui.add(ctrls, "orbSpaceEase", 0.4, 3, 0.05).name("space ease");
  1161. gui.add(ctrls, "orbWire", 0.01, 0.2, 0.005).name("wire start").onChange(v => { ORB.wire = v; });
  1162. gui.add(ctrls, "orbWireLow", 0.005, 0.12, 0.001).name("wire low").onFinishChange(() => restartScene());
  1163. gui.add(ctrls, "wireDropDuration", 0.4, 6, 0.05).name("wire drop (s)").onFinishChange(() => restartScene());
  1164. gui.add(ctrls, "orbContainNous", 0, 3, 0.05).name("orb contain NOUS");
  1165. gui.add(ctrls, "orbFadeDuration", 0.1, 3, 0.05).name("orb fade on NOUS");
  1166. gui.add(ctrls, "nousAfterWire", 0, 4, 0.05).name("NOUS after wire").onFinishChange(() => restartScene());
  1167. gui.add(ctrls, "nousLetterSpacing", 0, 4, 0.05).name("NOUS spacing");
  1168. gui.add(ctrls, "typeSpeed", 0, 4000, 10).name("type speed");
  1169. gui.addColor(ctrls, "bgColor").name("background").onChange(applyColors);
  1170. gui.addColor(ctrls, "mgColor").name("midground").onChange(applyColors);
  1171. gui.addColor(ctrls, "fgColor").name("foreground").onChange(applyColors);
  1172. const noiseFolder = gui.addFolder("noise");
  1173. noiseFolder.add(ctrls, "noiseEnabled").name("on");
  1174. noiseFolder.addColor(ctrls, "noiseColor").name("color");
  1175. noiseFolder.add(ctrls, "noiseDensity", 0, 1, 0.01).name("density");
  1176. noiseFolder.add(ctrls, "noiseOpacity", 0, 1, 0.01).name("opacity");
  1177. noiseFolder.add(ctrls, "noiseSize", 0.1, 10, 0.1).name("size");
  1178. noiseFolder.add(ctrls, "noiseBlend", [
  1179. "normal", "multiply", "screen", "difference", "exclusion",
  1180. "color-dodge", "color-burn", "hard-light", "soft-light", "overlay", "lighten",
  1181. ]).name("blend").onChange(v => { document.querySelector(".noise").style.mixBlendMode = v; });
  1182. gui.add(ctrls, "restart").name("restart anim");
  1183. }
  1184. const terminalCursorEl = document.getElementById("terminalCursor");
  1185. function getLastCharRect(lineEl) {
  1186. if (!lineEl) return null;
  1187. const walker = document.createTreeWalker(lineEl, NodeFilter.SHOW_TEXT);
  1188. let lastTextNode = null;
  1189. let node = walker.nextNode();
  1190. while (node) {
  1191. if (node.nodeValue && node.nodeValue.length) lastTextNode = node;
  1192. node = walker.nextNode();
  1193. }
  1194. if (!lastTextNode) return null;
  1195. const end = lastTextNode.nodeValue.length;
  1196. if (!end) return null;
  1197. const range = document.createRange();
  1198. range.setStart(lastTextNode, end - 1);
  1199. range.setEnd(lastTextNode, end);
  1200. const rects = range.getClientRects();
  1201. const rect = rects.length ? rects[rects.length - 1] : range.getBoundingClientRect();
  1202. return rect && (rect.width || rect.height) ? rect : null;
  1203. }
  1204. function updateTerminalCursor() {
  1205. if (!drawnLines.count || !terminalAnchorEl || !terminalLineEl) {
  1206. terminalCursorEl.hidden = true;
  1207. return;
  1208. }
  1209. const stageRect = stage.getBoundingClientRect();
  1210. const charRect = getLastCharRect(terminalLineEl);
  1211. const anchorRect = terminalAnchorEl.getBoundingClientRect();
  1212. if (!anchorRect.width && !anchorRect.height) {
  1213. terminalCursorEl.hidden = true;
  1214. return;
  1215. }
  1216. const fontSize = parseInt(BODY_FONT.match(/(\d+)px/)?.[1] || "12", 10);
  1217. const fallbackW = Math.max(6, Math.round(fontSize * 0.6));
  1218. const leftPx = (charRect?.left ?? (anchorRect.left - fallbackW)) - stageRect.left;
  1219. const topPx = (charRect?.top ?? anchorRect.top) - stageRect.top;
  1220. const widthPx = Math.max(1, Math.round(charRect?.width || fallbackW));
  1221. const heightPx = Math.max(1, Math.round(charRect?.height || (BODY_LINE_H - 4)));
  1222. const left = Math.round(leftPx);
  1223. const top = Math.round(topPx);
  1224. terminalCursorEl.style.left = `${left}px`;
  1225. terminalCursorEl.style.top = `${top}px`;
  1226. terminalCursorEl.style.height = `${heightPx}px`;
  1227. terminalCursorEl.style.width = `${widthPx}px`;
  1228. terminalCursorEl.style.fontSize = `${fontSize}px`;
  1229. terminalCursorEl.hidden = false;
  1230. }
  1231. const noiseCanvas = document.getElementById("noiseCanvas");
  1232. const noiseGL = noiseCanvas.getContext("webgl", { alpha: true, premultipliedAlpha: true })
  1233. || noiseCanvas.getContext("experimental-webgl", { alpha: true, premultipliedAlpha: true });
  1234. let noiseProgram = null;
  1235. let noiseLocs = null;
  1236. function initNoise() {
  1237. if (!noiseGL) return;
  1238. const vertSrc = `
  1239. attribute vec2 aPos;
  1240. varying vec2 vUv;
  1241. void main() {
  1242. vUv = aPos * 0.5 + 0.5;
  1243. gl_Position = vec4(aPos, 0.0, 1.0);
  1244. }
  1245. `;
  1246. const fragSrc = `
  1247. precision mediump float;
  1248. varying vec2 vUv;
  1249. uniform vec2 uRes;
  1250. uniform float uDpr;
  1251. uniform float uSize;
  1252. uniform float uDensity;
  1253. uniform float uOpacity;
  1254. uniform vec3 uColor;
  1255. float hash(vec2 p) {
  1256. vec3 p3 = fract(vec3(p.xyx) * 0.1031);
  1257. p3 += dot(p3, p3.yzx + 33.33);
  1258. return fract((p3.x + p3.y) * p3.z);
  1259. }
  1260. void main() {
  1261. float n = hash(floor(vUv * uRes / (uSize * uDpr)));
  1262. gl_FragColor = vec4(uColor, step(1.0 - uDensity, n)) * uOpacity;
  1263. }
  1264. `;
  1265. function compile(type, src) {
  1266. const sh = noiseGL.createShader(type);
  1267. noiseGL.shaderSource(sh, src);
  1268. noiseGL.compileShader(sh);
  1269. return sh;
  1270. }
  1271. const vs = compile(noiseGL.VERTEX_SHADER, vertSrc);
  1272. const fs = compile(noiseGL.FRAGMENT_SHADER, fragSrc);
  1273. noiseProgram = noiseGL.createProgram();
  1274. noiseGL.attachShader(noiseProgram, vs);
  1275. noiseGL.attachShader(noiseProgram, fs);
  1276. noiseGL.linkProgram(noiseProgram);
  1277. noiseGL.useProgram(noiseProgram);
  1278. const buf = noiseGL.createBuffer();
  1279. noiseGL.bindBuffer(noiseGL.ARRAY_BUFFER, buf);
  1280. noiseGL.bufferData(noiseGL.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), noiseGL.STATIC_DRAW);
  1281. const aPos = noiseGL.getAttribLocation(noiseProgram, "aPos");
  1282. noiseGL.enableVertexAttribArray(aPos);
  1283. noiseGL.vertexAttribPointer(aPos, 2, noiseGL.FLOAT, false, 0, 0);
  1284. noiseLocs = {
  1285. uRes: noiseGL.getUniformLocation(noiseProgram, "uRes"),
  1286. uDpr: noiseGL.getUniformLocation(noiseProgram, "uDpr"),
  1287. uSize: noiseGL.getUniformLocation(noiseProgram, "uSize"),
  1288. uDensity: noiseGL.getUniformLocation(noiseProgram, "uDensity"),
  1289. uOpacity: noiseGL.getUniformLocation(noiseProgram, "uOpacity"),
  1290. uColor: noiseGL.getUniformLocation(noiseProgram, "uColor"),
  1291. };
  1292. noiseGL.enable(noiseGL.BLEND);
  1293. noiseGL.blendFunc(noiseGL.ONE, noiseGL.ONE_MINUS_SRC_ALPHA);
  1294. noiseGL.clearColor(0, 0, 0, 0);
  1295. }
  1296. function resizeNoise() {
  1297. if (!noiseGL) return;
  1298. const dpr = Math.min(window.devicePixelRatio || 1, 2);
  1299. noiseCanvas.width = innerWidth * dpr;
  1300. noiseCanvas.height = innerHeight * dpr;
  1301. noiseGL.viewport(0, 0, noiseCanvas.width, noiseCanvas.height);
  1302. if (noiseLocs) {
  1303. noiseGL.uniform2f(noiseLocs.uRes, noiseCanvas.width, noiseCanvas.height);
  1304. noiseGL.uniform1f(noiseLocs.uDpr, dpr);
  1305. }
  1306. }
  1307. addEventListener("resize", resizeNoise);
  1308. initNoise();
  1309. resizeNoise();
  1310. function drawNoiseFrame() {
  1311. if (!noiseGL || !noiseProgram) return;
  1312. noiseGL.clear(noiseGL.COLOR_BUFFER_BIT);
  1313. if (!ctrls.noiseEnabled) return;
  1314. noiseGL.useProgram(noiseProgram);
  1315. noiseGL.uniform1f(noiseLocs.uSize, ctrls.noiseSize);
  1316. noiseGL.uniform1f(noiseLocs.uDensity, ctrls.noiseDensity);
  1317. noiseGL.uniform1f(noiseLocs.uOpacity, ctrls.noiseOpacity);
  1318. const [r, g, b] = hexToRGB(ctrls.noiseColor);
  1319. noiseGL.uniform3f(noiseLocs.uColor, r / 255, g / 255, b / 255);
  1320. noiseGL.drawArrays(noiseGL.TRIANGLE_STRIP, 0, 4);
  1321. }
  1322. function draw(time) {
  1323. if (!fontsReady || !bodyPrepared) { requestAnimationFrame(draw); return; }
  1324. const t = time * 0.001 - sceneEpoch;
  1325. const dt = lastFrameTime ? Math.min(0.05, (time - lastFrameTime) / 1000) : 0.016;
  1326. lastFrameTime = time;
  1327. ctx.clearRect(0, 0, canvasW, canvasH);
  1328. orbCtx.clearRect(0, 0, canvasW, canvasH);
  1329. rasterizeNOUS(t);
  1330. rasterizeOrb(t);
  1331. tickTyping(t, dt);
  1332. layoutParagraphs();
  1333. renderTextLayer();
  1334. updateTerminalCursor();
  1335. drawNoiseFrame();
  1336. ctx.font = ASCII_FONT;
  1337. ctx.textBaseline = "middle";
  1338. ctx.textAlign = "center";
  1339. ctx.fillStyle = LENS.mgBase;
  1340. orbCtx.font = ASCII_FONT;
  1341. orbCtx.textBaseline = "middle";
  1342. orbCtx.textAlign = "center";
  1343. orbCtx.fillStyle = LENS.mgBase;
  1344. for (let r = 0; r < canvasRows; r++) {
  1345. const base = r * canvasCols;
  1346. for (let c = 0; c < canvasCols; c++) {
  1347. const idx = base + c;
  1348. if (asciiMask[idx] === EMPTY) continue;
  1349. ctx.fillText(asciiGlyph[idx] || CHARS[asciiChar[idx]], c * CELL_W + CELL_W * 0.5, r * CELL_H + CELL_H * 0.5);
  1350. }
  1351. }
  1352. for (let r = 0; r < canvasRows; r++) {
  1353. const base = r * canvasCols;
  1354. for (let c = 0; c < canvasCols; c++) {
  1355. const idx = base + c;
  1356. if (orbMask[idx] === EMPTY) continue;
  1357. orbCtx.fillText(orbGlyph[idx] || CHARS[orbChar[idx]], c * CELL_W + CELL_W * 0.5, r * CELL_H + CELL_H * 0.5);
  1358. }
  1359. }
  1360. requestAnimationFrame(draw);
  1361. }
  1362. resize();
  1363. const DS_CDN = "https://esm.sh/@nous-research/ui@0.4.0/dist/fonts";
  1364. const FACES = [new FontFace("Mondwest", `url(${DS_CDN}/Mondwest-Regular.woff2) format("woff2")`, { weight: "400", display: "block" })];
  1365. (async () => {
  1366. try {
  1367. const loaded = await Promise.all(FACES.map(f => f.load()));
  1368. for (const f of loaded) document.fonts.add(f);
  1369. await document.fonts.load(BODY_FONT, "Aa");
  1370. await document.fonts.load(ASCII_FONT, "Aa");
  1371. } catch (err) {
  1372. console.warn("DS font load failed, using fallbacks:", err);
  1373. }
  1374. rebuildLayouts();
  1375. fontsReady = true;
  1376. requestAnimationFrame(draw);
  1377. })();
  1378. </script>
  1379. </body>
  1380. </html>