Procedural, game-ready vehicles for three.js: 13 body styles, blending, seeded random vehicles, three LODs, colliders, 13 parametric mods, paint and livery, a rig that drives, and GLB export that a game can load and drive. Ships with a studio (browser or Tauri desktop app) and a Play mode.
347 lines
14 KiB
TypeScript
347 lines
14 KiB
TypeScript
/**
|
|
* A small software rasteriser: a scene graph in, a PNG out. No browser, no GPU.
|
|
*
|
|
* It exists so a vehicle can be LOOKED AT from a script — in CI, in a review,
|
|
* in the README — without a display. Every other check is geometric, and none
|
|
* of them can say "that does not look like a pickup".
|
|
*
|
|
* Shading is deliberately simple: a key light, a sky/ground hemisphere, a
|
|
* Blinn highlight scaled by roughness and a fake environment tint for metals.
|
|
* Glass is drawn after everything opaque, blended and without depth writes.
|
|
* The image is rendered at 2× and box-filtered down for antialiasing.
|
|
*/
|
|
import { deflateSync } from 'node:zlib'
|
|
|
|
import {
|
|
Box3,
|
|
Color,
|
|
Matrix3,
|
|
Mesh,
|
|
type MeshStandardMaterial,
|
|
type Object3D,
|
|
PerspectiveCamera,
|
|
Sphere,
|
|
Vector3,
|
|
} from 'three'
|
|
|
|
interface Tri {
|
|
readonly p: [Vector3, Vector3, Vector3]
|
|
readonly n: [Vector3, Vector3, Vector3]
|
|
readonly c: [[number, number, number], [number, number, number], [number, number, number]]
|
|
readonly rough: number
|
|
readonly metal: number
|
|
readonly coat: number
|
|
readonly emissive: [number, number, number]
|
|
readonly opacity: number
|
|
}
|
|
|
|
export interface Frame {
|
|
readonly width: number
|
|
readonly height: number
|
|
readonly rgb: Float32Array
|
|
}
|
|
|
|
function collect(root: Object3D): { opaque: Tri[]; clear: Tri[] } {
|
|
root.updateMatrixWorld(true)
|
|
const opaque: Tri[] = []
|
|
const clear: Tri[] = []
|
|
root.traverseVisible((object) => {
|
|
if (!(object instanceof Mesh)) return
|
|
const g = object.geometry
|
|
const pos = g.getAttribute('position')
|
|
const nor = g.getAttribute('normal')
|
|
const col = g.getAttribute('color')
|
|
const index = g.getIndex()
|
|
const m = object.material as MeshStandardMaterial & { opacity: number; transparent: boolean }
|
|
const base = (m.color ?? new Color(1, 1, 1)) as Color
|
|
const em = m.emissive ? [m.emissive.r * m.emissiveIntensity, m.emissive.g * m.emissiveIntensity, m.emissive.b * m.emissiveIntensity] as [number, number, number] : [0, 0, 0] as [number, number, number]
|
|
const nm = new Matrix3().getNormalMatrix(object.matrixWorld)
|
|
const count = index ? index.count : pos.count
|
|
const vtx = (k: number): { p: Vector3; n: Vector3; c: [number, number, number] } => {
|
|
const i = index ? index.getX(k) : k
|
|
const p = new Vector3().fromBufferAttribute(pos, i).applyMatrix4(object.matrixWorld)
|
|
const n = nor ? new Vector3().fromBufferAttribute(nor, i).applyMatrix3(nm).normalize() : new Vector3(0, 1, 0)
|
|
const vc = col ? [col.getX(i), col.getY(i), col.getZ(i)] : [1, 1, 1]
|
|
return { p, n, c: [base.r * vc[0]!, base.g * vc[1]!, base.b * vc[2]!] }
|
|
}
|
|
for (let k = 0; k < count; k += 3) {
|
|
const a = vtx(k), b = vtx(k + 1), c = vtx(k + 2)
|
|
const tri: Tri = {
|
|
p: [a.p, b.p, c.p], n: [a.n, b.n, c.n], c: [a.c, b.c, c.c],
|
|
rough: m.roughness ?? 0.5, metal: m.metalness ?? 0, emissive: em,
|
|
coat: (m as unknown as { clearcoat?: number }).clearcoat ?? 0,
|
|
opacity: m.transparent ? m.opacity : 1,
|
|
}
|
|
;(m.transparent ? clear : opaque).push(tri)
|
|
}
|
|
})
|
|
return { opaque, clear }
|
|
}
|
|
|
|
const LIGHT = new Vector3(-0.5, 0.75, 0.45).normalize()
|
|
|
|
/**
|
|
* A photo-studio sky: bright soft horizon, darker zenith, a dark floor. What
|
|
* sells painted metal is the horizon line sweeping across the flanks, so the
|
|
* environment is mostly a gradient with a sharp step at the horizon.
|
|
*/
|
|
function environment(d: Vector3): [number, number, number] {
|
|
if (d.y >= 0) {
|
|
const t = Math.pow(d.y, 0.45)
|
|
const band = Math.exp(-d.y * 18) * 0.35
|
|
return [0.95 - 0.55 * t + band, 0.96 - 0.5 * t + band, 0.98 - 0.4 * t + band]
|
|
}
|
|
const t = Math.min(1, -d.y * 4)
|
|
return [0.2 - 0.12 * t, 0.2 - 0.12 * t, 0.21 - 0.12 * t]
|
|
}
|
|
|
|
function shade(n: Vector3, v: Vector3, c: readonly number[], tri: Tri): [number, number, number] {
|
|
const ndl = Math.max(0, n.dot(LIGHT))
|
|
const up = n.y * 0.5 + 0.5
|
|
const r = v.clone().negate().reflect(n)
|
|
const env = environment(r)
|
|
const ambient = environment(new Vector3(n.x * 0.3, Math.max(-0.2, n.y), n.z * 0.3).normalize())
|
|
const ndv = Math.max(0, n.dot(v))
|
|
const fres = 0.04 + 0.96 * Math.pow(1 - ndv, 5)
|
|
const h = LIGHT.clone().add(v).normalize()
|
|
const shin = 4 + (1 - tri.rough) ** 3 * 600
|
|
const spec = Math.pow(Math.max(0, n.dot(h)), shin) * (1 - tri.rough) ** 2 * 2.2
|
|
const gloss = Math.pow(1 - tri.rough, 2)
|
|
return [0, 1, 2].map((k) => {
|
|
const albedo = c[k]!
|
|
const diffuse = albedo * (1 - tri.metal) * (ndl * 1.25 + ambient[k]! * (0.35 + 0.35 * up))
|
|
const metal = albedo * tri.metal * (env[k]! * (0.35 + 0.65 * gloss) + spec)
|
|
const dielectric = (1 - tri.metal) * (fres * gloss * env[k]! + spec * 0.6)
|
|
const coat = tri.coat * fres * env[k]! * 0.9 + tri.coat * spec * 0.8
|
|
return diffuse + metal + dielectric + coat + tri.emissive[k]!
|
|
}) as [number, number, number]
|
|
}
|
|
|
|
export function render(
|
|
root: Object3D,
|
|
options: { width: number; height: number; direction?: Vector3; background?: [number, number, number]; fov?: number },
|
|
): Frame {
|
|
const W = options.width * 2
|
|
const H = options.height * 2
|
|
const { opaque, clear } = collect(root)
|
|
const box = new Box3().setFromObject(root)
|
|
const sphere = box.getBoundingSphere(new Sphere())
|
|
const fov = options.fov ?? 26
|
|
const camera = new PerspectiveCamera(fov, W / H, 0.05, 500)
|
|
// Three-quarter front from about head height: a camera looking down on a
|
|
// car from above is what makes it read as a toy.
|
|
const dir = (options.direction ?? new Vector3(0.95, 0.2, 1.0)).clone().normalize()
|
|
const fit = sphere.radius / Math.sin((Math.min(fov, fov * (W / H)) * Math.PI) / 360)
|
|
const target = box.getCenter(new Vector3())
|
|
camera.position.copy(target).addScaledVector(dir, fit * 0.74)
|
|
camera.lookAt(target)
|
|
camera.updateMatrixWorld(true)
|
|
camera.updateProjectionMatrix()
|
|
|
|
const bg = options.background ?? [0.93, 0.93, 0.92]
|
|
const rgb = new Float32Array(W * H * 3)
|
|
for (let y = 0; y < H; y += 1) {
|
|
const t = y / H
|
|
for (let x = 0; x < W; x += 1) {
|
|
const i = (y * W + x) * 3
|
|
rgb[i] = bg[0]; rgb[i + 1] = bg[1]; rgb[i + 2] = bg[2]
|
|
void t
|
|
}
|
|
}
|
|
const depth = new Float32Array(W * H).fill(Infinity)
|
|
|
|
// Contact shadow: darken the ground-plane footprint under the vehicle.
|
|
const floorY = box.min.y
|
|
const shadowTris = opaque
|
|
const project = (p: Vector3): [number, number, number] => {
|
|
const q = p.clone().project(camera)
|
|
return [(q.x * 0.5 + 0.5) * W, (1 - (q.y * 0.5 + 0.5)) * H, q.z]
|
|
}
|
|
const shadowMask = new Float32Array(W * H)
|
|
for (const tri of shadowTris) {
|
|
const pts = tri.p.map((p) => {
|
|
const h = Math.max(0, p.y - floorY)
|
|
return project(new Vector3(p.x + LIGHT.x * -h * 0.15, floorY, p.z + LIGHT.z * -h * 0.15))
|
|
})
|
|
fill(pts as [number, number, number][], W, H, (x, y) => {
|
|
shadowMask[y * W + x] = 1
|
|
})
|
|
}
|
|
// Blur the mask a little for a soft edge.
|
|
const soft = blur(shadowMask, W, H, Math.max(2, Math.round(W / 160)))
|
|
for (let i = 0; i < W * H; i += 1) {
|
|
const k = 1 - soft[i]! * 0.45
|
|
rgb[i * 3]! *= k; rgb[i * 3 + 1]! *= k; rgb[i * 3 + 2]! *= k
|
|
}
|
|
|
|
const draw = (tri: Tri, blend: boolean): void => {
|
|
const s = tri.p.map(project) as [number, number, number][]
|
|
const v = camera.position.clone().sub(tri.p[0]).normalize()
|
|
const faceN = tri.p[1].clone().sub(tri.p[0]).cross(tri.p[2].clone().sub(tri.p[0])).normalize()
|
|
if (!blend && faceN.dot(v) < 0) return
|
|
fill(s, W, H, (x, y, w0, w1, w2) => {
|
|
const z = s[0]![2] * w0 + s[1]![2] * w1 + s[2]![2] * w2
|
|
const di = y * W + x
|
|
if (z >= depth[di]!) return
|
|
const n = tri.n[0].clone().multiplyScalar(w0).add(tri.n[1].clone().multiplyScalar(w1)).add(tri.n[2].clone().multiplyScalar(w2)).normalize()
|
|
if (n.dot(v) < 0) n.negate()
|
|
const c = [0, 1, 2].map((k) => tri.c[0][k]! * w0 + tri.c[1][k]! * w1 + tri.c[2][k]! * w2)
|
|
const col = shade(n, v, c, tri)
|
|
const i = di * 3
|
|
if (blend) {
|
|
const a = tri.opacity
|
|
rgb[i] = rgb[i]! * (1 - a) + col[0] * a
|
|
rgb[i + 1] = rgb[i + 1]! * (1 - a) + col[1] * a
|
|
rgb[i + 2] = rgb[i + 2]! * (1 - a) + col[2] * a
|
|
} else {
|
|
depth[di] = z
|
|
rgb[i] = col[0]; rgb[i + 1] = col[1]; rgb[i + 2] = col[2]
|
|
}
|
|
})
|
|
}
|
|
for (const tri of opaque) draw(tri, false)
|
|
const far = (t: Tri): number => t.p[0].distanceToSquared(camera.position)
|
|
for (const tri of [...clear].sort((a, b) => far(b) - far(a))) draw(tri, true)
|
|
|
|
// Downsample 2× → 1×.
|
|
const out = new Float32Array(options.width * options.height * 3)
|
|
for (let y = 0; y < options.height; y += 1) {
|
|
for (let x = 0; x < options.width; x += 1) {
|
|
for (let k = 0; k < 3; k += 1) {
|
|
const a = rgb[((2 * y) * W + 2 * x) * 3 + k]!
|
|
const b = rgb[((2 * y) * W + 2 * x + 1) * 3 + k]!
|
|
const c = rgb[((2 * y + 1) * W + 2 * x) * 3 + k]!
|
|
const d = rgb[((2 * y + 1) * W + 2 * x + 1) * 3 + k]!
|
|
out[(y * options.width + x) * 3 + k] = (a + b + c + d) / 4
|
|
}
|
|
}
|
|
}
|
|
return { width: options.width, height: options.height, rgb: out }
|
|
}
|
|
|
|
function fill(
|
|
s: readonly [number, number, number][],
|
|
W: number,
|
|
H: number,
|
|
plot: (x: number, y: number, w0: number, w1: number, w2: number) => void,
|
|
): void {
|
|
const [a, b, c] = s as [[number, number, number], [number, number, number], [number, number, number]]
|
|
if (a[2] < -1 || b[2] < -1 || c[2] < -1) return
|
|
const minX = Math.max(0, Math.floor(Math.min(a[0], b[0], c[0])))
|
|
const maxX = Math.min(W - 1, Math.ceil(Math.max(a[0], b[0], c[0])))
|
|
const minY = Math.max(0, Math.floor(Math.min(a[1], b[1], c[1])))
|
|
const maxY = Math.min(H - 1, Math.ceil(Math.max(a[1], b[1], c[1])))
|
|
const area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
|
|
if (Math.abs(area) < 1e-9) return
|
|
for (let y = minY; y <= maxY; y += 1) {
|
|
for (let x = minX; x <= maxX; x += 1) {
|
|
const px = x + 0.5, py = y + 0.5
|
|
const w0 = ((b[0] - px) * (c[1] - py) - (b[1] - py) * (c[0] - px)) / area
|
|
const w1 = ((c[0] - px) * (a[1] - py) - (c[1] - py) * (a[0] - px)) / area
|
|
const w2 = 1 - w0 - w1
|
|
if (w0 < 0 || w1 < 0 || w2 < 0) continue
|
|
plot(x, y, w0, w1, w2)
|
|
}
|
|
}
|
|
}
|
|
|
|
function blur(src: Float32Array, W: number, H: number, r: number): Float32Array {
|
|
const tmp = new Float32Array(W * H)
|
|
const out = new Float32Array(W * H)
|
|
for (let y = 0; y < H; y += 1) {
|
|
let acc = 0
|
|
for (let x = -r; x < W + r; x += 1) {
|
|
acc += src[y * W + Math.min(W - 1, Math.max(0, x + r))]! - src[y * W + Math.min(W - 1, Math.max(0, x - r - 1))]!
|
|
if (x >= 0 && x < W) tmp[y * W + x] = acc / (2 * r + 1)
|
|
}
|
|
}
|
|
for (let x = 0; x < W; x += 1) {
|
|
let acc = 0
|
|
for (let y = -r; y < H + r; y += 1) {
|
|
acc += tmp[Math.min(H - 1, Math.max(0, y + r)) * W + x]! - tmp[Math.min(H - 1, Math.max(0, y - r - 1)) * W + x]!
|
|
if (y >= 0 && y < H) out[y * W + x] = acc / (2 * r + 1)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
/** Places frames on a grid. */
|
|
export function tile(frames: readonly Frame[], columns: number, background: [number, number, number] = [0.93, 0.93, 0.92]): Frame {
|
|
const w = frames[0]!.width
|
|
const h = frames[0]!.height
|
|
const rows = Math.ceil(frames.length / columns)
|
|
const W = w * columns
|
|
const H = h * rows
|
|
const rgb = new Float32Array(W * H * 3)
|
|
for (let i = 0; i < W * H; i += 1) { rgb[i * 3] = background[0]; rgb[i * 3 + 1] = background[1]; rgb[i * 3 + 2] = background[2] }
|
|
frames.forEach((f, n) => {
|
|
const ox = (n % columns) * w
|
|
const oy = Math.floor(n / columns) * h
|
|
for (let y = 0; y < h; y += 1) {
|
|
for (let x = 0; x < w; x += 1) {
|
|
for (let k = 0; k < 3; k += 1) rgb[((oy + y) * W + ox + x) * 3 + k] = f.rgb[(y * w + x) * 3 + k]!
|
|
}
|
|
}
|
|
})
|
|
return { width: W, height: H, rgb }
|
|
}
|
|
|
|
/* --------------------------------------------------------------------- PNG */
|
|
|
|
const CRC = new Uint32Array(256).map((_, n) => {
|
|
let c = n
|
|
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
|
|
return c >>> 0
|
|
})
|
|
|
|
export function crc32(bytes: Uint8Array): number {
|
|
let c = 0xffffffff
|
|
for (const b of bytes) c = CRC[(c ^ b) & 255]! ^ (c >>> 8)
|
|
return (c ^ 0xffffffff) >>> 0
|
|
}
|
|
|
|
function chunk(type: string, data: Uint8Array): Uint8Array {
|
|
const out = new Uint8Array(12 + data.length)
|
|
const view = new DataView(out.buffer)
|
|
view.setUint32(0, data.length)
|
|
for (let i = 0; i < 4; i += 1) out[4 + i] = type.charCodeAt(i)
|
|
out.set(data, 8)
|
|
view.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)))
|
|
return out
|
|
}
|
|
|
|
/** Linear light → ACES filmic (Narkowicz fit) → sRGB 8-bit. */
|
|
function encode(v: number): number {
|
|
const x = v * 0.8
|
|
const t = Math.min(1, Math.max(0, (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14)))
|
|
const s = t <= 0.0031308 ? 12.92 * t : 1.055 * Math.pow(t, 1 / 2.4) - 0.055
|
|
return Math.round(Math.min(1, Math.max(0, s)) * 255)
|
|
}
|
|
|
|
/** PNG; with `alpha` (0..1 per pixel) it is written as RGBA. */
|
|
export function encodePng(frame: Frame, alpha?: Float32Array): Uint8Array {
|
|
const { width, height, rgb } = frame
|
|
const channels = alpha ? 4 : 3
|
|
const stride = width * channels + 1
|
|
const raw = new Uint8Array(stride * height)
|
|
for (let y = 0; y < height; y += 1) {
|
|
raw[y * stride] = 0
|
|
for (let x = 0; x < width; x += 1) {
|
|
const o = y * stride + 1 + x * channels
|
|
for (let k = 0; k < 3; k += 1) raw[o + k] = encode(rgb[(y * width + x) * 3 + k]!)
|
|
if (alpha) raw[o + 3] = Math.round(Math.min(1, Math.max(0, alpha[y * width + x]!)) * 255)
|
|
}
|
|
}
|
|
const header = new Uint8Array(13)
|
|
const view = new DataView(header.buffer)
|
|
view.setUint32(0, width)
|
|
view.setUint32(4, height)
|
|
header[8] = 8
|
|
header[9] = alpha ? 6 : 2
|
|
const signature = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])
|
|
const parts = [signature, chunk('IHDR', header), chunk('IDAT', deflateSync(raw, { level: 9 })), chunk('IEND', new Uint8Array())]
|
|
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
|
|
let o = 0
|
|
for (const p of parts) { out.set(p, o); o += p.length }
|
|
return out
|
|
}
|