/** * The generator's conformance gate. Headless, no GPU. * * Runs every body style and a spread of random seeds through the generator * and checks what a game relies on: finite geometry, triangle budgets per * LOD, wheels on the ground, a rig whose hinges stay put, determinism, * blendability, every mod on every kind of body, a collider that encloses * the car, and a dispose that can be called twice. * * bun scripts/verify.ts */ import { Box3, Mesh, type Object3D, Vector3 } from 'three' import { BODY_STYLES, blendSpecs, generateVehicle, MOD_KINDS, MODS, preset, randomSpec, type Vehicle, type VehicleSpec, } from '../src/generator/index.ts' import { normalizeSpec, parseLibrary, toLibraryFile } from '../src/library/format.ts' import { addEntry, createLibrary, duplicateEntry, moveEntry, removeEntry, renameEntry } from '../src/library/store.ts' import { zip } from '../src/library/zip.ts' const failures: string[] = [] let checks = 0 function expect(label: string, ok: boolean, detail = ''): void { checks += 1 if (!ok) { failures.push(label) console.log(` FAIL ${label}${detail ? ` — ${detail}` : ''}`) } } // Stock vehicles stay under 60k triangles on LOD0; mods may add up to 6k on top. const BUDGET = { lod0: [15000, 60000], lod0Modded: 66000, lod1Ratio: 0.55, lod2Ratio: 0.5, lod2Max: 7000, drawCalls: 72, ms: 2000 } as const function fingerprint(root: Object3D): string { let hash = 2166136261 root.updateMatrixWorld(true) root.traverse((o) => { if (!(o instanceof Mesh)) return for (const c of o.name) { hash ^= c.charCodeAt(0); hash = Math.imul(hash, 16777619) } for (const name of ['position', 'normal', 'color'] as const) { const a = o.geometry.getAttribute(name)?.array as ArrayLike | undefined if (!a) continue for (let i = 0; i < a.length; i += 1) { hash ^= Math.round(a[i]! * 1e5) | 0 hash = Math.imul(hash, 16777619) } } }) return (hash >>> 0).toString(16) } function meshBox(root: Object3D, filter: (m: Mesh) => boolean): Box3 { const box = new Box3() root.updateMatrixWorld(true) root.traverse((o) => { if (o instanceof Mesh && filter(o)) box.expandByObject(o) }) return box } function findNode(root: Object3D, name: string): Object3D | undefined { let hit: Object3D | undefined root.traverse((o) => { if (!hit && o.name === name) hit = o }) return hit } function checkVehicle(label: string, spec: VehicleSpec): Vehicle { const t0 = performance.now() const v = generateVehicle(spec) const ms = performance.now() - t0 expect(`${label}: generated in < ${BUDGET.ms} ms`, ms < BUDGET.ms, `${ms.toFixed(0)} ms`) expect(`${label}: three LODs`, v.lods.length === 3) // --- geometry validity let bad = 0 let badNormals = 0 let emptyMeshes = 0 v.group.traverse((o) => { if (!(o instanceof Mesh)) return const p = o.geometry.getAttribute('position').array as ArrayLike const n = o.geometry.getAttribute('normal').array as ArrayLike if (p.length === 0) emptyMeshes += 1 for (let i = 0; i < p.length; i += 1) if (!Number.isFinite(p[i]!)) bad += 1 for (let i = 0; i < n.length; i += 3) { const l = Math.hypot(n[i]!, n[i + 1]!, n[i + 2]!) if (!Number.isFinite(l) || Math.abs(l - 1) > 1e-3) badNormals += 1 } const index = o.geometry.getIndex() if (index) { const count = o.geometry.getAttribute('position').count for (let i = 0; i < index.count; i += 1) if (index.getX(i) >= count) bad += 1 } }) expect(`${label}: finite positions, valid indices`, bad === 0, `${bad} bad values`) expect(`${label}: unit normals`, badNormals === 0, `${badNormals} bad normals`) expect(`${label}: no empty meshes`, emptyMeshes === 0) // --- budgets const [l0, l1, l2] = v.lods const cap = spec.mods.some((m) => m.kind !== 'rollCage') ? BUDGET.lod0Modded : BUDGET.lod0[1] expect(`${label}: LOD0 within ${BUDGET.lod0[0]}–${cap} triangles`, l0!.triangles >= BUDGET.lod0[0] && l0!.triangles <= cap, `${l0!.triangles}`) expect(`${label}: LOD1 ≤ ${BUDGET.lod1Ratio} × LOD0`, l1!.triangles <= l0!.triangles * BUDGET.lod1Ratio, `${l1!.triangles} vs ${l0!.triangles}`) expect(`${label}: LOD2 ≤ ${BUDGET.lod2Ratio} × LOD1 and ≤ ${BUDGET.lod2Max}`, l2!.triangles <= l1!.triangles * BUDGET.lod2Ratio && l2!.triangles <= BUDGET.lod2Max, `${l2!.triangles}`) expect(`${label}: ≤ ${BUDGET.drawCalls} draw calls on LOD0`, l0!.meshes <= BUDGET.drawCalls, `${l0!.meshes}`) // --- names are unique inside one LOD (glTF addresses animations by name) for (const level of v.lods) { const names = new Map() level.group.traverse((o) => names.set(o.name, (names.get(o.name) ?? 0) + 1)) const dup = [...names].filter(([n, c]) => n && c > 1).map(([n]) => n) expect(`${label}: unique node names in LOD${level.level}`, dup.length === 0, dup.slice(0, 4).join(', ')) } // --- wheels const lod0 = l0!.group expect(`${label}: four wheels`, v.wheels.length === 4 && v.rig.wheels.length === 4) expect(`${label}: only the front wheels steer`, v.wheels.every((w) => w.steer === (w.axle === 'front'))) expect(`${label}: at least one axle driven`, v.wheels.some((w) => w.drive)) for (const w of v.wheels) { const tyre = meshBox(lod0, (m) => m.name === `wheel_${w.id}_tyre`) expect(`${label}: ${w.id} tyre on the ground`, Math.abs(tyre.min.y) < 0.012, `min y ${tyre.min.y.toFixed(4)}`) } const body = meshBox(lod0, (m) => !m.name.startsWith('wheel_') && !m.name.startsWith('mod_')) expect(`${label}: body clears the ground`, body.min.y > 0.02, `min y ${body.min.y.toFixed(3)}`) // --- rig: every opening panel swings about a hinge that stays put for (const part of v.rig.openables) { const node = findNode(lod0, part) expect(`${label}: ${part} node exists`, node !== undefined) if (!node) continue const pivot = node.getWorldPosition(new Vector3()) const before = meshBox(node, () => true) v.rig.open(part, 1) const after = meshBox(node, () => true) const moved = before.min.distanceTo(after.min) + before.max.distanceTo(after.max) expect(`${label}: ${part} opens`, moved > 0.05, `moved ${moved.toFixed(3)}`) const pivotAfter = node.getWorldPosition(new Vector3()) expect(`${label}: ${part} hinge stays put`, pivot.distanceTo(pivotAfter) < 1e-9) expect(`${label}: ${part} hinge lies on the panel`, after.distanceToPoint(pivot) < 0.08, `${after.distanceToPoint(pivot).toFixed(3)} m`) v.rig.open(part, 0) const closed = meshBox(node, () => true) expect(`${label}: ${part} closes exactly`, closed.min.distanceTo(before.min) + closed.max.distanceTo(before.max) < 1e-6) } const expectedDoors = spec.body.doors * 2 const doors = v.rig.openables.filter((p) => p.startsWith('door')).length expect(`${label}: ${expectedDoors} doors rigged`, doors === expectedDoors || spec.style === 'buggy', `${doors}`) // --- steering const fl = findNode(lod0, 'wheel_FL')! const rl = findNode(lod0, 'wheel_RL')! const wheelNode = findNode(lod0, 'steering_wheel') v.rig.setSteer(0.4) expect(`${label}: front wheels steer`, Math.abs(fl.rotation.y) > 0.3) expect(`${label}: rear wheels do not`, rl.rotation.y === 0) const fr = findNode(lod0, 'wheel_FR')! expect(`${label}: Ackermann — inner wheel turns more`, fl.rotation.y > fr.rotation.y, `${fl.rotation.y.toFixed(3)} / ${fr.rotation.y.toFixed(3)}`) if (wheelNode) expect(`${label}: steering wheel turns`, Math.abs(wheelNode.rotation.z) > 1) v.rig.setSteer(0) v.rig.update(0.5, 10) const spin = findNode(lod0, 'wheel_FL_spin')! expect(`${label}: wheels roll with speed`, Math.abs(spin.rotation.x - (10 * 0.5) / v.wheels[0]!.radius) < 1e-9) v.rig.setWheelSpin(0) // Body roll: the sprung body leans, the wheels stay where they are. { const bodyNode = findNode(lod0, 'body')! const tyres = meshBox(lod0, (m) => m.name.startsWith('wheel') && m.name.endsWith('_tyre')) const before = meshBox(bodyNode, () => true) v.rig.setBodyPose(0.05, 0.02) const leaned = meshBox(bodyNode, () => true) const tyresAfter = meshBox(lod0, (m) => m.name.startsWith('wheel') && m.name.endsWith('_tyre')) expect(`${label}: body rolls`, leaned.min.distanceTo(before.min) > 0.005) expect(`${label}: wheels stay planted while the body rolls`, tyres.min.distanceTo(tyresAfter.min) + tyres.max.distanceTo(tyresAfter.max) < 1e-9) if (v.rig.openables.length) { const part = v.rig.openables[0]! v.rig.open(part, 1) v.rig.open(part, 0) } v.rig.setBodyPose(0, 0) const back = meshBox(bodyNode, () => true) expect(`${label}: body pose resets exactly`, back.min.distanceTo(before.min) + back.max.distanceTo(before.max) < 1e-6) } // --- glass: present on every level, facing out of the cabin, no slivers for (const level of v.lods) { level.group.updateMatrixWorld(true) const centre = new Vector3(0, (v.bounds.min.y + v.bounds.max.y) / 2, (v.bounds.min.z + v.bounds.max.z) / 2) let glassTris = 0 let outward = 0 let total = 0 let slivers = 0 let tris = 0 const a = new Vector3(), b = new Vector3(), c = new Vector3(), n = new Vector3(), m = new Vector3() level.group.traverse((o) => { const mesh = o as Mesh if (!mesh.isMesh) return const pos = mesh.geometry.getAttribute('position') const index = mesh.geometry.getIndex() const count = index ? index.count : pos.count const glass = mesh.name.includes('_glass') for (let i = 0; i < count; i += 3) { const at = (k: number): number => (index ? index.getX(i + k) : i + k) a.fromBufferAttribute(pos, at(0)).applyMatrix4(mesh.matrixWorld) b.fromBufferAttribute(pos, at(1)).applyMatrix4(mesh.matrixWorld) c.fromBufferAttribute(pos, at(2)).applyMatrix4(mesh.matrixWorld) n.subVectors(b, a).cross(m.subVectors(c, a)) const area = n.length() / 2 tris += 1 if (area < 1e-10) slivers += 1 if (!glass) continue glassTris += 1 total += area m.copy(a).add(b).add(c).divideScalar(3).sub(centre) if (n.dot(m) > 0) outward += area } }) const lvl = `LOD${v.lods.indexOf(level)}` if (spec.style !== 'buggy') { expect(`${label}: ${lvl} has glass`, glassTris > 0, `${glassTris}`) expect(`${label}: ${lvl} glass faces out of the cabin`, outward / Math.max(total, 1e-9) > 0.85, `${((100 * outward) / Math.max(total, 1e-9)).toFixed(1)} %`) } expect(`${label}: ${lvl} no degenerate triangles`, slivers / tris < 0.002, `${slivers} of ${tris}`) } if (spec.style !== 'buggy' && spec.style !== 'pickup' && spec.style !== 'truck') { expect(`${label}: boot or tailgate opens`, v.rig.openables.includes('trunk')) } // A tailgate car (short deck) shows its rear glass at the back, on the // roof slope or set into the gate; a van with a blank rear face fails. if (spec.body.deck < 0.1 && spec.style !== 'buggy' && spec.style !== 'pickup' && spec.style !== 'truck' && v.rig.openables.includes('trunk')) { const rearGlass = meshBox(lod0, (m) => m.name.includes('_glass')) expect(`${label}: rear glass reaches the back`, rearGlass.min.z < v.bounds.min.z + 0.6, `${(rearGlass.min.z - v.bounds.min.z).toFixed(2)} m from the tail`) } // --- collider const hull = v.collider.hull const hullTris = hull.getAttribute('position').count / 3 expect(`${label}: collider hull has 20–2000 triangles`, hullTris >= 20 && hullTris <= 2000, `${hullTris}`) hull.computeBoundingBox() const hb = hull.boundingBox! // Against the level the hull is built from: mirrors and other LOD0 details // are deliberately not part of a collision shape. const coarse = meshBox(l2!.group, (m) => !m.name.startsWith('wheel_') && !m.name.startsWith('mod_')) const bodySize = coarse.getSize(new Vector3()) const hullSize = hb.getSize(new Vector3()) expect(`${label}: hull encloses ≥ 90 % of the body extent`, hullSize.x >= bodySize.x * 0.9 && hullSize.y >= bodySize.y * 0.8 && hullSize.z >= bodySize.z * 0.9, `${hullSize.toArray().map((n) => n.toFixed(2))} vs ${bodySize.toArray().map((n) => n.toFixed(2))}`) let volume = 0 const hp = hull.getAttribute('position') for (let i = 0; i < hp.count; i += 3) { const a = new Vector3().fromBufferAttribute(hp, i) const b = new Vector3().fromBufferAttribute(hp, i + 1) const c = new Vector3().fromBufferAttribute(hp, i + 2) volume += a.dot(b.cross(c)) / 6 } expect(`${label}: hull wound outward`, volume > 0, `${volume.toFixed(3)}`) expect(`${label}: box colliders`, v.collider.boxes.length >= 1) expect(`${label}: animation clip per opening panel`, v.animations.filter((a) => a.name.startsWith('open_')).length === v.rig.openables.length) return v } // --- every body style console.log('body styles') const sheet: { style: string; lod: number[] }[] = [] for (const style of BODY_STYLES) { const v = checkVehicle(style, preset(style)) sheet.push({ style, lod: v.lods.map((l) => l.triangles) }) v.dispose() v.dispose() } // --- random vehicles console.log('random seeds') for (let seed = 1; seed <= 26; seed += 1) { const v = checkVehicle(`seed ${seed} (${randomSpec(seed).style})`, randomSpec(seed)) v.dispose() } // --- determinism console.log('determinism') for (const seed of [3, 77, 4096]) { const a = generateVehicle(randomSpec(seed)) const b = generateVehicle(randomSpec(seed)) const c = generateVehicle(randomSpec(seed + 1)) expect(`seed ${seed}: same seed, same bytes`, fingerprint(a.group) === fingerprint(b.group)) expect(`seed ${seed}: next seed differs`, fingerprint(a.group) !== fingerprint(c.group)) a.dispose(); b.dispose(); c.dispose() } // --- blending console.log('blending') { const a = preset('hatchback') const b = preset('suv') const at0 = generateVehicle(blendSpecs(a, b, 0)) const pure = generateVehicle(a) expect('blend t=0 is the first spec', fingerprint(at0.group) === fingerprint(pure.group)) at0.dispose(); pure.dispose() for (const t of [0.25, 0.5, 0.75]) { const v = checkVehicle(`hatchback→suv ${t}`, blendSpecs(a, b, t)) v.dispose() } } // --- every mod on every style console.log('mods') for (const style of BODY_STYLES) { const base = preset(style) const plain = generateVehicle(base, { lods: [0] }) const plainTris = plain.lods[0]!.triangles plain.dispose() for (const kind of MOD_KINDS) { const spec: VehicleSpec = { ...base, mods: [...base.mods.filter((m) => m.kind !== kind), { kind }] } let v: Vehicle | undefined try { v = generateVehicle(spec, { lods: [0] }) } catch (error) { expect(`${style} + ${kind}: builds`, false, String(error)) continue } const def = MODS[kind] if (def.build && !base.mods.some((m) => m.kind === kind)) { const node = findNode(v.lods[0]!.group, `mod_${kind}`) // Some mods skip bodies they do not fit (a roof rack on a buggy, a scoop without a bonnet). const optional = (kind === 'roofRack' && style === 'buggy') || (kind === 'hoodScoop' && v.rig.openables.indexOf('hood') < 0) || (kind === 'widebody') if (!optional) expect(`${style} + ${kind}: node mod_${kind}`, node !== undefined) } if (def.modifySpec) { expect(`${style} + ${kind}: spec modified`, JSON.stringify(v.spec) !== JSON.stringify(generateVehicle(base, { lods: [2] }).spec)) } let nan = 0 v.group.traverse((o) => { if (!(o instanceof Mesh)) return const a = o.geometry.getAttribute('position').array as ArrayLike for (let i = 0; i < a.length; i += 1) if (!Number.isFinite(a[i]!)) nan += 1 }) expect(`${style} + ${kind}: finite`, nan === 0) expect(`${style} + ${kind}: within LOD0 budget`, v.lods[0]!.triangles <= BUDGET.lod0Modded, `${v.lods[0]!.triangles} (plain ${plainTris})`) v.dispose() } // Everything at once. const all: VehicleSpec = { ...base, mods: MOD_KINDS.map((kind) => ({ kind })) } const v = generateVehicle(all, { lods: [0] }) expect(`${style}: all ${MOD_KINDS.length} mods at once, within budget`, v.lods[0]!.triangles <= BUDGET.lod0Modded && v.group.children.length > 0, `${v.lods[0]!.triangles}`) v.dispose() } // --- libraries console.log('library') { let lib = createLibrary('Test garage') ;[lib] = addEntry(lib, 'Daily', preset('hatchback')) ;[lib] = addEntry(lib, 'Daily', preset('suv')) expect('library: duplicate names made unique', lib.entries[1]!.name === 'Daily copy', lib.entries[1]!.name) const [dup, copy] = duplicateEntry(lib, lib.entries[0]!.id) lib = dup expect('library: duplicate inserted after its source', lib.entries[1]?.id === copy?.id && lib.entries.length === 3) lib = renameEntry(lib, lib.entries[0]!.id, ' Weekend ') expect('library: rename trims', lib.entries[0]!.name === 'Weekend') lib = renameEntry(lib, lib.entries[1]!.id, 'Weekend') expect('library: rename cannot collide', lib.entries[1]!.name === 'Weekend copy', lib.entries[1]!.name) lib = moveEntry(lib, lib.entries[2]!.id, 0) expect('library: move', lib.entries[0]!.spec.style === 'suv') lib = removeEntry(lib, lib.entries[0]!.id) expect('library: remove', lib.entries.length === 2 && lib.entries.every((e) => e.spec.style === 'hatchback')) const back = parseLibrary(JSON.parse(JSON.stringify(toLibraryFile(lib)))) expect('library: JSON round trip keeps names and specs', back.name === lib.name && back.entries.map((e) => e.name).join() === lib.entries.map((e) => e.name).join() && JSON.stringify(back.entries.map((e) => e.spec)) === JSON.stringify(lib.entries.map((e) => e.spec))) const partial = normalizeSpec({ style: 'pickup', body: { length: 5.6 }, mods: [{ kind: 'bullBar' }, { kind: 'nonsense' }] }) expect('library: partial spec completed from its preset', partial.body.length === 5.6 && partial.body.bed !== null && partial.mods.length === 1) let threw = false try { parseLibrary({ format: 'something-else', entries: [] }) } catch { threw = true } expect('library: foreign file rejected', threw) const archive = zip([{ name: 'a.glb', data: new Uint8Array([1, 2, 3]) }, { name: 'b.glb', data: new Uint8Array(10) }]) const view = new DataView(archive.buffer) const end = archive.length - 22 expect('zip: headers and directory', view.getUint32(0, true) === 0x04034b50 && view.getUint32(end, true) === 0x06054b50 && view.getUint16(end + 10, true) === 2) } // Livery: every pattern paints stripes on every style, lofted or authored. for (const style of BODY_STYLES) { for (const livery of ['stripes', 'side-stripe', 'rally'] as const) { const base = preset(style) const v = generateVehicle({ ...base, paint: { ...base.paint, livery } }, { lods: [0] }) let stripeTris = 0 v.group.traverse((o: Object3D) => { if (!(o instanceof Mesh) || !String((o.material as { name?: string }).name).includes('stripe')) return const g = o.geometry stripeTris += (g.index ? g.index.count : g.getAttribute('position').count) / 3 }) v.dispose() expect(`${style}: ${livery} livery painted`, stripeTris > 0, `${stripeTris} stripe triangles`) } } console.log('\nLOD triangles per style') for (const row of sheet) console.log(` ${row.style.padEnd(10)} ${row.lod.map((n) => String(n).padStart(6)).join(' ')}`) console.log(`\n${checks} checks · ${failures.length} failed`) console.log(failures.length === 0 ? 'All checks passed.' : 'Checks FAILED.') if (failures.length > 0) process.exitCode = 1