A mech game prototype, pushed by Gemini 4 Carbon
agent (cont.)
+37:02read_file{"EndLine":300,"Path":"~/work/sortie/src/render/mech.ts","StartLine":1}
input
{ "EndLine": 300, "Path": "~/work/sortie/src/render/mech.ts", "StartLine": 1 }result, 210 lines
Showing lines 1-209 of 209 1: import * as THREE from 'three'; 2: import { find, nodes } from './assets'; 3: import { Exhaust, KINDS, type NozzleKind, type ThrustReading } from './exhaust'; 4: import { PALETTES, type PaletteName } from './palette'; 5: import { PLUME_HULL, plumeMaterial, plumeVisible, setPlume } from './plume'; 6: 7: /** Joint rotations in degrees, glTF axes: X pitches a limb (negative swings it forward), Z swings it 8: * sideways (positive moves a left limb outward), Y twists. */ 9: export type Pose = Partial<Record<Joint, [number, number, number]>>; 10: 11: export const JOINTS = [ 12: 'pelvis', 'waist', 'torso', 'neck', 'head', 'backpack', 13: 'shoulder.L', 'upperarm.L', 'forearm.L', 'hand.L', 'shoulder.R', 'upperarm.R', 'forearm.R', 'hand.R', 14: 'thigh.L', 'shin.L', 'foot.L', 'thigh.R', 'shin.R', 'foot.R', 'binder.L', 'binder.R', 15: ] as const; 16: export type Joint = (typeof JOINTS)[number]; 17: 18: export const POSES = { 19: stand: { 20: 'upperarm.L': [0, 0, 6], 'upperarm.R': [0, 0, -6], 'forearm.L': [-12, 0, 0], 'forearm.R': [-12, 0, 0], 21: }, 22: /** Standing on the catapult: knees bent, leaning into the launch. */ 23: launch: { 24: pelvis: [8, 0, 0], torso: [10, 0, 0], head: [-14, 0, 0], 25: 'thigh.L': [-38, 0, 2], 'thigh.R': [-38, 0, -2], 'shin.L': [58, 0, 0], 'shin.R': [58, 0, 0], 26: 'foot.L': [-20, 0, 0], 'foot.R': [-20, 0, 0], 27: 'upperarm.L': [-18, 0, 14], 'forearm.L': [-40, 0, 0], 'upperarm.R': [-30, 0, -8], 'forearm.R': [-50, 0, 0], 28: 'binder.L': [18, 0, 0], 'binder.R': [18, 0, 0], 29: }, 30: /** The launch crouch for a heavy: 24 m in a 26 m tube, so knees deep, head down and binders folded, 31: * which brings it under the tube's signal box. */ 32: launch_heavy: { 33: pelvis: [12, 0, 0], torso: [12, 0, 0], head: [-20, 0, 0], 34: 'thigh.L': [-58, 0, 3], 'thigh.R': [-58, 0, -3], 'shin.L': [106, 0, 0], 'shin.R': [106, 0, 0], 35: 'foot.L': [-48, 0, 0], 'foot.R': [-48, 0, 0], 36: 'upperarm.L': [-18, 0, 14], 'forearm.L': [-40, 0, 0], 'upperarm.R': [-30, 0, -8], 'forearm.R': [-50, 0, 0], 37: 'binder.L': [40, 0, 0], 'binder.R': [40, 0, 0], 38: }, 39: /** Free flight, rifle up. */ 40: flight: { 41: pelvis: [6, 0, 0], torso: [-4, 0, 0], head: [-2, 0, 0], 42: 'thigh.L': [-22, 0, 4], 'thigh.R': [6, 0, -3], 'shin.L': [42, 0, 0], 'shin.R': [30, 0, 0], 43: 'foot.L': [8, 0, 0], 'foot.R': [18, 0, 0], 44: 'upperarm.L': [-22, 0, 16], 'forearm.L': [-46, 0, 0], 45: 'upperarm.R': [-62, -8, -6], 'forearm.R': [-26, 0, 0], 'hand.R': [0, 0, 0], 46: 'binder.L': [-6, 0, 0], 'binder.R': [-6, 0, 0], 47: }, 48: } satisfies Record<string, Pose>; 49: export type PoseName = keyof typeof POSES; 50: 51: /** The catapult pose for a size class: the striker's, with a deeper crouch for heavies. */ 52: export const launchPose = (cls: string): Pose => (cls === 'heavy' ? POSES.launch_heavy : POSES.launch); 53: 54: export interface Nozzle { 55: node: THREE.Object3D; 56: dir: THREE.Vector3; // exhaust direction in the node's parent space 57: radius: number; 58: kind: NozzleKind; 59: plume: THREE.Mesh; 60: } 61: 62: const tmpQ = new THREE.Quaternion(); 63: const _sum = new THREE.Vector3(); 64: const _at = new THREE.Vector3(); 65: const _white = new THREE.Color(1, 1, 1); 66: const tmpE = new THREE.Euler(); 67: const D = THREE.MathUtils.DEG2RAD; 68: 69: /** A frame model's joints, posed by rotation, with weapons held at grip.R and thruster plumes. */ 70: export class MechRig { 71: readonly joints = new Map<Joint, THREE.Object3D>(); 72: readonly nozzles: Nozzle[] = []; 73: readonly cockpit: THREE.Object3D; 74: readonly grip: THREE.Object3D; 75: held: THREE.Object3D | null = null; 76: /** Plume state, stepped by thrust(). */ 77: readonly exhaust = new Exhaust(); 78: /** One plume material per nozzle kind: a kind fires together. */ 79: private plumeMats: Record<NozzleKind, THREE.ShaderMaterial>; 80: private exhaustColor: THREE.Color; 81: private targets = new Map<Joint, THREE.Quaternion>(); 82: 83: constructor(readonly root: THREE.Object3D) { 84: const map = nodes(root); 85: for (const j of JOINTS) { 86: const n = find(map, j); 87: if (n) this.joints.set(j, n); 88: } 89: this.cockpit = find(map, 'cockpit') ?? root; 90: this.grip = find(map, 'grip.R') ?? root; 91: const paint = PALETTES[(root.userData.palette as PaletteName | undefined) ?? 'merc'].glow_exhaust; 92: this.exhaustColor = new THREE.Color(paint.color); 93: this.plumeMats = { 94: main: plumeMaterial(this.exhaustColor, paint.glow ?? 1, 0), 95: binder: plumeMaterial(this.exhaustColor, paint.glow ?? 1, 17.3), 96: calf: plumeMaterial(this.exhaustColor, paint.glow ?? 1, 41.7), 97: }; 98: root.traverse((o) => { 99: const dir = o.userData.dir as number[] | undefined; 100: if (!dir || !/^nozzle/.test(o.name)) return; 101: const kind: NozzleKind = /main/.test(o.name) ? 'main' : /binder/.test(o.name) ? 'binder' : 'calf'; 102: const radius = (o.userData.radius as number) ?? 0.5; 103: // the plume's own space is in nozzle radii (render/plume.ts) 104: const plume = new THREE.Mesh(PLUME_HULL, this.plumeMats[kind]); 105: const d = new THREE.Vector3(...(dir as [number, number, number])); 106: plume.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), d); 107: plume.scale.setScalar(radius); 108: plume.visible = false; 109: plume.renderOrder = 2; 110: o.add(plume); 111: this.nozzles.push({ node: o, dir: d, radius, kind, plume }); 112: }); 113: } 114: 115: /** Any named node of the model (extras like harken.L), or null. */ 116: node(name: string): THREE.Object3D | null { 117: return find(nodes(this.root), name) ?? null; 118: } 119: 120: /** Snap to a pose. */ 121: apply(pose: Pose) { 122: for (const [j, node] of this.joints) { 123: const r = pose[j] ?? [0, 0, 0]; 124: node.quaternion.setFromEuler(tmpE.set(r[0] * D, r[1] * D, r[2] * D)); 125: } 126: } 127: 128: /** Snap to a pose and measure how high its soles sit above the root, in world metres (root 129: * upright). A crouch lifts the feet, so the frame drops by this much to stand on its clamps. */ 130: soles(pose: Pose): number { 131: this.apply(pose); 132: this.root.updateMatrixWorld(true); 133: const v = new THREE.Vector3(); 134: let min = Infinity; 135: for (const j of ['foot.L', 'foot.R'] as const) { 136: this.joints.get(j)?.traverse((o) => { 137: const p = (o as THREE.Mesh).isMesh ? (o as THREE.Mesh).geometry.attributes.position : null; 138: if (!p) return; 139: for (let i = 0; i < p.count; i++) min = Math.min(min, v.fromBufferAttribute(p, i).applyMatrix4(o.matrixWorld).y); 140: }); 141: } 142: return Number.isFinite(min) ? min - this.root.getWorldPosition(v).y : 0; 143: } 144: 145: /** Ease toward a blend of poses; weights need not sum to 1 (the rest is the rest pose). */ 146: blend(poses: [Pose, number][], rate: number, dt: number) { 147: const k = 1 - Math.exp(-rate * dt); 148: for (const [j, node] of this.joints) { 149: let x = 0, y = 0, z = 0; 150: for (const [p, w] of poses) { 151: const r = p[j]; 152: if (r) { 153: x += r[0] * w; 154: y += r[1] * w; 155: z += r[2] * w; 156: } 157: } 158: let t = this.targets.get(j); 159: if (!t) this.targets.set(j, (t = new THREE.Quaternion())); 160: t.setFromEuler(tmpE.set(x * D, y * D, z * D)); 161: node.quaternion.slerp(t, k); 162: } 163: } 164: 165: /** Turn one joint by an extra rotation on top of its current pose (aim, lean). */ 166: add(j: Joint, x: number, y: number, z: number) { 167: const n = this.joints.get(j); 168: if (n) n.quaternion.multiply(tmpQ.setFromEuler(tmpE.set(x * D, y * D, z * D))); 169: } 170: 171: /** Put a weapon in the right hand: barrel along the forearm, handle in the fist. */ 172: hold(weapon: THREE.Object3D | null) { 173: if (this.held && this.held !== weapon) this.held.removeFromParent(); 174: this.held = weapon; 175: if (!weapon) return; 176: this.grip.add(weapon); 177: weapon.position.set(0, 0, 0); 178: weapon.quaternion.setFromEuler(tmpE.set(Math.PI / 2, 0, 0)); 179: } 180: 181: /** Step the plumes from this frame's flight reading and draw them. `time` drives the turbulence. */ 182: thrust(r: ThrustReading, time: number, dt: number) { 183: this.exhaust.step(r, dt); 184: for (const k of KINDS) setPlume(this.plumeMats[k], this.exhaust.plumes[k], time); 185: for (const n of this.nozzles) n.plume.visible = plumeVisible(this.exhaust.plumes[n.kind]); 186: } 187: 188: /** Put `light` at the burning plumes' weighted centre, as bright as they burn: the glow the 189: * exhaust throws on the frame. A light costs every lit pixel, so a scene gives one to the player 190: * and the nearest few frames at most, and keeps the count fixed (a change recompiles shaders). */ 191: lightExhaust(light: THREE.PointLight, strength = 1) { 192: let w = 0; 193: _sum.set(0, 0, 0); 194: const s = this.root.scale.x; 195: for (const n of this.nozzles) { 196: const p = this.exhaust.plumes[n.kind]; 197: const k = (Math.min(1, p.level) * (1 + 0.5 * p.heavy) + 0.4 * p.flash) * (n.radius * s) ** 2; 198: if (k <= 0 || !n.plume.visible) continue; 199: // a little way downstream, where the plume is brightest 200: n.plume.localToWorld(_at.set(0, 0, 2.5)); 201: _sum.addScaledVector(_at, k); 202: w += k; 203: } 204: light.visible = true; 205: light.color.copy(this.exhaustColor).lerp(_white, 0.4); 206: light.intensity = w > 0 ? w * 35 * strength : 0; 207: if (w > 0) light.position.copy(_sum).divideScalar(w); 208: } 209: }read_file{"EndLine":200,"Path":"~/work/sortie/src/render/plume.ts","StartLine":1}
input
{ "EndLine": 200, "Path": "~/work/sortie/src/render/plume.ts", "StartLine": 1 }result, 167 lines
Showing lines 1-166 of 166 1: import * as THREE from 'three'; 2: import type { Plume } from './exhaust'; 3: 4: // Thruster plumes drawn as a small volume: each nozzle gets one closed cylinder that bounds its 5: // plume, and the fragment shader marches a few steps through it, summing a density made of a white 6: // hot core (with shock diamonds), a coloured mantle that flares out and breaks up downstream, a 7: // glow in the throat, an ignition flash and a shock ring. Because it is a volume it reads from any 8: // angle, end on included, and has no hard cone edges. One draw call per nozzle, no textures. 9: // 10: // Plume space: the mesh is scaled by the nozzle radius, so one unit is one nozzle radius, the exit 11: // is at z = 0 and the exhaust runs along +z. 12: 13: const Z0 = -0.6; 14: const STEPS = 10; 15: /** Past this many nozzle radii from the camera a plume marches half the steps. */ 16: const FAR = 400; 17: 18: /** A unit cylinder, closed both ends: radius 1 in xz around y, y from 0 to 1. The vertex shader 19: * stretches it to the plume's bounds. */ 20: export const PLUME_HULL = new THREE.LatheGeometry([0, 1, 1, 0].map((x, i) => new THREE.Vector2(x, i < 2 ? 0 : 1)), 14); 21: // culling bounds in plume space, not the unit lathe: past the longest plume (assault plus surge, 22: // about 45 radii) and the widest flash or ring 23: PLUME_HULL.boundingSphere = new THREE.Sphere(new THREE.Vector3(0, 0, 22), 34); 24: 25: const vertexShader = /* glsl */ ` 26: #include <common> 27: #include <logdepthbuf_pars_vertex> 28: uniform float uLen, uFlare, uRing, uRingA, uFlash, uHeavy; 29: varying vec3 vP; 30: varying vec3 vCam; 31: varying float vR; 32: // the ring reaches two of its widths past its radius (see glow), or the wall cuts it off flat 33: float bound() { return max(max(1.0 + uFlare * 1.15 + 0.4 * uHeavy, uRingA > 0.01 ? uRing + 2.0 * (0.35 + 0.22 * uRing) : 0.0), 1.4 + uFlash); } 34: void main() { 35: float R = bound(); 36: vR = R; 37: // (x, -z, y): a rotation, not a mirror, so the faces keep their outward winding 38: vec3 p = vec3(position.x * R, -position.z * R, mix(${Z0.toFixed(2)}, uLen + 0.5, position.y)); 39: vP = p; 40: vCam = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz; 41: gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0); 42: #include <logdepthbuf_vertex> 43: }`; 44: 45: const fragmentShader = /* glsl */ ` 46: #include <logdepthbuf_pars_fragment> 47: uniform float uLen, uFlare, uPower, uCore, uDiamonds, uHeavy, uFlash, uRing, uRingA, uTime, uSeed; 48: uniform vec3 uColor, uHot; 49: varying vec3 vP; 50: varying vec3 vCam; 51: varying float vR; 52: 53: float hash(vec3 p) { p = fract(p * 0.3183099 + 0.1); p *= 17.0; return fract(p.x * p.y * p.z * (p.x + p.y + p.z)); } 54: float noise(vec3 x) { 55: vec3 i = floor(x); vec3 f = fract(x); f = f * f * (3.0 - 2.0 * f); 56: return mix(mix(mix(hash(i), hash(i + vec3(1,0,0)), f.x), mix(hash(i + vec3(0,1,0)), hash(i + vec3(1,1,0)), f.x), f.y), 57: mix(mix(hash(i + vec3(0,0,1)), hash(i + vec3(1,0,1)), f.x), mix(hash(i + vec3(0,1,1)), hash(i + vec3(1,1,1)), f.x), f.y), f.z); 58: } 59: 60: // emission at a point, plume space (the throat glow is added analytically, after the march) 61: vec3 glow(vec3 p) { 62: float z = p.z, r2 = dot(p.xy, p.xy); 63: float s = clamp(z / uLen, 0.0, 1.0); 64: float down = 1.0 - s; 65: // mantle: flares out past the exit (vacuum), breaks into streaks downstream, ragged at the edge. 66: // A heavy burn starts it wider and carries it further before it thins 67: float n = noise(vec3(p.xy * 1.7, z * 0.22 - uTime * 24.0) + uSeed); 68: float n2 = noise(vec3(p.xy * 3.1, z * 0.5 - uTime * 45.0) + uSeed * 1.7); 69: float rj = (0.7 + 0.3 * uHeavy + uFlare * (1.0 - exp(-max(z, 0.0) * 0.3))) * (1.0 + 0.12 * (2.0 * n - 1.0) * smoothstep(0.2, 0.8, s)); 70: float turb = mix(1.0, 0.1 + 1.8 * (n * 0.65 + n2 * 0.35), smoothstep(0.05, 0.45, s)); 71: float mantle = exp(-r2 / (rj * rj) * 2.0) * pow(down, 1.5 - 0.6 * uHeavy) * turb * smoothstep(${Z0.toFixed(2)}, 0.4, z); 72: // core: a narrow jet over half the plume, white at the exit and the exhaust colour by its tip; 73: // shock diamonds pinch and brighten it in three cells. A heavy burn fattens it 74: float sc = clamp(z / (uLen * 0.6), 0.0, 1.0); 75: float band = pow(0.5 + 0.5 * cos(18.85 * sc - 3.1416), 3.0) * uDiamonds; 76: float rc = (0.34 - 0.12 * band) * (1.0 + 0.45 * uHeavy); 77: float core = exp(-r2 / (rc * rc) * 2.0) * pow(1.0 - sc, 1.5) * step(0.0, z) * uCore * (1.0 + 1.5 * band); 78: // shock ring: a soft torus thrown out from the exit and carried a little downstream 79: float w = 0.35 + 0.22 * uRing; 80: float dr = sqrt(r2) - uRing, dz = z - 0.3 - 0.6 * uRing; 81: float ring = exp(-(dr * dr + dz * dz) / (w * w)) * uRingA * (0.6 + 0.6 * n); 82: vec3 tint = uColor * mix(vec3(1.0), vec3(0.65, 0.75, 1.2), s); 83: return tint * (mantle * 0.7 + ring * 0.7) + mix(uHot, uColor * 1.4, sc) * core * 2.6 + uHot * ring * 0.15; 84: } 85: 86: void main() { 87: #include <logdepthbuf_fragment> 88: vec3 rd = normalize(vP - vCam); 89: float R = vR, zEnd = uLen + 0.5; 90: bool inside = dot(vCam.xy, vCam.xy) < R * R && vCam.z > ${Z0.toFixed(2)} && vCam.z < zEnd; 91: vec3 ro; 92: float len; 93: if (inside) { 94: if (gl_FrontFacing) discard; 95: ro = vCam; 96: len = length(vP - vCam); 97: } else { 98: if (!gl_FrontFacing) discard; 99: ro = vP; 100: // leave the cylinder through its wall or an end 101: float a = dot(rd.xy, rd.xy), b = dot(vP.xy, rd.xy), c = dot(vP.xy, vP.xy) - R * R; 102: float tw = a > 1e-6 ? (-b + sqrt(max(b * b - a * c, 0.0))) / a : 1e6; 103: float te = rd.z > 0.0 ? (zEnd - vP.z) / rd.z : (${Z0.toFixed(2)} - vP.z) / min(rd.z, -1e-6); 104: len = max(0.0, min(tw, te)); 105: } 106: // far plumes are a few pixels: half the steps (distance in nozzle radii) 107: int n = dot(vCam, vCam) > ${FAR * FAR}.0 ? ${STEPS / 2} : ${STEPS}; 108: float dt = len / float(n); 109: // interleaved gradient noise jitters the start, so few steps don't band 110: float j = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))); 111: vec3 sum = vec3(0.0); 112: for (int i = 0; i < ${STEPS}; i++) { 113: if (i >= n) break; 114: sum += glow(ro + rd * ((float(i) + j) * dt)); 115: } 116: // the throat glow, a small gaussian ball in the exit: integrated along the ray in closed form, so 117: // few steps never miss it end on. An ignition flash and a heavy burn swell it. 118: float fr = 0.35 + 0.2 * uCore + 0.35 * uFlash + 0.2 * uHeavy; 119: vec3 oc = vec3(0.0, 0.0, 0.15) - ro; 120: float tc = dot(oc, rd); 121: float d2 = dot(oc, oc) - tc * tc; 122: float throat = 1.7725 * fr * exp(-d2 / (fr * fr)) * smoothstep(-fr, fr, tc) * smoothstep(-fr, fr, len - tc); 123: sum = sum * dt + uHot * throat * (0.5 + 0.8 * uCore + 1.0 * uFlash + 0.2 * uHeavy) * 1.2; 124: gl_FragColor = vec4(sum * uPower, 1.0); 125: }`; 126: 127: /** A plume material: shared by every nozzle of one kind on one frame, since they fire together. */ 128: export function plumeMaterial(color: THREE.Color, brightness: number, seed: number): THREE.ShaderMaterial { 129: return new THREE.ShaderMaterial({ 130: transparent: true, 131: depthWrite: false, 132: blending: THREE.AdditiveBlending, 133: side: THREE.DoubleSide, 134: uniforms: { 135: uLen: { value: 1 }, uFlare: { value: 0 }, uPower: { value: 0 }, uCore: { value: 0 }, uDiamonds: { value: 0 }, uHeavy: { value: 0 }, 136: uFlash: { value: 0 }, uRing: { value: 0 }, uRingA: { value: 0 }, uTime: { value: 0 }, uSeed: { value: seed }, 137: uColor: { value: color.clone().multiplyScalar(brightness) }, 138: // the core: the exhaust colour run almost to white 139: uHot: { value: color.clone().lerp(new THREE.Color(1, 1, 1), 0.82).multiplyScalar(brightness) }, 140: }, 141: vertexShader, 142: fragmentShader, 143: }); 144: } 145: 146: /** Copy a plume's numbers into its material. */ 147: export function setPlume(m: THREE.ShaderMaterial, p: Plume, time: number) { 148: const u = m.uniforms; 149: // the length breathes a little, faster than the eye follows 150: u.uLen.value = p.length * (0.96 + 0.04 * Math.sin(time * 53 + u.uSeed.value * 3)); 151: u.uFlare.value = p.flare; 152: // a fast flicker on top of the turbulence 153: const flicker = 0.9 + 0.1 * Math.sin(time * 71.3 + u.uSeed.value); 154: u.uPower.value = Math.min(1.5, p.level * 1.3 + 0.25 * p.flash) * flicker; 155: u.uCore.value = p.core; 156: u.uDiamonds.value = p.diamonds; 157: u.uHeavy.value = p.heavy; 158: u.uFlash.value = p.flash; 159: u.uRing.value = p.ring; 160: u.uRingA.value = p.ringA; 161: // wrapped, so a long session keeps float precision in the noise (one invisible jump every 128 s) 162: u.uTime.value = time % 128; 163: } 164: 165: /** Whether a plume draws anything. */ 166: export const plumeVisible = (p: Plume) => p.level > 0.01 || p.flash > 0.02 || p.ringA > 0.02;read_file{"EndLine":160,"Path":"~/work/sortie/src/render/palette.ts","StartLine":1}
input
{ "EndLine": 160, "Path": "~/work/sortie/src/render/palette.ts", "StartLine": 1 }result, 161 lines
Showing lines 1-160 of 175 1: // Material roles are named in the kit (kit/lib.py). A palette paints every role; factions and 2: // companies get their own palettes, the models stay the same. 3: 4: export type Role = 5: | 'main' | 'accent' | 'trim' | 'frame' | 'joint' | 'visor' | 'metal' | 'sensor' 6: | 'glow_eye' | 'glow_core' | 'glow_thruster' | 'glow_beam' | 'glow_exhaust' 7: | 'hull' | 'hull_dark' | 'interior' | 'deck' | 'hazard' | 'light' | 'screen' | 'glass' 8: | 'lamp_red' | 'lamp_green' | 'suit' | 'glow_hot' 9: // raider salvage: paint from the donor machines, primer patches, bare rust and hand paint 10: | 'donor_a' | 'donor_b' | 'donor_c' | 'primer' | 'rust' | 'handpaint' | 'warpaint' 11: | 'crystal' | 'crystal_lit' | 'glow_violet' 12: // markings on plates: pattern codes, service text, unit codes 13: | 'stencil'; 14: 15: export interface Paint { 16: color: string; 17: /** Emissive roles: brightness multiplier, values above 1 feed the bloom. */ 18: glow?: number; 19: /** Physically based surface: roughness, metalness, clearcoat (paint sheen). */ 20: rough?: number; 21: metal?: number; 22: coat?: number; 23: /** Rust blotches and streaks over the surface, 0..1 (raider salvage). */ 24: rust?: number; 25: /** A lit surface that also gives off its own colour at this strength (lit from inside). */ 26: emit?: number; 27: /** Painted roles: a lacquered finish, 0..1, kept under every look: roughness no higher than `rough`, less 28: * weathering of the colour, and from 0.5 a clear coat this strong. */ 29: lacquer?: number; 30: } 31: 32: export type Palette = Record<Role, Paint>; 33: 34: const paint = (color: string, rough = 0.42, coat = 0.35): Paint => ({ color, rough, metal: 0, coat }); 35: const metal = (color: string, rough = 0.42, m = 0.85): Paint => ({ color, rough, metal: m }); 36: 37: const base: Palette = { 38: main: paint('#d9dce1'), 39: accent: paint('#27527a'), 40: trim: paint('#c9452f', 0.4), 41: frame: metal('#5b6069', 0.48, 0.8), 42: joint: metal('#33363c', 0.55, 0.9), 43: visor: { color: '#06080b', rough: 0.22, metal: 0.2, coat: 1 }, 44: metal: metal('#9aa0a8', 0.3, 1), 45: sensor: { color: '#1d6b5c', rough: 0.2, metal: 0.3, coat: 1 }, 46: glow_eye: { color: '#7ef7e6', glow: 4 }, 47: glow_core: { color: '#7ef7e6', glow: 2.4 }, 48: /** The lit throat inside a thruster bell, the exhaust's colour. */ 49: glow_thruster: { color: '#9cc6ff', glow: 3 }, 50: /** Thruster plumes (render/plume.ts): the mantle colour, the core runs it to white. Glow scales 51: * the whole plume. A maker or faction tints its drives here. */ 52: glow_exhaust: { color: '#4f8fff', glow: 1 }, 53: glow_beam: { color: '#ff5ccf', glow: 5 }, 54: hull: paint('#a9adb4', 0.55, 0.15), 55: hull_dark: metal('#4a4f57', 0.6, 0.6), 56: interior: metal('#5e6168', 0.7, 0.3), 57: deck: metal('#3f434a', 0.7, 0.6), 58: hazard: paint('#e3b62b', 0.6, 0), 59: light: { color: '#fff3df', glow: 1.7 }, 60: screen: { color: '#4fd8cc', glow: 1.6 }, 61: glass: { color: '#8f9fc4', rough: 0.22, metal: 0.1, coat: 1 }, 62: lamp_red: { color: '#ff3a2e', glow: 4 }, 63: lamp_green: { color: '#48ff6c', glow: 4 }, 64: suit: paint('#1f2a4f', 0.6, 0), 65: /** The white-hot core inside an eye or sensor lamp. */ 66: glow_hot: { color: '#eafffb', glow: 2.6 }, 67: /** Donor paint on salvaged parts: in a clean palette, the merc's own colours and an olive. */ 68: donor_a: paint('#d9dce1'), 69: donor_b: paint('#27527a'), 70: donor_c: paint('#5c6143'), 71: primer: paint('#8a8d84', 0.7, 0), 72: rust: metal('#6a3a20', 0.85, 0.35), 73: handpaint: paint('#ece4cc', 0.7, 0), 74: warpaint: paint('#c9452f', 0.6, 0), 75: /** The aliens' one material: unpainted silver, no seams. */ 76: crystal: metal('#c6c9d0', 0.44, 0.95), 77: /** Alien crystal lit from inside by the core, the lining of an opened geode. */ 78: crystal_lit: { color: '#a796dc', rough: 0.4, metal: 0.9, emit: 0.42 }, 79: /** The alien core light. */ 80: glow_violet: { color: '#7b3dff', glow: 2.6 }, 81: /** Stencilled markings: dark ink on light plates, light ink on dark ones. */ 82: stencil: { color: '#23272d', rough: 0.7, metal: 0 }, 83: }; 84: 85: const worn = (color: string, rust: number, rough = 0.6): Paint => ({ color, rough, metal: 0, coat: 0, rust }); 86: 87: export const PALETTES = { 88: /** The player's default frame paint. */ 89: merc: base, 90: /** The Administration: gate white plates, petrol blue accent blocks (the chest, the boots, the cheeks), 91: * gate cyan lights and trim. A light livery, so the frame goes darker to keep the value step. */ 92: admin: { 93: ...base, 94: main: paint('#e4e8eb'), 95: accent: paint('#1b5c5a', 0.45), 96: trim: paint('#3fa7c9', 0.35), 97: frame: metal('#3a3e45', 0.5, 0.8), 98: joint: metal('#24262b', 0.55, 0.9), 99: glow_eye: { color: '#5fd0f0', glow: 4 }, 100: glow_core: { color: '#5fd0f0', glow: 2.4 }, 101: glow_hot: { color: '#e6fbff', glow: 2.6 }, 102: glow_thruster: { color: '#9ee6ff', glow: 3 }, 103: glow_exhaust: { color: '#3fc4ff', glow: 1 }, 104: }, 105: /** The houses: lacquered wine plates, ivory accent fields (the crest, the breastplate, the back panel, the 106: * tabard and the shield pale), warm gold trim on the hems and the crest's edge, emerald lenses and pale gold 107: * drives. The wine is lifted a step and lacquered so its curves carry highlights, the frame is a darker, less 108: * metallic steel so the plates keep a value step above it in shade too (docs/study-atelier.md). */ 109: houses: { 110: ...base, 111: main: { ...paint('#781c33', 0.36, 0.5), lacquer: 0.45 }, 112: accent: { ...paint('#ece3cc', 0.38, 0.4), lacquer: 0.4 }, 113: trim: metal('#e6b84a', 0.3, 0.75), 114: frame: metal('#4c5058', 0.55, 0.4), 115: joint: metal('#3a3c42', 0.55, 0.9), 116: metal: metal('#b5ab98', 0.3, 1), 117: stencil: { color: '#e6dcc4', rough: 0.7, metal: 0 }, 118: glow_eye: { color: '#4dffa6', glow: 4 }, 119: // the reactor glow through the chest sides stays low, the lenses carry the green 120: glow_core: { color: '#2fb877', glow: 0.7 }, 121: glow_hot: { color: '#eafff2', glow: 2.6 }, 122: glow_thruster: { color: '#ffe3a8', glow: 3 }, 123: glow_exhaust: { color: '#ffcf6a', glow: 1 }, 124: }, 125: /** Automated pilotless frames: black and gunmetal shell, red only in lenses, seam lines and stencils. The 126: * gunmetal is light enough to read as a block against the black at range. */ 127: automaton: { 128: ...base, 129: main: paint('#1d1e23', 0.38), 130: accent: paint('#5e646c', 0.34), 131: metal: metal('#3e4046', 0.5, 0.8), 132: trim: paint('#d12b35', 0.4), 133: frame: metal('#2c2d33', 0.5), 134: stencil: { color: '#c9c4b8', rough: 0.7, metal: 0 }, 135: glow_eye: { color: '#ff2f3f', glow: 4.5 }, 136: glow_core: { color: '#ff2f3f', glow: 5 }, 137: glow_hot: { color: '#ffe4e4', glow: 2.6 }, 138: glow_thruster: { color: '#ff9a7a', glow: 3 }, 139: glow_exhaust: { color: '#ff3a2a', glow: 1 }, 140: }, 141: /** Raiders: sun-faded salvage in three donors' paint, primer patches, rust, hand paint. */ 142: raider: { 143: ...base, 144: main: worn('#9c8550', 0.35), 145: accent: worn('#5e2c22', 0.3), 146: trim: worn('#c0561a', 0.3), 147: frame: { ...metal('#4d4842', 0.6, 0.75), rust: 0.25 }, 148: joint: metal('#2f2c29', 0.62, 0.85), 149: metal: { ...metal('#8c8780', 0.45, 0.9), rust: 0.3 }, 150: hazard: worn('#d9a92a', 0.3), 151: donor_a: worn('#c6c3b8', 0.3), 152: donor_b: worn('#3e566e', 0.3), 153: donor_c: worn('#5c6143', 0.35), 154: primer: worn('#8a8d84', 0.2, 0.75), 155: rust: { ...metal('#5e3019', 0.85, 0.35), rust: 0.75 }, 156: handpaint: worn('#ece4cc', 0.15, 0.75), 157: warpaint: worn('#9e1f16', 0.2, 0.7), 158: stencil: worn('#2a2723', 0.2, 0.8), 159: glow_eye: { color: '#ffb347', glow: 4 }, 160: glow_core: { color: '#ff9a3c', glow: 2.6 },read_file{"EndLine":160,"Path":"~/work/sortie/src/render/assets.ts","StartLine":1}
input
{ "EndLine": 160, "Path": "~/work/sortie/src/render/assets.ts", "StartLine": 1 }result, 161 lines
Showing lines 1-160 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' | 'atelier_estoc' | 'atelier_tilt' | '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++) {read_file{"EndLine":120,"Path":"~/work/sortie/kit/props.py","StartLine":1}
input
{ "EndLine": 120, "Path": "~/work/sortie/kit/props.py", "StartLine": 1 }result, 70 lines
Showing lines 1-69 of 69 1: """Weapons and the training drone. 2: 3: Weapons are authored around their grip: the handle runs down from the origin (where a hand's grip.* 4: empty sits) and the barrel points -Y. A "muzzle" empty marks where shots leave. 5: """ 6: from mathutils import Matrix 7: 8: from lib import circle, cylinder, empty, loft, merge, octo, prism, rot, solid, transform, two_view 9: from mech import gltf_dir 10: 11: 12: def build_rifle(): 13: root = empty("rifle", (0, 0, 0), weapon="beam_rifle") 14: solid("handle", transform(loft([(-1.0, octo(.3, .5, .08, y=.05)), (.2, octo(.32, .52, .08, y=.05))]), 15: rot("X", 14)), "frame", root, 0.03) 16: solid("receiver", loft([(1.7, octo(.6, .95, .16, y=.62)), (-2.5, octo(.62, 1.0, .16, y=.62))], axis="y"), 17: "metal", root, 0.05) 18: solid("receiver_top", loft([(1.2, octo(.5, .3, .08, y=1.2)), (-2.2, octo(.5, .3, .08, y=1.2))], axis="y"), 19: "frame", root, 0.03) 20: solid("stock", loft([(1.6, octo(.5, .8, .15, y=.55)), (3.1, octo(.44, 1.05, .15, y=.42))], axis="y"), 21: "frame", root, 0.04) 22: solid("shroud", loft([(-2.4, octo(.52, .6, .14, y=.72)), (-4.7, octo(.46, .52, .12, y=.74))], axis="y"), 23: "metal", root, 0.04) 24: solid("barrel", cylinder(.17, -4.6, -5.7, 10, axis="y", at=(0, .74)), "frame", root, smooth=True) 25: solid("muzzle_ring", cylinder(.26, -5.6, -5.92, 10, axis="y", at=(0, .74)), "accent", root, smooth=True) 26: solid("muzzle_glow", cylinder(.12, -5.93, -5.95, 10, axis="y", at=(0, .74)), "glow_beam", root, outline=False) 27: solid("scope", loft([(-1.25, octo(.34, .4, .08, y=1.48)), (.25, octo(.34, .4, .08, y=1.48))], axis="y"), 28: "frame", root, 0.03) 29: solid("lens", prism(circle(.13, 6, 0, 1.48, phase=0), -1.32, -1.24, "xz"), "glow_eye", root, outline=False) 30: solid("cell", two_view([(-.27, -.6), (.27, -.6), (.27, .25), (-.27, .25)], 31: [(-1.45, -.7), (-.75, -.7), (-.55, .25), (-1.35, .25)]), "accent", root, 0.04) 32: empty("muzzle", (0, -5.96, .74), root, dir=gltf_dir((0, -1, 0))) 33: return root 34: 35: 36: def build_cannon(): 37: root = empty("cannon", (0, 0, 0), weapon="heavy_cannon") 38: solid("handle", transform(loft([(-1.0, octo(.32, .5, .08, y=.05)), (.25, octo(.34, .52, .08, y=.05))]), 39: rot("X", 12)), "frame", root, 0.03) 40: solid("tube", loft([(2.6, circle(.62, 12, 0, 1.0)), (-5.4, circle(.62, 12, 0, 1.0))], axis="y"), 41: "hull_dark", root, smooth=True) 42: solid("tube_band", loft([(-2.0, circle(.7, 12, 0, 1.0)), (-2.6, circle(.7, 12, 0, 1.0))], axis="y"), 43: "trim", root, smooth=True) 44: solid("breech", loft([(1.6, octo(1.45, 1.6, .3, y=1.0)), (3.0, octo(1.3, 1.4, .3, y=1.0))], axis="y"), 45: "main", root, 0.05) 46: solid("muzzle", loft([(-5.3, circle(.82, 12, 0, 1.0)), (-6.1, circle(.78, 12, 0, 1.0))], axis="y"), 47: "frame", root, smooth=True) 48: solid("drum", cylinder(.75, -.35, .35, 12, axis="x", at=(.4, .2)), "accent", root, smooth=True) 49: solid("sight", loft([(-.5, octo(.3, .45, .08, y=1.9)), (.6, octo(.3, .45, .08, y=1.9))], axis="y"), 50: "frame", root, 0.03) 51: empty("muzzle", (0, -6.15, 1.0), root, dir=gltf_dir((0, -1, 0))) 52: return root 53: 54: 55: def build_drone(): 56: root = empty("drone", (0, 0, 0), target="drone") 57: solid("core", loft([(-1.5, octo(.3, .3, .1)), (0, octo(2.2, 2.2, .7)), (1.5, octo(.3, .3, .1))]), 58: "main", root, 0.05) 59: ring = [] 60: for i in range(8): 61: seg = loft([(-.18, octo(1.15, .32, .06, y=-2.5)), (.18, octo(1.15, .32, .06, y=-2.5))]) 62: ring.append(transform(seg, rot("Z", 45 * i))) 63: solid("ring", merge(*ring), "trim", root, 0.03) 64: for i in range(4): 65: fin = prism([(1.1, -.45), (1.1, .5), (3.3, .2), (3.1, -.3)], -.07, .07, "yz") 66: solid(f"fin{i}", transform(fin, rot("Z", 90 * i + 45)), "frame", root, 0.02) 67: solid("eye", prism(circle(.35, 8, 0, 0), -1.25, -1.05, "xz"), "glow_eye", root, outline=False) 68: solid("eye_rim", prism(circle(.5, 8, 0, 0), -1.2, -.8, "xz"), "frame", root, 0.02) 69: return root