@wildshard/kit 0.0.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/GUIDE.md +221 -0
  2. package/content/abilities/bite.json +24 -0
  3. package/content/abilities/charge.json +25 -0
  4. package/content/abilities/claw.json +24 -0
  5. package/content/abilities/slam.json +24 -0
  6. package/content/abilities/swing.json +25 -0
  7. package/content/animated/bear/pbr/black-blaze.glb +0 -0
  8. package/content/animated/bear/pbr/black-blaze.json +1 -0
  9. package/content/animated/bear/pbr/black-old.glb +0 -0
  10. package/content/animated/bear/pbr/black-old.json +1 -0
  11. package/content/animated/bear/pbr/black.glb +0 -0
  12. package/content/animated/bear/pbr/black.json +1 -0
  13. package/content/animated/bear/pbr/brown-old.glb +0 -0
  14. package/content/animated/bear/pbr/brown-old.json +1 -0
  15. package/content/animated/bear/pbr/brown.glb +0 -0
  16. package/content/animated/bear/pbr/brown.json +1 -0
  17. package/content/animated/bear/toon/black-blaze.glb +0 -0
  18. package/content/animated/bear/toon/black-blaze.json +1 -0
  19. package/content/animated/bear/toon/black-old.glb +0 -0
  20. package/content/animated/bear/toon/black-old.json +1 -0
  21. package/content/animated/bear/toon/black.glb +0 -0
  22. package/content/animated/bear/toon/black.json +1 -0
  23. package/content/animated/bear/toon/brown-old.glb +0 -0
  24. package/content/animated/bear/toon/brown-old.json +1 -0
  25. package/content/animated/bear/toon/brown.glb +0 -0
  26. package/content/animated/bear/toon/brown.json +1 -0
  27. package/content/animated/boar/pbr/big.glb +0 -0
  28. package/content/animated/boar/pbr/big.json +1 -0
  29. package/content/animated/boar/pbr/black.glb +0 -0
  30. package/content/animated/boar/pbr/black.json +1 -0
  31. package/content/animated/boar/pbr/boar.glb +0 -0
  32. package/content/animated/boar/pbr/boar.json +1 -0
  33. package/content/animated/boar/pbr/ironhide.glb +0 -0
  34. package/content/animated/boar/pbr/ironhide.json +1 -0
  35. package/content/animated/boar/pbr/scarback.glb +0 -0
  36. package/content/animated/boar/pbr/scarback.json +1 -0
  37. package/content/animated/boar/pbr/sow.glb +0 -0
  38. package/content/animated/boar/pbr/sow.json +1 -0
  39. package/content/animated/boar/toon/big.glb +0 -0
  40. package/content/animated/boar/toon/big.json +1 -0
  41. package/content/animated/boar/toon/black.glb +0 -0
  42. package/content/animated/boar/toon/black.json +1 -0
  43. package/content/animated/boar/toon/boar.glb +0 -0
  44. package/content/animated/boar/toon/boar.json +1 -0
  45. package/content/animated/boar/toon/ironhide.glb +0 -0
  46. package/content/animated/boar/toon/ironhide.json +1 -0
  47. package/content/animated/boar/toon/scarback.glb +0 -0
  48. package/content/animated/boar/toon/scarback.json +1 -0
  49. package/content/animated/boar/toon/sow.glb +0 -0
  50. package/content/animated/boar/toon/sow.json +1 -0
  51. package/content/animated/catalogue.json +1 -0
  52. package/content/bodies/biped.json +5 -0
  53. package/content/bodies/quadruped.json +5 -0
  54. package/content/clips/quadruped.json +1 -0
  55. package/content/creatures/bear/look.json +199 -0
  56. package/content/creatures/bear/pbr/black-blaze.glb +0 -0
  57. package/content/creatures/bear/pbr/black-old.glb +0 -0
  58. package/content/creatures/bear/pbr/black.glb +0 -0
  59. package/content/creatures/bear/pbr/brown-old.glb +0 -0
  60. package/content/creatures/bear/pbr/brown.glb +0 -0
  61. package/content/creatures/bear/toon/black-blaze.glb +0 -0
  62. package/content/creatures/bear/toon/black-old.glb +0 -0
  63. package/content/creatures/bear/toon/black.glb +0 -0
  64. package/content/creatures/bear/toon/brown-old.glb +0 -0
  65. package/content/creatures/bear/toon/brown.glb +0 -0
  66. package/content/creatures/bear.json +257 -0
  67. package/content/creatures/boar/look.json +184 -0
  68. package/content/creatures/boar/pbr/big.glb +0 -0
  69. package/content/creatures/boar/pbr/black.glb +0 -0
  70. package/content/creatures/boar/pbr/boar.glb +0 -0
  71. package/content/creatures/boar/pbr/ironhide.glb +0 -0
  72. package/content/creatures/boar/pbr/scarback.glb +0 -0
  73. package/content/creatures/boar/pbr/sow.glb +0 -0
  74. package/content/creatures/boar/toon/big.glb +0 -0
  75. package/content/creatures/boar/toon/black.glb +0 -0
  76. package/content/creatures/boar/toon/boar.glb +0 -0
  77. package/content/creatures/boar/toon/ironhide.glb +0 -0
  78. package/content/creatures/boar/toon/scarback.glb +0 -0
  79. package/content/creatures/boar/toon/sow.glb +0 -0
  80. package/content/creatures/boar.json +275 -0
  81. package/content/creatures/bodies.json +4754 -0
  82. package/content/harvest-items.json +98 -0
  83. package/content/harvest.json +31 -0
  84. package/content/journal-icons/antlers.png +0 -0
  85. package/content/journal-icons/bear.png +0 -0
  86. package/content/journal-icons/boar.png +0 -0
  87. package/content/journal-icons/deer.png +0 -0
  88. package/content/journal-icons/elk.png +0 -0
  89. package/content/journal-icons/ghost.png +0 -0
  90. package/content/journal-icons/ironhide.png +0 -0
  91. package/content/journal-icons.json +9 -0
  92. package/content/shared/pickupCatalogue.json +1008 -0
  93. package/content/shared/starterBow.json +21 -0
  94. package/content/species/bear.json +144 -0
  95. package/content/species/boar.json +147 -0
  96. package/content/sword-debris.json +7 -0
  97. package/content/temperaments.json +519 -0
  98. package/content/tuning/bear.json +43 -0
  99. package/content/tuning/boar.json +32 -0
  100. package/content/tuning/deer.json +32 -0
  101. package/content/tuning/pursue.json +12 -0
  102. package/package.json +57 -4
  103. package/src/abilities.ts +85 -0
  104. package/src/body.ts +25 -0
  105. package/src/clips.ts +139 -0
  106. package/src/creatures.ts +76 -0
  107. package/src/geometry/arms.ts +725 -0
  108. package/src/geometry/bear.ts +521 -0
  109. package/src/geometry/boar.ts +604 -0
  110. package/src/geometry/bowProfile.ts +34 -0
  111. package/src/geometry/export.ts +101 -0
  112. package/src/geometry/meleeProfile.ts +261 -0
  113. package/src/geometry/nativeInteractionFacts.ts +7 -0
  114. package/src/geometry/nativeLooks.ts +54 -0
  115. package/src/geometry/riderArms.ts +215 -0
  116. package/src/geometry/sharedSpecs.ts +26 -0
  117. package/src/geometry/species.ts +768 -0
  118. package/src/geometry/specimenCatalogue.ts +80 -0
  119. package/src/geometry/starterCombat.ts +194 -0
  120. package/src/geometry/starterGlyphs.ts +12 -0
  121. package/src/geometry/starterMeleeProfile.ts +134 -0
  122. package/src/geometry/starterMoves.ts +172 -0
  123. package/src/index.ts +26 -0
  124. package/src/legacyCombat.ts +25 -0
  125. package/src/legacyHarvest.ts +104 -0
  126. package/src/legacyJournalIcons.ts +10 -0
  127. package/src/legacySpecies.ts +127 -0
  128. package/src/temperament.ts +97 -0
  129. package/README.md +0 -3
@@ -0,0 +1,768 @@
1
+ import { Noise2D } from '@wildshard/sdk/noise'
2
+ import { Rng, type RngState } from '@wildshard/sdk/random'
3
+ import {
4
+ readSpecies,
5
+ SpeciesSchema,
6
+ type SpeciesData,
7
+ } from '@wildshard/shard-format/speciesPrograms'
8
+ import * as THREE from 'three'
9
+
10
+ import bear from '../../content/species/bear.json' with { type: 'json' }
11
+ import boar from '../../content/species/boar.json' with { type: 'json' }
12
+ import { legacyCreatureProfile } from '../legacySpecies.ts'
13
+ import { createBearLook } from './bear.ts'
14
+ import { createBoarLook } from './boar.ts'
15
+
16
+ /** A geometry recipe's palette and shape knobs, without simulation or runtime owners. */
17
+ export interface VariantDef {
18
+ id: string
19
+ label: string
20
+ weight: number
21
+ rarity: 'common' | 'uncommon' | 'rare' | 'legendary'
22
+ scale: [number, number]
23
+ tint?: Record<string, [number, number, number]>
24
+ hp?: number
25
+ mods?: NonNullable<SpeciesData['variants'][number]['mods']>
26
+ fur?: Partial<FurStyle>
27
+ traits?: Record<string, number | boolean | string>
28
+ }
29
+ /** One authored joint in model space. */
30
+ export interface BoneDef {
31
+ name: string
32
+ parent: string | null
33
+ pos: [number, number, number]
34
+ }
35
+ /** Data-only dimensions accompanying the baked skin. */
36
+ export interface AnimalDims {
37
+ /** height of the body bone (spine centre) above ground in the bind pose */
38
+ bodyY: number
39
+ /** half-length of the body capsule along Z (for hit tests) */
40
+ bodyHalfLen: number
41
+ /** radius of the body capsule */
42
+ bodyRadius: number
43
+ /** head hit-sphere radius */
44
+ headRadius: number
45
+ /** rest length of the front leg (shoulder → hoof) — drives stride frequency */
46
+ legLen: number
47
+ /** foot rest positions (x, z) per leg FL, FR, BL, BR */
48
+ feet: [number, number][]
49
+ /** width of the body (for the corpse's resting height when rolled on its side) */
50
+ halfWidth: number
51
+ /** body hit-capsule axis: 'z' (default, along the spine of a quadruped) or 'y' (upright: the Drowned Sailor) */
52
+ capsuleAxis?: 'z' | 'y'
53
+ /** the head ball's centre, head-bone local (model units); default the joint itself. A hull whose skull sits off its head
54
+ * joint (the Antler King, E350 F-X2) moves the ball onto it */
55
+ headAt?: readonly [number, number, number]
56
+ /** the body capsule's centre, body-bone local (model units; default the joint), and its axis tilted `bodyPitch` rad from
57
+ * the bone's z toward its y (+ = the front up) — a 'z' capsule only */
58
+ bodyAt?: readonly [number, number, number]
59
+ bodyPitch?: number
60
+ /** a second body capsule across `bone`'s x axis (the Antler King's shoulders and chest, E350 F-X2): centre (bone local,
61
+ * model units), half-length along x and radius. Its hits are body hits */
62
+ fore?: {
63
+ readonly bone: string
64
+ readonly at: readonly [number, number, number]
65
+ readonly halfLen: number
66
+ readonly radius: number
67
+ }
68
+ }
69
+ /** Owned, unmerged body parts produced offline. */
70
+ export interface AnimalSpecies {
71
+ bones: BoneDef[]
72
+ /** geometries drawn with the fur material + fur shells (loft() output: has color / skin / furLen attributes) */
73
+ furParts: THREE.BufferGeometry[]
74
+ /** hard parts: hooves, antlers, tusks, snout (no fur shells, vertex colours only) */
75
+ hardParts: THREE.BufferGeometry[]
76
+ /** eye spheres (glossy clearcoat material) */
77
+ eyeParts: THREE.BufferGeometry[]
78
+ dims: AnimalDims
79
+ /** low-poly style: a base-colour texture on the rig's material (a generated model's own paint, e.g. the Drowned
80
+ * Captain); the vertex colours multiply it, so textured parts carry white */
81
+ map?: THREE.Texture
82
+ /** low-poly style: the per-facet lightness jitter (lowpoly.ts facetGeometry, default 0.12) — 0 for a textured model */
83
+ facetJitter?: number
84
+ /** low-poly style, with `map`: the texture fed back as emissive at this intensity, so a painted model keeps its colours
85
+ * in shade (the flat toon fill alone left the captain's navy coat near-black) */
86
+ selfLight?: number
87
+ }
88
+
89
+ export interface FurStyle {
90
+ /** seed + parameters of the tileable strand albedo / normal texture (baked as fur-<kind>-{map,normal}) */
91
+ texSeed: number
92
+ tex: {
93
+ contrast: number
94
+ grizzle: number
95
+ normalStrength: number
96
+ bristle: number
97
+ strandLen: number
98
+ root: number
99
+ }
100
+ roughness: number
101
+ sheen: number
102
+ sheenColor: [number, number, number]
103
+ envMapIntensity: number
104
+ /** backlit Fresnel tip colour (linear rgb) */
105
+ rim: [number, number, number]
106
+ /** metres the outermost fur shell stands off the skin for furLen = 1 */
107
+ shellLen: number
108
+ /** metres of noise displacement on the body/neck/head silhouette (shaggy coat); 0 = smooth */
109
+ shag: number
110
+ /** optional self-glow (linear rgb × intensity) — the Ghost stag uses it */
111
+ emissive?: [number, number, number]
112
+ emissiveIntensity?: number
113
+ }
114
+
115
+ /** Build-time look content with no live creature owner. */
116
+ export interface CommonLook {
117
+ id: string
118
+ species: string
119
+ kind: string
120
+ rigContract: { skeleton: string; clips: string[]; sockets: string[] }
121
+ fur: FurStyle
122
+ pose?: { grazeNeck: number; gallopTail: number }
123
+ variants?: Readonly<
124
+ Record<string, Pick<VariantDef, 'tint' | 'fur' | 'traits'>>
125
+ >
126
+ build: (variant: VariantDef, rng: Rng) => AnimalSpecies
127
+ }
128
+
129
+ /** Offline loft math preserves the runtime station order and floating-point arithmetic. */
130
+ export interface Station {
131
+ x: number
132
+ y: number
133
+ z: number
134
+ rx: number
135
+ ry: number
136
+ top: number
137
+ bot: number // asymmetric vertical scale (withers hump / deep belly)
138
+ b0: number
139
+ b1: number
140
+ w1: number // skin: bone b0 with weight 1-w1, bone b1 with w1
141
+ }
142
+
143
+ /** vertex colour callback: (out, x, y, z, nx, ny, nz, part, t = 0..1 along the part, a = ring angle) */
144
+ export type Paint = (
145
+ out: THREE.Color,
146
+ x: number,
147
+ y: number,
148
+ z: number,
149
+ nx: number,
150
+ ny: number,
151
+ nz: number,
152
+ part: string,
153
+ t: number,
154
+ a: number,
155
+ ) => void
156
+
157
+ export const TEX_M = 0.32 // metres per detail-texture repeat
158
+
159
+ /** sRGB colour triple, 0..1 (palette entries and VariantDef.tint values) */
160
+ export type RGB = [number, number, number]
161
+
162
+ const _t = new THREE.Vector3(),
163
+ _side = new THREE.Vector3(),
164
+ _up = new THREE.Vector3(),
165
+ _n = new THREE.Vector3(),
166
+ _c = new THREE.Color()
167
+
168
+ /** shared low-frequency noise for coat mottling / patches (fbm ≈ -1..1) */
169
+ export const paintNoise: Noise2D = new Noise2D(4242)
170
+
171
+ export const srgb = (r: number, g: number, b: number): THREE.Color =>
172
+ new THREE.Color().setRGB(r, g, b, THREE.SRGBColorSpace)
173
+ export const mix = (
174
+ out: THREE.Color,
175
+ a: THREE.Color,
176
+ b: THREE.Color,
177
+ t: number,
178
+ ): THREE.Color => {
179
+ out.copy(a).lerp(b, THREE.MathUtils.clamp(t, 0, 1))
180
+ return out
181
+ }
182
+ // the one smoothstep (E357 X5)
183
+
184
+ /** the species palette as THREE.Colors, each entry overridden by the variant's tint of the same name (VariantDef.tint) */
185
+ export function paletteColors<K extends string>(
186
+ base: Record<K, RGB>,
187
+ tint: Record<string, RGB> | undefined,
188
+ ): Record<K, THREE.Color> {
189
+ const out: Partial<Record<K, THREE.Color>> = {}
190
+ for (const k of Object.keys(base) as K[]) {
191
+ const c = tint?.[k] ?? base[k]
192
+ out[k] = srgb(c[0], c[1], c[2])
193
+ }
194
+ return out as Record<K, THREE.Color> // every key of `base` was just filled in
195
+ }
196
+
197
+ /** station helper */
198
+ export const S: (
199
+ x: number,
200
+ y: number,
201
+ z: number,
202
+ rx: number,
203
+ ry: number,
204
+ b0: number,
205
+ b1?: number,
206
+ w1?: number,
207
+ top?: number,
208
+ bot?: number,
209
+ ) => Station = (
210
+ x: number,
211
+ y: number,
212
+ z: number,
213
+ rx: number,
214
+ ry: number,
215
+ b0: number,
216
+ b1: number = b0,
217
+ w1 = 0,
218
+ top = 1,
219
+ bot = 1,
220
+ ): Station => ({ x, y, z, rx, ry, top, bot, b0, b1, w1 })
221
+
222
+ /** name → index lookup for a BoneDef list (throws on a typo) */
223
+ export function boneIndex(bones: { name: string }[]): (name: string) => number {
224
+ const m = new Map<string, number>()
225
+ bones.forEach((b, i) => {
226
+ m.set(b.name, i)
227
+ })
228
+ return (name: string) => {
229
+ const i = m.get(name)
230
+ if (i === undefined) throw new Error(`no bone ${name}`)
231
+ return i
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Relative fur length per vertex (1 = the species' base shell length). Long on the body, neck mane and
237
+ * boar crest; short on the face, ears and lower legs; none on hard parts.
238
+ */
239
+ function furLength(part: string, y: number, ny: number, t: number): number {
240
+ switch (part) {
241
+ case 'body':
242
+ return ny < -0.5 ? 0.7 : 1.0
243
+ case 'neck':
244
+ return 1.15
245
+ case 'head':
246
+ return t < 0.5 ? 0.45 : 0.2
247
+ case 'ear':
248
+ return 0.25
249
+ case 'leg':
250
+ return y > 0.5 ? 0.55 : y > 0.25 ? 0.3 : 0.15
251
+ case 'tail':
252
+ return 0.9
253
+ case 'crest':
254
+ return 1.9
255
+ default:
256
+ return 0
257
+ }
258
+ }
259
+
260
+ /** metres of noise displacement along the ring normal (set per species before lofting; reset to 0 after build) */
261
+ let shagAmp = 0
262
+ export function setShag(amp: number): void {
263
+ shagAmp = amp
264
+ }
265
+
266
+ /**
267
+ * An optional surface-shape function for the lofts that follow: (x, y, z, part) → metres to push the vertex out along
268
+ * its normal (the sheep's wool lumps, a wolf's fur clumps). The Paint callback sees the displaced position, so it can
269
+ * shade the troughs. Set per species in build(), reset to null after (Pine Hollow / Driftwood never set it).
270
+ */
271
+ let shapeFn:
272
+ | ((x: number, y: number, z: number, part: string) => number)
273
+ | null = null
274
+ export function setShapeFn(
275
+ fn: ((x: number, y: number, z: number, part: string) => number) | null,
276
+ ): void {
277
+ shapeFn = fn
278
+ }
279
+
280
+ /**
281
+ * Low-poly mode (Driftwood Isle, `ShardManifest.style === 'toon'`; set by AnimalFactory around `build()`):
282
+ * every loft gets `lowPolySides()` sides instead of what it asks for and no shag noise; the factory then
283
+ * de-indexes the merged model for flat facets (see `src/client/engine/entities/lowpoly.ts`). Species files may branch on
284
+ * `isLowPoly()` for a different palette or part (the boar's crest becomes a row of spikes).
285
+ */
286
+ let lowPoly = false
287
+ const authorPaints = new Map<string, (variant?: VariantDef) => Paint>()
288
+ /** Current explicit offline geometry style; independent of any runtime species owner. */
289
+ export function isLowPoly(): boolean {
290
+ return lowPoly
291
+ }
292
+ /** Palette supplied to the author geometry context; no runtime registry is lent out. */
293
+ export function toonPaint(
294
+ kind: string,
295
+ ): ((variant?: VariantDef) => Paint) | null {
296
+ return authorPaints.get(kind) ?? null
297
+ }
298
+
299
+ /** Pure geometry kernels a recipe consumes; native before-controls may supply an independent compiler. */
300
+ export interface SpeciesGeometryCompiler {
301
+ readonly loft: typeof loft
302
+ readonly tube: typeof tube
303
+ readonly skinPlain: typeof skinPlain
304
+ readonly S: typeof S
305
+ readonly boneIndex: typeof boneIndex
306
+ readonly srgb: typeof srgb
307
+ readonly mix: typeof mix
308
+ readonly paintNoise: Pick<Noise2D, 'fbm'>
309
+ readonly setShag: typeof setShag
310
+ readonly isLowPoly: typeof isLowPoly
311
+ readonly toonPaint: typeof toonPaint
312
+ readonly paletteColors: typeof paletteColors
313
+ }
314
+
315
+ /** ring sides for a loft that asks for `seg` in PBR: big parts 6, legs 5, ears / hooves / tusks 4 */
316
+ export function lowPolySides(seg: number): number {
317
+ return seg >= 16 ? 6 : seg >= 11 ? 5 : 4
318
+ }
319
+
320
+ /** Loft a closed tube through `st` stations with `seg` sides; returns an indexed geometry with position/normal/uv/color/skinIndex/skinWeight. */
321
+ export function loft(
322
+ st: Station[],
323
+ sides: number,
324
+ part: string,
325
+ paint: Paint,
326
+ capStart = true,
327
+ capEnd = true,
328
+ frame: 'x' | 'z' = 'x',
329
+ ): THREE.BufferGeometry {
330
+ const seg = lowPoly ? lowPolySides(sides) : sides
331
+ const n = st.length
332
+ const at = (i: number): Station => {
333
+ const s = st[i]
334
+ if (s === undefined) throw new Error(`loft: no station ${i}`)
335
+ return s
336
+ }
337
+ const pos: number[] = [],
338
+ nor: number[] = [],
339
+ uv: number[] = [],
340
+ col: number[] = [],
341
+ si: number[] = [],
342
+ sw: number[] = [],
343
+ fl: number[] = []
344
+ const idx: number[] = []
345
+ // arc length along the spine for v
346
+ const along: number[] = [0]
347
+ for (let i = 1; i < n; i++) {
348
+ const a = at(i),
349
+ b = at(i - 1)
350
+ along.push(
351
+ (along[i - 1] ?? 0) + Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z),
352
+ )
353
+ }
354
+ const total = (along[n - 1] ?? 0) || 1
355
+ let circ = 0
356
+ for (const s of st) circ += Math.PI * (s.rx + s.ry)
357
+ const uRep = Math.max(1, Math.round(circ / n / TEX_M))
358
+ const ringVerts = seg + 1
359
+ for (let i = 0; i < n; i++) {
360
+ const s = at(i),
361
+ al = along[i] ?? 0
362
+ const p0 = at(Math.max(0, i - 1)),
363
+ p1 = at(Math.min(n - 1, i + 1))
364
+ _t.set(p1.x - p0.x, p1.y - p0.y, p1.z - p0.z).normalize()
365
+ // ring frame: 'x' keeps the ring's side axis on +X (no twist along bilateral parts; order stations
366
+ // so the tangent runs +Z or down), 'z' keeps the ring's thin axis facing +Z (ears)
367
+ if (frame === 'x') _side.set(1, 0, 0).addScaledVector(_t, -_t.x).normalize()
368
+ else _side.set(0, 0, 1).cross(_t).normalize()
369
+ _up.crossVectors(_t, _side).normalize()
370
+ // radius change per metre → tilts normals along the taper
371
+ const dr =
372
+ ((p1.rx + p1.ry - (p0.rx + p0.ry)) * 0.5) /
373
+ Math.max(
374
+ 1e-3,
375
+ (along[Math.min(n - 1, i + 1)] ?? 0) - (along[Math.max(0, i - 1)] ?? 0),
376
+ )
377
+ const t = al / total
378
+ for (let j = 0; j <= seg; j++) {
379
+ const a = (j / seg) * Math.PI * 2
380
+ const ca = Math.cos(a),
381
+ sa = Math.sin(a)
382
+ const vs = sa > 0 ? s.top : s.bot
383
+ const rx = Math.max(1e-4, s.rx),
384
+ ry = Math.max(1e-4, s.ry * vs)
385
+ let px = s.x + _side.x * rx * ca + _up.x * ry * sa
386
+ let py = s.y + _side.y * rx * ca + _up.y * ry * sa
387
+ let pz = s.z + _side.z * rx * ca + _up.z * ry * sa
388
+ // ellipse normal: (cos/rx, sin/ry) in the ring frame, then tilt by the taper
389
+ _n.set(
390
+ (_side.x * ca) / rx + (_up.x * sa) / ry,
391
+ (_side.y * ca) / rx + (_up.y * sa) / ry,
392
+ (_side.z * ca) / rx + (_up.z * sa) / ry,
393
+ ).normalize()
394
+ _n.addScaledVector(_t, -dr).normalize()
395
+ // shaggy coat: push the surface in/out with noise so the silhouette isn't a smooth tube (big parts only)
396
+ if (
397
+ shagAmp > 0 &&
398
+ !lowPoly &&
399
+ (part === 'body' ||
400
+ part === 'neck' ||
401
+ part === 'head' ||
402
+ part === 'crest')
403
+ ) {
404
+ const amp =
405
+ shagAmp * Math.min(1, (rx + ry) / 0.25) * (part === 'crest' ? 2.5 : 1)
406
+ const d = paintNoise.fbm(px * 9 + py * 3, pz * 9 - py * 4, 3) * amp
407
+ px += _n.x * d
408
+ py += _n.y * d
409
+ pz += _n.z * d
410
+ }
411
+ if (shapeFn !== null && !lowPoly) {
412
+ const d = shapeFn(px, py, pz, part)
413
+ px += _n.x * d
414
+ py += _n.y * d
415
+ pz += _n.z * d
416
+ }
417
+ pos.push(px, py, pz)
418
+ nor.push(_n.x, _n.y, _n.z)
419
+ uv.push((j / seg) * uRep, al / TEX_M)
420
+ paint(_c, px, py, pz, _n.x, _n.y, _n.z, part, t, a)
421
+ col.push(_c.r, _c.g, _c.b)
422
+ si.push(s.b0, s.b1, 0, 0)
423
+ sw.push(1 - s.w1, s.w1, 0, 0)
424
+ fl.push(furLength(part, py, _n.y, t))
425
+ }
426
+ }
427
+ for (let i = 0; i < n - 1; i++)
428
+ for (let j = 0; j < seg; j++) {
429
+ const a = i * ringVerts + j,
430
+ b = a + 1,
431
+ c = a + ringVerts,
432
+ d = c + 1
433
+ idx.push(a, b, c, b, d, c)
434
+ }
435
+ const cap = (i: number, flip: boolean) => {
436
+ const s = at(i),
437
+ al = along[i] ?? 0
438
+ const p0 = at(Math.max(0, i - 1)),
439
+ p1 = at(Math.min(n - 1, i + 1))
440
+ _t.set(p1.x - p0.x, p1.y - p0.y, p1.z - p0.z).normalize()
441
+ if (flip) _t.negate()
442
+ const ci = pos.length / 3
443
+ pos.push(s.x, s.y, s.z)
444
+ nor.push(_t.x, _t.y, _t.z)
445
+ uv.push(0.5 * uRep, al / TEX_M)
446
+ paint(_c, s.x, s.y, s.z, _t.x, _t.y, _t.z, part, al / total, 0)
447
+ col.push(_c.r, _c.g, _c.b)
448
+ si.push(s.b0, s.b1, 0, 0)
449
+ sw.push(1 - s.w1, s.w1, 0, 0)
450
+ fl.push(furLength(part, s.y, _t.y, al / total))
451
+ for (let j = 0; j < seg; j++) {
452
+ const a = i * ringVerts + j,
453
+ b = a + 1
454
+ if (flip) idx.push(ci, b, a)
455
+ else idx.push(ci, a, b)
456
+ }
457
+ }
458
+ if (capStart) cap(0, true)
459
+ if (capEnd) cap(n - 1, false)
460
+ const g = new THREE.BufferGeometry()
461
+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3))
462
+ g.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3))
463
+ g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2))
464
+ g.setAttribute('color', new THREE.Float32BufferAttribute(col, 3))
465
+ g.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(si, 4))
466
+ g.setAttribute('skinWeight', new THREE.Float32BufferAttribute(sw, 4))
467
+ g.setAttribute('furLen', new THREE.Float32BufferAttribute(fl, 1))
468
+ g.setIndex(idx)
469
+ // smooth face-averaged normals (more robust than the analytic ring normal on coarse lofts); the
470
+ // duplicated uv-seam vertices get the average of both sides so the seam is invisible
471
+ g.computeVertexNormals()
472
+ const na = g.getAttribute('normal') as THREE.BufferAttribute
473
+ for (let i = 0; i < n; i++) {
474
+ const a = i * ringVerts,
475
+ b = a + seg
476
+ _n.set(
477
+ na.getX(a) + na.getX(b),
478
+ na.getY(a) + na.getY(b),
479
+ na.getZ(a) + na.getZ(b),
480
+ ).normalize()
481
+ na.setXYZ(a, _n.x, _n.y, _n.z)
482
+ na.setXYZ(b, _n.x, _n.y, _n.z)
483
+ }
484
+ return g
485
+ }
486
+
487
+ /** Give a plain geometry (sphere) colour + skin attributes for one bone. */
488
+ export function skinPlain(
489
+ g: THREE.BufferGeometry,
490
+ bone: number,
491
+ part: string,
492
+ paint: Paint,
493
+ ): THREE.BufferGeometry {
494
+ const p = g.getAttribute('position') as THREE.BufferAttribute,
495
+ nrm = g.getAttribute('normal') as THREE.BufferAttribute
496
+ const cnt = p.count
497
+ const col = new Float32Array(cnt * 3),
498
+ si = new Uint16Array(cnt * 4),
499
+ sw = new Float32Array(cnt * 4)
500
+ for (let i = 0; i < cnt; i++) {
501
+ paint(
502
+ _c,
503
+ p.getX(i),
504
+ p.getY(i),
505
+ p.getZ(i),
506
+ nrm.getX(i),
507
+ nrm.getY(i),
508
+ nrm.getZ(i),
509
+ part,
510
+ 0.5,
511
+ 0,
512
+ )
513
+ col[i * 3] = _c.r
514
+ col[i * 3 + 1] = _c.g
515
+ col[i * 3 + 2] = _c.b
516
+ si[i * 4] = bone
517
+ sw[i * 4] = 1
518
+ }
519
+ g.setAttribute('color', new THREE.BufferAttribute(col, 3))
520
+ g.setAttribute('skinIndex', new THREE.BufferAttribute(si, 4))
521
+ g.setAttribute('skinWeight', new THREE.BufferAttribute(sw, 4))
522
+ g.setAttribute('furLen', new THREE.BufferAttribute(new Float32Array(cnt), 1)) // eyes: no fur
523
+ return g
524
+ }
525
+
526
+ /** Sweep a tapered tube along a polyline (antler beams, tusks). */
527
+ export function tube(
528
+ points: [number, number, number][],
529
+ r0: number,
530
+ r1: number,
531
+ bone: number,
532
+ part: string,
533
+ paint: Paint,
534
+ seg = 7,
535
+ ): THREE.BufferGeometry {
536
+ // subdivide for smoothness (catmull-rom)
537
+ const curve = new THREE.CatmullRomCurve3(
538
+ points.map(p => new THREE.Vector3(...p)),
539
+ false,
540
+ 'catmullrom',
541
+ 0.3,
542
+ )
543
+ const N = lowPoly
544
+ ? Math.max(3, points.length + 1)
545
+ : Math.max(4, points.length * 4) // faceted tusks / antlers: one bend per point
546
+ const st: Station[] = []
547
+ for (let i = 0; i <= N; i++) {
548
+ const t = i / N
549
+ const p = curve.getPoint(t)
550
+ const r = THREE.MathUtils.lerp(r0, r1, t ** 0.8)
551
+ st.push({
552
+ x: p.x,
553
+ y: p.y,
554
+ z: p.z,
555
+ rx: r,
556
+ ry: r,
557
+ top: 1,
558
+ bot: 1,
559
+ b0: bone,
560
+ b1: bone,
561
+ w1: 0,
562
+ })
563
+ }
564
+ // rounded tip
565
+ const last = st[st.length - 1],
566
+ prev = st[st.length - 2]
567
+ if (last === undefined || prev === undefined)
568
+ throw new Error('tube: fewer than two stations') // N >= 3 above
569
+ st.push({
570
+ ...last,
571
+ x: last.x + (last.x - prev.x) * 0.6,
572
+ y: last.y + (last.y - prev.y) * 0.6,
573
+ z: last.z + (last.z - prev.z) * 0.6,
574
+ rx: r1 * 0.35,
575
+ ry: r1 * 0.35,
576
+ })
577
+ return loft(st, seg, part, paint)
578
+ }
579
+
580
+ /** Build with explicit style and paint, restoring outer state even on refusal. */
581
+ export function withBodyGeometry<T>(
582
+ low: boolean,
583
+ paints: Readonly<Record<string, (variant?: VariantDef) => Paint>>,
584
+ run: () => T,
585
+ ): T {
586
+ const previous = { lowPoly, shagAmp, shapeFn, paints: new Map(authorPaints) }
587
+ lowPoly = low
588
+ authorPaints.clear()
589
+ for (const [kind, paint] of Object.entries(paints))
590
+ authorPaints.set(kind, paint)
591
+ try {
592
+ return run()
593
+ } finally {
594
+ lowPoly = previous.lowPoly
595
+ shagAmp = previous.shagAmp
596
+ shapeFn = previous.shapeFn
597
+ authorPaints.clear()
598
+ for (const [kind, paint] of previous.paints) authorPaints.set(kind, paint)
599
+ }
600
+ }
601
+
602
+ /** Callback-free author metadata and visual knobs; no live body or engine owner. */
603
+ export type AuthorSpeciesRows = Partial<
604
+ Omit<SpeciesData, 'id' | 'variants' | 'spawnOnly'>
605
+ > & {
606
+ kind: string
607
+ label: string
608
+ rigContract: CommonLook['rigContract']
609
+ variants: VariantDef[]
610
+ spawnOnly?: VariantDef[]
611
+ fur: FurStyle
612
+ pose?: { grazeNeck: number; gallopTail: number }
613
+ gait?: { trot: number; gallop: number }
614
+ rig?: 'quadruped' | 'custom'
615
+ tick?: 'ai' | 'always'
616
+ phased?: boolean
617
+ corpseFade?: number
618
+ eyeGlow?: [number, number, number]
619
+ eyeGlowIntensity?: number
620
+ postPose?: unknown
621
+ animate?: unknown
622
+ think?: unknown
623
+ act?: unknown
624
+ damageMul?: unknown
625
+ }
626
+
627
+ /** Fresh gameplay content in the original authored order. */
628
+ export function commonSpeciesRows(
629
+ kind: CommonBodyKind,
630
+ speciesId: string,
631
+ ): SpeciesData {
632
+ return readSpecies({ ...(kind === 'boar' ? boar : bear), id: speciesId })
633
+ }
634
+ /** Build-only extraction of gameplay fields from a resolved species. Visual variants stay with their look;
635
+ * a species with native think/act callbacks refuses instead of silently discarding its behaviour. */
636
+ export function bakeSpecies(
637
+ row: {
638
+ variants: readonly SpeciesData['variants'][number][]
639
+ spawnOnly?: readonly SpeciesData['variants'][number][]
640
+ think?: unknown
641
+ act?: unknown
642
+ },
643
+ speciesId: string,
644
+ ): SpeciesData {
645
+ if (row.think !== undefined || row.act !== undefined)
646
+ throw new Error('Species programmes require callback-free gameplay rows')
647
+ const fields: Record<string, unknown> = { id: speciesId }
648
+ for (const key of Object.keys(SpeciesSchema.entries)) {
649
+ if (
650
+ key === 'id' ||
651
+ key === 'variants' ||
652
+ key === 'spawnOnly' ||
653
+ !Object.hasOwn(row, key)
654
+ )
655
+ continue
656
+ const value: unknown = Reflect.get(row, key)
657
+ fields[key] = value
658
+ }
659
+ const variant = ({
660
+ id,
661
+ label,
662
+ weight,
663
+ rarity,
664
+ scale,
665
+ hp,
666
+ mods,
667
+ }: SpeciesData['variants'][number]): SpeciesData['variants'][number] => ({
668
+ id,
669
+ label,
670
+ weight,
671
+ rarity,
672
+ scale,
673
+ ...(hp === undefined ? {} : { hp }),
674
+ ...(mods === undefined ? {} : { mods }),
675
+ })
676
+ fields['variants'] = row.variants.map(variant)
677
+ if (row.spawnOnly !== undefined)
678
+ fields['spawnOnly'] = row.spawnOnly.map(variant)
679
+ let copiedTuning = false
680
+ const kind = fields['kind']
681
+ if (fields['tuning'] === undefined && typeof kind === 'string') {
682
+ const profile = legacyCreatureProfile(kind)
683
+ if (
684
+ profile?.temperament.brain === 'hunt' &&
685
+ profile.temperament.tuning !== undefined
686
+ ) {
687
+ fields['tuning'] = Object.fromEntries(
688
+ Object.entries(profile.temperament.tuning).filter(
689
+ ([name]) => name !== 'motion',
690
+ ),
691
+ )
692
+ copiedTuning = true
693
+ }
694
+ }
695
+ const result = readSpecies(fields)
696
+ if (copiedTuning)
697
+ console.warn(
698
+ `species \`${speciesId}\` uses old kind \`${String(kind)}\`: copied kit hunting tuning; declare it explicitly`,
699
+ )
700
+ return result
701
+ }
702
+
703
+ /** Derive callback-free author data, preserving inherited fields and the original tuning merge. */
704
+ export function deriveSpeciesRows(
705
+ parent: SpeciesData,
706
+ patch: Partial<SpeciesData> & { id: string },
707
+ ): SpeciesData {
708
+ const row = { ...parent, ...patch }
709
+ if (parent.tuning !== undefined && patch.tuning !== undefined)
710
+ row.tuning = { ...parent.tuning, ...patch.tuning }
711
+ return readSpecies(row)
712
+ }
713
+
714
+ /** Existing author recipes build in the kit's explicit low-poly context. */
715
+ export function withSpeciesGeometry<T>(
716
+ paints: Readonly<Record<string, (variant?: VariantDef) => Paint>>,
717
+ run: () => T,
718
+ ): T {
719
+ return withBodyGeometry(true, paints, run)
720
+ }
721
+
722
+ const compiler: SpeciesGeometryCompiler = {
723
+ loft,
724
+ tube,
725
+ skinPlain,
726
+ S,
727
+ boneIndex,
728
+ mix,
729
+ paintNoise,
730
+ setShag,
731
+ isLowPoly,
732
+ paletteColors,
733
+ srgb,
734
+ toonPaint,
735
+ }
736
+ export const BOAR_LOOK: CommonLook = createBoarLook(compiler)
737
+ export const BEAR_LOOK: CommonLook = createBearLook(compiler)
738
+ export type CommonBodyKind = 'boar' | 'bear'
739
+ export type CommonSpeciesKind = CommonBodyKind
740
+ const looks = { boar: BOAR_LOOK, bear: BEAR_LOOK }
741
+ /** Authored shape and palette controls in the original gameplay order. */
742
+ export function commonBodyVariants(kind: CommonBodyKind): VariantDef[] {
743
+ return commonSpeciesRows(kind, `kit.creature.${kind}`).variants.map(
744
+ ({ id }) => {
745
+ const variant: VariantDef = {
746
+ id,
747
+ label: id,
748
+ weight: 1,
749
+ rarity: 'common',
750
+ scale: [1, 1],
751
+ }
752
+ return Object.assign(
753
+ variant,
754
+ structuredClone(looks[kind].variants?.[id] ?? {}),
755
+ )
756
+ },
757
+ )
758
+ }
759
+ /** The author owns the body and the exact next random continuation. */
760
+ export function bakeCommonBody(
761
+ kind: CommonBodyKind,
762
+ variant: VariantDef,
763
+ state: RngState,
764
+ ): { body: AnimalSpecies; random: RngState } {
765
+ const rng = new Rng(0)
766
+ rng.restore(state)
767
+ return { body: looks[kind].build(variant, rng), random: rng.snapshot() }
768
+ }