A mech game prototype, pushed by Gemini 4 Carbon
agent (cont.)
+10:26read_file{"Path":"~/work/sortie/src/render/assets.ts"}
input
{ "Path": "~/work/sortie/src/render/assets.ts" }result, 229 lines
Showing lines 1-228 of 228 1: import * as THREE from 'three'; 2: import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; 3: import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js'; 4: import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js'; 5: import { PALETTES, type PaletteName } from './palette'; 6: import { DETAIL_LAYER } from './pipeline'; 7: import { BARE, isRole, material } from './materials'; 8: 9: const loader = new GLTFLoader(); 10: loader.setMeshoptDecoder(MeshoptDecoder); 11: const sources = new Map<string, Promise<THREE.Object3D>>(); 12: 13: /** Every model the kit builds (kit/build.py). */ 14: export type ModelName = 'alien_acicular' | 'alien_druse' | 'alien_druse_mimic' | 'alien_geode' 15: | 'striker' | 'striker_a' | 'striker_b' | 'light' | 'light_line' | 'light_lancer' | 'heavy' | 'heavy_B' | 'heavy_C' 16: | 'auto_tally' | 'auto_tick' | 'auto_ledger' | 'rifle' | 'cannon' | 'drone' | 'cockpit' | 'cockpit_light' | 'ship' | 'station' 17: | 'wreck_field' | 'salvage_pod' | 'escape_pod' | 'raider_grunt' | 'raider_brawler' | 'raider_boss'; 18: 19: /** 20: * Models ship as .glb. Artifact pages serve neither .glb nor fetches of data: URLs, so the artifact 21: * build wraps each model as base64 in JSON (VITE_MODEL_EXT=glb.json) and the page decodes it here. 22: * Those are squeezed (tools/squeeze.mjs): meshopt compressed, plus a quantized-only copy 23: * (.q.glb.json) for a page that can't run the WebAssembly decoder. 24: */ 25: const EXT: string = import.meta.env.VITE_MODEL_EXT ?? 'glb'; 26: const meshopt: Promise<boolean> = EXT === 'glb' ? Promise.resolve(true) : MeshoptDecoder.ready.then(() => true, () => false); 27: 28: async function fetchGlb(url: string): Promise<ArrayBuffer> { 29: const res = await fetch(url); 30: if (!res.ok) throw new Error(`${url}: ${res.status}`); 31: if (!url.endsWith('.json')) return res.arrayBuffer(); 32: const b64 = (await res.json()).glb as string; 33: const bin = atob(b64); 34: const out = new Uint8Array(bin.length); 35: for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); 36: return out.buffer; 37: } 38: 39: /** Models loading now and loaded so far, for a loading indicator. */ 40: export const loading = { pending: 0, done: 0, listeners: new Set<() => void>() }; 41: function track<T>(p: Promise<T>): Promise<T> { 42: loading.pending++; 43: const tell = () => { 44: for (const f of loading.listeners) f(); 45: }; 46: tell(); 47: const end = () => { 48: loading.pending--; 49: loading.done++; 50: tell(); 51: }; 52: p.then(end, end); 53: return p; 54: } 55: 56: function source(name: ModelName, merge = true): Promise<THREE.Object3D> { 57: const key = merge ? name : `${name}:parts`; 58: let p = sources.get(key); 59: if (!p) { 60: const url = (ok: boolean) => `${import.meta.env.BASE_URL}assets/${name}.${ok ? EXT : `q.${EXT}`}`; 61: p = track(meshopt.then((ok) => fetchGlb(url(ok))).then((glb) => parseModel(glb, merge))); 62: sources.set(key, p); 63: } 64: return p; 65: } 66: 67: /** A model's scene from GLB bytes, plain or squeezed. `merge` false keeps every part its own mesh. */ 68: export async function parseModel(glb: ArrayBuffer, merge = true): Promise<THREE.Object3D> { 69: const root = unquantize((await loader.parseAsync(glb, '')).scene); 70: return merge ? mergeParts(root) : root; 71: } 72: 73: /** Start loading models now, side by side, so later awaits find them ready. */ 74: export function preload(names: Iterable<ModelName>) { 75: for (const n of names) source(n).catch((e) => console.error(e)); 76: } 77: 78: /** A fresh copy of a model, painted with a palette and tagged for ink lines. `merge` false keeps every 79: * part its own mesh, for models whose parts move apart (the aliens). */ 80: export async function model(name: ModelName, palette: PaletteName = 'merc', merge = true): Promise<THREE.Object3D> { 81: const root = (await source(name, merge)).clone(true); 82: paint(root, palette); 83: return root; 84: } 85: 86: export function paint(root: THREE.Object3D, palette: PaletteName) { 87: const pal = PALETTES[palette]; 88: // the plumes (render/mech.ts) take their colour from the same palette 89: root.userData.palette = palette; 90: root.traverse((o) => { 91: const mesh = o as THREE.Mesh; 92: if (!mesh.isMesh) return; 93: const src = mesh.userData.role ?? (mesh.material as THREE.Material).name; 94: mesh.userData.role = src; 95: if (isRole(src)) mesh.material = material(pal, src, palette); 96: const glows = (mesh.material as THREE.MeshBasicMaterial).isMeshBasicMaterial; 97: mesh.castShadow = !glows; 98: mesh.receiveShadow = !glows; 99: if (glows || BARE.has(src)) mesh.layers.disable(DETAIL_LAYER); 100: else mesh.layers.enable(DETAIL_LAYER); 101: }); 102: } 103: 104: /** Named nodes of a model, for joints and markers. */ 105: export function nodes(root: THREE.Object3D): Map<string, THREE.Object3D> { 106: const out = new Map<string, THREE.Object3D>(); 107: root.traverse((o) => { 108: if (o.name) out.set(o.name, o); 109: }); 110: return out; 111: } 112: 113: /** glTF node names lose dots (three.js sanitises them to underscores); look up either form. */ 114: export function find(map: Map<string, THREE.Object3D>, name: string): THREE.Object3D | undefined { 115: return map.get(name) ?? map.get(name.replace(/\./g, '_')) ?? map.get(name.replace(/\./g, '')); 116: } 117: 118: /** 119: * Rigid parts that share a joint and a material become one mesh: a frame is ~150 parts but only a 120: * few dozen joint/material pairs, and every mesh is a draw call (twice, with shadows). 121: */ 122: function mergeParts(root: THREE.Object3D): THREE.Object3D { 123: const groups = new Map<THREE.Object3D, Map<THREE.Material, THREE.Mesh[]>>(); 124: root.traverse((o) => { 125: const m = o as THREE.Mesh; 126: if (!m.isMesh || m.children.length || !m.parent || Array.isArray(m.material)) return; 127: let byMat = groups.get(m.parent); 128: if (!byMat) groups.set(m.parent, (byMat = new Map())); 129: const list = byMat.get(m.material) ?? []; 130: list.push(m); 131: byMat.set(m.material, list); 132: }); 133: for (const [parent, byMat] of groups) { 134: for (const [mat, meshes] of byMat) { 135: if (meshes.length < 2) continue; 136: const geoms = meshes.map((m) => { 137: m.updateMatrix(); 138: const g = m.geometry.clone(); 139: for (const k of Object.keys(g.attributes)) if (k !== 'position' && k !== 'normal') g.deleteAttribute(k); 140: return g.applyMatrix4(m.matrix); 141: }); 142: const merged = mergeGeometries(geoms, false); 143: if (!merged) continue; 144: const mesh = new THREE.Mesh(merged, mat); 145: mesh.name = `${parent.name}:${mat.name}`; 146: mesh.userData = { ...meshes[0].userData }; 147: for (const m of meshes) m.removeFromParent(); 148: parent.add(mesh); 149: } 150: } 151: return root; 152: } 153: 154: /** tools/squeeze.mjs puts each mesh on a child node of this name, holding its dequantizing transform. */ 155: const QUANT_NODE = 'q__'; 156: 157: /** A float copy of a (possibly quantized) vec3 attribute, as unit vectors if `unit`. */ 158: function toFloat(a: THREE.BufferAttribute | THREE.InterleavedBufferAttribute, unit = false) { 159: const out = new THREE.Float32BufferAttribute(a.count * 3, 3); 160: for (let i = 0; i < a.count; i++) { 161: _v.fromBufferAttribute(a, i); 162: if (unit) _v.normalize(); 163: out.setXYZ(i, _v.x, _v.y, _v.z); 164: } 165: return out; 166: } 167: const _v = new THREE.Vector3(); 168: 169: /** 170: * Fold squeezed meshes back into the nodes the kit built: bake each quantized mesh's transform into 171: * float vertices and put the mesh where its node was, with the node's name, transform, extras and 172: * children. A plain GLB passes through untouched. 173: */ 174: function unquantize(root: THREE.Object3D): THREE.Object3D { 175: const found: THREE.Object3D[] = []; 176: root.traverse((o) => { 177: if (o.name.startsWith(QUANT_NODE)) found.push(o); 178: }); 179: // a mesh used by several nodes shares its geometry: each gets its own before any is baked 180: const seen = new Set<THREE.BufferGeometry>(); 181: for (const q of found) { 182: q.traverse((o) => { 183: const m = o as THREE.Mesh; 184: if (!m.isMesh) return; 185: if (seen.has(m.geometry)) m.geometry = m.geometry.clone(); 186: seen.add(m.geometry); 187: }); 188: } 189: const bake = (m: THREE.Mesh, matrix: THREE.Matrix4) => { 190: const g = m.geometry; 191: g.setAttribute('position', toFloat(g.attributes.position).applyMatrix4(matrix)); 192: if (g.attributes.normal) g.setAttribute('normal', toFloat(g.attributes.normal, true)); 193: g.boundingBox = null; 194: g.computeBoundingSphere(); 195: }; 196: for (const q of found) { 197: const node = q.parent!; 198: q.updateMatrix(); 199: if (!(q as THREE.Mesh).isMesh) { 200: // a mesh of several primitives: its parts go straight under the node 201: for (const c of [...q.children] as THREE.Mesh[]) { 202: c.updateMatrix(); 203: bake(c, q.matrix.clone().multiply(c.matrix)); 204: c.position.set(0, 0, 0); 205: c.quaternion.identity(); 206: c.scale.set(1, 1, 1); 207: node.add(c); 208: } 209: q.removeFromParent(); 210: continue; 211: } 212: // the mesh takes its node's place 213: const mesh = q as THREE.Mesh; 214: bake(mesh, mesh.matrix); 215: mesh.name = node.name; 216: mesh.userData = { ...mesh.userData, ...node.userData }; 217: mesh.position.copy(node.position); 218: mesh.quaternion.copy(node.quaternion); 219: mesh.scale.copy(node.scale); 220: mesh.visible = node.visible; 221: for (const c of [...node.children]) if (c !== mesh) mesh.add(c); 222: const parent = node.parent!; 223: parent.children[parent.children.indexOf(node)] = mesh; 224: mesh.parent = parent; 225: node.parent = null; 226: } 227: return root; 228: }read_file{"Path":"~/work/sortie/src/render/pipeline.ts"}
input
{ "Path": "~/work/sortie/src/render/pipeline.ts" }result, 259 lines
Showing lines 1-258 of 258 1: import * as THREE from 'three'; 2: import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js'; 3: import { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js'; 4: import { OutputPass } from 'three/addons/postprocessing/OutputPass.js'; 5: import { Pass } from 'three/addons/postprocessing/Pass.js'; 6: import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js'; 7: import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js'; 8: import { DetailShader, GradeShader, look, type Look } from './look'; 9: 10: /** Meshes on this layer get surface detail (edge wear, grime, ink); glows, effects and sky stay off it. */ 11: export const DETAIL_LAYER = 1; 12: 13: /** 14: * Rendering tiers. high: everything. medium: no multisampling, a smaller shadow map. low, for weak 15: * or software rendering: no multisampling, no shadows, no surface detail, bloom or grain, and at most 16: * 0.6 resolution. Multisampling the half-float buffers is by far the dearest part on a weak GPU. 17: */ 18: export type Tier = 'high' | 'medium' | 'low'; 19: export const TIERS: readonly Tier[] = ['high', 'medium', 'low']; 20: 21: export interface Quality { 22: /** Render resolution relative to CSS pixels (1 ignores high-DPI scaling). */ 23: scale: number; 24: ao: boolean; 25: shadows: boolean; 26: tier: Tier; 27: } 28: 29: export const DEFAULT_QUALITY: Quality = { scale: 1, ao: false, shadows: true, tier: 'high' }; 30: /** The low tier's resolution cap. */ 31: const LOW_SCALE = 0.6; 32: 33: /** Clamp before the bloom: one infinite or NaN pixel would otherwise blur over the whole frame. */ 34: const Sanitize = { 35: uniforms: { tDiffuse: { value: null } }, 36: vertexShader: 'varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }', 37: fragmentShader: ` 38: uniform sampler2D tDiffuse; varying vec2 vUv; 39: void main() { 40: vec4 c = texture2D(tDiffuse, vUv); 41: if (any(isnan(c)) || any(isinf(c))) c = vec4(0.0, 0.0, 0.0, 1.0); 42: gl_FragColor = vec4(min(c.rgb, vec3(48.0)), c.a); 43: }`, 44: }; 45: 46: /** 47: * Frame order: the backdrop at infinity (stars, nebula, planet), the world, ambient occlusion on the 48: * world, then the cockpit in its own pass (it sits centimetres from the eye, the world runs to tens 49: * of kilometres, so they don't share a depth range), then bloom and filmic tone mapping. 50: */ 51: class ScenePass extends Pass { 52: private bc = new THREE.PerspectiveCamera(60, 1, 1, 1e7); 53: 54: constructor( 55: public scene: THREE.Scene, 56: public camera: THREE.PerspectiveCamera, 57: public backdrop: THREE.Scene | null, 58: private clearFirst: boolean, 59: ) { 60: super(); 61: this.needsSwap = false; 62: } 63: 64: render(renderer: THREE.WebGLRenderer, _write: THREE.WebGLRenderTarget, read: THREE.WebGLRenderTarget) { 65: renderer.setRenderTarget(read); 66: if (this.clearFirst) { 67: renderer.setClearColor(0x000000, 1); 68: renderer.clear(); 69: } else renderer.clearDepth(); 70: if (this.backdrop) { 71: const bc = this.bc; 72: bc.fov = this.camera.fov; 73: bc.aspect = this.camera.aspect; 74: bc.updateProjectionMatrix(); 75: this.camera.getWorldQuaternion(bc.quaternion); 76: bc.updateMatrixWorld(); 77: renderer.render(this.backdrop, bc); 78: renderer.clearDepth(); 79: } 80: renderer.render(this.scene, this.camera); 81: } 82: } 83: 84: /** Size the composer's buffers for `w` x `h` CSS pixels at the renderer's pixel ratio. The composer 85: * keeps its own copy of the ratio from construction, so a tier change has to hand it the new one. */ 86: export function fitComposer(composer: Pick<EffectComposer, 'setPixelRatio' | 'setSize'>, w: number, h: number, pr: number) { 87: composer.setPixelRatio(pr); 88: composer.setSize(w, h); 89: } 90: 91: export class Pipeline { 92: readonly renderer: THREE.WebGLRenderer; 93: readonly composer: EffectComposer; 94: readonly bloom: UnrealBloomPass; 95: readonly ao: GTAOPass; 96: private detail: ShaderPass; 97: private grade: ShaderPass; 98: private sanitize: ShaderPass; 99: /** The look's own choice for the detail pass, before the tier. */ 100: private detailWanted = true; 101: private sun: THREE.DirectionalLight | null = null; 102: private normals: THREE.WebGLRenderTarget; 103: private normalMat = new THREE.MeshNormalMaterial(); 104: private world: ScenePass; 105: private overlay: ScenePass | null = null; 106: 107: quality: Quality; 108: 109: constructor(canvas: HTMLCanvasElement, world: THREE.Scene, camera: THREE.PerspectiveCamera, backdrop: THREE.Scene | null, 110: quality: Quality = DEFAULT_QUALITY) { 111: this.quality = { ...quality }; 112: const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance' }); 113: renderer.setPixelRatio(this.quality.scale); 114: renderer.toneMapping = THREE.AgXToneMapping; 115: renderer.toneMappingExposure = 1.15; 116: renderer.shadowMap.enabled = true; 117: renderer.shadowMap.type = THREE.PCFShadowMap; 118: renderer.autoClear = false; 119: this.renderer = renderer; 120: 121: const target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, samples: 4 }); 122: this.composer = new EffectComposer(renderer, target); 123: this.world = new ScenePass(world, camera, backdrop, true); 124: this.composer.addPass(this.world); 125: this.ao = new GTAOPass(world, camera, 1, 1); 126: this.ao.blendIntensity = 0.9; 127: this.ao.updateGtaoMaterial({ radius: 1.6, distanceExponent: 1.4, thickness: 2, scale: 1.2, samples: 8 }); 128: this.composer.addPass(this.ao); 129: this.normals = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType }); 130: this.normals.depthTexture = new THREE.DepthTexture(1, 1, THREE.FloatType); 131: this.detail = new ShaderPass(DetailShader); 132: this.detail.uniforms.tNormal.value = this.normals.texture; 133: this.detail.uniforms.tDepth.value = this.normals.depthTexture; 134: this.composer.addPass(this.detail); 135: this.sanitize = new ShaderPass(Sanitize); 136: this.composer.addPass(this.sanitize); 137: this.bloom = new UnrealBloomPass(new THREE.Vector2(256, 256), 0.32, 0.22, 1.6); 138: this.composer.addPass(this.bloom); 139: this.composer.addPass(new OutputPass()); 140: this.grade = new ShaderPass(GradeShader); 141: this.composer.addPass(this.grade); 142: this.applyLook(look()); 143: this.setQuality({}); 144: } 145: 146: /** The GPU the browser gave us, and whether it's a software rasteriser (very slow). */ 147: gpu(): { name: string; software: boolean } { 148: const gl = this.renderer.getContext(); 149: const ext = gl.getExtension('WEBGL_debug_renderer_info'); 150: const name = String(ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER)); 151: return { name, software: /swiftshader|llvmpipe|softpipe|software|basic render/i.test(name) }; 152: } 153: 154: setQuality(q: Partial<Quality>) { 155: Object.assign(this.quality, q); 156: const { tier } = this.quality; 157: const low = tier === 'low'; 158: this.renderer.setPixelRatio(low ? Math.min(LOW_SCALE, this.quality.scale) : this.quality.scale); 159: this.ao.enabled = this.quality.ao && !low; 160: this.renderer.shadowMap.enabled = this.quality.shadows && !low; 161: const samples = tier === 'high' ? 4 : 0; 162: for (const t of [this.composer.renderTarget1, this.composer.renderTarget2]) { 163: if (t.samples === samples) continue; 164: t.samples = samples; 165: t.dispose(); 166: } 167: this.detail.enabled = this.detailWanted && !low; 168: this.bloom.enabled = this.sanitize.enabled = this.grade.enabled = !low; 169: this.shadowSize(); 170: this.resize(); 171: } 172: 173: /** The sun whose shadow map follows the tier. */ 174: set shadowLight(sun: THREE.DirectionalLight) { 175: this.sun = sun; 176: this.shadowSize(); 177: } 178: 179: private shadowSize() { 180: const s = this.quality.tier === 'high' ? 2048 : 1024; 181: const sh = this.sun?.shadow; 182: if (!sh || sh.mapSize.x === s) return; 183: sh.mapSize.set(s, s); 184: sh.map?.dispose(); 185: sh.map = null; 186: } 187: 188: applyLook(l: Look) { 189: const u = this.detail.uniforms; 190: u.ridgeK.value = l.ridge; 191: u.valleyK.value = l.valley; 192: u.inkK.value = l.ink; 193: u.chipped.value = l.chipped ? 1 : 0; 194: u.hatch.value = l.hatch ?? 0; 195: this.grade.uniforms.paper.value = l.paper ?? 0; 196: this.detailWanted = l.ridge + l.valley + l.ink > 0; 197: this.detail.enabled = this.detailWanted && this.quality?.tier !== 'low'; 198: this.grade.uniforms.grain.value = l.grain; 199: this.grade.uniforms.vignette.value = l.vignette; 200: } 201: 202: /** A scene drawn over the world with its own depth range (the cockpit), after the world's detail pass. */ 203: setOverlay(scene: THREE.Scene, camera: THREE.PerspectiveCamera) { 204: this.overlay = new ScenePass(scene, camera, null, false); 205: this.composer.insertPass(this.overlay, this.composer.passes.indexOf(this.detail) + 1); 206: this.resize(); 207: } 208: 209: set backdrop(scene: THREE.Scene | null) { 210: this.world.backdrop = scene; 211: } 212: 213: set overlayVisible(v: boolean) { 214: if (this.overlay) this.overlay.enabled = v; 215: } 216: 217: get camera() { 218: return this.world.camera; 219: } 220: 221: resize(w = window.innerWidth, h = window.innerHeight) { 222: this.renderer.setSize(w, h, false); 223: const pr = this.renderer.getPixelRatio(); 224: fitComposer(this.composer, w, h, pr); 225: this.normals?.setSize(Math.round(w * pr), Math.round(h * pr)); 226: this.detail?.uniforms.px.value.set(1 / (w * pr), 1 / (h * pr)); 227: for (const c of [this.world.camera, this.overlay?.camera]) { 228: if (!c) continue; 229: c.aspect = w / h; 230: c.updateProjectionMatrix(); 231: } 232: } 233: 234: render() { 235: if (this.detail.enabled) { 236: // normals and depth of detailed meshes only, for the detail pass 237: const { renderer } = this; 238: const scene = this.world.scene, camera = this.world.camera; 239: camera.layers.set(DETAIL_LAYER); 240: const bg = scene.background; 241: scene.background = null; 242: scene.overrideMaterial = this.normalMat; 243: renderer.setRenderTarget(this.normals); 244: renderer.setClearColor(0x000000, 0); 245: renderer.clear(); 246: renderer.render(scene, camera); 247: scene.overrideMaterial = null; 248: scene.background = bg; 249: camera.layers.set(0); 250: this.detail.uniforms.near.value = camera.near; 251: this.detail.uniforms.far.value = camera.far; 252: this.detail.uniforms.projInv.value.copy(camera.projectionMatrixInverse); 253: this.detail.uniforms.viewInv.value.copy(camera.matrixWorld); 254: } 255: this.grade.uniforms.time.value = (performance.now() % 10000) / 1000; 256: this.composer.render(); 257: } 258: }read_file{"Path":"~/work/sortie/src/render/decals.ts"}
input
{ "Path": "~/work/sortie/src/render/decals.ts" }result, 139 lines
Showing lines 1-138 of 138 1: import * as THREE from 'three'; 2: import { DecalGeometry } from 'three/addons/geometries/DecalGeometry.js'; 3: 4: // Markings projected onto armour: unit numbers, designations, caution stencils, hazard bands and the 5: // company emblem. Each decal is found by casting a ray at the rest pose, projected onto the mesh it 6: // hits, and parented to that mesh so it moves with its joint. 7: 8: export type DecalKind = 'number' | 'stencil' | 'hazard' | 'emblem'; 9: 10: export interface DecalSpec { 11: kind: DecalKind; 12: text?: string; 13: /** A point just off the surface, model space (three.js axes: +X the frame's left, +Z forward). */ 14: at: [number, number, number]; 15: /** Direction into the surface. */ 16: dir: [number, number, number]; 17: /** Width and height in metres. */ 18: size: [number, number]; 19: /** Roll around the surface normal, degrees. */ 20: roll?: number; 21: color?: string; 22: } 23: 24: const textures = new Map<string, THREE.CanvasTexture>(); 25: 26: function texture(spec: DecalSpec): THREE.CanvasTexture { 27: const key = `${spec.kind}:${spec.text ?? ''}:${spec.color ?? ''}:${spec.size.join('x')}`; 28: const hit = textures.get(key); 29: if (hit) return hit; 30: const W = 512, H = Math.max(32, Math.round((512 * spec.size[1]) / spec.size[0])); 31: const c = document.createElement('canvas'); 32: c.width = W; 33: c.height = H; 34: const g = c.getContext('2d')!; 35: const ink = spec.color ?? '#20242a'; 36: g.fillStyle = ink; 37: g.strokeStyle = ink; 38: g.textAlign = 'center'; 39: g.textBaseline = 'middle'; 40: if (spec.kind === 'hazard') { 41: g.fillStyle = '#e2b42a'; 42: g.fillRect(0, 0, W, H); 43: g.fillStyle = '#15171a'; 44: for (let x = -H; x < W + H; x += H * 1.4) { 45: g.beginPath(); 46: g.moveTo(x, H); g.lineTo(x + H * 0.7, H); g.lineTo(x + H * 1.4, 0); g.lineTo(x + H * 0.7, 0); 47: g.fill(); 48: } 49: } else if (spec.kind === 'emblem') { 50: const r = Math.min(W, H) * 0.42; 51: g.lineWidth = r * 0.12; 52: g.beginPath(); 53: g.arc(W / 2, H / 2, r, 0, Math.PI * 2); 54: g.stroke(); 55: g.beginPath(); 56: g.moveTo(W / 2 - r * 0.55, H / 2 - r * 0.25); 57: g.lineTo(W / 2, H / 2 + r * 0.45); 58: g.lineTo(W / 2 + r * 0.55, H / 2 - r * 0.25); 59: g.lineTo(W / 2 + r * 0.3, H / 2 - r * 0.25); 60: g.lineTo(W / 2, H / 2 + r * 0.05); 61: g.lineTo(W / 2 - r * 0.3, H / 2 - r * 0.25); 62: g.closePath(); 63: g.fill(); 64: } else { 65: const size = spec.kind === 'number' ? H * 0.92 : H * 0.62; 66: g.font = `600 ${size}px "Chakra Petch", "Arial Narrow", sans-serif`; 67: g.fillText(spec.text ?? '', W / 2, H / 2 + size * 0.04, W * 0.96); 68: if (spec.kind === 'stencil') { 69: // stencil bridges: thin vertical breaks through the letters 70: g.globalCompositeOperation = 'destination-out'; 71: for (let x = W * 0.08; x < W; x += W / Math.max(4, (spec.text ?? '').length)) g.fillRect(x, 0, W * 0.006, H); 72: g.globalCompositeOperation = 'source-over'; 73: } 74: } 75: // wear: knock speckles out of the paint 76: g.globalCompositeOperation = 'destination-out'; 77: let s = key.length * 9973; 78: const rnd = () => ((s = (s * 16807) % 2147483647) / 2147483647); 79: for (let i = 0; i < (W * H) / 900; i++) { 80: g.globalAlpha = 0.3 + rnd() * 0.7; 81: g.fillRect(rnd() * W, rnd() * H, 1 + rnd() * 3, 1 + rnd() * 2); 82: } 83: g.globalAlpha = 1; 84: g.globalCompositeOperation = 'source-over'; 85: const t = new THREE.CanvasTexture(c); 86: t.colorSpace = THREE.SRGBColorSpace; 87: t.anisotropy = 8; 88: textures.set(key, t); 89: return t; 90: } 91: 92: const ray = new THREE.Raycaster(); 93: const helper = new THREE.Object3D(); 94: 95: export function applyDecals(root: THREE.Object3D, specs: DecalSpec[]) { 96: root.updateMatrixWorld(true); 97: const meshes: THREE.Mesh[] = []; 98: root.traverse((o) => { 99: const m = o as THREE.Mesh; 100: if (m.isMesh && !(m.material as THREE.MeshBasicMaterial).isMeshBasicMaterial && !m.userData.decal) meshes.push(m); 101: }); 102: for (const spec of specs) { 103: const dir = new THREE.Vector3(...spec.dir).normalize(); 104: const at = new THREE.Vector3(...spec.at).applyMatrix4(root.matrixWorld); 105: ray.set(at.clone().addScaledVector(dir, -3), dir.clone().transformDirection(root.matrixWorld)); 106: const hit = ray.intersectObjects(meshes, false)[0]; 107: if (!hit?.face) continue; 108: const mesh = hit.object as THREE.Mesh; 109: const normal = hit.face.normal.clone().transformDirection(mesh.matrixWorld); 110: helper.position.copy(hit.point); 111: helper.lookAt(hit.point.clone().add(normal)); 112: helper.rotateZ(THREE.MathUtils.degToRad(spec.roll ?? 0)); 113: const geo = new DecalGeometry(mesh, hit.point, helper.rotation, new THREE.Vector3(spec.size[0], spec.size[1], 0.6)); 114: geo.applyMatrix4(mesh.matrixWorld.clone().invert()); 115: const mat = new THREE.MeshStandardMaterial({ 116: map: texture(spec), transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -4, 117: roughness: 0.55, metalness: 0, 118: }); 119: const decal = new THREE.Mesh(geo, mat); 120: decal.userData.decal = true; 121: decal.receiveShadow = true; 122: mesh.add(decal); 123: } 124: } 125: 126: /** The striker's markings: unit number on the shoulders and leg, designation, stencils, hazard bands. */ 127: export const STRIKER_DECALS: DecalSpec[] = [ 128: { kind: 'number', text: '07', at: [4.8, 15.15, 0], dir: [-1, 0, 0], size: [0.95, 0.7], color: '#e9edf0' }, 129: { kind: 'emblem', at: [-4.8, 15.15, 0], dir: [1, 0, 0], size: [0.8, 0.8], color: '#e9edf0' }, 130: { kind: 'number', text: '07', at: [2.6, 3.6, 0.15], dir: [-1, 0, 0], size: [0.55, 0.42], color: '#e9edf0' }, 131: { kind: 'stencil', text: 'MF-07', at: [1.15, 9.25, 3], dir: [0, 0, -1], size: [0.7, 0.2] }, 132: { kind: 'stencil', text: 'NO STEP', at: [1.3, 10.05, 3], dir: [0, 0, -1], size: [0.6, 0.15], roll: -20 }, 133: { kind: 'stencil', text: 'NO STEP', at: [-1.3, 10.05, 3], dir: [0, 0, -1], size: [0.6, 0.15], roll: 20 }, 134: { kind: 'hazard', at: [1.2, 6.55, 3], dir: [0, 0, -1], size: [0.6, 0.12] }, 135: { kind: 'hazard', at: [-1.2, 6.55, 3], dir: [0, 0, -1], size: [0.6, 0.12] }, 136: { kind: 'stencil', text: 'DANGER EXHAUST', at: [0, 12.9, -4], dir: [0, 0, 1], size: [1.1, 0.16] }, 137: { kind: 'stencil', text: 'STRIKER', at: [-2.6, 3.4, 0.15], dir: [1, 0, 0], size: [0.9, 0.2], roll: 90, color: '#e9edf0' }, 138: ];read_file{"Path":"~/work/sortie/src/render/ship.ts"}
input
{ "Path": "~/work/sortie/src/render/ship.ts" }result, 120 lines
Showing lines 1-119 of 119 1: import * as THREE from 'three'; 2: import { signal, LAUNCH, type LaunchState } from '../sim/launch'; 3: import type { FrameClassId } from '../sim/frames'; 4: import { find, model, nodes } from './assets'; 5: 6: const CLASSES: FrameClassId[] = ['light', 'standard', 'heavy']; 7: /** Node name suffix per class in kit/ship.py. */ 8: const TAG: Record<FrameClassId, string> = { light: 'light', standard: 'std', heavy: 'heavy' }; 9: 10: /** Where frames of each class stand in a bay, and its work platform heights (ship space). */ 11: export interface BaySlots { 12: light: THREE.Vector3[]; 13: standard: THREE.Vector3[]; 14: heavy: THREE.Vector3[]; 15: platforms: Record<FrameClassId, number[]>; 16: } 17: 18: /** 19: * Show one gantry fit per bay and the shuttle clamps for the frame riding it (kit/ship.py). Light 20: * frames ride a sled on top of the striker clamps, heavies swap them for their own set. 21: */ 22: export function fitShip(root: THREE.Object3D, bays: readonly FrameClassId[], frame: FrameClassId) { 23: const map = nodes(root); 24: for (const [i, fit] of bays.entries()) { 25: for (const c of CLASSES) { 26: const g = find(map, `gantry.${i + 1}.${TAG[c]}`); 27: if (g) g.visible = c === fit; 28: } 29: } 30: for (const c of CLASSES) { 31: const g = find(map, `clamps.${TAG[c]}`); 32: if (g) g.visible = c === frame || (c === 'standard' && frame === 'light'); 33: } 34: } 35: 36: /** The ship model with its moving parts driven by the launch state. */ 37: export class ShipRig { 38: readonly root: THREE.Object3D; 39: private doors: { node: THREE.Object3D; slide: THREE.Vector3; base: THREE.Vector3 }[] = []; 40: private shuttle: THREE.Object3D | null; 41: private shuttleBase = new THREE.Vector3(); 42: private lamps: Record<'red' | 'green', THREE.Object3D | undefined>; 43: readonly start = new THREE.Vector3(); 44: readonly bays: THREE.Vector3[] = []; 45: /** Standing points per bay and class. */ 46: readonly slots: BaySlots[] = []; 47: private starts: Partial<Record<FrameClassId, THREE.Vector3>> = {}; 48: /** The hangar and tube lights. */ 49: readonly lights: THREE.PointLight[] = []; 50: 51: private constructor(root: THREE.Object3D) { 52: this.root = root; 53: const map = nodes(root); 54: root.updateMatrixWorld(true); 55: for (const s of ['L', 'R']) { 56: const n = find(map, `door.${s}`); 57: if (n) this.doors.push({ node: n, slide: new THREE.Vector3(...(n.userData.slide as [number, number, number])), base: n.position.clone() }); 58: } 59: this.shuttle = find(map, 'shuttle') ?? null; 60: if (this.shuttle) this.shuttleBase.copy(this.shuttle.position); 61: this.lamps = { red: find(map, 'signal.red'), green: find(map, 'signal.green') }; 62: find(map, 'launch.start')?.getWorldPosition(this.start); 63: const at = (name: string) => find(map, name)?.getWorldPosition(new THREE.Vector3()); 64: for (const c of CLASSES) { 65: const p = at(`launch.start.${TAG[c]}`); 66: if (p) this.starts[c] = p; 67: } 68: for (const b of ['bay.1', 'bay.2']) { 69: const n = find(map, b); 70: if (!n) continue; 71: this.bays.push(n.getWorldPosition(new THREE.Vector3())); 72: const slot: BaySlots = { light: [], standard: [], heavy: [], platforms: { light: [], standard: [], heavy: [] } }; 73: for (const name of [`${b}.light.a`, `${b}.light.b`, `${b}.std`, `${b}.heavy`]) { 74: const m = find(map, name); 75: if (!m) continue; 76: const c = m.userData.cls as FrameClassId; 77: slot[c].push(m.getWorldPosition(new THREE.Vector3())); 78: slot.platforms[c] = (m.userData.platforms as number[]) ?? []; 79: } 80: this.slots.push(slot); 81: } 82: fitShip(root, ['standard', 'standard'], 'standard'); 83: // Hangar and tube lights from the kit's markers. 84: root.traverse((o) => { 85: if (!/^light/.test(o.name) || !o.userData.color) return; 86: const [r, g, b] = o.userData.color as number[]; 87: const l = new THREE.PointLight(new THREE.Color(r, g, b), 320 * (o.userData.power ?? 1), 0, 2); 88: o.add(l); 89: this.lights.push(l); 90: }); 91: } 92: 93: /** Fit the bays (one class per bay) and the shuttle clamps for the frame riding it. */ 94: configure(bays: readonly FrameClassId[], frame: FrameClassId) { 95: fitShip(this.root, bays, frame); 96: } 97: 98: /** Where a frame of this class stands on the shuttle: on the light sled, on the clamps otherwise. */ 99: startFor(c: FrameClassId): THREE.Vector3 { 100: return this.starts[c] ?? this.start; 101: } 102: 103: static async load(): Promise<ShipRig> { 104: return new ShipRig(await model('ship')); 105: } 106: 107: update(s: LaunchState) { 108: const open = THREE.MathUtils.smoothstep(s.door, 0, 1); 109: for (const d of this.doors) d.node.position.copy(d.base).addScaledVector(d.slide, open * 10.5); 110: if (this.shuttle) { 111: // the shuttle runs with the mech, then brakes to a stop at the end of the tube 112: const travel = s.phase === 'released' ? LAUNCH.length : s.shuttle; 113: this.shuttle.position.copy(this.shuttleBase).add(new THREE.Vector3(0, 0, travel)); 114: } 115: const sig = signal(s, LAUNCH); 116: if (this.lamps.red) this.lamps.red.visible = sig === 'red' || sig === 'amber'; 117: if (this.lamps.green) this.lamps.green.visible = sig === 'green' || sig === 'amber'; 118: } 119: }read_file{"Path":"~/work/sortie/src/view/clip-plan.ts"}
input
{ "Path": "~/work/sortie/src/view/clip-plan.ts" }result, 105 lines
Showing lines 1-104 of 104 1: import type { Pose } from '../render/mech'; 2: import type { BenchState } from './thrusters'; 3: 4: /** 5: * The timeline of a review clip (src/view/clip.ts), as a pure function of frame number, so a clip is the 6: * same every run whatever the machine's speed. Shots frame the model and nothing here is a design choice: 7: * the chase shot sits where the game's camera sits, the rest show it from all round, bending and to scale. 8: */ 9: export const SHOTS = { chase: 3.5, orbit: 3, turn: 4, bend: 3, scale: 2.5 } as const; 10: export type ShotName = keyof typeof SHOTS; 11: export const SHOT_NAMES = Object.keys(SHOTS) as ShotName[]; 12: 13: /** Thruster states through a shot: [start second, state]. */ 14: const SCHEDULE: Partial<Record<ShotName, [number, BenchState][]>> = { 15: chase: [[0, 'cruise'], [1, 'boost'], [2.4, 'quick'], [3, 'cruise']], 16: orbit: [[0, 'boost'], [1.4, 'brake'], [2.2, 'idle']], 17: }; 18: 19: export interface ClipFrame { 20: shot: ShotName; 21: /** Seconds into the shot, and the same as a 0..1 fraction. */ 22: t: number; 23: u: number; 24: state: BenchState; 25: /** Seconds since this thruster state began. */ 26: stateT: number; 27: /** First frame of a shot: everything snaps. */ 28: cut: boolean; 29: } 30: 31: export function clipFrames(shots: readonly ShotName[], fps: number): ClipFrame[] { 32: const out: ClipFrame[] = []; 33: for (const shot of shots) { 34: const n = Math.max(1, Math.round(SHOTS[shot] * fps)); 35: const plan = SCHEDULE[shot] ?? [[0, 'idle'] as [number, BenchState]]; 36: for (let i = 0; i < n; i++) { 37: const t = i / fps; 38: let at = plan[0]; 39: for (const p of plan) if (p[0] <= t + 1e-9) at = p; 40: out.push({ shot, t, u: n > 1 ? i / (n - 1) : 0, state: at[1], stateT: t - at[0], cut: i === 0 }); 41: } 42: } 43: return out; 44: } 45: 46: /** Where things are in a shot. Lengths are in frame heights, angles in degrees. Yaw 0 looks at the 47: * frame's front, 180 at its back. `chase` means the game's chase camera, turned by mechYaw. */ 48: export interface ShotView { 49: chase: boolean; 50: mechYaw: number; 51: camYaw: number; 52: pitch: number; 53: dist: number; 54: /** Look point height as a fraction of the frame's height. */ 55: lookAt: number; 56: pose: 'flight' | 'stand'; 57: /** How far toward BEND_POSE, 0..1. */ 58: bend: number; 59: /** The pilot and the deck are in shot. */ 60: ground: boolean; 61: } 62: 63: const ease = (x: number) => x * x * (3 - 2 * x); 64: 65: export function shotView(f: ClipFrame): ShotView { 66: const base = { chase: false, mechYaw: 0, camYaw: 0, pitch: 8, dist: 2.4, lookAt: 0.5, pose: 'stand', bend: 0, ground: false } as ShotView; 67: switch (f.shot) { 68: case 'chase': { 69: // a gentle turn and back: the camera trails the frame, so the stars pan and the frame leans in shot 70: const turn = Math.sin(f.u * Math.PI * 2) * 22; 71: return { ...base, chase: true, mechYaw: turn, camYaw: turn * 0.75, pose: 'flight' }; 72: } 73: case 'orbit': 74: return { ...base, camYaw: 165 - 75 * ease(f.u), pitch: 12, dist: 2.2, pose: 'flight' }; 75: case 'turn': 76: return { ...base, camYaw: 180 + 360 * f.u }; 77: case 'bend': 78: return { ...base, camYaw: 35, pitch: 6, bend: Math.sin(f.u * Math.PI) ** 2 }; 79: case 'scale': 80: // from the deck beside the pilot, looking up at the frame, pushing in slowly 81: return { ...base, camYaw: 28, pitch: -6 + 2 * f.u, dist: 2.25 - 0.15 * ease(f.u), lookAt: 0.42, ground: true }; 82: } 83: } 84: 85: /** A deliberately large range of motion, to find plates that collide or joints that show. Glances at 86: * every limb: one arm up and forward, the other out, one knee high, a twist. */ 87: export const BEND_POSE: Pose = { 88: torso: [12, 18, 0], head: [-8, -24, 0], 89: 'upperarm.L': [-115, 0, 22], 'forearm.L': [-80, 0, 0], 90: 'upperarm.R': [-20, 0, -72], 'forearm.R': [-100, 0, 0], 91: 'thigh.L': [-85, 0, 10], 'shin.L': [100, 0, 0], 'foot.L': [-22, 0, 0], 92: 'thigh.R': [-8, 0, -14], 'shin.R': [22, 0, 0], 'foot.R': [8, 0, 0], 93: 'binder.L': [-20, 0, 0], 'binder.R': [20, 0, 0], 94: }; 95: 96: /** A blend of two poses, joint by joint. */ 97: export function mixPose(a: Pose, b: Pose, w: number): Pose { 98: const out: Pose = {}; 99: for (const j of new Set([...Object.keys(a), ...Object.keys(b)]) as Set<keyof Pose>) { 100: const p = a[j] ?? [0, 0, 0], q = b[j] ?? [0, 0, 0]; 101: out[j] = [p[0] + (q[0] - p[0]) * w, p[1] + (q[1] - p[1]) * w, p[2] + (q[2] - p[2]) * w]; 102: } 103: return out; 104: }