Remove a scratch directory that came in with the last commit
`my-registry/undefined/` — ten files, a copy of core and one barrel. It is the output of a `vibe3d add` run made from a directory with no `models.json` resolved against it, so the CLI wrote the install under the string "undefined". It was a pre-publish audit's scratch work, not part of the kit, and `git add -A` swept it up. Nothing referenced it and nothing shipped it: the npm tarball is driven by package.json "files" (dist, README.md, LICENSE) so it was never going to reach the registry. Removed all the same, because a directory called "undefined" in a repository someone is meant to read from is its own kind of defect.
This commit is contained in:
parent
7ab416aa66
commit
195f895c61
10 changed files with 0 additions and 2304 deletions
|
|
@ -1,870 +0,0 @@
|
|||
import { BufferAttribute, BufferGeometry, Color } from 'three'
|
||||
import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js'
|
||||
|
||||
/**
|
||||
* The kit's geometry vocabulary.
|
||||
*
|
||||
* Everything is generated NON-INDEXED. The reason: on non-indexed geometry
|
||||
* computeVertexNormals() gives every triangle its own normal, so flat shading
|
||||
* becomes a natural consequence of the geometry — no material flag is needed.
|
||||
* In lowpoly that is exactly what we want.
|
||||
*
|
||||
* Position frame: point(a, r, y) = (sin a · r, y, cos a · r)
|
||||
* So a = 0 → the +Z direction; as a grows it turns toward +X.
|
||||
*
|
||||
* The windings were worked out by hand and the audit inside
|
||||
* `scripts/verify-model.ts` tests them by mutation: radial faces on the outer
|
||||
* shell must point away from the axis.
|
||||
*/
|
||||
|
||||
export type Vec3 = readonly [number, number, number]
|
||||
|
||||
export interface Level {
|
||||
/** Vertical position (metres). */
|
||||
readonly y: number
|
||||
/** OUTER radius at that height (metres). */
|
||||
readonly radius: number
|
||||
}
|
||||
|
||||
function point(angle: number, radius: number, y: number): Vec3 {
|
||||
return [Math.sin(angle) * radius, y, Math.cos(angle) * radius]
|
||||
}
|
||||
|
||||
interface Sink {
|
||||
readonly position: number[]
|
||||
readonly color: number[]
|
||||
}
|
||||
|
||||
function tri(sink: Sink, a: Vec3, b: Vec3, c: Vec3, colour: Color): void {
|
||||
sink.position.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2])
|
||||
for (let i = 0; i < 3; i += 1) sink.color.push(colour.r, colour.g, colour.b)
|
||||
}
|
||||
|
||||
/** Triangle with a separate colour per corner — for vertical colour ramps. */
|
||||
function triShaded(sink: Sink, a: Vec3, b: Vec3, c: Vec3, ca: Color, cb: Color, cc: Color): void {
|
||||
sink.position.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2])
|
||||
sink.color.push(ca.r, ca.g, ca.b, cb.r, cb.g, cb.b, cc.r, cc.g, cc.b)
|
||||
}
|
||||
|
||||
/** Splits the quad (a,b,c,d) in order into two triangles. The normal follows from the a→b→c winding. */
|
||||
function quad(sink: Sink, a: Vec3, b: Vec3, c: Vec3, d: Vec3, colour: Color): void {
|
||||
tri(sink, a, b, c, colour)
|
||||
tri(sink, a, c, d, colour)
|
||||
}
|
||||
|
||||
function finish(sink: Sink): BufferGeometry {
|
||||
const geometry = new BufferGeometry()
|
||||
geometry.setAttribute('position', new BufferAttribute(new Float32Array(sink.position), 3))
|
||||
geometry.setAttribute('color', new BufferAttribute(new Float32Array(sink.color), 3))
|
||||
return geometry
|
||||
}
|
||||
|
||||
/**
|
||||
* Axis-aligned box. The kit's most used part: boards, rails, iron straps,
|
||||
* feet — all of them are this.
|
||||
*/
|
||||
export function boxGeometry(
|
||||
size: Vec3,
|
||||
centre: Vec3,
|
||||
colour: Color,
|
||||
): BufferGeometry {
|
||||
const sink: Sink = { position: [], color: [] }
|
||||
const [hx, hy, hz] = [size[0] / 2, size[1] / 2, size[2] / 2]
|
||||
const [cx, cy, cz] = centre
|
||||
const v = (sx: number, sy: number, sz: number): Vec3 => [cx + sx * hx, cy + sy * hy, cz + sz * hz]
|
||||
|
||||
quad(sink, v(-1, -1, 1), v(1, -1, 1), v(1, 1, 1), v(-1, 1, 1), colour) // +Z
|
||||
quad(sink, v(1, -1, -1), v(-1, -1, -1), v(-1, 1, -1), v(1, 1, -1), colour) // -Z
|
||||
quad(sink, v(1, -1, 1), v(1, -1, -1), v(1, 1, -1), v(1, 1, 1), colour) // +X
|
||||
quad(sink, v(-1, -1, -1), v(-1, -1, 1), v(-1, 1, 1), v(-1, 1, -1), colour) // -X
|
||||
quad(sink, v(-1, 1, 1), v(1, 1, 1), v(1, 1, -1), v(-1, 1, -1), colour) // +Y
|
||||
quad(sink, v(-1, -1, -1), v(1, -1, -1), v(1, -1, 1), v(-1, -1, 1), colour) // -Y
|
||||
|
||||
return finish(sink)
|
||||
}
|
||||
|
||||
/**
|
||||
* Chamfered box — the kit's most important primitive. It can taper.
|
||||
*
|
||||
* A sharp 90° corner does not exist in nature. The edge of a hand-planed board
|
||||
* chips, the corner of forged iron rounds over. The chamfer band catches light
|
||||
* at a different angle than its neighbouring faces, and the object stops being
|
||||
* a "box" and turns into a physical part. The first version of the kit was
|
||||
* chamferless boxes from end to end and all of it looked like toys.
|
||||
*
|
||||
* Because the bottom and top cross sections can be given separately, it stands
|
||||
* in for both the straight box and the tapering box — keeping the two as
|
||||
* separate primitives would have permanently left open the risk of chamfering
|
||||
* one and leaving the other sharp.
|
||||
*
|
||||
* Single-facet chamfer (vibe3d modelling rule 2: one facet by default, a second
|
||||
* only on masses that carry the silhouette). The cost is 44 triangles instead of 12.
|
||||
*
|
||||
* Winding: the 6 faces were worked out by hand; the 12 edges and 8 corners
|
||||
* CORRECT THEMSELVES against the expected outward direction. Deriving the
|
||||
* winding of twenty pieces by hand invites mistakes, while the expected normal
|
||||
* is already known — flipping whatever comes out reversed is both shorter and certain.
|
||||
*/
|
||||
export function chamferedBoxGeometry(
|
||||
bottom: readonly [number, number],
|
||||
top: readonly [number, number],
|
||||
height: number,
|
||||
chamfer: number,
|
||||
centre: Vec3,
|
||||
colour: Color,
|
||||
colourTop?: Color,
|
||||
): BufferGeometry {
|
||||
const sink: Sink = { position: [], color: [] }
|
||||
const [cx, cy, cz] = centre
|
||||
const hy = height / 2
|
||||
const minHalf = Math.min(bottom[0], bottom[1], top[0], top[1]) / 2
|
||||
const c = Math.max(1e-6, Math.min(chamfer, minHalf * 0.5, hy * 0.5))
|
||||
const upper = colourTop ?? colour
|
||||
|
||||
/**
|
||||
* `full` sits exactly at the end on its axis, the others a chamfer inside.
|
||||
* The horizontal half-measures are interpolated between the bottom and top
|
||||
* cross section according to height.
|
||||
*/
|
||||
const p = (sx: number, sy: number, sz: number, full: 0 | 1 | 2): Vec3 => {
|
||||
const y = cy + sy * (full === 1 ? hy : hy - c)
|
||||
const t = height <= 1e-9 ? 0 : (y - (cy - hy)) / height
|
||||
const hx = (bottom[0] + (top[0] - bottom[0]) * t) / 2
|
||||
const hz = (bottom[1] + (top[1] - bottom[1]) * t) / 2
|
||||
return [
|
||||
cx + sx * (full === 0 ? hx : hx - c),
|
||||
y,
|
||||
cz + sz * (full === 2 ? hz : hz - c),
|
||||
]
|
||||
}
|
||||
const shade = (v: Vec3): Color =>
|
||||
colourTop ? new Color().copy(colour).lerp(upper, (v[1] - (cy - hy)) / Math.max(1e-9, height)) : colour
|
||||
|
||||
const face = (a: Vec3, b: Vec3, d: Vec3, e: Vec3): void => {
|
||||
tri(sink, a, b, d, shade(a)); tri(sink, a, d, e, shade(a))
|
||||
}
|
||||
face(p(-1, -1, 1, 2), p(1, -1, 1, 2), p(1, 1, 1, 2), p(-1, 1, 1, 2)) // +Z
|
||||
face(p(1, -1, -1, 2), p(-1, -1, -1, 2), p(-1, 1, -1, 2), p(1, 1, -1, 2)) // -Z
|
||||
face(p(1, -1, 1, 0), p(1, -1, -1, 0), p(1, 1, -1, 0), p(1, 1, 1, 0)) // +X
|
||||
face(p(-1, -1, -1, 0), p(-1, -1, 1, 0), p(-1, 1, 1, 0), p(-1, 1, -1, 0)) // -X
|
||||
face(p(-1, 1, 1, 1), p(1, 1, 1, 1), p(1, 1, -1, 1), p(-1, 1, -1, 1)) // +Y
|
||||
face(p(-1, -1, -1, 1), p(1, -1, -1, 1), p(1, -1, 1, 1), p(-1, -1, 1, 1)) // -Y
|
||||
|
||||
/** Writes the triangle against the expected outward direction, flipping it if needed. */
|
||||
const oriented = (a: Vec3, b: Vec3, d: Vec3, outward: readonly number[]): void => {
|
||||
const e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]
|
||||
const e2 = [d[0] - a[0], d[1] - a[1], d[2] - a[2]]
|
||||
const n = [
|
||||
e1[1]! * e2[2]! - e1[2]! * e2[1]!,
|
||||
e1[2]! * e2[0]! - e1[0]! * e2[2]!,
|
||||
e1[0]! * e2[1]! - e1[1]! * e2[0]!,
|
||||
]
|
||||
const dot = n[0]! * outward[0]! + n[1]! * outward[1]! + n[2]! * outward[2]!
|
||||
if (dot >= 0) tri(sink, a, b, d, shade(a))
|
||||
else tri(sink, a, d, b, shade(a))
|
||||
}
|
||||
|
||||
const signs = [-1, 1] as const
|
||||
for (const axis of [0, 1, 2] as const) {
|
||||
const [u, v] = [0, 1, 2].filter((i) => i !== axis) as [0 | 1 | 2, 0 | 1 | 2]
|
||||
for (const su of signs) for (const sv of signs) {
|
||||
const at = (along: number, full: 0 | 1 | 2): Vec3 => {
|
||||
const sign: [number, number, number] = [0, 0, 0]
|
||||
sign[axis] = along; sign[u] = su; sign[v] = sv
|
||||
return p(sign[0], sign[1], sign[2], full)
|
||||
}
|
||||
const outward = [0, 1, 2].map((i) => (i === u ? su : i === v ? sv : 0))
|
||||
oriented(at(-1, u), at(-1, v), at(1, v), outward)
|
||||
oriented(at(-1, u), at(1, v), at(1, u), outward)
|
||||
}
|
||||
}
|
||||
for (const sx of signs) for (const sy of signs) for (const sz of signs) {
|
||||
oriented(p(sx, sy, sz, 0), p(sx, sy, sz, 1), p(sx, sy, sz, 2), [sx, sy, sz])
|
||||
}
|
||||
|
||||
return finish(sink)
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncated cone / prism: feet, shafts, bowls, flame tongues.
|
||||
*
|
||||
* If `colourTop` is given the colour ramps with height — needed for the flame,
|
||||
* because the base of a flame is not the same colour as its tip.
|
||||
*/
|
||||
export function prismGeometry(
|
||||
radiusBottom: number,
|
||||
radiusTop: number,
|
||||
height: number,
|
||||
segments: number,
|
||||
centre: Vec3,
|
||||
colour: Color,
|
||||
options: { readonly capTop?: boolean; readonly capBottom?: boolean; readonly colourTop?: Color } = {},
|
||||
): BufferGeometry {
|
||||
const sink: Sink = { position: [], color: [] }
|
||||
const { capTop = true, capBottom = true } = options
|
||||
const top = options.colourTop ?? colour
|
||||
const [cx, cy, cz] = centre
|
||||
const low = cy - height / 2
|
||||
const high = cy + height / 2
|
||||
const stepAngle = (Math.PI * 2) / segments
|
||||
const shift = (p: Vec3): Vec3 => [p[0] + cx, p[1], p[2] + cz]
|
||||
|
||||
for (let i = 0; i < segments; i += 1) {
|
||||
const a0 = i * stepAngle
|
||||
const a1 = (i + 1) * stepAngle
|
||||
const l0 = shift(point(a0, radiusBottom, low))
|
||||
const l1 = shift(point(a1, radiusBottom, low))
|
||||
const h0 = shift(point(a0, radiusTop, high))
|
||||
const h1 = shift(point(a1, radiusTop, high))
|
||||
|
||||
// Side face: points outward.
|
||||
triShaded(sink, l0, l1, h1, colour, colour, top)
|
||||
triShaded(sink, l0, h1, h0, colour, top, top)
|
||||
|
||||
if (capTop && radiusTop > 0) tri(sink, [cx, high, cz], h0, h1, top)
|
||||
if (capBottom && radiusBottom > 0) tri(sink, [cx, low, cz], l1, l0, colour)
|
||||
}
|
||||
|
||||
return finish(sink)
|
||||
}
|
||||
|
||||
/**
|
||||
* Turned surface: revolves a profile around the Y axis.
|
||||
*
|
||||
* `prismGeometry` is the two-level version of this. When more levels are needed
|
||||
* this one is used and NO INTERIOR SURFACE FORMS in between — that is the real
|
||||
* reason to use this instead of stacking prisms on top of each other: stacked
|
||||
* prisms leave a pair of coincident faces where they touch, a single lathe
|
||||
* does not.
|
||||
*
|
||||
* Everything round in the kit comes out of this: tool shafts and grip bulges,
|
||||
* conical sockets, pitchfork tines, and later jugs/candlesticks/wheel hubs.
|
||||
*/
|
||||
export function latheGeometry(
|
||||
levels: readonly Level[],
|
||||
segments: number,
|
||||
centre: Vec3,
|
||||
colour: Color,
|
||||
options: { readonly capTop?: boolean; readonly capBottom?: boolean; readonly colourTop?: Color } = {},
|
||||
): BufferGeometry {
|
||||
if (levels.length < 2) throw new Error('latheGeometry needs at least two levels')
|
||||
const sink: Sink = { position: [], color: [] }
|
||||
const { capTop = true, capBottom = true } = options
|
||||
const top = options.colourTop ?? colour
|
||||
const [cx, cy, cz] = centre
|
||||
const stepAngle = (Math.PI * 2) / segments
|
||||
const shift = (p: Vec3): Vec3 => [p[0] + cx, p[1] + cy, p[2] + cz]
|
||||
const lerp = (t: number): Color => new Color().copy(colour).lerp(top, t)
|
||||
|
||||
for (let i = 0; i < levels.length - 1; i += 1) {
|
||||
const low = levels[i]!
|
||||
const high = levels[i + 1]!
|
||||
const tLow = i / (levels.length - 1)
|
||||
const tHigh = (i + 1) / (levels.length - 1)
|
||||
const cLow = lerp(tLow)
|
||||
const cHigh = lerp(tHigh)
|
||||
|
||||
for (let j = 0; j < segments; j += 1) {
|
||||
const a0 = j * stepAngle
|
||||
const a1 = (j + 1) * stepAngle
|
||||
const l0 = shift(point(a0, low.radius, low.y))
|
||||
const l1 = shift(point(a1, low.radius, low.y))
|
||||
const h0 = shift(point(a0, high.radius, high.y))
|
||||
const h1 = shift(point(a1, high.radius, high.y))
|
||||
// At a level whose radius is zero that edge collapses to a point; it is
|
||||
// closed with a single triangle so no degenerate triangle is produced.
|
||||
if (low.radius <= 1e-6) { triShaded(sink, l0, h1, h0, cLow, cHigh, cHigh); continue }
|
||||
if (high.radius <= 1e-6) { triShaded(sink, l0, l1, h0, cLow, cLow, cHigh); continue }
|
||||
triShaded(sink, l0, l1, h1, cLow, cLow, cHigh)
|
||||
triShaded(sink, l0, h1, h0, cLow, cHigh, cHigh)
|
||||
}
|
||||
}
|
||||
|
||||
const first = levels[0]!
|
||||
const last = levels.at(-1)!
|
||||
for (let j = 0; j < segments; j += 1) {
|
||||
const a0 = j * stepAngle
|
||||
const a1 = (j + 1) * stepAngle
|
||||
if (capBottom && first.radius > 1e-6) {
|
||||
tri(sink, shift([0, first.y, 0]),
|
||||
shift(point(a1, first.radius, first.y)), shift(point(a0, first.radius, first.y)), colour)
|
||||
}
|
||||
if (capTop && last.radius > 1e-6) {
|
||||
tri(sink, shift([0, last.y, 0]),
|
||||
shift(point(a0, last.radius, last.y)), shift(point(a1, last.radius, last.y)), top)
|
||||
}
|
||||
}
|
||||
return finish(sink)
|
||||
}
|
||||
|
||||
/**
|
||||
* A single barrel stave: one slice of the ring, a closed solid with thickness.
|
||||
*
|
||||
* Every level has four corners:
|
||||
* A = outer/start angle B = outer/end angle
|
||||
* C = inner/end angle D = inner/start angle
|
||||
*/
|
||||
export function staveGeometry(
|
||||
levels: readonly Level[],
|
||||
angleStart: number,
|
||||
angleEnd: number,
|
||||
thickness: number,
|
||||
colour: Color,
|
||||
): BufferGeometry {
|
||||
if (levels.length < 2) throw new Error('staveGeometry needs at least two levels')
|
||||
|
||||
const sink: Sink = { position: [], color: [] }
|
||||
|
||||
const corners = levels.map((level) => {
|
||||
// Thickness cannot exceed half the thinnest radius; otherwise the inner surface breaks out.
|
||||
const inner = Math.max(level.radius * 0.5, level.radius - thickness)
|
||||
return {
|
||||
a: point(angleStart, level.radius, level.y),
|
||||
b: point(angleEnd, level.radius, level.y),
|
||||
c: point(angleEnd, inner, level.y),
|
||||
d: point(angleStart, inner, level.y),
|
||||
}
|
||||
})
|
||||
|
||||
for (let i = 0; i < corners.length - 1; i += 1) {
|
||||
const low = corners[i]!
|
||||
const high = corners[i + 1]!
|
||||
quad(sink, low.a, low.b, high.b, high.a, colour) // outer face → points outward
|
||||
quad(sink, low.c, low.d, high.d, high.c, colour) // inner face → points at the axis
|
||||
quad(sink, low.d, low.a, high.a, high.d, colour) // start edge
|
||||
quad(sink, low.b, low.c, high.c, high.b, colour) // end edge
|
||||
}
|
||||
|
||||
const top = corners.at(-1)!
|
||||
const bottom = corners[0]!
|
||||
quad(sink, top.a, top.b, top.c, top.d, colour) // top cap → +Y
|
||||
quad(sink, bottom.d, bottom.c, bottom.b, bottom.a, colour) // bottom cap → -Y
|
||||
|
||||
return finish(sink)
|
||||
}
|
||||
|
||||
/**
|
||||
* Iron hoop: a ring with a rectangular cross section.
|
||||
*
|
||||
* The inner surface is deliberately not generated — the body it leans against
|
||||
* hides it from every camera. A quarter of the triangle budget is won here.
|
||||
*/
|
||||
export function bandGeometry(
|
||||
radius: number,
|
||||
y: number,
|
||||
height: number,
|
||||
thickness: number,
|
||||
segments: number,
|
||||
colour: Color,
|
||||
options: {
|
||||
/**
|
||||
* Generate the inner face as well.
|
||||
*
|
||||
* Not generated by default, because a hoop always wraps a body and the
|
||||
* inner face is not visible — not generating it is a free triangle saving.
|
||||
* But a free-standing ring (the cord of a sack, the tie of a bale) becomes
|
||||
* a solid that is NOT CLOSED this way, and the "no reversed faces" check in
|
||||
* the validation rightly fails. This flag is for that case.
|
||||
*/
|
||||
readonly inner?: boolean
|
||||
} = {},
|
||||
): BufferGeometry {
|
||||
const sink: Sink = { position: [], color: [] }
|
||||
const half = height / 2
|
||||
const inner = radius - thickness
|
||||
const stepAngle = (Math.PI * 2) / segments
|
||||
|
||||
for (let i = 0; i < segments; i += 1) {
|
||||
const a0 = i * stepAngle
|
||||
const a1 = (i + 1) * stepAngle
|
||||
|
||||
const outerLow0 = point(a0, radius, y - half)
|
||||
const outerLow1 = point(a1, radius, y - half)
|
||||
const outerHigh0 = point(a0, radius, y + half)
|
||||
const outerHigh1 = point(a1, radius, y + half)
|
||||
const innerHigh0 = point(a0, inner, y + half)
|
||||
const innerHigh1 = point(a1, inner, y + half)
|
||||
const innerLow0 = point(a0, inner, y - half)
|
||||
const innerLow1 = point(a1, inner, y - half)
|
||||
|
||||
quad(sink, outerLow0, outerLow1, outerHigh1, outerHigh0, colour) // outer → outward
|
||||
quad(sink, outerHigh0, outerHigh1, innerHigh1, innerHigh0, colour) // top → +Y
|
||||
quad(sink, innerLow0, innerLow1, outerLow1, outerLow0, colour) // bottom → -Y
|
||||
// Inner face: the corner order is the reverse of the outer one so the normal points AT THE AXIS.
|
||||
if (options.inner) {
|
||||
quad(sink, innerHigh0, innerHigh1, innerLow1, innerLow0, colour)
|
||||
}
|
||||
}
|
||||
|
||||
return finish(sink)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fan disc: barrel head, bowl bottom.
|
||||
*
|
||||
* So that it reads as built from several boards rather than one piece of wood,
|
||||
* every triangle falls into a "board band" according to the X position of its
|
||||
* centre, and the tone of that band is written into the vertex colour. The
|
||||
* geometry cost is zero.
|
||||
*/
|
||||
export function headGeometry(
|
||||
radius: number,
|
||||
y: number,
|
||||
segments: number,
|
||||
facing: 'up' | 'down',
|
||||
colour: Color,
|
||||
plankCount: number,
|
||||
plankShade: number,
|
||||
): BufferGeometry {
|
||||
const sink: Sink = { position: [], color: [] }
|
||||
const centre: Vec3 = [0, y, 0]
|
||||
const stepAngle = (Math.PI * 2) / segments
|
||||
const plankWidth = (radius * 2) / Math.max(1, plankCount)
|
||||
const tint = new Color()
|
||||
|
||||
for (let i = 0; i < segments; i += 1) {
|
||||
const p0 = point(i * stepAngle, radius, y)
|
||||
const p1 = point((i + 1) * stepAngle, radius, y)
|
||||
|
||||
// The boards are strips sliced along the X axis; whichever strip the X of
|
||||
// the triangle's centroid falls into gives it its tone.
|
||||
const centroidX = (p0[0] + p1[0]) / 3
|
||||
const band = Math.floor((centroidX + radius) / plankWidth)
|
||||
tint.copy(colour).multiplyScalar(1 + (band % 2 === 0 ? plankShade : -plankShade))
|
||||
|
||||
if (facing === 'up') tri(sink, centre, p0, p1, tint)
|
||||
else tri(sink, centre, p1, p0, tint)
|
||||
}
|
||||
|
||||
return finish(sink)
|
||||
}
|
||||
|
||||
/**
|
||||
* Tapering box: a body whose bottom and top rectangles may differ.
|
||||
*
|
||||
* Anvil horn, stool leg, fence post tip, tool handle — every "box but carved"
|
||||
* part of the kit is this. The winding follows the same logic as boxGeometry.
|
||||
*/
|
||||
export function taperedBoxGeometry(
|
||||
bottom: readonly [number, number],
|
||||
top: readonly [number, number],
|
||||
height: number,
|
||||
centre: Vec3,
|
||||
colour: Color,
|
||||
colourTop?: Color,
|
||||
): BufferGeometry {
|
||||
const sink: Sink = { position: [], color: [] }
|
||||
const [cx, cy, cz] = centre
|
||||
const low = cy - height / 2
|
||||
const high = cy + height / 2
|
||||
const upper = colourTop ?? colour
|
||||
|
||||
// b = bottom corners, t = top corners; both in the same order:
|
||||
// (-x,+z) (+x,+z) (+x,-z) (-x,-z)
|
||||
const corner = (size: readonly [number, number], y: number, sx: number, sz: number): Vec3 =>
|
||||
[cx + (sx * size[0]) / 2, y, cz + (sz * size[1]) / 2]
|
||||
|
||||
const b0 = corner(bottom, low, -1, 1), b1 = corner(bottom, low, 1, 1)
|
||||
const b2 = corner(bottom, low, 1, -1), b3 = corner(bottom, low, -1, -1)
|
||||
const t0 = corner(top, high, -1, 1), t1 = corner(top, high, 1, 1)
|
||||
const t2 = corner(top, high, 1, -1), t3 = corner(top, high, -1, -1)
|
||||
|
||||
const side = (bl: Vec3, br: Vec3, tr: Vec3, tl: Vec3): void => {
|
||||
triShaded(sink, bl, br, tr, colour, colour, upper)
|
||||
triShaded(sink, bl, tr, tl, colour, upper, upper)
|
||||
}
|
||||
side(b0, b1, t1, t0) // +Z
|
||||
side(b2, b3, t3, t2) // -Z
|
||||
side(b1, b2, t2, t1) // +X
|
||||
side(b3, b0, t0, t3) // -X
|
||||
|
||||
quad(sink, t0, t1, t2, t3, upper) // top → +Y
|
||||
quad(sink, b3, b2, b1, b0, colour) // bottom → -Y
|
||||
return finish(sink)
|
||||
}
|
||||
|
||||
/**
|
||||
* Square-section bar swept along an arc — bucket handle, ring, hook.
|
||||
*
|
||||
* The cross section is laid out counter-clockwise relative to the sweep
|
||||
* direction (the tangent); that is what makes the outer faces point outward.
|
||||
* The arc is generated in the XY plane, the model rotates it as it likes.
|
||||
*/
|
||||
export function arcBarGeometry(
|
||||
radius: number,
|
||||
thickness: number,
|
||||
fromAngle: number,
|
||||
toAngle: number,
|
||||
segments: number,
|
||||
centre: Vec3,
|
||||
colour: Color,
|
||||
): BufferGeometry {
|
||||
const sink: Sink = { position: [], color: [] }
|
||||
const h = thickness / 2
|
||||
const [cx, cy, cz] = centre
|
||||
const rings: Vec3[][] = []
|
||||
|
||||
for (let i = 0; i <= segments; i += 1) {
|
||||
const a = fromAngle + ((toAngle - fromAngle) * i) / segments
|
||||
// p: the point on the arc. r: the radial direction. z: the plane normal.
|
||||
const px = cx + Math.cos(a) * radius
|
||||
const py = cy + Math.sin(a) * radius
|
||||
const rx = Math.cos(a), ry = Math.sin(a)
|
||||
const at = (su: number, sv: number): Vec3 =>
|
||||
[px + sv * h * rx, py + sv * h * ry, cz + su * h]
|
||||
// u = the plane normal, v = the radial direction. Since u×v equals the
|
||||
// tangent, this ordering is counter-clockwise relative to the sweep direction.
|
||||
rings.push([at(1, 1), at(-1, 1), at(-1, -1), at(1, -1)])
|
||||
}
|
||||
|
||||
for (let i = 0; i < segments; i += 1) {
|
||||
const a = rings[i]!, b = rings[i + 1]!
|
||||
for (let j = 0; j < 4; j += 1) {
|
||||
const k = (j + 1) % 4
|
||||
quad(sink, a[j]!, a[k]!, b[k]!, b[j]!, colour)
|
||||
}
|
||||
}
|
||||
|
||||
const first = rings[0]!, last = rings[segments]!
|
||||
quad(sink, first[0]!, first[3]!, first[2]!, first[1]!, colour) // start cap
|
||||
quad(sink, last[0]!, last[1]!, last[2]!, last[3]!, colour) // end cap
|
||||
return finish(sink)
|
||||
}
|
||||
|
||||
export interface SheetLevel {
|
||||
/** Vertical position. */
|
||||
readonly y: number
|
||||
/** Half width at that height. */
|
||||
readonly halfWidth: number
|
||||
/** Sheet thickness. */
|
||||
readonly thickness: number
|
||||
/** Curve height: how far the edges rise relative to the middle. 0 = flat. */
|
||||
readonly curve: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Dished sheet — a single piece, a seamless concave surface.
|
||||
*
|
||||
* I tried twice to build the shovel blade from three separate flat panels and
|
||||
* both times the result was "three boards side by side": because each panel
|
||||
* rotates around its own centre, a step is left between them and the eye did
|
||||
* not read it as one surface.
|
||||
*
|
||||
* The right way is to produce ONE sheet whose cross section is curved. The
|
||||
* cross section is an arc bent by `curve` at every level; width and thickness
|
||||
* can change from level to level. The hollow faces the +Z direction.
|
||||
*
|
||||
* Besides the shovel, the shield, the trough, the roof covering and the mill
|
||||
* sail all want this.
|
||||
*/
|
||||
export function dishedSheetGeometry(
|
||||
levels: readonly SheetLevel[],
|
||||
segments: number,
|
||||
colour: Color,
|
||||
colourTop?: Color,
|
||||
): BufferGeometry {
|
||||
if (levels.length < 2) throw new Error('dishedSheetGeometry needs at least two levels')
|
||||
const sink: Sink = { position: [], color: [] }
|
||||
const top = colourTop ?? colour
|
||||
const shade = (i: number): Color =>
|
||||
colourTop ? new Color().copy(colour).lerp(top, i / (levels.length - 1)) : colour
|
||||
|
||||
// front[i][j] / back[i][j]: level i, position j along the cross section
|
||||
const front: Vec3[][] = []
|
||||
const back: Vec3[][] = []
|
||||
for (const level of levels) {
|
||||
const f: Vec3[] = []
|
||||
const b: Vec3[] = []
|
||||
for (let j = 0; j <= segments; j += 1) {
|
||||
const u = (j / segments) * 2 - 1 // -1 .. +1
|
||||
const x = u * level.halfWidth
|
||||
// Parabolic cross section: 0 in the middle, `curve` at the edges. The
|
||||
// rise of the edges is what forms the hollow.
|
||||
const z = level.curve * u * u
|
||||
f.push([x, level.y, z + level.thickness / 2])
|
||||
b.push([x, level.y, z - level.thickness / 2])
|
||||
}
|
||||
front.push(f)
|
||||
back.push(b)
|
||||
}
|
||||
|
||||
const last = levels.length - 1
|
||||
for (let i = 0; i < last; i += 1) {
|
||||
for (let j = 0; j < segments; j += 1) {
|
||||
// Front face: points at +Z. (a→b = +X, a→c = +X+Y, cross product +Z.)
|
||||
triShaded(sink, front[i]![j]!, front[i]![j + 1]!, front[i + 1]![j + 1]!,
|
||||
shade(i), shade(i), shade(i + 1))
|
||||
triShaded(sink, front[i]![j]!, front[i + 1]![j + 1]!, front[i + 1]![j]!,
|
||||
shade(i), shade(i + 1), shade(i + 1))
|
||||
// Back face: reversed winding.
|
||||
triShaded(sink, back[i]![j]!, back[i + 1]![j + 1]!, back[i]![j + 1]!,
|
||||
shade(i), shade(i + 1), shade(i))
|
||||
triShaded(sink, back[i]![j]!, back[i + 1]![j]!, back[i + 1]![j + 1]!,
|
||||
shade(i), shade(i + 1), shade(i + 1))
|
||||
}
|
||||
|
||||
// Side edges: the right one points at +X, the left one at -X.
|
||||
quad(sink, front[i]![segments]!, back[i]![segments]!,
|
||||
back[i + 1]![segments]!, front[i + 1]![segments]!, shade(i))
|
||||
quad(sink, back[i]![0]!, front[i]![0]!,
|
||||
front[i + 1]![0]!, back[i + 1]![0]!, shade(i))
|
||||
}
|
||||
|
||||
// Top and bottom edge strips.
|
||||
for (let j = 0; j < segments; j += 1) {
|
||||
quad(sink, front[last]![j]!, front[last]![j + 1]!,
|
||||
back[last]![j + 1]!, back[last]![j]!, shade(last))
|
||||
quad(sink, back[0]![j]!, back[0]![j + 1]!,
|
||||
front[0]![j + 1]!, front[0]![j]!, shade(0))
|
||||
}
|
||||
|
||||
return finish(sink)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverses the winding of every triangle, i.e. turns all the normals around.
|
||||
*
|
||||
* Needed for vessels whose inside is visible: the outer surface of a bowl must
|
||||
* point outward, the inner surface inward. Instead of writing the two
|
||||
* separately, we generate the same cone and flip one of them.
|
||||
*/
|
||||
export function flipGeometry(geometry: BufferGeometry): BufferGeometry {
|
||||
for (const name of ['position', 'color'] as const) {
|
||||
const attribute = geometry.getAttribute(name)
|
||||
if (!attribute) continue
|
||||
const array = attribute.array as Float32Array
|
||||
const stride = attribute.itemSize
|
||||
// Swapping the 2nd and 3rd corner of a triangle reverses the winding.
|
||||
for (let i = 0; i < attribute.count; i += 3) {
|
||||
for (let k = 0; k < stride; k += 1) {
|
||||
const b = (i + 1) * stride + k
|
||||
const c = (i + 2) * stride + k
|
||||
const swap = array[b]!
|
||||
array[b] = array[c]!
|
||||
array[c] = swap
|
||||
}
|
||||
}
|
||||
attribute.needsUpdate = true
|
||||
}
|
||||
return geometry
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces parts that share the same material into a single geometry — one draw
|
||||
* call per material. The normals are computed AFTER merging: on non-indexed
|
||||
* geometry that gives every triangle its own normal, i.e. flat shading.
|
||||
*/
|
||||
export function mergeColoured(geometries: readonly BufferGeometry[]): BufferGeometry {
|
||||
// The normals of the inputs are dropped. The reason is a trap: because this
|
||||
// function computes normals AFTER merging, its output has a `normal`
|
||||
// attribute while the raw geometries do not. Trying to merge the two
|
||||
// together made mergeGeometries fail with "attribute counts do not match".
|
||||
// Since they are recomputed below anyway, the input normal data is worthless.
|
||||
for (const geometry of geometries) geometry.deleteAttribute('normal')
|
||||
|
||||
const merged = mergeGeometries(geometries as BufferGeometry[], false)
|
||||
if (!merged) throw new Error('Could not merge geometries: attribute sets do not match')
|
||||
for (const geometry of geometries) geometry.dispose()
|
||||
merged.computeVertexNormals()
|
||||
return merged
|
||||
}
|
||||
|
||||
/**
|
||||
* Bends a straight body into an arc (along the Y axis, in the YZ plane).
|
||||
*
|
||||
* Written for pitchfork tines. A straight tine, however thick it is, looks
|
||||
* like a technical drawing; a slight curve turns it into a forged tool. Hooks,
|
||||
* horns and scythes have the same need.
|
||||
*
|
||||
* The simple "rotate every point in proportion to its own height" approach
|
||||
* stretched the body and thinned it. The transform here is a real arc mapping:
|
||||
* the body is WRAPPED onto a circle of radius 1/curvature, so the length of the
|
||||
* centre line is preserved.
|
||||
*
|
||||
* TWO TRAPS, both found by measuring:
|
||||
*
|
||||
* 1. The arc is wrapped around y=0, so THE RESULT DEPENDS ON WHERE THE GEOMETRY
|
||||
* SITS IN Y. A bar whose base is at the origin really does curve; a body
|
||||
* CENTRED on y=0 bends symmetrically — its two ends go the same way, its
|
||||
* middle stays put, and the silhouette barely changes at all. That is exactly
|
||||
* what happened with the hoe blade: on a 0.235 m blade the bend produced
|
||||
* 14 mm of displacement but DROPPED the Z range from 0.0337 to 0.0327. Build
|
||||
* the same blade with its base at the origin and bend it, and the offset is
|
||||
* 44 mm and the range 0.078. START whatever you want to bend at the origin.
|
||||
*
|
||||
* 2. The arc is only as smooth as the number of CROSS SECTIONS the geometry has
|
||||
* along the Y axis. A two-level box (chamferedBoxGeometry) bent gives not an
|
||||
* arc but a skewed box. A real arc needs a body with intermediate levels,
|
||||
* like `latheGeometry`.
|
||||
*
|
||||
* @param curvature 1/radius. A positive value bends toward +Z. 0 does nothing.
|
||||
*/
|
||||
export function bendGeometry(geometry: BufferGeometry, curvature: number): BufferGeometry {
|
||||
if (Math.abs(curvature) < 1e-9) return geometry
|
||||
const position = geometry.getAttribute('position')
|
||||
|
||||
// A bend needs something to bend.
|
||||
//
|
||||
// Every vertex is mapped by its own Y, so the curve only exists where there
|
||||
// are Y levels to sample it at. Hand this a `boxGeometry` -- two levels, top
|
||||
// and bottom -- and there is no midpoint to displace: the top face swings to
|
||||
// one angle, the bottom to another, and the result is a sheared wedge that
|
||||
// looks nothing like an arc. It fails silently, which is the expensive part.
|
||||
//
|
||||
// This session found the same mistake in three separate models: the
|
||||
// tankard's handle, and both the brace and the curl of the tavern sign. In
|
||||
// each the author had written a curve, the geometry had never curved, and
|
||||
// the renders had been shipping the wedge. Three is a pattern, so the
|
||||
// helper refuses rather than waiting for a fourth.
|
||||
//
|
||||
// The fix is never to nudge the curvature -- it is to give the piece levels
|
||||
// (a lathe or a stack of them), or to use `arcBarGeometry`, which sweeps a
|
||||
// real arc and takes the two things that actually matter: where the ends go.
|
||||
const seen = new Set<number>()
|
||||
for (let i = 0; i < position.count && seen.size < 3; i += 1) {
|
||||
seen.add(Math.round(position.getY(i) * 1e5))
|
||||
}
|
||||
if (seen.size < 3) {
|
||||
throw new Error(
|
||||
`bendGeometry: geometry has ${seen.size} distinct Y level(s); a bend needs at least 3. ` +
|
||||
'Two levels shear into a wedge instead of curving. Build the piece with ' +
|
||||
'levels (latheGeometry / staveGeometry) or use arcBarGeometry.',
|
||||
)
|
||||
}
|
||||
|
||||
const radius = 1 / curvature
|
||||
for (let i = 0; i < position.count; i += 1) {
|
||||
const y = position.getY(i)
|
||||
const z = position.getZ(i)
|
||||
const angle = y * curvature
|
||||
const sin = Math.sin(angle)
|
||||
const cos = Math.cos(angle)
|
||||
// Centre line + the cross section's offset perpendicular to the tangent.
|
||||
position.setY(i, radius * sin - z * sin)
|
||||
position.setZ(i, radius * (1 - cos) + z * cos)
|
||||
}
|
||||
position.needsUpdate = true
|
||||
geometry.computeVertexNormals()
|
||||
return geometry
|
||||
}
|
||||
|
||||
/** Deterministic hash derived from position. The same point always gives the same value. */
|
||||
function positionHash(x: number, y: number, z: number, salt: number): number {
|
||||
// The point is rounded to a 0.1 mm grid: "identical" corners getting
|
||||
// different hashes because of floating point noise was the one bug that tore
|
||||
// the surface open.
|
||||
let h = Math.imul(Math.round(x * 1e4) | 0, 0x27d4eb2d)
|
||||
h ^= Math.imul(Math.round(y * 1e4) | 0, 0x165667b1)
|
||||
h ^= Math.imul(Math.round(z * 1e4) | 0, 0x9e3779b1)
|
||||
h = Math.imul(h ^ salt, 0x85ebca6b)
|
||||
h ^= h >>> 13
|
||||
return ((h >>> 0) / 0xffffffff) * 2 - 1
|
||||
}
|
||||
|
||||
export interface RoughenOptions {
|
||||
/** For distorting the same geometry in a different way. */
|
||||
readonly salt?: number
|
||||
/** Deviation multiplier on the Y axis. Kept low on the straw bale. */
|
||||
readonly scaleY?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the surface irregular: every corner shifts by a fixed amount derived
|
||||
* from its own position.
|
||||
*
|
||||
* Why it is derived from position: these geometries are NON-INDEXED, i.e. every
|
||||
* triangle carries its own corners and three or four copies sit at one point.
|
||||
* Moving the corners independently tears the surface — on the first attempt the
|
||||
* straw bale ended up riddled with holes. Because the position hash gives all
|
||||
* the copies at the same point the SAME shift, the surface stays closed.
|
||||
*
|
||||
* This is the only thing that makes straw look like straw: a tidy box looks
|
||||
* like a sponge whatever colour you give it.
|
||||
*/
|
||||
export function roughenGeometry(
|
||||
geometry: BufferGeometry,
|
||||
amount: number,
|
||||
options: RoughenOptions = {},
|
||||
): BufferGeometry {
|
||||
if (amount <= 0) return geometry
|
||||
const salt = options.salt ?? 0
|
||||
const scaleY = options.scaleY ?? 1
|
||||
const position = geometry.getAttribute('position')
|
||||
for (let i = 0; i < position.count; i += 1) {
|
||||
const x = position.getX(i)
|
||||
const y = position.getY(i)
|
||||
const z = position.getZ(i)
|
||||
position.setXYZ(
|
||||
i,
|
||||
x + positionHash(x, y, z, salt + 1) * amount,
|
||||
y + positionHash(x, y, z, salt + 2) * amount * scaleY,
|
||||
z + positionHash(x, y, z, salt + 3) * amount,
|
||||
)
|
||||
}
|
||||
position.needsUpdate = true
|
||||
geometry.computeVertexNormals()
|
||||
return geometry
|
||||
}
|
||||
|
||||
export interface MottleOptions {
|
||||
/** For giving the same geometry a different pattern. */
|
||||
readonly salt?: number
|
||||
/**
|
||||
* The size of the specks (metres). Because positions are rounded to this
|
||||
* grid and then hashed, corners in the same cell take the same tone — so what
|
||||
* forms is not noise but MOTTLE. A small value gives sand, a large one a
|
||||
* mottled surface.
|
||||
*/
|
||||
readonly cell?: number
|
||||
/** The ratio of the hue shift to the brightness shift. A high value colours the mottle. */
|
||||
readonly hue?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Works surface mottle into the vertex colours.
|
||||
*
|
||||
* This is this kit's answer to the question "what are we going to do about
|
||||
* texture?". A bitmap texture would have wanted three things: UV coordinates
|
||||
* (our geometry has none), image files the registry would have to carry, and a
|
||||
* change to the kit's identity. All three cost more than they give back.
|
||||
*
|
||||
* Instead, a mottle pattern derived from the surface's OWN position is used.
|
||||
* `bakeOcclusion` produced shadow from the SHAPE of the surface; this gives the
|
||||
* surface a material texture. Together, with no texture file at all, the two
|
||||
* make a flat-coloured lowpoly surface look like material.
|
||||
*
|
||||
* The limit should be stated honestly: the specks are sampled at the corners of
|
||||
* the geometry, so triangle density sets their resolution. On a wide, sparsely
|
||||
* subdivided surface shrinking `cell` does not help — there the cure is to
|
||||
* subdivide the triangle, which eats into the lowpoly budget.
|
||||
*/
|
||||
export function mottleGeometry(
|
||||
geometry: BufferGeometry,
|
||||
amount: number,
|
||||
options: MottleOptions = {},
|
||||
): BufferGeometry {
|
||||
const colour = geometry.getAttribute('color')
|
||||
if (!colour || amount <= 0) return geometry
|
||||
const position = geometry.getAttribute('position')
|
||||
const salt = options.salt ?? 0
|
||||
const cell = options.cell ?? 0.05
|
||||
const hue = options.hue ?? 0.35
|
||||
|
||||
for (let i = 0; i < colour.count; i += 1) {
|
||||
const x = Math.round(position.getX(i) / cell) * cell
|
||||
const y = Math.round(position.getY(i) / cell) * cell
|
||||
const z = Math.round(position.getZ(i) / cell) * cell
|
||||
const shade = 1 + positionHash(x, y, z, salt + 7) * amount
|
||||
// A small difference between the channels: on a real material a lightened
|
||||
// spot does not just get brighter, it also loses a little saturation.
|
||||
const warm = positionHash(x, y, z, salt + 8) * amount * hue
|
||||
colour.setXYZ(
|
||||
i,
|
||||
Math.max(0, colour.getX(i) * (shade + warm)),
|
||||
Math.max(0, colour.getY(i) * shade),
|
||||
Math.max(0, colour.getZ(i) * (shade - warm)),
|
||||
)
|
||||
}
|
||||
colour.needsUpdate = true
|
||||
return geometry
|
||||
}
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
export { createRandom, jitter } from './random.ts'
|
||||
export {
|
||||
arcBarGeometry,
|
||||
bandGeometry,
|
||||
bendGeometry,
|
||||
boxGeometry,
|
||||
chamferedBoxGeometry,
|
||||
dishedSheetGeometry,
|
||||
flipGeometry,
|
||||
headGeometry,
|
||||
latheGeometry,
|
||||
mergeColoured,
|
||||
mottleGeometry,
|
||||
prismGeometry,
|
||||
roughenGeometry,
|
||||
staveGeometry,
|
||||
taperedBoxGeometry,
|
||||
} from './geometry.ts'
|
||||
export type { Level, MottleOptions, RoughenOptions, SheetLevel, Vec3 } from './geometry.ts'
|
||||
export { bakeOcclusion } from './occlusion.ts'
|
||||
export type { OcclusionOptions } from './occlusion.ts'
|
||||
export { createKitModel } from './kit.ts'
|
||||
export type { BuildContext, BuiltPart, KitModelOptions, PartBody, RuntimeContext } from './kit.ts'
|
||||
export { createPart } from './parts.ts'
|
||||
export type { PartSlot } from './parts.ts'
|
||||
export { ironTint, steelTint, toolShaft, toolSocket } from './tool.ts'
|
||||
export type { ShaftOptions, SocketOptions, ToolShaft } from './tool.ts'
|
||||
export { MEDIEVAL_PALETTE, createMedievalMaterials } from './materials.ts'
|
||||
export { createTinter } from './tint.ts'
|
||||
export type { Tinter } from './tint.ts'
|
||||
export type { MedievalPalette, MedievalSlot } from './materials.ts'
|
||||
|
|
@ -1,320 +0,0 @@
|
|||
import { Group, Mesh, type BufferGeometry, type Material } from 'three'
|
||||
|
||||
import type { ConfigureResult, MaterialBindings, ModelInstance, PartHandle } from '@vibe3d/model.ts'
|
||||
import { ResourceScope } from '@vibe3d/ownership.ts'
|
||||
|
||||
import type { Vec3 } from './geometry.ts'
|
||||
import { mottleGeometry } from './geometry.ts'
|
||||
import { bakeOcclusion, type OcclusionOptions } from './occlusion.ts'
|
||||
import { createPart, type PartSlot } from './parts.ts'
|
||||
import { createRandom } from './random.ts'
|
||||
import { createMedievalMaterials, type MedievalSlot, type SlotMaterial } from './materials.ts'
|
||||
|
||||
/**
|
||||
* Kit model scaffold.
|
||||
*
|
||||
* Every model has to set up the same contract: resource ownership, material
|
||||
* resolution and overrides, fixed anchor + replaceable content, a configure()
|
||||
* that does not break identity, an idempotent dispose(). Writing that by hand
|
||||
* in every model means ~80 lines of repetition plus a chance to get it wrong
|
||||
* on each repetition — and indeed I got the anchor/content split wrong in the
|
||||
* first three models at once.
|
||||
*
|
||||
* From here on, writing a model is just producing geometry: `build` returns a
|
||||
* part name → geometry mapping, this function handles the rest.
|
||||
*/
|
||||
|
||||
/** The body of a part that uses a single material slot. */
|
||||
export interface PartBody<S extends string> {
|
||||
readonly slot: S
|
||||
readonly geometry: BufferGeometry
|
||||
}
|
||||
|
||||
export interface BuiltPart<S extends string> extends PartBody<S> {
|
||||
/**
|
||||
* Extra bodies belonging to the same part that use a DIFFERENT slot.
|
||||
*
|
||||
* Parts are sibling children of the root, so when one moves the others
|
||||
* cannot follow it. A chest's lid is oak boards and iron bands and the
|
||||
* lock's hasp all at once, and the three MUST rotate together — if they were
|
||||
* separate parts, the bands would hang in mid-air as the lid opened.
|
||||
*
|
||||
* So this field does not preserve the assumption "one part = one mesh", it
|
||||
* preserves the principle "one part = one meaning". The meaning is not
|
||||
* split, only the material is.
|
||||
*/
|
||||
readonly extras?: readonly PartBody<S>[]
|
||||
/**
|
||||
* The part's own centre of rotation (in model space).
|
||||
*
|
||||
* When given, the anchor is positioned here and the geometry is assumed to
|
||||
* have been written RELATIVE TO THIS POINT. This is the only thing needed
|
||||
* for a chest lid to rotate around its hinge: the lid geometry is produced
|
||||
* at the hinge origin, the anchor is moved to the hinge, and
|
||||
* `anchor.rotation.x` now opens the lid.
|
||||
*
|
||||
* Objects the consumer attached to the anchor join this rotation too — a
|
||||
* candle placed on top of the lid rises with the lid. That is the correct
|
||||
* behaviour.
|
||||
*/
|
||||
readonly origin?: Vec3
|
||||
}
|
||||
|
||||
export interface BuildContext<C, S extends MedievalSlot> {
|
||||
readonly config: Readonly<C>
|
||||
/** Seed-bound deterministic randomness. Starts over on every rebuild. */
|
||||
readonly random: () => number
|
||||
/** The slot's current material (the override, if there is one). */
|
||||
resolve(slot: S): Material
|
||||
/** The slot's default material — even if it has been overridden. */
|
||||
readonly defaults: Pick<SlotMaterial, S>
|
||||
}
|
||||
|
||||
/**
|
||||
* The runtime context handed to actions and to `update`.
|
||||
*
|
||||
* It gives access to the PARTS, not to the geometry: an action must not
|
||||
* trigger a rebuild, it should only move something in the scene graph. Opening
|
||||
* the lid does not change the model's identity, so it is not `configure()`'s
|
||||
* job.
|
||||
*/
|
||||
export interface RuntimeContext<C, P extends string> {
|
||||
readonly parts: Record<P, PartHandle<Group>>
|
||||
getConfig(): Readonly<C>
|
||||
}
|
||||
|
||||
export interface KitModelOptions<
|
||||
C extends { seed: number },
|
||||
S extends MedievalSlot,
|
||||
P extends string,
|
||||
A extends object = Record<string, never>,
|
||||
> {
|
||||
/** Registry item name; used in mesh names and in userData. */
|
||||
readonly id: string
|
||||
readonly defaults: C
|
||||
readonly slots: readonly S[]
|
||||
/** Part name → geometry. `undefined` means absent in that configuration. */
|
||||
build(context: BuildContext<C, S>): Record<P, BuiltPart<S> | undefined>
|
||||
/**
|
||||
* Ambient occlusion to bake into the vertex colours. `false` turns it off.
|
||||
*
|
||||
* All parts are evaluated TOGETHER: the place where a board darkens is the
|
||||
* surface of the neighbouring post, not its own surface.
|
||||
*/
|
||||
readonly occlusion?: OcclusionOptions | false
|
||||
/**
|
||||
* Surface mottle written into the vertex colours. `false` turns it off.
|
||||
*
|
||||
* The amount is scaled BY SLOT (see the table below): burnished steel is not
|
||||
* mottled, straw is mottled badly. The model does not have to do anything
|
||||
* else.
|
||||
*/
|
||||
readonly mottle?: { readonly amount?: number; readonly cell?: number } | false
|
||||
/**
|
||||
* The model's typed actions. Set up once, after the first build — so state
|
||||
* held in the closure (is the lid open, which flame phase) survives a
|
||||
* rebuild.
|
||||
*/
|
||||
actions?(context: RuntimeContext<C, P>): A
|
||||
/** Called each frame. If the consumer never calls it, the model stays fully static. */
|
||||
update?(deltaSeconds: number, context: RuntimeContext<C, P>): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Mottle multiplier per slot.
|
||||
*
|
||||
* The rule comes from the physics of the material: the more polished a surface
|
||||
* is, the more it becomes a SINGLE COLOUR, because the light reaching the eye
|
||||
* comes from the reflection rather than from the surface's own pigment. For
|
||||
* straw and cloth the exact opposite holds.
|
||||
*
|
||||
* Tying this to the slot is better than tuning it separately in every model:
|
||||
* within the kit the same material looks the same everywhere.
|
||||
*/
|
||||
const MOTTLE_BY_SLOT: Readonly<Record<MedievalSlot, number>> = {
|
||||
straw: 1.35,
|
||||
cloth: 1.15,
|
||||
oak: 1,
|
||||
char: 0.85,
|
||||
leather: 0.7,
|
||||
produce: 0.6,
|
||||
iron: 0.5,
|
||||
brass: 0.35,
|
||||
steel: 0.22,
|
||||
glass: 0.15,
|
||||
// Between timber and iron. Rubble masonry varies block to block, but each
|
||||
// block is fairly even in itself, so the mottle wants to read at the scale
|
||||
// of a stone rather than of a grain.
|
||||
stone: 0.75,
|
||||
ember: 0, // a flame is not mottled: its colour is already the final colour
|
||||
water: 0.2,
|
||||
}
|
||||
|
||||
export function createKitModel<
|
||||
C extends { seed: number },
|
||||
S extends MedievalSlot,
|
||||
P extends string,
|
||||
A extends object = Record<string, never>,
|
||||
>(
|
||||
options: KitModelOptions<C, S, P, A>,
|
||||
overrides: Partial<C> = {},
|
||||
): ModelInstance<C, Record<P, PartHandle<Group>>, A> {
|
||||
let config: C = { ...options.defaults, ...overrides }
|
||||
|
||||
// The resources the model owns. Materials handed in by the consumer never
|
||||
// enter here, so dispose() does not touch them.
|
||||
const scope = new ResourceScope()
|
||||
const defaults = createMedievalMaterials(scope, options.slots)
|
||||
const overridesBySlot = new Map<S, Material>()
|
||||
const resolve = (slot: S): Material => overridesBySlot.get(slot) ?? defaults[slot]
|
||||
|
||||
const root = new Group()
|
||||
root.name = options.id
|
||||
|
||||
const parts = {} as Record<P, PartSlot>
|
||||
let owned: BufferGeometry[] = []
|
||||
|
||||
function build(): void {
|
||||
for (const geometry of owned) geometry.dispose()
|
||||
owned = []
|
||||
|
||||
const produced = options.build({
|
||||
config,
|
||||
random: createRandom(config.seed),
|
||||
resolve,
|
||||
defaults,
|
||||
})
|
||||
|
||||
const built = Object.values(produced)
|
||||
.filter((part): part is BuiltPart<S> => part !== undefined)
|
||||
const geometriesOf = (part: BuiltPart<S>): BufferGeometry[] =>
|
||||
[part, ...(part.extras ?? [])]
|
||||
// A flame neither TAKES shadow nor CASTS one. `ember` is an unlit
|
||||
// material, so its vertex colour is the final colour going straight to
|
||||
// the screen — if occlusion darkened it, the flame would go out. The
|
||||
// rule is tied to the slot itself, not to a per-model flag: it must
|
||||
// not be possible to forget it.
|
||||
.filter((body) => body.slot !== 'ember')
|
||||
.map((body) => body.geometry)
|
||||
|
||||
if (options.occlusion !== false) {
|
||||
// Occlusion has to be computed in ASSEMBLY space: a lid written at its
|
||||
// own origin looks as though it sits inside the body rather than beside
|
||||
// it, and darkens the wrong places. So everything is first moved into
|
||||
// place, baked, then moved back — the resulting geometries stay
|
||||
// hinge-local.
|
||||
const moved = built.filter((part) => part.origin !== undefined)
|
||||
for (const part of moved) {
|
||||
const [x, y, z] = part.origin!
|
||||
for (const geometry of geometriesOf(part)) geometry.translate(x, y, z)
|
||||
}
|
||||
bakeOcclusion(built.flatMap(geometriesOf), options.occlusion ?? {})
|
||||
for (const part of moved) {
|
||||
const [x, y, z] = part.origin!
|
||||
for (const geometry of geometriesOf(part)) geometry.translate(-x, -y, -z)
|
||||
}
|
||||
}
|
||||
|
||||
if (options.mottle !== false) {
|
||||
const amount = options.mottle?.amount ?? 0.125
|
||||
// The mottle size is derived from the model's scale, but WITH ABSOLUTE
|
||||
// BOUNDS.
|
||||
//
|
||||
// The bounds were added later and closed a real bug: with scale used on
|
||||
// its own, a 4.89 m fence got a 0.27 m cell. The fence's post is 0.09 m
|
||||
// — so the entire post fell into ONE cell and came out completely flat.
|
||||
// The model paid the cost of the texture system and got nothing back.
|
||||
//
|
||||
// The truth is this: wood grain mottle is 2–8 cm and has nothing to do
|
||||
// with the size of the object. A fence post and a tankard stave come out
|
||||
// of the same tree.
|
||||
const extent = built.reduce((largest, part) => {
|
||||
part.geometry.computeBoundingBox()
|
||||
const box = part.geometry.boundingBox
|
||||
if (!box) return largest
|
||||
return Math.max(largest, box.max.x - box.min.x, box.max.y - box.min.y, box.max.z - box.min.z)
|
||||
}, 0)
|
||||
const cell = options.mottle?.cell ?? Math.min(0.08, Math.max(0.015, extent * 0.055))
|
||||
for (const part of built) {
|
||||
for (const body of [part, ...(part.extras ?? [])]) {
|
||||
mottleGeometry(body.geometry, amount * MOTTLE_BY_SLOT[body.slot], { cell, salt: 3 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const [name, part] of Object.entries(produced) as Array<[P, BuiltPart<S> | undefined]>) {
|
||||
// The anchor is created on first setup and NEVER changes again; only its
|
||||
// content is renewed. That is why objects the consumer attached to the
|
||||
// anchor survive a rebuild.
|
||||
let slot = parts[name]
|
||||
if (!slot) {
|
||||
slot = createPart(`${options.id}/${name}`)
|
||||
parts[name] = slot
|
||||
root.add(slot.anchor)
|
||||
}
|
||||
const target = slot.reset()
|
||||
if (!part) continue
|
||||
|
||||
// The position is updated but the ROTATION is not: the angle an action
|
||||
// moved has to survive a rebuild, otherwise the chest's lid slams shut
|
||||
// every time `configure()` is called.
|
||||
if (part.origin) slot.anchor.position.set(...part.origin)
|
||||
|
||||
for (const body of [part, ...(part.extras ?? [])]) {
|
||||
owned.push(body.geometry)
|
||||
const mesh = new Mesh(body.geometry, resolve(body.slot))
|
||||
mesh.name = `${options.id}/${name}`
|
||||
mesh.userData.vibe3d = {
|
||||
model: `@medieval-kit/${options.id}`,
|
||||
part: name,
|
||||
materialSlot: body.slot,
|
||||
}
|
||||
target.add(mesh)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
build()
|
||||
|
||||
const runtime: RuntimeContext<C, P> = {
|
||||
parts: parts as unknown as Record<P, PartHandle<Group>>,
|
||||
getConfig: () => config,
|
||||
}
|
||||
const actions = (options.actions?.(runtime) ?? {}) as A
|
||||
|
||||
const materials: MaterialBindings = {
|
||||
get: (slot) => (options.slots.includes(slot as S) ? resolve(slot as S) : undefined),
|
||||
override: (slot, material) => {
|
||||
if (!options.slots.includes(slot as S)) return
|
||||
overridesBySlot.set(slot as S, material)
|
||||
build()
|
||||
},
|
||||
reset: (slot) => {
|
||||
if (!overridesBySlot.delete(slot as S)) return
|
||||
build()
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
root,
|
||||
parts: parts as unknown as Record<P, PartHandle<Group>>,
|
||||
actions,
|
||||
materials,
|
||||
getConfig: () => config,
|
||||
configure: (patch): ConfigureResult => {
|
||||
const next = { ...config, ...patch }
|
||||
const changed = (Object.keys(next) as Array<keyof C>).some((key) => next[key] !== config[key])
|
||||
if (!changed) return { rebuilt: false }
|
||||
config = next
|
||||
build()
|
||||
return { rebuilt: true }
|
||||
},
|
||||
update: (deltaSeconds) => options.update?.(deltaSeconds, runtime),
|
||||
dispose: () => {
|
||||
for (const geometry of owned) geometry.dispose()
|
||||
owned = []
|
||||
for (const part of Object.values(parts) as PartSlot[]) part.reset()
|
||||
scope.dispose()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -1,392 +0,0 @@
|
|||
import { Color, DoubleSide, MeshBasicMaterial, MeshStandardMaterial } from 'three'
|
||||
|
||||
import type { ResourceScope } from '@vibe3d/ownership.ts'
|
||||
|
||||
/**
|
||||
* The kit's shared material set.
|
||||
*
|
||||
* The critical choice: every material is `vertexColors: true`. Colour
|
||||
* variation is carried in the GEOMETRY, not in the material. That way 13
|
||||
* boards can have 13 separate tones while all of them share a single
|
||||
* material, and therefore a single draw call.
|
||||
*
|
||||
* This is the small version of the idea behind scifi-kit's wear pipeline:
|
||||
* write the surface identity into a vertex attribute, then merge.
|
||||
*/
|
||||
export type MedievalSlot =
|
||||
| 'oak' // timber
|
||||
| 'iron' // wrought iron
|
||||
| 'steel' // steel burnished by use
|
||||
| 'brass' // bronze and copper: bells, coins
|
||||
| 'straw' // straw, wicker, besom bristles
|
||||
| 'cloth' // linen, sackcloth, parchment
|
||||
| 'leather' // leather: book covers, pouches
|
||||
| 'glass' // blown glass
|
||||
| 'produce' // fruit and vegetable skin
|
||||
| 'ember' // flame — does not take light, it emits it
|
||||
| 'char' // charcoal, pitch
|
||||
| 'stone' // dressed and rubble masonry
|
||||
| 'water' // standing water
|
||||
|
||||
/**
|
||||
* The material TYPE can differ per slot. `ember` is an unlit MeshBasicMaterial;
|
||||
* the rest are PBR. Thanks to this mapping the model code knows at compile
|
||||
* time which type it is getting.
|
||||
*/
|
||||
export interface SlotMaterial {
|
||||
readonly oak: MeshStandardMaterial
|
||||
readonly iron: MeshStandardMaterial
|
||||
readonly steel: MeshStandardMaterial
|
||||
readonly brass: MeshStandardMaterial
|
||||
readonly straw: MeshStandardMaterial
|
||||
readonly cloth: MeshStandardMaterial
|
||||
readonly leather: MeshStandardMaterial
|
||||
readonly glass: MeshStandardMaterial
|
||||
readonly produce: MeshStandardMaterial
|
||||
readonly ember: MeshBasicMaterial
|
||||
readonly char: MeshStandardMaterial
|
||||
readonly stone: MeshStandardMaterial
|
||||
readonly water: MeshStandardMaterial
|
||||
}
|
||||
|
||||
export interface MedievalPalette {
|
||||
/** Oak body tone. */
|
||||
readonly oak: Color
|
||||
/** Lid board — a little cooler and lighter than the body (end grain). */
|
||||
readonly oakEnd: Color
|
||||
/** Wrought iron: fresh off the anvil, the oxide layer still on it. */
|
||||
readonly iron: Color
|
||||
/** Steel burnished by use: the anvil's face, the shovel's blade, the fork's tines. */
|
||||
readonly steel: Color
|
||||
/** Bronze — bells, mortars, coins. */
|
||||
readonly brass: Color
|
||||
/**
|
||||
* Bell bronze that has stood outside.
|
||||
*
|
||||
* Separate from `brass` because they are not the same colour and the models
|
||||
* that use each are not the same models. Fresh bronze on a coin or a book's
|
||||
* corner boss is the yellow `brass` is; a bell that has hung in weather for a
|
||||
* century is dark and grey. Measured against a reference photograph the bell
|
||||
* sits at hue 33, saturation 0.34, value 0.33, against 39 / 0.56 / 0.56 for
|
||||
* the brass we were painting it with.
|
||||
*
|
||||
* This is a PALETTE entry, not a slot: the mesh still resolves through the
|
||||
* `brass` material. The palette carries colour, the slot carries material,
|
||||
* and keeping them separate is what lets one model recolour without dragging
|
||||
* the coin pouch and the book's fittings along with it.
|
||||
*/
|
||||
readonly bronze: Color
|
||||
/** Dry straw. */
|
||||
readonly straw: Color
|
||||
/** Straw tips bleached by the sun. */
|
||||
readonly strawPale: Color
|
||||
/** Raw linen / sackcloth. */
|
||||
readonly cloth: Color
|
||||
/** Tanned leather. */
|
||||
readonly leather: Color
|
||||
/** Blown glass — slightly greenish, glass of the period was not clear. */
|
||||
readonly glass: Color
|
||||
/** Base tone of fruit skin. The actual colour comes from the model's `hue` field. */
|
||||
readonly produce: Color
|
||||
/** Base of the flame — hot and bright. */
|
||||
readonly ember: Color
|
||||
/** Tip of the flame — more saturated, more red. */
|
||||
readonly emberTip: Color
|
||||
/** Burnt-out charcoal. */
|
||||
readonly char: Color
|
||||
/** Charcoal that is still glowing. */
|
||||
readonly charHot: Color
|
||||
/**
|
||||
* Masonry.
|
||||
*
|
||||
* The kit had no stone at all, which for a medieval catalogue is a hole
|
||||
* rather than an omission: a well, a trough, a millstone, a boundary wall
|
||||
* and a hearth are all stone before they are anything else. Its colour is
|
||||
* close to weathered oak on purpose -- what separates the two at a glance is
|
||||
* not hue but that stone scatters light completely flat, which is carried by
|
||||
* the material's roughness rather than by the palette.
|
||||
*/
|
||||
readonly stone: Color
|
||||
|
||||
/**
|
||||
* Living bark, which is NOT the timber colour and is not close to it.
|
||||
*
|
||||
* Measured off a photograph of a standing oak: hue 70 degrees, saturation
|
||||
* 0.17. Sawn oak in this palette sits at hue 26 and saturation 0.36 -- the
|
||||
* bark is 44 degrees cooler and half as saturated, because it is grey-green
|
||||
* with lichen and algae on it rather than brown. Reaching for the `oak` key
|
||||
* on a trunk gives a plank standing on end.
|
||||
*
|
||||
* Measured off the WINTER photograph, after the first attempt took it off
|
||||
* the summer one and came out 28 degrees too green. A trunk under a crown in
|
||||
* full leaf is lit through the leaves, and the green it bounces down is in
|
||||
* every pixel of it; the same tree bare reads hue 42 and saturation 0.27
|
||||
* against 70 and 0.17. Two photographs of the same species disagreeing by
|
||||
* that much is not noise, it is one of them measuring the light instead of
|
||||
* the bark.
|
||||
*
|
||||
* The low saturation of the first attempt made it worse than the hue alone:
|
||||
* a nearly neutral colour takes its hue from whatever is lighting it, and in
|
||||
* this kit's renderer that is a blue-grey sky, which dragged the rendered
|
||||
* bole all the way to hue 119 -- properly green, on a tree whose bark is
|
||||
* brown. Saturation here is what holds the hue still.
|
||||
*
|
||||
* Lightness is the one number not taken straight: the photograph averages
|
||||
* 0.21, but a good part of that is shadow inside bark fissures millimetres
|
||||
* deep which nine flat facets cannot reproduce. The straw note below is the
|
||||
* same trap.
|
||||
*/
|
||||
readonly bark: Color
|
||||
|
||||
|
||||
/**
|
||||
* Weathered limestone, which is NOT the same rock as `stone`.
|
||||
*
|
||||
* `stone` was measured off dressed and rubble masonry: hue 44, saturation
|
||||
* 0.05 — a wall stone, grey, and grey because a wall is quarried and laid
|
||||
* face out. A trough is one block left in the open for a century, and the
|
||||
* same measurement on one reads hue 36, saturation 0.16, lightness 0.48:
|
||||
* warmer, THREE TIMES more saturated, and lighter. Reaching for `stone` on
|
||||
* it gives a concrete planter.
|
||||
*
|
||||
* Both are correct and neither replaces the other, which is why this is a
|
||||
* palette key rather than an edit to `stone` — the well and the forge were
|
||||
* each measured against their own references and are not this rock.
|
||||
*/
|
||||
readonly limestone: Color
|
||||
|
||||
/**
|
||||
* Standing water, and it is far less green than it feels.
|
||||
*
|
||||
* Sampled inside the reference trough's basin the film reads hue 39.5 —
|
||||
* which is the hue of the stone underneath it, not a colour of its own. It
|
||||
* is shallow and it is clear; what it does is DARKEN and slightly saturate
|
||||
* whatever it lies on (lightness 0.48 down to 0.36, saturation 0.16 up to
|
||||
* 0.23). So this is nearly neutral, barely cool, and it does its work
|
||||
* through the material's transparency rather than through its hue. Painted
|
||||
* the pond green a first-instinct would have reached for, the composite
|
||||
* would have missed the reference by 100 degrees of hue.
|
||||
*/
|
||||
readonly water: Color
|
||||
}
|
||||
|
||||
/**
|
||||
* The colours are written as sRGB; with ColorManagement enabled three stores
|
||||
* them internally in linear space. Since the vertex colour attribute expects
|
||||
* linear values, `color.r/g/b` can be written straight through — no extra
|
||||
* conversion needed.
|
||||
*/
|
||||
/**
|
||||
* Base colours, measured against reference photographs rather than chosen.
|
||||
*
|
||||
* The hue was already right -- our oak sits at 26 degrees and real oak in a
|
||||
* photograph sits at 27 -- but the saturation was consistently too high, by a
|
||||
* median of 0.08 across ten wooden models, and worst on the ones made almost
|
||||
* entirely of bare timber: the ladder and the fence were each 0.16 over. That
|
||||
* is the difference between weathered oak and new pine, and it was making the
|
||||
* whole kit read as plastic.
|
||||
*
|
||||
* Straw and linen are deliberately NOT adjusted, although the same measurement
|
||||
* said they were too yellow and too washed out. Following it made them visibly
|
||||
* worse. A photograph of a bale reads as desaturated because it is thousands of
|
||||
* individual straws each casting a shadow on its neighbour; pushing a flat
|
||||
* lowpoly surface up to that number does not reproduce the texture, it just
|
||||
* makes the surface garish. The statistic was real and the inference from it
|
||||
* was wrong -- which is worth leaving written down, because the same trap is
|
||||
* there for any material whose reference gets its character from fine detail.
|
||||
*
|
||||
* Two follow-up measurements ruled out the other colour explanations: our
|
||||
* saturation spread is 93% of the references', so it is not a lack of
|
||||
* variation, and the hue was never off. What remains between these models and
|
||||
* their references is geometry, not colour.
|
||||
*/
|
||||
export const MEDIEVAL_PALETTE: MedievalPalette = {
|
||||
oak: new Color(0x8a6141),
|
||||
oakEnd: new Color(0x9a7a5e),
|
||||
iron: new Color(0x40464d),
|
||||
steel: new Color(0x8d979f),
|
||||
brass: new Color(0xa9843f),
|
||||
bronze: new Color(0x63523e),
|
||||
straw: new Color(0xc2a049),
|
||||
strawPale: new Color(0xdcc182),
|
||||
cloth: new Color(0xb9a888),
|
||||
leather: new Color(0x6b452c),
|
||||
glass: new Color(0xbcd4cb),
|
||||
produce: new Color(0xa8452f),
|
||||
ember: new Color(0xffd27a),
|
||||
emberTip: new Color(0xd8571b),
|
||||
char: new Color(0x241f1c),
|
||||
stone: new Color(0x6e6b63),
|
||||
charHot: new Color(0xc4441a),
|
||||
bark: new Color(0x585032),
|
||||
limestone: new Color(0x94846b),
|
||||
water: new Color(0x3b4e45),
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates materials for the requested slots.
|
||||
*
|
||||
* The slot list is required on purpose: the brazier does not need oak, the
|
||||
* barrel does not need an emissive material. Creating unused materials is both
|
||||
* a wasted GPU resource and a lie that contradicts the model's `materialSlots`
|
||||
* declaration.
|
||||
*
|
||||
* The return type is narrowed to the requested slots, so `materials.ember`
|
||||
* only compiles in a model that asked for it.
|
||||
*/
|
||||
export function createMedievalMaterials<S extends MedievalSlot>(
|
||||
scope: ResourceScope,
|
||||
slots: readonly S[],
|
||||
): Pick<SlotMaterial, S> {
|
||||
const build: { [K in MedievalSlot]: () => SlotMaterial[K] } = {
|
||||
oak: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / oak',
|
||||
// White base: all colour information comes from the vertex colour, so
|
||||
// the material must not multiply it away.
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
roughness: 0.82,
|
||||
metalness: 0,
|
||||
}),
|
||||
// Iron occurs in two states and they cannot be told with ONE material.
|
||||
// The anvil's body is forged, oxidised, matte; its face is like a mirror
|
||||
// because it has been worked on for years. The difference between them is
|
||||
// not one of colour but of ROUGHNESS — vertex colour cannot carry that,
|
||||
// because roughness is not an attribute.
|
||||
//
|
||||
// Hence two slots: `iron` is the forged surface, `steel` is the surface
|
||||
// the work has touched. It is normal for a model to want both; it is worth
|
||||
// a separate draw call, because a bright cutting edge sells the model on
|
||||
// its own.
|
||||
iron: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / wrought iron',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
roughness: 0.62,
|
||||
metalness: 0.78,
|
||||
}),
|
||||
steel: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / burnished steel',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
// Low roughness + high metalness, i.e. almost fully reflective. This
|
||||
// only works if there is an environment map; in a scene without an
|
||||
// environment it looks pitch black. The viewer supplies a PMREM sky.
|
||||
roughness: 0.19,
|
||||
metalness: 0.95,
|
||||
}),
|
||||
brass: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / bronze',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
roughness: 0.38,
|
||||
metalness: 0.85,
|
||||
}),
|
||||
// Straw and cloth are fully matte: metalness 0, roughness almost 1. The
|
||||
// difference between them is not in the numbers but in the vertex colours
|
||||
// — both follow the same lighting model, but keeping them in separate
|
||||
// slots matters, because a model's `materialSlots` declaration is a
|
||||
// CONTRACT: a straw bale declaring an "oak" slot would be a lie told to
|
||||
// the consumer.
|
||||
straw: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / straw',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
roughness: 0.94,
|
||||
metalness: 0,
|
||||
}),
|
||||
cloth: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / linen',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
roughness: 0.97,
|
||||
metalness: 0,
|
||||
}),
|
||||
leather: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / leather',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
// Leather is not fully matte; being oiled, it has a slight sheen.
|
||||
roughness: 0.66,
|
||||
metalness: 0,
|
||||
}),
|
||||
// Glass is a thin SHELL, not a solid block. That has two consequences:
|
||||
// `side` has to be DoubleSide (otherwise it disappears when seen from
|
||||
// inside) and `depthWrite` has to be off (otherwise it hides the wick
|
||||
// behind it).
|
||||
glass: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / blown glass',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
roughness: 0.08,
|
||||
metalness: 0,
|
||||
transparent: true,
|
||||
opacity: 0.34,
|
||||
depthWrite: false,
|
||||
side: DoubleSide,
|
||||
}),
|
||||
// Fruit skin is waxy: not fully matte, but not metallic either. The reason
|
||||
// it is a separate slot is not the name but the BEHAVIOUR — had I given it
|
||||
// the same roughness as straw, an apple would look like dry hay.
|
||||
produce: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / produce',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
roughness: 0.52,
|
||||
metalness: 0,
|
||||
}),
|
||||
// A flame does not TAKE light, it emits it. MeshStandardMaterial would be
|
||||
// the wrong tool here: `emissive` is a single Color, it is not fed from
|
||||
// vertex colours — so no colour gradient from the flame's base to its tip
|
||||
// is possible. MeshBasicMaterial skips lighting entirely and shows the
|
||||
// vertex colour as it is; toneMapped is off so the scene exposure cannot
|
||||
// put the flame out.
|
||||
ember: () => new MeshBasicMaterial({
|
||||
name: 'medieval-kit / ember',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
toneMapped: false,
|
||||
}),
|
||||
stone: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / stone',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
// Rougher than anything else here. Dressed stone is not polished and
|
||||
// rubble certainly is not; any sheen at all reads as ceramic.
|
||||
roughness: 0.97,
|
||||
metalness: 0,
|
||||
}),
|
||||
// Water is a THIN TRANSPARENT FILM, not a body of liquid. Everything in
|
||||
// this kit that holds water holds a few centimetres of it over a floor you
|
||||
// can see, so the colour that reaches the eye is mostly what is underneath
|
||||
// — which is why the opacity is the important number here and the hue is
|
||||
// nearly not a number at all. Smooth, because a trough out of the wind is
|
||||
// the one surface in this kit that reflects.
|
||||
water: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / standing water',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
roughness: 0.11,
|
||||
metalness: 0,
|
||||
transparent: true,
|
||||
opacity: 0.72,
|
||||
}),
|
||||
char: () => new MeshStandardMaterial({
|
||||
name: 'medieval-kit / charcoal',
|
||||
color: 0xffffff,
|
||||
vertexColors: true,
|
||||
roughness: 0.95,
|
||||
metalness: 0,
|
||||
}),
|
||||
}
|
||||
|
||||
const materials = {} as { [K in S]: SlotMaterial[K] }
|
||||
for (const slot of slots) {
|
||||
// TypeScript cannot follow correlated unions: `build[slot]` widens to a
|
||||
// union of functions, so it cannot know that the return is exactly
|
||||
// SlotMaterial[slot]. The cast is safe because the mapping is built by
|
||||
// hand above.
|
||||
materials[slot] = scope.ownMaterial(build[slot]()) as SlotMaterial[S]
|
||||
}
|
||||
return materials
|
||||
}
|
||||
|
|
@ -1,176 +0,0 @@
|
|||
import type { BufferGeometry } from 'three'
|
||||
|
||||
/**
|
||||
* Ambient occlusion baked into vertex colours.
|
||||
*
|
||||
* Why this and not a texture: a bitmap texture would bring three things — UV
|
||||
* coordinates (our geometry has none), image files the registry would have to
|
||||
* carry, and a change to the kit's identity. Lowpoly + flat shading + vertex
|
||||
* colour is a coherent style; a half-hearted texture breaks it.
|
||||
*
|
||||
* Instead we derive the darkening from the surface's OWN shape: the more
|
||||
* neighbouring surfaces surround a point, the less sky it sees. The result is
|
||||
* darkening in cavities and at contact points — between the boards, under the
|
||||
* hoop, where the logs touch. The models suddenly look "used" and it costs
|
||||
* zero memory, zero textures.
|
||||
*
|
||||
* Method: a grid is built from the triangle centroids, then for each vertex
|
||||
* the neighbour density within its own normal hemisphere is measured. No ray
|
||||
* tracing — at this scale (hundreds of triangles) it would be needlessly
|
||||
* expensive and the difference is negligible.
|
||||
*/
|
||||
|
||||
export interface OcclusionOptions {
|
||||
/** Radius searched for neighbours. Derived from the model's size if omitted. */
|
||||
readonly radius?: number
|
||||
/** How much the darkest point is darkened. 0 = off. */
|
||||
readonly strength?: number
|
||||
/** Neighbour weight where saturation is reached. Raising it softens the darkening. */
|
||||
readonly saturation?: number
|
||||
}
|
||||
|
||||
interface Sample {
|
||||
readonly x: number
|
||||
readonly y: number
|
||||
readonly z: number
|
||||
readonly area: number
|
||||
}
|
||||
|
||||
/** Simple spatial grid: for quickly finding the samples within a radius. */
|
||||
class Grid {
|
||||
readonly #cells = new Map<string, Sample[]>()
|
||||
readonly #size: number
|
||||
|
||||
constructor(samples: readonly Sample[], cellSize: number) {
|
||||
this.#size = cellSize
|
||||
for (const sample of samples) {
|
||||
const key = this.#key(sample.x, sample.y, sample.z)
|
||||
const bucket = this.#cells.get(key)
|
||||
if (bucket) bucket.push(sample)
|
||||
else this.#cells.set(key, [sample])
|
||||
}
|
||||
}
|
||||
|
||||
#key(x: number, y: number, z: number): string {
|
||||
return `${Math.floor(x / this.#size)},${Math.floor(y / this.#size)},${Math.floor(z / this.#size)}`
|
||||
}
|
||||
|
||||
/** The samples of the 27 cells surrounding the given point. */
|
||||
near(x: number, y: number, z: number): Sample[] {
|
||||
const cx = Math.floor(x / this.#size)
|
||||
const cy = Math.floor(y / this.#size)
|
||||
const cz = Math.floor(z / this.#size)
|
||||
const found: Sample[] = []
|
||||
for (let i = -1; i <= 1; i += 1) {
|
||||
for (let j = -1; j <= 1; j += 1) {
|
||||
for (let k = -1; k <= 1; k += 1) {
|
||||
const bucket = this.#cells.get(`${cx + i},${cy + j},${cz + k}`)
|
||||
if (bucket) found.push(...bucket)
|
||||
}
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the occlusion of the given geometries TOGETHER and writes it into
|
||||
* their colours.
|
||||
*
|
||||
* They all have to be evaluated as one: the place where a board darkens is the
|
||||
* surface of the neighbouring post, not its own surface. Processing them one
|
||||
* by one would miss the contact points entirely.
|
||||
*/
|
||||
export function bakeOcclusion(
|
||||
geometries: readonly BufferGeometry[],
|
||||
options: OcclusionOptions = {},
|
||||
): void {
|
||||
const strength = options.strength ?? 0.42
|
||||
if (strength <= 0 || geometries.length === 0) return
|
||||
|
||||
// --- 1. Samples: each triangle's centroid, weighted by its area ---
|
||||
const samples: Sample[] = []
|
||||
let minX = Infinity, minY = Infinity, minZ = Infinity
|
||||
let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity
|
||||
|
||||
for (const geometry of geometries) {
|
||||
const position = geometry.getAttribute('position')
|
||||
if (!position) continue
|
||||
const index = geometry.getIndex()
|
||||
const count = index ? index.count : position.count
|
||||
for (let i = 0; i < count; i += 3) {
|
||||
const at = (k: number): [number, number, number] => {
|
||||
const v = index ? index.getX(i + k) : i + k
|
||||
return [position.getX(v), position.getY(v), position.getZ(v)]
|
||||
}
|
||||
const [ax, ay, az] = at(0)
|
||||
const [bx, by, bz] = at(1)
|
||||
const [cx, cy, cz] = at(2)
|
||||
const ux = bx - ax, uy = by - ay, uz = bz - az
|
||||
const vx = cx - ax, vy = cy - ay, vz = cz - az
|
||||
const nx = uy * vz - uz * vy
|
||||
const ny = uz * vx - ux * vz
|
||||
const nz = ux * vy - uy * vx
|
||||
const area = Math.hypot(nx, ny, nz) / 2
|
||||
if (area <= 0) continue
|
||||
const x = (ax + bx + cx) / 3
|
||||
const y = (ay + by + cy) / 3
|
||||
const z = (az + bz + cz) / 3
|
||||
samples.push({ x, y, z, area })
|
||||
minX = Math.min(minX, x); maxX = Math.max(maxX, x)
|
||||
minY = Math.min(minY, y); maxY = Math.max(maxY, y)
|
||||
minZ = Math.min(minZ, z); maxZ = Math.max(maxZ, z)
|
||||
}
|
||||
}
|
||||
if (samples.length === 0) return
|
||||
|
||||
const extent = Math.max(maxX - minX, maxY - minY, maxZ - minZ, 1e-6)
|
||||
// The radius is derived from the scale but has an ABSOLUTE ceiling. Without
|
||||
// the ceiling a 4.89 m fence gets a 0.69 m radius and the definition of
|
||||
// "neighbour" loses its meaning: everything is everything's neighbour, and
|
||||
// instead of showing the contact points the occlusion smears a flat
|
||||
// darkening over the whole model.
|
||||
//
|
||||
// The physical meaning says the same thing: what shades a surface is what is
|
||||
// NEAR it. A post half a metre away is not making the shadow between the
|
||||
// boards.
|
||||
const radius = options.radius ?? Math.min(0.16, Math.max(0.015, extent * 0.14))
|
||||
const grid = new Grid(samples, radius)
|
||||
// Saturation has to be proportional to the model's scale: as the radius
|
||||
// grows so does the area it covers, and a fixed threshold would turn small
|
||||
// models pitch black.
|
||||
const saturation = options.saturation ?? radius * radius * 1.9
|
||||
|
||||
// --- 2. Neighbour density for each vertex ---
|
||||
for (const geometry of geometries) {
|
||||
const position = geometry.getAttribute('position')
|
||||
const colour = geometry.getAttribute('color')
|
||||
if (!position || !colour) continue
|
||||
if (!geometry.getAttribute('normal')) geometry.computeVertexNormals()
|
||||
const normal = geometry.getAttribute('normal')!
|
||||
|
||||
for (let i = 0; i < position.count; i += 1) {
|
||||
const px = position.getX(i), py = position.getY(i), pz = position.getZ(i)
|
||||
const nx = normal.getX(i), ny = normal.getY(i), nz = normal.getZ(i)
|
||||
|
||||
let weight = 0
|
||||
for (const sample of grid.near(px, py, pz)) {
|
||||
const dx = sample.x - px, dy = sample.y - py, dz = sample.z - pz
|
||||
const distance = Math.hypot(dx, dy, dz)
|
||||
if (distance < 1e-6 || distance > radius) continue
|
||||
// Only neighbours in the hemisphere the vertex FACES occlude it.
|
||||
const facing = (dx * nx + dy * ny + dz * nz) / distance
|
||||
if (facing <= 0) continue
|
||||
// The effect fades with distance; a soft falloff instead of the
|
||||
// inverse-square law, because the goal is not physical accuracy but a
|
||||
// readable cavity shadow.
|
||||
weight += sample.area * facing * (1 - distance / radius)
|
||||
}
|
||||
|
||||
const occlusion = Math.min(1, weight / saturation)
|
||||
const factor = 1 - strength * occlusion
|
||||
colour.setXYZ(i, colour.getX(i) * factor, colour.getY(i) * factor, colour.getZ(i) * factor)
|
||||
}
|
||||
colour.needsUpdate = true
|
||||
}
|
||||
}
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
import { Group } from 'three'
|
||||
|
||||
import type { PartHandle } from '@vibe3d/model.ts'
|
||||
|
||||
/**
|
||||
* Semantic part slot: fixed anchor + replaceable content.
|
||||
*
|
||||
* This is the most easily misunderstood contract in vibe3d. `PartHandle`
|
||||
* declares two separate objects and they CANNOT BE THE SAME:
|
||||
*
|
||||
* anchor the same object for the lifetime of the model. The consumer
|
||||
* attaches its light, its label, its collision body, its gameplay
|
||||
* object here.
|
||||
* content the geometry that is thrown away and rebuilt every time
|
||||
* configure() is called.
|
||||
*
|
||||
* Making both the same Group and calling `clear()` on rebuild silently deletes
|
||||
* everything the consumer attached too — the model keeps working, but the
|
||||
* protocol's actual promise is broken. `scripts/verify-model.ts` tests this
|
||||
* separately.
|
||||
*/
|
||||
export interface PartSlot extends PartHandle<Group> {
|
||||
readonly anchor: Group
|
||||
readonly content: Group
|
||||
/** Replaces the content with a fresh Group and returns it. Leaves the anchor alone. */
|
||||
reset(): Group
|
||||
}
|
||||
|
||||
export function createPart(name: string): PartSlot {
|
||||
const anchor = new Group()
|
||||
anchor.name = name
|
||||
let content = new Group()
|
||||
content.name = `${name}/content`
|
||||
anchor.add(content)
|
||||
|
||||
return {
|
||||
anchor,
|
||||
get content(): Group {
|
||||
return content
|
||||
},
|
||||
reset(): Group {
|
||||
anchor.remove(content)
|
||||
content = new Group()
|
||||
content.name = `${name}/content`
|
||||
anchor.add(content)
|
||||
return content
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
/**
|
||||
* Deterministic randomness.
|
||||
*
|
||||
* A procedural kit needs variation — perfect symmetry reads as "generated".
|
||||
* But the variation has to be repeatable: the same seed must always give the
|
||||
* same model, otherwise neither previews, nor tests, nor art direction hold
|
||||
* up. That is why Math.random() is not used.
|
||||
*
|
||||
* mulberry32: 32-bit state, fast, not cryptographic but far more than enough
|
||||
* for visual variation.
|
||||
*/
|
||||
export function createRandom(seed: number): () => number {
|
||||
let state = seed >>> 0
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0
|
||||
let t = state
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1)
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
|
||||
}
|
||||
}
|
||||
|
||||
/** Symmetric deviation in the range -amount .. +amount. */
|
||||
export function jitter(random: () => number, amount: number): number {
|
||||
return (random() * 2 - 1) * amount
|
||||
}
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
import { Color } from 'three'
|
||||
|
||||
import { MEDIEVAL_PALETTE, type MedievalPalette } from './materials.ts'
|
||||
import { jitter } from './random.ts'
|
||||
|
||||
/**
|
||||
* Factory that produces colours deviated from the palette.
|
||||
*
|
||||
* Every model used to rewrite this inline — the same five lines thirteen
|
||||
* times. The cost of the repetition was not just line count: the deviation
|
||||
* amounts had drifted from model to model, so when two models were put side
|
||||
* by side one of them visibly had more variation than the other.
|
||||
*
|
||||
* Every call returns A NEW Color.
|
||||
*
|
||||
* It used to return one shared object and mutate it, on the reasoning that the
|
||||
* geometry helpers read the colour immediately and an allocation per call is
|
||||
* waste. The reasoning holds right up until two tints appear as arguments of
|
||||
* the SAME call:
|
||||
*
|
||||
* latheGeometry(profile, 7, origin, tint('char', 0.06),
|
||||
* { colourTop: tint('charHot', -0.12) })
|
||||
*
|
||||
* Both arguments are the same object, so both carry whatever the second call
|
||||
* computed. That is not a hypothetical: it is why the torch's pitch head
|
||||
* rendered hot orange instead of black, and the same mistake was made twice
|
||||
* more in one session -- once in the anvil's stump, which came out painted in
|
||||
* end grain on every face, and once nearly in the shovel. Three times means
|
||||
* the hazard is in the helper, not in the callers.
|
||||
*
|
||||
* A few hundred Color allocations at build time is not a cost worth one class
|
||||
* of silent, invisible bug.
|
||||
*/
|
||||
export function createTinter(random: () => number) {
|
||||
return (
|
||||
key: keyof MedievalPalette,
|
||||
/** Lightness shift. Negative darkens. */
|
||||
lift = 0,
|
||||
/** Deviation multiplier. 0 gives a completely flat colour. */
|
||||
spread = 1,
|
||||
): Color => {
|
||||
const scratch = new Color(MEDIEVAL_PALETTE[key])
|
||||
scratch.offsetHSL(
|
||||
jitter(random, 0.012 * spread),
|
||||
jitter(random, 0.05 * spread),
|
||||
lift + jitter(random, 0.05 * spread),
|
||||
)
|
||||
return scratch
|
||||
}
|
||||
}
|
||||
|
||||
export type Tinter = ReturnType<typeof createTinter>
|
||||
|
|
@ -1,131 +0,0 @@
|
|||
import { Color, type BufferGeometry } from 'three'
|
||||
|
||||
import { latheGeometry, mergeColoured, type Level } from './geometry.ts'
|
||||
import { jitter } from './random.ts'
|
||||
import { MEDIEVAL_PALETTE } from './materials.ts'
|
||||
|
||||
/**
|
||||
* The shared language of hand tools.
|
||||
*
|
||||
* In the first attempt all three tools were just a straight prismatic shaft +
|
||||
* a boxy head, and they looked like toys. The reasons were small, individual
|
||||
* things:
|
||||
*
|
||||
* - The shaft was the same thickness end to end. A real shaft has a swell
|
||||
* at its base (the grip) — so the hand does not slip off. That is the one
|
||||
* detail that makes the silhouette readable.
|
||||
* - The head was stuck directly onto the shaft. A real tool has a conical
|
||||
* socket; the shaft goes inside it.
|
||||
* - There was no geometric variation anywhere, only the colour changed. A
|
||||
* forged tool is not perfectly symmetric.
|
||||
*
|
||||
* This module supplies all three from one place, so adding a new tool to the
|
||||
* kit is now just a matter of answering "what is the head".
|
||||
*/
|
||||
|
||||
export interface ShaftOptions {
|
||||
readonly length: number
|
||||
readonly radius: number
|
||||
/** How many sides. 6 is enough: on a hand-held stick 8 adds nothing to the silhouette. */
|
||||
readonly segments?: number
|
||||
readonly random: () => number
|
||||
}
|
||||
|
||||
export interface ToolShaft {
|
||||
readonly geometry: BufferGeometry
|
||||
/** Y position of the shaft's top end — the head sits here. */
|
||||
readonly top: number
|
||||
/** The shaft's radius at the top end. */
|
||||
readonly topRadius: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool shaft: grip swell at the bottom, a long straight body in the middle, a
|
||||
* slight taper towards the top. Produced as a single lathe — stacking prisms
|
||||
* on top of each other would leave coplanar face pairs between them.
|
||||
*/
|
||||
export function toolShaft(options: ShaftOptions): ToolShaft {
|
||||
const { length, radius, random } = options
|
||||
const segments = options.segments ?? 6
|
||||
const bottom = -length / 2
|
||||
const top = length / 2
|
||||
const r = (scale: number): number => radius * scale * (1 + jitter(random, 0.02))
|
||||
|
||||
const profile: Level[] = [
|
||||
{ y: bottom, radius: r(0.78) }, // bottom: rounded end
|
||||
{ y: bottom + length * 0.012, radius: r(1.18) }, // underside of the grip swell
|
||||
{ y: bottom + length * 0.075, radius: r(1.1) }, // top of the grip
|
||||
{ y: bottom + length * 0.14, radius: r(0.94) }, // waist between grip and body
|
||||
{ y: bottom + length * 0.55, radius: r(1) }, // body
|
||||
{ y: top, radius: r(0.9) }, // taper towards the head
|
||||
]
|
||||
|
||||
const tint = new Color(MEDIEVAL_PALETTE.oak)
|
||||
tint.offsetHSL(jitter(random, 0.012), jitter(random, 0.05), 0.05 + jitter(random, 0.05))
|
||||
const tintTop = new Color(MEDIEVAL_PALETTE.oak)
|
||||
// The head end passes through the hand less often, so it stays a bit darker.
|
||||
tintTop.offsetHSL(jitter(random, 0.01), jitter(random, 0.04), -0.02 + jitter(random, 0.04))
|
||||
|
||||
return {
|
||||
geometry: latheGeometry(profile, segments, [0, 0, 0], tint, { colourTop: tintTop }),
|
||||
top,
|
||||
topRadius: profile.at(-1)!.radius,
|
||||
}
|
||||
}
|
||||
|
||||
export interface SocketOptions {
|
||||
/** Y position where the socket sits (the shaft's top end). */
|
||||
readonly y: number
|
||||
/** The shaft's radius at that point. */
|
||||
readonly shaftRadius: number
|
||||
/** Socket length. */
|
||||
readonly length: number
|
||||
readonly segments?: number
|
||||
readonly random: () => number
|
||||
}
|
||||
|
||||
/**
|
||||
* Forged socket: a cone that wraps the shaft and widens upwards, with a collar
|
||||
* on top.
|
||||
*
|
||||
* It is extended DOWN INTO the shaft — because its lower end stays inside the
|
||||
* shaft's body, no surface ends up coplanar with the shaft's surface.
|
||||
*/
|
||||
export function toolSocket(options: SocketOptions): BufferGeometry {
|
||||
const { y, shaftRadius, length, random } = options
|
||||
const segments = options.segments ?? 6
|
||||
const tint = new Color(MEDIEVAL_PALETTE.iron)
|
||||
tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.05))
|
||||
const collar = new Color(MEDIEVAL_PALETTE.iron)
|
||||
collar.offsetHSL(0, jitter(random, 0.02), 0.04 + jitter(random, 0.04))
|
||||
|
||||
const profile: Level[] = [
|
||||
{ y: y - length * 0.9, radius: shaftRadius * 1.12 },
|
||||
{ y: y - length * 0.45, radius: shaftRadius * 1.34 },
|
||||
{ y: y + length * 0.1, radius: shaftRadius * 1.5 },
|
||||
{ y: y + length * 0.22, radius: shaftRadius * 1.72 }, // collar
|
||||
{ y: y + length * 0.34, radius: shaftRadius * 1.46 },
|
||||
]
|
||||
return mergeColoured([latheGeometry(profile, segments, [0, 0, 0], tint, { colourTop: collar })])
|
||||
}
|
||||
|
||||
/** Iron tone with a small deviation. So all three tools look like one hand made them. */
|
||||
export function ironTint(random: () => number, lift = 0): Color {
|
||||
const tint = new Color(MEDIEVAL_PALETTE.iron)
|
||||
tint.offsetHSL(0, jitter(random, 0.02), lift + jitter(random, 0.05))
|
||||
return tint
|
||||
}
|
||||
|
||||
/**
|
||||
* Burnished steel tone — for the `steel` slot.
|
||||
*
|
||||
* The deviation is kept narrower than in `ironTint`: what determines the
|
||||
* colour of a polished surface is not its own pigment but the environment it
|
||||
* reflects. Shifting hue in the vertex colour looks dirty here, so there is
|
||||
* only a tiny wobble in lightness.
|
||||
*/
|
||||
export function steelTint(random: () => number, lift = 0): Color {
|
||||
const tint = new Color(MEDIEVAL_PALETTE.steel)
|
||||
tint.offsetHSL(0, jitter(random, 0.008), lift + jitter(random, 0.025))
|
||||
return tint
|
||||
}
|
||||
|
|
@ -1,257 +0,0 @@
|
|||
/**
|
||||
* @medieval-kit/wooden-barrel
|
||||
*
|
||||
* A real barrel is not a single piece: it is built from separate boards
|
||||
* (staves) that narrow towards the ends, squeezed together by iron hoops, its
|
||||
* head sunk into the body, and the staves leave a collar (the chime) above the
|
||||
* head. This model builds it that way — not as an inflated cylinder.
|
||||
*
|
||||
* Dependencies: plain `three` and `@medieval-kit/core`. It never touches
|
||||
* scifi-kit's primitive/wear pipeline; WebGL is enough.
|
||||
*/
|
||||
import { Color, type BufferGeometry } from 'three'
|
||||
|
||||
import {
|
||||
MEDIEVAL_PALETTE,
|
||||
bandGeometry,
|
||||
createKitModel,
|
||||
createRandom,
|
||||
headGeometry,
|
||||
jitter,
|
||||
mergeColoured,
|
||||
prismGeometry,
|
||||
staveGeometry,
|
||||
type Level,
|
||||
} from '../core/index.ts'
|
||||
|
||||
export interface WoodenBarrelConfig {
|
||||
/** Total height (metres). */
|
||||
readonly height: number
|
||||
/** Outer radius at the belly (bilge), in metres. */
|
||||
readonly radius: number
|
||||
/** How far the ends narrow against the belly. 0.16 = ends at 84% width. */
|
||||
readonly taper: number
|
||||
/** Stave count. Odd by default, because it breaks perfect symmetry. */
|
||||
readonly staveCount: number
|
||||
/** Iron hoop count. */
|
||||
readonly hoopCount: number
|
||||
/**
|
||||
* Rivets per hoop.
|
||||
*
|
||||
* A hoop is a strip of iron bent into a circle and riveted where its ends
|
||||
* overlap; a cooper then adds more along its length to stop it springing.
|
||||
* They are small, but they are the detail that makes a dark band read as
|
||||
* FORGED IRON rather than as a painted stripe, so they earn their triangles.
|
||||
*/
|
||||
readonly rivets: number
|
||||
/** Variation seed. The same seed always gives the same barrel. */
|
||||
readonly seed: number
|
||||
}
|
||||
|
||||
export const woodenBarrelDefaults: WoodenBarrelConfig = {
|
||||
height: 1.04,
|
||||
radius: 0.41,
|
||||
taper: 0.17,
|
||||
// Stave and hoop counts come from a reference photograph of a real cask,
|
||||
// not from taste. Thirteen staves left a visibly polygonal silhouette and
|
||||
// four hoops read as too few for the height.
|
||||
staveCount: 17,
|
||||
hoopCount: 6,
|
||||
rivets: 6,
|
||||
seed: 7,
|
||||
}
|
||||
|
||||
export type WoodenBarrelParts = 'staves' | 'heads' | 'hoops'
|
||||
|
||||
const SLOTS = ['oak', 'iron'] as const
|
||||
type Slot = (typeof SLOTS)[number]
|
||||
|
||||
/** Barrel profile: t ∈ [-1,1], narrow at the ends, wide at the belly. */
|
||||
function profileAt(t: number, taper: number): number {
|
||||
return 1 - taper * t * t
|
||||
}
|
||||
|
||||
/**
|
||||
* The hoops sit symmetrically from the ends inwards: the outermost ones are the
|
||||
* "chime" (end) hoops, the inner ones the "bilge" (belly) hoops.
|
||||
*/
|
||||
function hoopPositions(count: number): number[] {
|
||||
if (count <= 0) return []
|
||||
if (count === 1) return [0]
|
||||
const outer = 0.87
|
||||
const inner = count <= 2 ? 0.87 : 0.33
|
||||
const pairs = Math.floor(count / 2)
|
||||
const positions: number[] = []
|
||||
for (let i = 0; i < pairs; i += 1) {
|
||||
const t = pairs === 1 ? outer : outer - (outer - inner) * (i / (pairs - 1))
|
||||
positions.push(t, -t)
|
||||
}
|
||||
if (count % 2 === 1) positions.push(0)
|
||||
return positions
|
||||
}
|
||||
|
||||
export function createModel(overrides: Partial<WoodenBarrelConfig> = {}) {
|
||||
return createKitModel<WoodenBarrelConfig, 'oak' | 'iron', WoodenBarrelParts>({
|
||||
id: 'wooden-barrel',
|
||||
defaults: woodenBarrelDefaults,
|
||||
slots: SLOTS,
|
||||
build: ({ config, random }) => {
|
||||
const half = config.height / 2
|
||||
// Five levels: ends, quarters and belly. Enough for a lowpoly barrel
|
||||
// curve; a sixth level adds nothing measurable to the silhouette.
|
||||
const levels = [-1, -0.58, 0, 0.58, 1]
|
||||
|
||||
function buildStaves(random: () => number, half: number, levels: number[]): BufferGeometry {
|
||||
const wallThickness = config.radius * 0.13
|
||||
const step = (Math.PI * 2) / config.staveCount
|
||||
// A thin gap between the staves — the one detail that makes this read
|
||||
// as "assembled" instead of "a single piece".
|
||||
const gap = step * 0.055
|
||||
const tint = new Color()
|
||||
const pieces: BufferGeometry[] = []
|
||||
|
||||
for (let index = 0; index < config.staveCount; index += 1) {
|
||||
// Every stave carries its own small deviations: radius, end height,
|
||||
// tone. Perfect repetition reads "manufactured"; rule: break mirrors.
|
||||
const radiusBias = 1 + jitter(random, 0.014)
|
||||
const topBias = jitter(random, 0.006)
|
||||
const bottomBias = jitter(random, 0.006)
|
||||
|
||||
const shaped: Level[] = levels.map((t, level) => {
|
||||
const edge = level === 0 ? bottomBias : level === levels.length - 1 ? topBias : 0
|
||||
return {
|
||||
y: t * half + edge,
|
||||
radius: config.radius * profileAt(t, config.taper) * radiusBias,
|
||||
}
|
||||
})
|
||||
|
||||
tint.copy(MEDIEVAL_PALETTE.oak)
|
||||
tint.offsetHSL(jitter(random, 0.014), jitter(random, 0.05), jitter(random, 0.055))
|
||||
|
||||
pieces.push(staveGeometry(
|
||||
shaped,
|
||||
index * step + gap / 2,
|
||||
(index + 1) * step - gap / 2,
|
||||
wallThickness,
|
||||
tint,
|
||||
))
|
||||
}
|
||||
|
||||
return mergeColoured(pieces)
|
||||
}
|
||||
|
||||
function buildHeads(random: () => number, half: number): BufferGeometry {
|
||||
const wallThickness = config.radius * 0.13
|
||||
const endRadius = config.radius * profileAt(1, config.taper)
|
||||
// The head seats INSIDE the body, a little back from the end; the
|
||||
// collar (chime) the staves leave above it makes a barrel a barrel.
|
||||
const seatRadius = endRadius - wallThickness * 0.9
|
||||
// Deep enough to SEE. At 0.055 the collar existed in the geometry
|
||||
// but was too shallow to read at any normal viewing distance, so the
|
||||
// head looked flush with the stave ends — the one silhouette detail
|
||||
// that distinguishes a cask from a bucket.
|
||||
const inset = config.height * 0.07
|
||||
const tint = new Color(MEDIEVAL_PALETTE.oakEnd)
|
||||
tint.offsetHSL(0, jitter(random, 0.03), jitter(random, 0.03))
|
||||
|
||||
return mergeColoured([
|
||||
headGeometry(seatRadius, half - inset, config.staveCount, 'up', tint, 3, 0.06),
|
||||
headGeometry(seatRadius, -half + inset, config.staveCount, 'down', tint, 3, 0.06),
|
||||
])
|
||||
}
|
||||
|
||||
function buildHoops(random: () => number, half: number): BufferGeometry | undefined {
|
||||
const positions = hoopPositions(config.hoopCount)
|
||||
if (positions.length === 0) return undefined
|
||||
|
||||
const tint = new Color()
|
||||
const pieces: BufferGeometry[] = []
|
||||
|
||||
for (const t of positions) {
|
||||
const seat = config.radius * profileAt(t, config.taper)
|
||||
// The end hoops are wider: that is where the strain is greatest.
|
||||
const bandHeight = config.height * (0.045 + 0.03 * Math.abs(t))
|
||||
tint.copy(MEDIEVAL_PALETTE.iron)
|
||||
tint.offsetHSL(0, jitter(random, 0.02), jitter(random, 0.05))
|
||||
|
||||
const bandRadius = seat + config.radius * 0.022
|
||||
pieces.push(bandGeometry(
|
||||
bandRadius,
|
||||
t * half,
|
||||
bandHeight,
|
||||
config.radius * 0.05,
|
||||
config.staveCount,
|
||||
tint,
|
||||
))
|
||||
|
||||
// Rivets. Centred ON the band's outer face, so the inner half is
|
||||
// buried in the iron rather than resting against it — the same
|
||||
// deliberate interpenetration the rest of the kit uses instead of
|
||||
// coplanar faces.
|
||||
// Wide and shallow. The first attempt was long and thin and read
|
||||
// as a row of nails driven through the hoop; a rivet is a domed
|
||||
// button that barely stands off the iron. Only a quarter of the
|
||||
// length shows — the rest is buried in the band.
|
||||
const studLength = config.radius * 0.05
|
||||
const studRadius = config.radius * 0.042
|
||||
// Each hoop's rivets start at their own angle. Aligning them into
|
||||
// vertical columns is the giveaway that a thing was generated.
|
||||
const phase = random() * Math.PI * 2
|
||||
// Rivets are struck iron: their domes are polished by the hammer
|
||||
// and by every hand that has ever moved the cask, so they catch
|
||||
// light the flat band does not. Without this they were the right
|
||||
// shape in the right place and still invisible against the hoop.
|
||||
const studTint = tint.clone()
|
||||
studTint.offsetHSL(0, 0, 0.09)
|
||||
for (let i = 0; i < config.rivets; i += 1) {
|
||||
const angle = phase + (i / config.rivets) * Math.PI * 2
|
||||
// The head FLARES outward, it does not taper. That is what a
|
||||
// hammered rivet actually looks like — the smith spreads the end
|
||||
// over the iron — and it is also the only version that keeps the
|
||||
// radial winding check honest: a stud narrowing outwards tilts
|
||||
// its side normals ~9.5 degrees back towards the barrel axis,
|
||||
// which the check correctly reports as faces pointing inward.
|
||||
const stud = prismGeometry(
|
||||
studRadius * 0.72,
|
||||
studRadius,
|
||||
studLength,
|
||||
4,
|
||||
[0, 0, 0],
|
||||
studTint,
|
||||
// No back face. The rivet's inner end is buried in the band, so
|
||||
// that cap is never visible — the same saving `bandGeometry`
|
||||
// makes on the inside of a hoop. It is not only free: once the
|
||||
// stud is seated deep enough to look right, the buried cap
|
||||
// falls inside the 94% shell the radial check inspects, and a
|
||||
// cap pointing at the axis is exactly what that check hunts.
|
||||
{ capBottom: false },
|
||||
)
|
||||
stud.rotateX(Math.PI / 2)
|
||||
stud.rotateY(angle)
|
||||
const seatDepth = bandRadius - studLength * 0.25
|
||||
stud.translate(
|
||||
Math.sin(angle) * seatDepth,
|
||||
t * half,
|
||||
Math.cos(angle) * seatDepth,
|
||||
)
|
||||
pieces.push(stud)
|
||||
}
|
||||
}
|
||||
|
||||
return mergeColoured(pieces)
|
||||
}
|
||||
|
||||
// The call ORDER must be kept: the seeded randomness advances as a
|
||||
// stream, and if the order changes so does the geometry.
|
||||
const stavesPart = buildStaves(random, half, levels)
|
||||
const headsPart = buildHeads(random, half)
|
||||
const hoopsPart = buildHoops(random, half)
|
||||
|
||||
return {
|
||||
staves: { slot: 'oak' as const, geometry: stavesPart },
|
||||
heads: { slot: 'oak' as const, geometry: headsPart },
|
||||
hoops: hoopsPart ? { slot: 'iron' as const, geometry: hoopsPart } : undefined,
|
||||
}
|
||||
},
|
||||
}, overrides)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue