A mech game prototype, pushed by Gemini 4 Argon
agent (cont.)
+0:34read_file{"Path":"~/work/sortie/tools/outlines-lib.mjs"}
input
{ "Path": "~/work/sortie/tools/outlines-lib.mjs" }result, 91 lines
Showing lines 1-90 of 90 1: // Outline sheets: rough black shapes at one scale, for reacting to in seconds (docs/handbook.md). 2: // A spec is plain data, in metres, x across, z up, ground at z = 0, centre line at x = 0: 3: // { "title": "round 1", "outlines": [ { "note": "optional", "parts": [ 4: // { "pts": [[x, z], ...], "mirror": true }, a polygon, and its mirror across x = 0 5: // { "circle": [x, z, r], "mirror": true } ], a circle 6: // "side": [ ... same parts ... ] } ] } optional side view, drawn beside the front 7: const PILOT_M = 1.75; 8: 9: function bounds(parts) { 10: let x = 0, z = 0; 11: for (const p of parts ?? []) { 12: if (p.circle) { 13: x = Math.max(x, Math.abs(p.circle[0]) + p.circle[2]); 14: z = Math.max(z, p.circle[1] + p.circle[2]); 15: } else for (const [px, pz] of p.pts) { 16: x = Math.max(x, Math.abs(px)); 17: z = Math.max(z, pz); 18: } 19: } 20: return { halfWidth: x, height: z }; 21: } 22: 23: function shape(p, tx, ty, s, flip) { 24: const sign = flip ? -1 : 1; 25: if (p.circle) { 26: const [x, z, r] = p.circle; 27: return `<circle cx="${(tx + sign * x * s).toFixed(1)}" cy="${(ty - z * s).toFixed(1)}" r="${(r * s).toFixed(1)}"/>`; 28: } 29: const pts = p.pts.map(([x, z]) => `${(tx + sign * x * s).toFixed(1)},${(ty - z * s).toFixed(1)}`).join(' '); 30: return `<polygon points="${pts}"/>`; 31: } 32: 33: function shapes(parts, tx, ty, s) { 34: const out = []; 35: for (const p of parts ?? []) { 36: out.push(shape(p, tx, ty, s, false)); 37: if (p.mirror) out.push(shape(p, tx, ty, s, true)); 38: } 39: return out.join(''); 40: } 41: 42: /** A person for scale: plain enough not to read as part of any design. */ 43: function person(x, ground, s) { 44: const h = PILOT_M * s, w = Math.max(h * 0.28, 2); 45: return `<g fill="#b03a2e"><rect x="${(x - w / 2).toFixed(1)}" y="${(ground - h * 0.82).toFixed(1)}" width="${w.toFixed(1)}" height="${(h * 0.82).toFixed(1)}"/>` + 46: `<circle cx="${x.toFixed(1)}" cy="${(ground - h * 0.9).toFixed(1)}" r="${(h * 0.1).toFixed(1)}"/></g>`; 47: } 48: 49: /** The sheet as an SVG string, with its pixel size. Every outline is drawn at the same scale. */ 50: export function outlineSheet(spec, { cols = 6, tileHeight = 460 } = {}) { 51: const list = spec.outlines ?? []; 52: if (!list.length) throw new Error('outlines: the spec has no outlines'); 53: let tall = 0, front = 0, side = 0; 54: for (const o of list) { 55: const f = bounds(o.parts), b = bounds(o.side); 56: tall = Math.max(tall, f.height, b.height); 57: front = Math.max(front, f.halfWidth); 58: side = Math.max(side, b.halfWidth); 59: } 60: if (tall <= 0 || front <= 0) throw new Error('outlines: nothing has any size'); 61: const margin = { top: 34, bottom: 18, gap: 16 }; 62: const s = (tileHeight - margin.top - margin.bottom) / tall; 63: const frontW = front * 2 * s, sideW = side * 2 * s; 64: const tileW = Math.ceil(frontW + (side ? sideW + margin.gap : 0) + margin.gap * 2 + 14); 65: const rows = Math.ceil(list.length / cols); 66: const head = spec.title ? 34 : 0; 67: const W = Math.min(cols, list.length) * tileW, H = rows * tileHeight + head; 68: const tiles = list.map((o, i) => { 69: const x0 = (i % cols) * tileW, y0 = Math.floor(i / cols) * tileHeight + head; 70: const ground = y0 + tileHeight - margin.bottom; 71: const fx = x0 + margin.gap + frontW / 2; 72: const sx = fx + frontW / 2 + margin.gap + sideW / 2; 73: const px = x0 + tileW - 9; 74: return `<rect x="${x0 + .5}" y="${y0 + .5}" width="${tileW - 1}" height="${tileHeight - 1}" fill="none" stroke="#d6d6d2"/>` + 75: `<line x1="${x0 + 6}" x2="${x0 + tileW - 6}" y1="${ground}" y2="${ground}" stroke="#a9a9a4"/>` + 76: `<text x="${x0 + 8}" y="${y0 + 22}" class="n">${i + 1}</text>` + 77: (o.note ? `<text x="${x0 + 38}" y="${y0 + 22}" class="t">${escapeXml(o.note)}</text>` : '') + 78: `<g fill="#111" stroke="#111" stroke-width=".8">${shapes(o.parts, fx, ground, s)}${o.side ? shapes(o.side, sx, ground, s) : ''}</g>` + 79: person(px, ground, s); 80: }).join(''); 81: const title = spec.title ? `<text x="8" y="23" class="h">${escapeXml(spec.title)}</text>` : ''; 82: const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">` + 83: `<style>text{font-family:system-ui,sans-serif;fill:#333}.n{font-size:18px;font-weight:700}.t{font-size:12px}.h{font-size:16px;font-weight:600}</style>` + 84: `<rect width="${W}" height="${H}" fill="#f4f4f1"/>${title}${tiles}</svg>`; 85: return { svg, width: W, height: H, count: list.length, scale: s }; 86: } 87: 88: function escapeXml(t) { 89: return String(t).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]); 90: }read_file{"Path":"~/work/sortie/tools/clip.mjs"}
input
{ "Path": "~/work/sortie/tools/clip.mjs" }result, 69 lines
Showing lines 1-68 of 68 1: // A review clip of one model: chase camera, orbit, turntable, range of motion, next to a pilot. 2: // node tools/clip.mjs <model> [--quick] [--shots chase,turn] [--fps 24] [--size 854x480] [--palette merc] [--look kit] [--out file.mp4] 3: // --quick is for the loop: chase and turntable only, 12 fps, 640x360. 4: // Starts its own dev server on a free port and always stops it. Frames are rendered one at a time, so 5: // the clip is smooth however slow the machine (src/view/clip.ts). Writes the mp4 and, because a reader 6: // that can't watch video still has to judge it, a contact sheet of frames beside it. Headless only. 7: import { spawn, spawnSync } from 'node:child_process'; 8: import { mkdirSync } from 'node:fs'; 9: import { dirname, resolve } from 'node:path'; 10: import { chromium } from 'playwright'; 11: import { createServer } from 'vite'; 12: 13: const args = process.argv.slice(2); 14: const flag = (name, fallback) => { 15: const i = args.indexOf(`--${name}`); 16: return i >= 0 ? args[i + 1] : fallback; 17: }; 18: const name = args[0]; 19: if (!name || name.startsWith('--')) { 20: console.error('usage: node tools/clip.mjs <model> [--quick] [--shots chase,orbit,turn,bend,scale] [--fps 24] [--size 854x480] [--palette merc] [--look kit] [--out file.mp4]'); 21: process.exit(2); 22: } 23: const quick = args.includes('--quick'); 24: const [w, h] = flag('size', quick ? '640x360' : '854x480').split('x').map(Number); 25: const fps = Number(flag('fps', quick ? 12 : 24)); 26: const out = resolve(flag('out', `review/out/one-mech/clips/${name}.mp4`)); 27: const params = new URLSearchParams({ view: 'clip', model: name, w, h, fps, palette: flag('palette', 'merc') }); 28: for (const k of ['shots', 'look']) if (flag(k)) params.set(k, flag(k)); 29: if (quick && !flag('shots')) params.set('shots', 'chase,turn'); 30: mkdirSync(dirname(out), { recursive: true }); 31: 32: const started = Date.now(); 33: const server = await createServer({ server: { host: '127.0.0.1', port: 5230, strictPort: false }, logLevel: 'error' }); 34: await server.listen(); 35: const browser = await chromium.launch({ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] }); 36: let failed = false; 37: try { 38: const page = await browser.newPage({ viewport: { width: w, height: h } }); 39: page.setDefaultTimeout(300000); 40: page.on('pageerror', (e) => { failed = true; console.error('[pageerror]', e.message); }); 41: page.on('console', (m) => { if (m.type() === 'error') console.error('[console]', m.text().slice(0, 300)); }); 42: await page.goto(`${server.resolvedUrls.local[0]}?${params}`); 43: await page.waitForFunction(() => window.__ready === true); 44: const frames = await page.evaluate(() => window.__clip.frames); 45: const loaded = Date.now(); 46: const ffmpeg = spawn('ffmpeg', ['-loglevel', 'error', '-y', '-f', 'image2pipe', '-c:v', 'mjpeg', '-framerate', String(fps), '-i', '-', 47: '-c:v', 'libx264', '-crf', '20', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', out], { stdio: ['pipe', 'inherit', 'inherit'] }); 48: const ended = new Promise((ok) => ffmpeg.on('close', ok)); 49: for (let i = 0; i < frames; i++) { 50: const url = await page.evaluate((n) => window.__clip.render(n), i); 51: const jpeg = Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'); 52: if (!ffmpeg.stdin.write(jpeg)) await new Promise((ok) => ffmpeg.stdin.once('drain', ok)); 53: } 54: ffmpeg.stdin.end(); 55: const code = await ended; 56: if (code !== 0) throw new Error(`ffmpeg exited ${code}`); 57: const every = Math.max(1, Math.floor(frames / 12)); 58: const sheet = out.replace(/\.mp4$/, '.sheet.jpg'); 59: spawnSync('ffmpeg', ['-loglevel', 'error', '-y', '-i', out, '-vf', `select=not(mod(n\\,${every})),scale=480:-1,tile=4x3`, '-frames:v', '1', '-q:v', '4', sheet], { stdio: 'inherit' }); 60: const secs = (Date.now() - started) / 1000; 61: console.log(`clip: ${out}`); 62: console.log(`clip: ${sheet}`); 63: console.log(`clip: ${frames} frames, ${(frames / fps).toFixed(1)} s of video, ${secs.toFixed(0)} s to make (${((Date.now() - loaded) / frames).toFixed(0)} ms a frame)`); 64: } finally { 65: await browser.close(); 66: await server.close(); 67: } 68: process.exit(failed ? 1 : 0);read_file{"Path":"~/work/sortie/kit/block.py"}
input
{ "Path": "~/work/sortie/kit/block.py" }result, 113 lines
Showing lines 1-112 of 112 1: """Block models: plain boxes on the 22 joint rig, for judging mass and motion before any plate exists. 2: 3: A block model is one file, kit/blocks/<name>.py, with a build() that takes this module's Blocks class. 4: It builds in seconds, into a gitignored public/assets/block_<name>.glb: 5: 6: npm run kit -- block_dummy 7: npm run clip -- block_dummy 8: 9: Geometry is authored in world rest pose coordinates in metres, models facing -Y, Z up, left is +X, as 10: in the rest of the kit. Roles are the usual ones (main, accent, frame, joint). Nothing here is a design 11: rule: no maker, frame or grade carries over unless a block file asks for it. 12: """ 13: import importlib 14: 15: import bpy 16: from mathutils import Vector 17: 18: from lib import loft, merge, mirror_x, octo, solid 19: from mech import joints as striker_joints, nozzle_pair, pair 20: 21: SIDED = {"shoulder", "upperarm", "forearm", "hand", "grip", "thigh", "shin", "foot", "binder"} 22: BEVEL = .03 23: 24: 25: class Blocks: 26: """The rig plus block primitives. `joints` overrides rest positions: {"thigh": (1.1, 0, 9.5)} moves 27: both thighs (give the left, +X, the right mirrors), {"pelvis": (0, 0, 9.8)} moves one node. Other 28: joints stay where the striker has them, in world coordinates, so moving one moves nothing else.""" 29: 30: def __init__(self, joints=None, height=17.6): 31: J = striker_joints() 32: self.nodes = {o.name: o for o in J.values()} 33: self.n = 0 34: J["frame"]["frame"] = "block" 35: J["frame"]["height"] = height 36: place = {name: o.matrix_world.translation.copy() for name, o in self.nodes.items()} 37: for key, at in (joints or {}).items(): 38: if key in SIDED: 39: place[f"{key}.L"] = Vector(at) 40: place[f"{key}.R"] = Vector((-at[0], at[1], at[2])) 41: elif key in place: 42: place[key] = Vector(at) 43: else: 44: raise KeyError(f"block: no joint {key}") 45: for name, o in self.nodes.items(): # striker_joints() makes parents first 46: if o.parent is not None: 47: o.location = o.parent.matrix_world.inverted() @ place[name] 48: bpy.context.view_layer.update() 49: 50: def at(self, name): 51: return self.nodes[name].matrix_world.translation.copy() 52: 53: def _put(self, joint, bm, role, mirror): 54: self.n += 1 55: name = f"block{self.n}_{joint}" 56: if joint in SIDED: 57: pair(name, bm, role, self.nodes[f"{joint}.L"], self.nodes[f"{joint}.R"], bevel=BEVEL, panels=False) 58: elif mirror: 59: solid(name, merge(bm, mirror_x(bm)), role, self.nodes[joint], bevel=BEVEL, panels=False) 60: else: 61: solid(name, bm, role, self.nodes[joint], bevel=BEVEL, panels=False) 62: 63: def box(self, joint, x, y, z, role="main", mirror=False): 64: """A box from x, y, z ranges (lo, hi). A sided joint (thigh, shin, ...) takes the left's numbers 65: and mirrors to the right. `mirror` does the same for a box on a centre joint.""" 66: r = [(x[0], y[0]), (x[1], y[0]), (x[1], y[1]), (x[0], y[1])] 67: self._put(joint, loft([(z[0], r), (z[1], r)]), role, mirror) 68: 69: def taper(self, joint, rings, role="main", mirror=False, chamfer=.15): 70: """A lofted block through rings (z, width, depth, x, y), bottom to top.""" 71: self._put(joint, loft([(z, octo(w, d, chamfer, x=x, y=y)) for z, w, d, x, y in rings]), role, mirror) 72: 73: def bone(self, joint, a, b, w, d, role="main", chamfer=.1): 74: """A block from joint a to joint b, both named for the left side: bone("thigh", "thigh.L", "shin.L", 1, 1).""" 75: pa, pb = self.at(a), self.at(b) 76: lo, hi = (pa, pb) if pa.z < pb.z else (pb, pa) 77: self.taper(joint, [(lo.z, w, d, lo.x, lo.y), (hi.z, w, d, hi.x, hi.y)], role, chamfer=chamfer) 78: 79: def nozzles(self, joint, at, direction, r=.45, length=.9, kind="main"): 80: """A nozzle pair that fires plumes in the game. `kind`: main, binder or calf.""" 81: if joint in SIDED: 82: jl, jr = self.nodes[f"{joint}.L"], self.nodes[f"{joint}.R"] 83: else: 84: jl = jr = self.nodes[joint] 85: nozzle_pair(kind, at, direction, r, length, jl, jr, housing=False) 86: 87: def mannequin(self): 88: """A neutral box on every bone, sized from the joints alone. For testing tools, not a design.""" 89: for joint, a, b, w, d in (("thigh", "thigh.L", "shin.L", 1.0, 1.0), ("shin", "shin.L", "foot.L", 1.0, 1.0), 90: ("upperarm", "upperarm.L", "forearm.L", .7, .7), ("forearm", "forearm.L", "hand.L", .7, .7)): 91: self.bone(joint, a, b, w, d) 92: foot = self.at("foot.L") 93: self.box("foot", (foot.x - .5, foot.x + .5), (foot.y - 1.2, foot.y + .6), (0, foot.z)) 94: hand = self.at("hand.L") 95: self.box("hand", (hand.x - .3, hand.x + .3), (hand.y - .3, hand.y + .3), (hand.z - .8, hand.z)) 96: pelvis, torso, neck, head = self.at("pelvis"), self.at("torso"), self.at("neck"), self.at("head") 97: self.box("pelvis", (-1.3, 1.3), (-.8, .8), (pelvis.z - .8, pelvis.z + .4)) 98: self.box("waist", (-.8, .8), (-.6, .6), (pelvis.z + .4, torso.z)) 99: shoulder = self.at("shoulder.L") 100: self.box("torso", (-shoulder.x, shoulder.x), (-1, 1), (torso.z, neck.z)) 101: self.box("shoulder", (shoulder.x, shoulder.x + .9), (-.6, .6), (shoulder.z - .6, shoulder.z + .4)) 102: self.box("neck", (-.3, .3), (-.3, .3), (neck.z, head.z)) 103: self.box("head", (-.5, .5), (-.6, .6), (head.z, head.z + 1.1)) 104: pack = self.at("backpack") 105: self.box("backpack", (-.9, .9), (pack.y - .5, pack.y + .5), (pack.z - 1, pack.z + 1)) 106: 107: 108: def build_block(name): 109: """block_<name> from kit/blocks/<name>.py.""" 110: module = importlib.import_module(f"blocks.{name.removeprefix('block_')}") 111: importlib.reload(module) 112: module.build(Blocks)read_file{"Path":"~/work/sortie/kit/blocks/dummy.py"}
input
{ "Path": "~/work/sortie/kit/blocks/dummy.py" }result, 10 lines
Showing lines 1-9 of 9 1: """Test fixture for the block tools: an automatic box on every bone, sized from the default joints. 2: Not a design. Delete nothing here, copy it to start a real block file.""" 3: 4: 5: def build(Blocks): 6: b = Blocks() 7: b.mannequin() 8: pack = b.at("backpack") 9: b.nozzles("backpack", (.5, pack.y + .4, pack.z - .9), (0, .45, -.9))read_file{"Path":"~/work/sortie/src/view/clip.ts"}
input
{ "Path": "~/work/sortie/src/view/clip.ts" }result, 140 lines
Showing lines 1-139 of 139 1: import * as THREE from 'three'; 2: import { model, type ModelName } from '../render/assets'; 3: import { STRIKER_DECALS, applyDecals } from '../render/decals'; 4: import { treatEyes } from '../render/eyes'; 5: import type { ThrustReading } from '../render/exhaust'; 6: import { setLook, look } from '../render/look'; 7: import { MechRig, POSES } from '../render/mech'; 8: import type { PaletteName } from '../render/palette'; 9: import { Pipeline } from '../render/pipeline'; 10: import { addSpaceLight, createBackdrop, followSun, spaceEnvironment } from '../render/space'; 11: import { BEND_POSE, SHOT_NAMES, clipFrames, mixPose, shotView, type ShotName } from './clip-plan'; 12: import { CameraRig } from './cameras'; 13: import { benchInput } from './thrusters'; 14: 15: /** 16: * A review clip of one model, rendered frame by frame so it comes out the same on any machine. Driven by 17: * tools/clip.mjs, which calls window.__clip.render(i) and pipes the frames into ffmpeg. 18: * /?view=clip&model=block_dummy&shots=chase,turn&fps=24&palette=merc&look=kit 19: * Any model with the 22 joint rig. Lab lineups hold many frames under slots, so they don't rig. 20: */ 21: export async function startClip(canvas: HTMLCanvasElement, q: URLSearchParams) { 22: setLook(q.get('look')); 23: await document.fonts.ready; 24: const w = Number(q.get('w') ?? 854), h = Number(q.get('h') ?? 480), fps = Number(q.get('fps') ?? 24); 25: const shots = (q.get('shots')?.split(',') ?? SHOT_NAMES) as ShotName[]; 26: const frames = clipFrames(shots, fps); 27: 28: const scene = new THREE.Scene(); 29: const camera = new THREE.PerspectiveCamera(35, w / h, 0.3, 2e5); 30: const backdrop = createBackdrop(); 31: const pipe = new Pipeline(canvas, scene, camera, backdrop); 32: pipe.resize(w, h); 33: const sun = addSpaceLight(scene); 34: scene.environment = spaceEnvironment(pipe.renderer, backdrop); 35: scene.environmentIntensity = 0.8 * look().fill; 36: 37: const name = (q.get('model') ?? 'striker') as ModelName; 38: const palette = (q.get('palette') ?? 'merc') as PaletteName; 39: const root = await model(name, palette); 40: if (name === 'striker') applyDecals(root, STRIKER_DECALS); 41: treatEyes(root, 'spill'); 42: scene.add(root); 43: const rig = new MechRig(root); 44: root.updateMatrixWorld(true); 45: rig.apply(POSES.stand); 46: root.updateMatrixWorld(true); 47: const box = new THREE.Box3().setFromObject(root); 48: const height = box.getSize(new THREE.Vector3()).y; 49: const footY = box.min.y; 50: const size = height / 17.6; 51: 52: const light = new THREE.PointLight('#ffffff', 0, 0, 2); 53: scene.add(light); 54: 55: // the pilot and deck for the scale shot: a person is the one thing everyone knows the size of 56: const ground = new THREE.Group(); 57: const deck = new THREE.Mesh(new THREE.CircleGeometry(height * 2, 48), new THREE.MeshStandardMaterial({ color: '#2a2f36', roughness: 0.85, metalness: 0.2 })); 58: deck.rotation.x = -Math.PI / 2; 59: deck.position.y = footY; 60: ground.add(deck); 61: const pilot = await model('lab_pilot' as ModelName, palette); 62: pilot.traverse((o) => { if (/^slot\d+$/.test(o.name) && o.name !== 'slot0') o.visible = false; }); 63: // lab slot 0 stands at x = -.55: bring the pilot beside the frame's foot, facing the camera 64: pilot.position.set(0.55 + height * 0.3, footY, height * 0.16); 65: pilot.rotation.y = 0.4; 66: ground.add(pilot); 67: scene.add(ground); 68: 69: // the game's chase camera, read for its numbers: this view moves its own camera 70: const chase = new CameraRig(); 71: const reading: ThrustReading = { x: 0, y: 0, z: 0, boosting: false }; 72: const centre = new THREE.Vector3(); 73: const offset = new THREE.Vector3(); 74: const look_ = new THREE.Vector3(); 75: const up = new THREE.Vector3(0, 1, 0); 76: const yawQ = new THREE.Quaternion(); 77: const DT = 1 / 120; 78: let clock = 0; 79: 80: const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => { 81: const f = benchInput(state, t); 82: reading.x = f.thrust.x; 83: reading.y = f.thrust.y; 84: reading.z = f.thrust.z; 85: reading.boosting = f.boosting; 86: reading.assault = f.assault; 87: reading.quick = f.quick; 88: rig.thrust(reading, clock, dt); 89: rig.lightExhaust(light); 90: }; 91: 92: const render = (i: number) => { 93: const f = frames[i]; 94: const v = shotView(f); 95: // thrusters step at 120 Hz whatever the clip's frame rate, as a game would 96: const dt = f.cut ? 0 : 1 / fps; 97: if (f.cut) for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); } 98: for (let s = 0; s < dt - 1e-9; s += DT) { 99: clock += DT; 100: feed(f.state, Math.max(0, f.stateT - dt + s), DT); 101: } 102: if (dt === 0) feed(f.state, f.stateT, 0); 103: 104: root.rotation.y = THREE.MathUtils.degToRad(v.mechYaw); 105: rig.apply(v.bend > 0 ? mixPose(POSES.stand, BEND_POSE, v.bend) : POSES[v.pose]); 106: root.updateMatrixWorld(true); 107: ground.visible = v.ground; 108: centre.set(0, footY + height * v.lookAt, 0); 109: const fov = v.chase ? chase.camera.fov : 35; 110: if (camera.fov !== fov) { 111: camera.fov = fov; 112: camera.updateProjectionMatrix(); 113: } 114: if (v.chase) { 115: // where the game's chase camera sits (src/view/cameras.ts), over the shoulder, scaled to the frame 116: yawQ.setFromAxisAngle(up, THREE.MathUtils.degToRad(v.camYaw)); 117: offset.set(chase.shoulder * size, chase.chaseOffset.y * size, chase.chaseOffset.z * size).applyQuaternion(yawQ); 118: camera.position.copy(centre).add(offset); 119: look_.set(chase.shoulder * size, (chase.chaseOffset.y - chase.lookDrop) * size, 400).applyQuaternion(yawQ).add(centre); 120: camera.up.copy(up); 121: camera.lookAt(look_); 122: } else { 123: const yaw = THREE.MathUtils.degToRad(v.camYaw), pitch = THREE.MathUtils.degToRad(v.pitch); 124: camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(v.dist * height).add(centre); 125: if (v.ground) camera.position.y = Math.max(camera.position.y, footY + 1.6); // eye height, above the deck 126: camera.up.copy(up); 127: camera.lookAt(centre); 128: } 129: camera.updateMatrixWorld(true); 130: followSun(sun, centre); 131: pipe.render(); 132: // read straight after the draw, in the same task, while the buffer still holds it 133: return canvas.toDataURL('image/jpeg', 0.93); 134: }; 135: 136: const win = window as unknown as { __clip: unknown; __ready: boolean }; 137: win.__clip = { frames: frames.length, fps, render }; 138: win.__ready = true; 139: }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: }read_file{"Path":"~/work/sortie/src/view/viewer.ts"}
input
{ "Path": "~/work/sortie/src/view/viewer.ts" }result, 144 lines
Showing lines 1-143 of 143 1: import * as THREE from 'three'; 2: import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; 3: import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js'; 4: import { model, type ModelName } from '../render/assets'; 5: import { MechRig, POSES, type PoseName } from '../render/mech'; 6: import type { PaletteName } from '../render/palette'; 7: import { Pipeline } from '../render/pipeline'; 8: import { addSpaceLight, createBackdrop, followSun, spaceEnvironment } from '../render/space'; 9: import { STRIKER_DECALS, applyDecals, type DecalSpec } from '../render/decals'; 10: import { PALETTES } from '../render/palette'; 11: import { look, setLook } from '../render/look'; 12: import { treatEyes, type EyeMode } from '../render/eyes'; 13: import { fitShip } from '../render/ship'; 14: import type { FrameClassId } from '../sim/frames'; 15: 16: /** 17: * Model viewer for review shots, in the game's own renderer: 18: * /?view=striker&yaw=35&pitch=8&dist=34&pose=flight&weapon=rifle&palette=automaton 19: * /?view=lineup (the frame in each palette, side by side) 20: * /?view=ship&bays=light,heavy&frame=light (bay fits and shuttle clamps) 21: * /?view=light&pose=launch&weapon=rifle (light and heavy frames and their variants pose like the striker) 22: */ 23: const FRAMES: string[] = ['striker_a', 'striker_b', 'light', 'light_line', 'light_lancer', 'heavy', 'heavy_B', 'heavy_C']; 24: 25: /** An emblem at every bearing anchor of a model: the anchor's position, its direction into the plate, its size. */ 26: function bearingDecals(root: THREE.Object3D, color: string): DecalSpec[] { 27: root.updateMatrixWorld(true); 28: const out: DecalSpec[] = []; 29: root.traverse((o) => { 30: if (!o.name.startsWith('bearing') || !o.visible) return; 31: const at = root.worldToLocal(o.getWorldPosition(new THREE.Vector3())); 32: const dir = o.userData.dir as [number, number, number] | undefined; 33: const size = Number(o.userData.size ?? 0.5); 34: if (dir) out.push({ kind: 'emblem', at: [at.x, at.y, at.z], dir, size: [size, size], color }); 35: }); 36: return out; 37: } 38: 39: export async function startViewer(canvas: HTMLCanvasElement, q: URLSearchParams) { 40: setLook(q.get('look')); 41: await document.fonts.ready; 42: const scene = new THREE.Scene(); 43: const camera = new THREE.PerspectiveCamera(Number(q.get('fov') ?? 35), 1, 0.5, 2e5); 44: // ?bg=studio: a plain grey ground, an even room light and little bloom, for judging shape 45: const studio = q.get('bg') === 'studio'; 46: const backdrop = createBackdrop(); 47: const pipe = new Pipeline(canvas, scene, camera, studio ? null : backdrop); 48: const sun = addSpaceLight(scene); 49: if (studio) { 50: scene.background = new THREE.Color('#3a3e45'); 51: const pmrem = new THREE.PMREMGenerator(pipe.renderer); 52: scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture; 53: pipe.bloom.strength = Number(q.get('bloom') ?? 0.12); 54: } else scene.environment = spaceEnvironment(pipe.renderer, backdrop); 55: scene.environmentIntensity = Number(q.get('env') ?? (studio ? 0.6 : 0.8) * look().fill); 56: const name = q.get('view') as ModelName | 'lineup'; 57: const target = new THREE.Vector3(); 58: const pose = (q.get('pose') ?? 'stand') as PoseName; 59: const weapon = q.get('weapon') as ModelName | null; 60: 61: async function frame(palette: PaletteName, x: number, mech: ModelName = 'striker') { 62: const root = await model(mech, palette); 63: root.position.x = x; 64: scene.add(root); 65: if (mech === 'striker') applyDecals(root, STRIKER_DECALS); 66: treatEyes(root, (q.get('eye') ?? 'spill') as EyeMode); 67: const rig = new MechRig(root); 68: rig.apply(POSES[pose] ?? POSES.stand); 69: if (weapon) { 70: rig.hold(await model(weapon, palette)); 71: // weapons are striker sized: scale to the frame's height 72: const h = root.getObjectByName('frame')?.userData.height as number | undefined; 73: if (h) rig.held!.scale.setScalar(h / 17.6); 74: } 75: return root; 76: } 77: 78: if (name === 'lineup') { 79: await frame('merc', -6); 80: await frame('automaton', 6); 81: target.set(0, 9, 0); 82: } else if (name === 'striker') { 83: await frame((q.get('palette') ?? 'merc') as PaletteName, 0); 84: target.set(0, 9, 0); 85: } else if (FRAMES.includes(name)) { 86: const root = await frame((q.get('palette') ?? 'merc') as PaletteName, 0, name); 87: new THREE.Box3().setFromObject(root).getCenter(target); 88: } else { 89: const root = await model(name, (q.get('palette') ?? 'merc') as PaletteName); 90: treatEyes(root, (q.get('eye') ?? 'spill') as EyeMode, q.has('t') ? Number(q.get('t')) : null); 91: scene.add(root); 92: // ?only=slot2 shows one variant of a lab lineup 93: const only = q.get('only'); 94: if (only) root.traverse((o) => { if (/^slot\d+$/.test(o.name) && o.name !== only) o.visible = false; }); 95: // ?view=ship&bays=light,heavy&frame=light fits the bays and the shuttle clamps 96: if (name === 'ship') { 97: const ids = (s: string | null, n: number) => (s?.split(',') ?? []).concat(Array(n).fill('standard')).slice(0, n) as FrameClassId[]; 98: fitShip(root, ids(q.get('bays'), 2), ids(q.get('frame'), 1)[0]); 99: } 100: // ?bearings=1 puts a test emblem on every bearing anchor (bearing.*), in the palette's trim colour 101: if (q.has('bearings')) applyDecals(root, bearingDecals(root, PALETTES[(q.get('palette') ?? 'merc') as PaletteName].trim.color)); 102: const box = new THREE.Box3().setFromObject(root); 103: box.getCenter(target); 104: } 105: // ?sil=1: flat black forms on a white ground, for judging silhouettes without paint or stencils 106: if (q.has('sil')) { 107: const black = new THREE.MeshBasicMaterial({ color: 0x000000 }); 108: scene.traverse((o) => { 109: const m = o as THREE.Mesh; 110: if (m.isMesh) m.material = black; 111: else if ((o as THREE.Sprite).isSprite || (o as THREE.Points).isPoints) o.visible = false; 112: }); 113: scene.background = new THREE.Color('#ffffff'); 114: // the low tier drops the edge detail, bloom and grade passes, which would draw over the forms 115: pipe.setQuality({ tier: 'low' }); 116: } 117: const dist = Number(q.get('dist') ?? 36); 118: const yaw = THREE.MathUtils.degToRad(Number(q.get('yaw') ?? 30)); 119: const pitch = THREE.MathUtils.degToRad(Number(q.get('pitch') ?? 8)); 120: if (q.has('ty')) target.y = Number(q.get('ty')); 121: if (q.has('tx')) target.x = Number(q.get('tx')); 122: if (q.has('tz')) target.z = Number(q.get('tz')); 123: camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(dist).add(target); 124: followSun(sun, target); 125: if (name !== 'striker' && name !== 'lineup' && !FRAMES.includes(name)) { 126: const c = sun.shadow.camera; 127: c.left = c.bottom = -dist; 128: c.right = c.top = dist; 129: c.far = dist * 20; 130: c.updateProjectionMatrix(); 131: } 132: camera.lookAt(target); 133: const controls = new OrbitControls(camera, canvas); 134: controls.target.copy(target); 135: controls.update(); 136: window.addEventListener('resize', () => pipe.resize()); 137: const loop = () => { 138: pipe.render(); 139: requestAnimationFrame(loop); 140: }; 141: loop(); 142: (window as unknown as { __ready: boolean }).__ready = true; 143: }read_file{"Path":"~/work/sortie/src/render/look.ts"}
input
{ "Path": "~/work/sortie/src/render/look.ts" }result, 214 lines
Showing lines 1-213 of 213 1: import * as THREE from 'three'; 2: 3: // The rendering style: how much edge wear, recess grime, ink lining, paint variation and film grain. 4: // Two candidates under review: a weathered "field" machine and a clean "kit" (a painted model kit). 5: 6: export interface Look { 7: name: 'field' | 'kit' | 'service' | 'sketch'; 8: /** Convex edges lightened (worn paint catching light), 0..1. */ 9: ridge: number; 10: /** Recesses and seams darkened (grime), 0..1. */ 11: valley: number; 12: /** Dark lining at creases, seams and silhouettes, 0..1. */ 13: ink: number; 14: /** Paint variation across surfaces (albedo and roughness noise), 0..1. */ 15: grime: number; 16: /** Film grain and vignette strength, 0..1. */ 17: grain: number; 18: vignette: number; 19: /** Paint finish: roughness for armour paint and whether it has a clear coat. */ 20: paintRough: number; 21: gloss: boolean; 22: /** Edges chip to bare metal in a broken pattern (field) instead of a clean highlight (kit). */ 23: chipped: boolean; 24: /** How far paint colours are pulled toward grey (weathered field paint). */ 25: desaturate: number; 26: /** Soft fill from the environment, as a multiplier: low for hard field light, high for a studio look. */ 27: fill: number; 28: /** Cel-banded lighting, pencil hatching in shadow, and a paper tone (the sketch look). */ 29: toon?: boolean; 30: hatch?: number; 31: paper?: number; 32: } 33: 34: export const LOOKS: Record<Look['name'], Look> = { 35: field: { name: 'field', ridge: 0.85, valley: 0.7, ink: 0.15, grime: 1, grain: 0.045, vignette: 0.35, paintRough: 0.66, gloss: false, 36: chipped: true, desaturate: 0.28, fill: 0.5 }, 37: kit: { name: 'kit', ridge: 0.22, valley: 0.2, ink: 0.95, grime: 0, grain: 0, vignette: 0.12, paintRough: 0.32, gloss: true, 38: chipped: false, desaturate: 0, fill: 1.15 }, 39: // between field and kit: kit's lining at two-thirds, field's wear at a lighter touch, semi-matte 40: service: { name: 'service', ridge: 0.5, valley: 0.45, ink: 0.6, grime: 0.5, grain: 0.025, vignette: 0.25, paintRough: 0.48, gloss: false, 41: chipped: true, desaturate: 0.12, fill: 0.85 }, 42: sketch: { name: 'sketch', ridge: 0.1, valley: 0.25, ink: 1, grime: 0, grain: 0.02, vignette: 0.2, paintRough: 0.55, gloss: false, 43: chipped: false, desaturate: 0.12, fill: 0.85, toon: true, hatch: 1, paper: 1 }, 44: }; 45: 46: let current: Look = LOOKS.field; 47: export const look = () => current; 48: export function setLook(name: string | null) { 49: current = LOOKS[(name as Look['name']) ?? 'field'] ?? LOOKS.field; 50: return current; 51: } 52: 53: /** Screen-space surface detail from the normal/depth pre-pass: [redacted: secret] wear, grime, ink. */ 54: export const DetailShader = { 55: uniforms: { 56: tDiffuse: { value: null }, 57: tNormal: { value: null }, 58: tDepth: { value: null }, 59: px: { value: new THREE.Vector2(1, 1) }, 60: near: { value: 0.5 }, 61: far: { value: 60000 }, 62: ridgeK: { value: 0.5 }, 63: valleyK: { value: 0.5 }, 64: inkK: { value: 0.2 }, 65: chipped: { value: 0 }, 66: hatch: { value: 0 }, 67: projInv: { value: new THREE.Matrix4() }, 68: viewInv: { value: new THREE.Matrix4() }, 69: }, 70: vertexShader: 'varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }', 71: fragmentShader: /* glsl */ ` 72: #include <packing> 73: uniform sampler2D tDiffuse, tNormal, tDepth; 74: uniform vec2 px; 75: uniform float near, far, ridgeK, valleyK, inkK, chipped, hatch; 76: uniform mat4 projInv, viewInv; 77: varying vec2 vUv; 78: float hash3(vec3 p) { return fract(sin(dot(p, vec3(7.1, 157.3, 113.7))) * 43758.5); } 79: float vnoise(vec3 p) { vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f); 80: return mix(mix(mix(hash3(i), hash3(i + vec3(1,0,0)), f.x), mix(hash3(i + vec3(0,1,0)), hash3(i + vec3(1,1,0)), f.x), f.y), 81: mix(mix(hash3(i + vec3(0,0,1)), hash3(i + vec3(1,0,1)), f.x), mix(hash3(i + vec3(0,1,1)), hash3(i + vec3(1,1,1)), f.x), f.y), f.z); } 82: vec3 worldAt(vec2 uv) { 83: float d = texture2D(tDepth, uv).x; 84: vec4 v = projInv * vec4(uv * 2.0 - 1.0, d * 2.0 - 1.0, 1.0); 85: return (viewInv * vec4(v.xyz / v.w, 1.0)).xyz; 86: } 87: vec4 N(vec2 uv) { vec4 n = texture2D(tNormal, uv); return vec4(n.xyz * 2.0 - 1.0, n.a); } 88: float Z(vec2 uv) { return -perspectiveDepthToViewZ(texture2D(tDepth, uv).x, near, far); } 89: void main() { 90: vec4 c = texture2D(tDiffuse, vUv); 91: vec4 n0 = N(vUv); 92: if (n0.a < 0.5) { gl_FragColor = c; return; } 93: vec4 l = N(vUv - vec2(px.x, 0.0)), r = N(vUv + vec2(px.x, 0.0)), d = N(vUv - vec2(0.0, px.y)), u = N(vUv + vec2(0.0, px.y)); 94: float z0 = Z(vUv); 95: // convex where neighbouring normals spread apart, concave where they close in 96: float curv = ((r.x - l.x) * r.a * l.a + (u.y - d.y) * u.a * d.a) * 0.5; 97: float ridge = smoothstep(0.08, 0.45, curv); 98: float valley = smoothstep(0.08, 0.45, -curv); 99: // ink at creases and wherever depth steps (seams, overlaps, silhouettes) 100: float turn = max(max(1.0 - dot(n0.xyz, l.xyz), 1.0 - dot(n0.xyz, r.xyz)), max(1.0 - dot(n0.xyz, u.xyz), 1.0 - dot(n0.xyz, d.xyz))); 101: float zs = max(max(abs(Z(vUv - vec2(px.x, 0.0)) - z0), abs(Z(vUv + vec2(px.x, 0.0)) - z0)), 102: max(abs(Z(vUv - vec2(0.0, px.y)) - z0), abs(Z(vUv + vec2(0.0, px.y)) - z0))); 103: float edge = max(smoothstep(0.35, 0.7, turn), smoothstep(0.015, 0.04, zs / z0)); 104: edge = max(edge, 1.0 - min(min(l.a, r.a), min(u.a, d.a))); 105: // detail fades with distance so far-off ships don't turn to noise 106: float near_ = 1.0 - smoothstep(60.0, 600.0, z0); 107: vec3 col = c.rgb; 108: // grime settles in recesses: darker and a little brown 109: col = mix(col, col * vec3(0.55, 0.5, 0.45), valley * valleyK * near_); 110: if (chipped > 0.5) { 111: // chipped paint on convex edges shows the metal beneath, in a broken pattern fixed to the surface 112: vec3 wp = worldAt(vUv); 113: float n = vnoise(wp * 3.1) * 0.65 + vnoise(wp * 11.0) * 0.35; 114: float chip = ridge * smoothstep(0.42, 0.62, n) * ridgeK * near_; 115: col = mix(col, vec3(0.32, 0.33, 0.35) * (0.6 + 0.8 * vnoise(wp * 23.0)), chip); 116: } else { 117: col += (vec3(1.0) - col) * ridge * ridgeK * 0.45 * near_ * clamp(dot(col, vec3(0.33)) * 2.0, 0.3, 1.0); 118: } 119: if (hatch > 0.0) { 120: // pencil hatching in shadow: one direction in half shade, crossed in deep shade 121: float lum = dot(col, vec3(0.3, 0.59, 0.11)); 122: vec2 fc = gl_FragCoord.xy; 123: float h1 = step(0.55, fract((fc.x + fc.y) / 6.0)); 124: float h2 = step(0.55, fract((fc.x - fc.y) / 6.0)); 125: float shade1 = 1.0 - smoothstep(0.18, 0.32, lum), shade2 = 1.0 - smoothstep(0.08, 0.18, lum); 126: col *= 1.0 - hatch * 0.35 * (h1 * shade1 + h2 * shade2); 127: } 128: col = mix(col, col * 0.18, edge * inkK * mix(0.4, 1.0, near_)); 129: gl_FragColor = vec4(col, c.a); 130: }`, 131: }; 132: 133: /** After tone mapping: vignette and fine grain. */ 134: export const GradeShader = { 135: uniforms: { tDiffuse: { value: null }, grain: { value: 0 }, vignette: { value: 0 }, time: { value: 0 }, paper: { value: 0 } }, 136: vertexShader: 'varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }', 137: fragmentShader: /* glsl */ ` 138: uniform sampler2D tDiffuse; uniform float grain, vignette, time, paper; varying vec2 vUv; 139: float h(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233)) + time) * 43758.5453); } 140: void main() { 141: vec4 c = texture2D(tDiffuse, vUv); 142: vec2 q = vUv - 0.5; 143: c.rgb *= 1.0 - vignette * smoothstep(0.25, 0.85, dot(q, q) * 2.2); 144: c.rgb += (h(vUv * 1000.0) - 0.5) * grain; 145: if (paper > 0.0) { 146: // a warm paper tone and its fibre, multiplied under the picture 147: float fib = fract(sin(dot(floor(gl_FragCoord.xy / 2.0), vec2(12.9898, 78.233))) * 43758.5453); 148: vec3 tone = vec3(1.0, 0.97, 0.9) * (0.94 + 0.06 * fib); 149: c.rgb = mix(c.rgb, c.rgb * tone + vec3(0.03, 0.025, 0.015), paper); 150: } 151: gl_FragColor = c; 152: }`, 153: }; 154: 155: /** World-space paint variation: blotches in albedo and roughness so large panels aren't uniform. */ 156: export function addPaintVariation(m: THREE.MeshStandardMaterial, amount: number) { 157: if (amount <= 0) return; 158: const prev = m.onBeforeCompile; 159: m.onBeforeCompile = (shader, r) => { 160: prev?.call(m, shader, r); 161: shader.vertexShader = shader.vertexShader 162: .replace('#include <common>', '#include <common>\nvarying vec3 vPaintPos;') 163: .replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\nvPaintPos = (modelMatrix * vec4(transformed, 1.0)).xyz;'); 164: shader.fragmentShader = shader.fragmentShader 165: .replace('#include <common>', `#include <common> 166: varying vec3 vPaintPos; 167: float pn(vec3 p) { vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f); 168: float a = fract(sin(dot(i, vec3(7.1, 157.3, 113.7))) * 43758.5); 169: float b = fract(sin(dot(i + vec3(1,0,0), vec3(7.1, 157.3, 113.7))) * 43758.5); 170: float c2 = fract(sin(dot(i + vec3(0,1,0), vec3(7.1, 157.3, 113.7))) * 43758.5); 171: float d = fract(sin(dot(i + vec3(1,1,0), vec3(7.1, 157.3, 113.7))) * 43758.5); 172: float e = fract(sin(dot(i + vec3(0,0,1), vec3(7.1, 157.3, 113.7))) * 43758.5); 173: float f2 = fract(sin(dot(i + vec3(1,0,1), vec3(7.1, 157.3, 113.7))) * 43758.5); 174: float g = fract(sin(dot(i + vec3(0,1,1), vec3(7.1, 157.3, 113.7))) * 43758.5); 175: float hh = fract(sin(dot(i + vec3(1,1,1), vec3(7.1, 157.3, 113.7))) * 43758.5); 176: return mix(mix(mix(a, b, f.x), mix(c2, d, f.x), f.y), mix(mix(e, f2, f.x), mix(g, hh, f.x), f.y), f.z); } 177: #ifdef PAINT_LITE 178: float paintN(vec3 p) { return pn(p * 0.7); } 179: #else 180: float paintN(vec3 p) { return pn(p * 0.7) * 0.5 + pn(p * 2.3) * 0.3 + pn(p * 9.0) * 0.2; } 181: #endif`) 182: .replace('#include <color_fragment>', `#include <color_fragment> 183: float pv = paintN(vPaintPos); 184: // blotches, plus dirt streaks running down the surfaces (the low tier keeps the broad blotches only) 185: #ifdef PAINT_LITE 186: float streak = 0.0; 187: #else 188: float streak = pn(vec3(vPaintPos.x * 3.0, vPaintPos.y * 0.25, vPaintPos.z * 3.0)); 189: #endif 190: diffuseColor.rgb *= 1.0 - ${(0.14 * amount).toFixed(3)} * smoothstep(0.3, 0.8, pv) - ${(0.1 * amount).toFixed(3)} * smoothstep(0.55, 0.9, streak);`) 191: .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment> 192: roughnessFactor = clamp(roughnessFactor + ${(0.12 * amount).toFixed(3)} * (paintN(vPaintPos * 1.7) - 0.5), 0.05, 1.0);`); 193: }; 194: const key = m.customProgramCacheKey?.bind(m); 195: m.customProgramCacheKey = () => `${key ? key() : ''}paint${amount}`; 196: painted.add(m); 197: setLite(m, paintLite); 198: } 199: 200: /** Paint variation's fine noise is dear per pixel on a weak GPU: the low tier keeps one octave. */ 201: const painted = new Set<THREE.Material>(); 202: let paintLite = false; 203: function setLite(m: THREE.Material, on: boolean) { 204: m.defines ??= {}; 205: if (on === 'PAINT_LITE' in m.defines) return; 206: if (on) m.defines.PAINT_LITE = ''; 207: else delete m.defines.PAINT_LITE; 208: m.needsUpdate = true; 209: } 210: export function setPaintLite(on: boolean) { 211: paintLite = on; 212: for (const m of painted) setLite(m, on); 213: }