code wiki / _hdl_build / nx_body_gen_profile_qualified_t239.nx
nx_body_gen_profile_qualified_t239.nx source
↩ module page · 1263 lines · 78507 B
1// nx_body_gen.nx -- ★THE PRODUCT: a SOVEREIGN PROCEDURAL human body, generated from the first byte up.
2// No scanned mesh, no third-party asset: the body is EMITTED from anthropometric parameters (fractions of
3// stature, per-mille). BodyParts3D is the ORACLE we measure against -- never the product. Competitor
4// platforms are benchmarked on CAPABILITY only; none of their assets are used.
5//
6// v2 (GX-23): the body is now built from CONTINUOUS RING PROFILES, not disjoint cylinders. Each part
7// (torso, arm, leg) is ONE tube threaded through control rings and sub-sampled, so there are no seams
8// where segments used to butt together -- that was the largest silhouette defect vs the oracle. Hands and
9// feet are ring extensions of the arm/leg tubes, so they attach continuously. Normals include the taper
10// slope, so shading follows the true surface rather than a stack of cylinders.
11// nx_body_gen <out.nxmesh> <height> [radial] [sub] [relief] [canonpath] [fat] [prof] [?] [hf]
12// ★★THE CANON PATH IS argv[6] AND IT WAS UNDOCUMENTED (seq1377). It is the single most important input --
13// this emitter carries NO geometry literals, so WHICH canon you hand it is the whole product -- and its
14// absence from this line is why the nx_skullgen -> mesh chain LOOKED non-composable and cost a
15// measurement cycle. Defaults: relief/RLF argv[5], canon argv[6] (knowledge/canon_male.dat), fat argv[7],
16// prof argv[8], hf argv[10]. ★A usage line that omits a positional does not merely under-document it --
17// it makes every LATER positional unreachable, because you cannot skip one.
18// license_tier: ORIGINAL expect_exit: 0
19import "nx_syscalls.nx"
20import "nx_profile_contract.nx"
21import "nx_itoa_lib.nx" // shared MSB-first emitter (zero-alloc)
22const BG_SMOOTHSTEP_3_PERMIL: i64 = 3000
23const BG_PERMIL_CUBE: i64 = 1000000000
24const BG_PERMIL_SQ: i64 = 1000000
25const BG_CATMULL_DEN: i64 = 2000000
26const BG_F32_MANT_SCALE: i64 = 8388608
27const BG_F32_MANT_MASK: i64 = 8388607
28const BG_DEFAULT_STATURE_MM: i64 = 1750
29
30const BG_Q14: i64 = 16384
31// Bhaskara I's sine approximation (7th century): sin(x deg) ~= 4x(180-x) / (40500 - x(180-x)).
32// 40500 is that method's published constant, not a tuning knob -- the old name BG_MAGIC_40500 hid
33// the fact that this line implements a named algorithm at all.
34const BG_BHASKARA_K: i64 = 40500
35// raised for the face-parts program (F1083): 21 parts at radial 52/sub 8 reached 393,432 of the old 400k,
36// i.e. 6.5k from SILENT truncation of the skin head. Headroom + a truncated flag are now reported every run.
37// ★RAISED AGAIN 2026-08-10, measured binding LIVE: radial 96/sub 24 on even the 5-part canon truncated at
38// 599,998/600,000 (truncated:1) -- 600k sat at MetaHuman-ENTRY density while the ladder (ZBrush-class
39// sculpt density, 32 teeth, 200 eyelashes) needs millions. 2^23 tris = 1.41GB emit buffer of ADDRESS SPACE
40// (lazily mmap'd, resident only what is touched) + ~700MB NXMSH2 write buffer at FULL cap; the renderer
41// (nx_anat_sov) streams ntris from the header with NO cap of its own. Still a loud threshold, and the
42// manifest now reports tris_offered (demand) so a capped emit can never again pass as a complete one.
43const BG_MAXTRI: i64 = 8388608
44// ★★CAPS RAISED TO WHAT THE HARDWARE SUPPORTS, NOT TO A NUMBER SOMEBODY ONCE TYPED. 256 rings and 48 parts
45// were never measured against anything -- and the anatomy ladder ahead (32 teeth, 20 nails, 200 eyelashes,
46// each its own part with its own rings) walks straight through both. The arrays are lazily mmap'd, so a
47// larger cap costs address space rather than resident memory: 8192 rings across 5 arrays is 320KB of
48// reservation. ★The cap is now a REFUSAL THRESHOLD, not a silent truncation point -- which is only safe
49// because the guards above landed in the same change. Raising a bound without a check would have converted
50// a near-miss into a much larger silent overwrite.
51const BG_MAXRING: i64 = 8192
52const BG_MAXFEAT: i64 = 4096
53// ★PART CAP, named + guarded (was a bare 16 in six mmap sizes with NO bound check on the parser's write:
54// a canon with a 17th P row wrote past a 128-byte allocation -- an unguarded array write driven by an
55// EXTERNAL file, which is the classic overflow class and silently "worked" only because mmap rounds to a
56// page. The canon is external input to this emitter, so it is a boundary and must be defensive. Raised to
57// 48 because the face-geometry program needs real feature PARTS (nose, lips, ears) and the canon already
58// carried exactly 16.
59const BG_MAXPART: i64 = 2048
60// surface points are kept at BG_PSUB sub-units so the central-difference tangents keep their precision;
61// integer rounding of a raw-unit point would be ~3% of a one-step tangent and swamp the relief signal
62const BG_PSUB: i64 = 512
63const BG_MAXRS: i64 = 256
64// components are halved down to this before squaring -- keeps enx*enx+... far inside i64
65const BG_NCAP: i64 = 1000000
66// ★LAYER STACK -- the body is built from the first cell up: a bone core, a muscle envelope on the bone, and
67// the skin as the outer envelope of muscle+fat. Each is a real NXMSH2 layer, so it renders/peels separately
68// and the skin's SHAPE EMERGES from the layers beneath instead of being painted on a shell.
69// ★MEASURED SECTION PROFILES (GX-31). Every ring was an ELLIPSE modulated by relief bumps; a real human
70// cross-section is not an ellipse (flat back, scapular bulges, sternal hollow, iliac flare). nx_profile_fit
71// measures those sections off the oracle and emits a DIMENSIONLESS per-angle ratio (1000 = on the ellipse);
72// this emitter applies the ratio to whatever size the rule engine asked for, so the prior is shape-only and
73// the body stays procedural. Same idea as Infinigen taking creature profiles from real references.
74// the prior's angular resolution is carried IN the data file ('N <bins>'), never duplicated as a const in
75// two organs -- a silent bin-count mismatch would misread every row as a rotated body.
76const BG_NBMAX: i64 = 96
77// ★512 -> 2048 (2026-07-30, ws=neuro). A profile carrying every canon part needs parts x stations rows:
78// the skull canon alone is 7 x 167 = 1169, so 512 silently dropped 47 percent of a 973-row file and the
79// emitter reported prof_rows:512 as though that WERE the data. sR is BG_MAXPROF*BG_NBMAX*8 = 1.5MB at 2048.
80const BG_MAXPROF: i64 = 2048
81const BG_PROFCLAMP: i64 = 300 // a single bad measured row can never deform the body more than +/-30%
82// ★per-mille-of-stature band at each part's data extremes over which the prior fades to neutral, so a
83// per-part modulation can never pull two parts apart at the boundary the canon built them to share.
84const BG_PROFEDGE: i64 = 45
85const BG_NLAYER: i64 = 3
86const BG_BONEF: i64 = 400 // bone core radius = 40% of the skin radius (the skeletal armature)
87const BG_MUSCF: i64 = 820 // muscle envelope = 82% of the skin radius (muscle bellies fill toward skin)
88
89// ★★★ONE PLACEMENT ROTATION, USED BY ALL FOUR TRANSFORM SITES. The Z->X->Y chain was written out FOUR
90// TIMES -- position, normal, cap normal, cap centre -- as twenty-four hand-copied lines. That is the
91// duplication class this programme keeps finding the hard way: when rotY was added, the same six lines had
92// to be inserted four times and any one of them could have been missed or transposed silently, because a
93// body with three correct sites and one wrong one still renders.
94// ★A TRANSFORM APPLIED IN FOUR PLACES IS ONE RULE WITH THREE CHANCES TO DRIFT.
95// Extracting it also makes the chain TESTABLE: bg_rot3 is a pure function of nine integers, so the gate can
96// assert the composition order and the mirror convention directly instead of inferring them from a mesh.
97// ORDER IS LOAD-BEARING: rotZ turns the cross-section in its own plane, rotX pitches the part, and rotY --
98// applied LAST -- is a true world AZIMUTH. Applied first it would merely spin the cross-section.
99func bg_rot3(x: i64, y: i64, z: i64, pzc: i64, pzs: i64, prc: i64, prs: i64, pyc: i64, pys: i64, o: *i64) -> i64 {
100 let zx: i64 = (x*pzc - y*pzs)/BG_Q14
101 let zy: i64 = (x*pzs + y*pzc)/BG_Q14
102 let ry: i64 = (zy*prc - z*prs)/BG_Q14
103 let rz: i64 = (zy*prs + z*prc)/BG_Q14
104 o[2] = (rz*pyc - zx*pys)/BG_Q14
105 o[0] = (rz*pys + zx*pyc)/BG_Q14
106 o[1] = ry
107 return 0
108}
109func bg_hw(s: *u8) -> i64 { var n: i64=0; while s[n]!=(0 as u8){n=n+1} sys_write(1,s,n); return 0 }
110// MIGRATED to the shared emitter (debt 1785563586). The old body mmapped a scratch buffer
111// per call and never freed it. At PAGE granularity that is 4096B leaked PER CALL -- the
112// defect that took 28.5GB of a 36GB host in nx_ts_lumadiff (2MB input, ~3.66M calls).
113// nxi_* is MSB-first, allocates NOTHING, and emits identical bytes including the sign.
114func bg_pn(v: i64) -> i64 { nxi_out(v); return 0 }
115func bg_satoi(s: *u8) -> i64 { var i: i64=0; var n: i64=0
116 while s[i]!=(0 as u8) { let c: i64=s[i] as i64; if c>=48 { if c<=57 { n=n*10+(c-48) } } i=i+1 } return n }
117func bg_sin_fill(t: *i64) -> i64 {
118 var d: i64=0
119 while d<180 { let P: i64=d*(180-d); t[d]=BG_Q14*4*P/(BG_BHASKARA_K-P); t[d+180]=0-t[d]; d=d+1 }
120 return 0
121}
122func bg_wrap(d: i64) -> i64 { var x: i64=d%360; if x<0 { x=x+360 } return x }
123// shortest angular separation, 0..180
124func bg_angsep(a: i64, b: i64) -> i64 {
125 var d: i64 = bg_wrap(a) - bg_wrap(b)
126 if d < 0 { d = 0-d }
127 if d > 180 { d = 360-d }
128 return d
129}
130// ★ANATOMICAL SURFACE RELIEF. Until now every ring was a plain ellipse, so the body had correct OUTLINE but a
131// featureless surface -- which is exactly what the normal-field judge was penalising (it became the binding
132// constraint at 749 once the silhouettes were fixed). Real anatomy modulates the radius with ANGLE as well as
133// height: pectorals and abdominal bulges at the front, the spinal groove and scapulae at the back, glutes,
134// quadriceps, calves. Each feature is a (part, height, angle, extent, amplitude) tuple with quadratic falloff,
135// summed -- data, not hand-carved geometry. theta: 0=+X right, 90=+Z front, 180=-X left, 270=-Z back.
136func bg_relief(part: i64, ymil: i64, th: i64, fP: *i64, fY: *i64, fYw: *i64, fT: *i64, fTw: *i64, fA: *i64, nf: i64) -> i64 {
137 var s: i64 = 0
138 var k: i64 = 0
139 while k < nf {
140 if fP[k] == part {
141 var dy: i64 = ymil - fY[k]
142 if dy < 0 { dy = 0-dy }
143 if dy < fYw[k] {
144 let dt: i64 = bg_angsep(th, fT[k])
145 if dt < fTw[k] {
146 let wy: i64 = 1000 - dy*1000/fYw[k]
147 let wt: i64 = 1000 - dt*1000/fTw[k]
148 s = s + fA[k]*wy/1000*wt/1000
149 }
150 }
151 }
152 k = k + 1
153 }
154 return s
155}
156// ANALYTIC SHAPE BASIS (GX-41). displacement = sum of beta_i * basis_i(coord): the body as a mean shape
157// plus weighted deformation functions, the genome being the coefficients. Two properties earned it this slot:
158// (1) REGISTRATION-FREE BY CONSTRUCTION -- the basis is evaluated in OUR body's own parameter space, so the
159// misregistration that killed measured detail transfer (residual sampled at the oracle's coordinates)
160// cannot occur here;
161// (2) it creates surface that faces UP and DOWN. A smooth vertical body has ny approx 0 everywhere, which is
162// why the environment light had nothing to differentiate and why the detail judge sees no busyness. What
163// matters is the GRADIENT dr/dy, not the amplitude -- so the bases vary in HEIGHT, not just in angle,
164// unlike the relief-feature table that measured as worth 1 permil.
165// Anatomical, not noise: intercostal banding over the ribcage, the clavicle trough, the inframammary fold.
166const BG_WK_RAMP: i64 = 1
167const BG_WK_TRI: i64 = 2
168const BG_WK_RIDGE: i64 = 3
169const BG_YK_FLAT: i64 = 1
170const BG_YK_WAVE_RIB: i64 = 2
171const BG_YK_WAVE_SPAN: i64 = 3
172const BG_HALFTURN_DEG: i64 = 180
173// ★THE ROW TAGS AND THE LINE TERMINATOR, NAMED. The walkers below tested `== 66` and `== 10` -- ASCII
174// 'B' and newline written as bare integers. Those two values ARE the grammar of the canon file, and a
175// reader cannot tell a row tag from a threshold at a glance when both are just numbers.
176const BG_ROW_BASIS: i64 = 66 // 'B' -- a shape-basis feature row
177const BG_ROW_LAYER: i64 = 76 // 'L' -- a layer palette row
178const BG_LF: i64 = 10 // end of line
179// walks the basis file for 'B' rows. Same independent-walker shape as bg_parse_open, for the same reason:
180// bg_parse_canon already carries 24 arguments and widening it is the wrong direction.
181func bg_parse_basis(b: *u8, len: i64, kP: *i64, kYlo: *i64, kYhi: *i64, kTh: *i64, kWk: *i64, kW0: *i64, kW1: *i64, kW2: *i64, kAmp: *i64, kYk: *i64, kP0: *i64, kP1: *i64, kP2: *i64, cnt: *i64) -> i64 {
182 let pos: *i64 = sys_mmap(16) as *i64
183 var n: i64 = 0
184 var i: i64 = 0
185 var bol: i64 = 1
186 while i < len {
187 if bol == 1 {
188 if (b[i] as i64) == BG_ROW_BASIS {
189 if n < BG_MAXFEAT {
190 pos[0] = i+1
191 kP[n]=bg_rdint(b,pos,len); kYlo[n]=bg_rdint(b,pos,len); kYhi[n]=bg_rdint(b,pos,len)
192 kTh[n]=bg_rdint(b,pos,len); kWk[n]=bg_rdint(b,pos,len)
193 kW0[n]=bg_rdint(b,pos,len); kW1[n]=bg_rdint(b,pos,len); kW2[n]=bg_rdint(b,pos,len)
194 kAmp[n]=bg_rdint(b,pos,len); kYk[n]=bg_rdint(b,pos,len)
195 kP0[n]=bg_rdint(b,pos,len); kP1[n]=bg_rdint(b,pos,len); kP2[n]=bg_rdint(b,pos,len)
196 i = pos[0]
197 n = n + 1
198 }
199 }
200 }
201 if (b[i] as i64) == BG_LF { bol = 1 } else { bol = 0 }
202 i = i + 1
203 }
204 cnt[0] = n
205 return n
206}
207// ★THE LAYER PALETTE IS DATA TOO. The three layer colours were an IF-LADDER inside the emit loop --
208// skin 880/700/620, muscle 760/286/262, bone 928/918/872 -- while the radius scales sitting on the SAME
209// lines (BG_MUSCF, BG_BONEF) were already named consts. Half a table named and half raw is the signature
210// of an oversight, not a decision. And as an if-ladder a FOURTH layer could not be expressed at all
211// without editing the emit loop -- the same defect anat_sov's 5-row anchor ladder had.
212// Rows are 'L <layer> <r> <g> <b>' in the SAME canon file, so there is still one file, one read, one
213// walker shape. A row naming a layer outside 0..BG_NLAYER-1 is skipped rather than writing past the array.
214func bg_parse_layers(b: *u8, len: i64, lR: *i64, lG: *i64, lB: *i64, cnt: *i64) -> i64 {
215 let pos: *i64 = sys_mmap(16) as *i64
216 var n: i64 = 0
217 var i: i64 = 0
218 var bol: i64 = 1
219 while i < len {
220 if bol == 1 {
221 if (b[i] as i64) == BG_ROW_LAYER {
222 pos[0] = i+1
223 let ly: i64 = bg_rdint(b,pos,len)
224 if ly >= 0 { if ly < BG_NLAYER {
225 lR[ly]=bg_rdint(b,pos,len); lG[ly]=bg_rdint(b,pos,len); lB[ly]=bg_rdint(b,pos,len)
226 n = n + 1
227 } }
228 i = pos[0]
229 }
230 }
231 if (b[i] as i64) == BG_LF { bol = 1 } else { bol = 0 }
232 i = i + 1
233 }
234 cnt[0] = n
235 return n
236}
237// ★THE SHAPE-BASIS CANON IS DATA (2026-08-14). Every band edge, angular window and amplitude below used to
238// be a literal here: the anatomy this body claims to have, written into the emitter where it could not be
239// revised or varied without a rebuild. nx_magic at threshold 2 surfaced them; at its DEFAULT threshold they
240// all sit under the bar and the organ reports clean. They now live in knowledge/body_shape_basis.conf.
241// ★★THE ARITHMETIC ORDER OF EACH SHAPE IS PRESERVED EXACTLY, because integer division is not associative:
242// amp*(z*1000/half)/1000 and amp*z*1000/half/1000 are DIFFERENT expressions. The acceptance proof is a
243// BIT-IDENTICAL mesh against the banked pre-refactor artifact, so a shape rewritten "equivalently" fails it.
244func bg_shape_basis(part: i64, ymil: i64, th: i64, sinT: *i64, kP: *i64, kYlo: *i64, kYhi: *i64, kTh: *i64, kWk: *i64, kW0: *i64, kW1: *i64, kW2: *i64, kAmp: *i64, kYk: *i64, kP0: *i64, kP1: *i64, kP2: *i64, nk: i64) -> i64 {
245 var s: i64 = 0
246 var k: i64 = 0
247 while k < nk {
248 var hit: i64 = 0
249 if part == kP[k] { if ymil > kYlo[k] { if ymil < kYhi[k] { hit = 1 } } }
250 if hit == 1 {
251 let w: i64 = bg_angsep(th, kTh[k])
252 let amp: i64 = kAmp[k]
253 if kWk[k] == BG_WK_RAMP { if kYk[k] == BG_YK_FLAT {
254 if w < kW1[k] { s = s + amp*(1000 - w*1000/kW1[k])/1000 }
255 } }
256 if kWk[k] == BG_WK_RAMP { if kYk[k] == BG_YK_WAVE_SPAN {
257 if w < kW1[k] {
258 let ph2: i64 = (ymil-kYlo[k])*1000/(kYhi[k]-kYlo[k])
259 s = s + amp*sinT[bg_wrap(ph2*BG_HALFTURN_DEG/1000)]/BG_Q14*(1000 - w*1000/kW1[k])/1000
260 }
261 } }
262 if kWk[k] == BG_WK_TRI { if kYk[k] == BG_YK_FLAT {
263 if w > kW0[k] { if w < kW0[k]+2*kW1[k] {
264 var z: i64 = w - kW0[k]
265 if z > kW1[k] { z = 2*kW1[k] - z }
266 if z > 0 { s = s + amp*z*1000/kW1[k]/1000 }
267 } }
268 } }
269 if kWk[k] == BG_WK_RIDGE { if kYk[k] == BG_YK_WAVE_RIB {
270 let dy: i64 = ymil - kYlo[k]
271 let ph: i64 = (dy*kP0[k] - dy*dy/kP1[k] + w*kP2[k]) % 360
272 var aw: i64 = 0
273 if w > kW0[k] { if w < kW1[k] { aw = (w-kW0[k])*1000/(kW1[k]-kW0[k]) } }
274 if w >= kW1[k] { if w < kW2[k] { aw = (kW2[k]-w)*1000/(kW2[k]-kW1[k]) } }
275 if aw > 0 { s = s + amp*sinT[bg_wrap(ph)]/BG_Q14*aw/1000 }
276 } }
277 }
278 k = k + 1
279 }
280 return s
281}
282// ⚠⚠DEAD CODE -- NOTHING CALLS THIS. 2026-08-14: the shape-basis canon moved OUT of the emitter and into
283// knowledge/body_shape_basis.conf, and the live implementation is bg_shape_basis() above, which is table
284// driven. This copy is kept only because a sibling seat was mid-edit in it when the move landed (the
285// zyg_lo/zyg_span/szy_half hoists below are theirs, and they are hoists to NAMED LOCALS -- which satisfies
286// a magic-number ratchet while leaving the policy in code; the numbers are now DATA one function up).
287// ★IF YOU ARE EDITING THIS FUNCTION, YOUR CHANGE HAS NO EFFECT ON ANY EMITTED MESH. Edit the .conf.
288// Delete this whole function once the sibling's lane has landed; the mesh is bit-identical without it
289// (proven: sha f318ade9 both sides, 3,784,792 B).
290// bg_shape_basis_retired REMOVED 2026-08-14: 92 lines, ZERO call sites (grep coverage_complete=1,
291// corpus_complete=1 over 8,769 files -- the only match was its own definition). Its 8 anatomical
292// features now live as B rows in knowledge/body_shape_basis.conf, read by the live bg_shape_basis,
293// which derives every span from the data ((kW1[k]-kW0[k])) instead of carrying a typed copy.
294// ★A RETIRED FUNCTION IS A MEASUREMENT LIABILITY, NOT INERT WEIGHT. nx_magic scans SOURCE, so this
295// fossil's ~30 hardcoded per-mille constants kept being counted as live defects in this organ: the
296// headline "510 magic-number sites in nx_body_gen" was mostly THIS, and a reader diagnosing the organ
297// (2026-08-14) fixed the retired copy believing it was the shipping one. Deleting the body is what
298// makes the count honest -- a _retired SUFFIX IS NOT A GUARD, because a name is read only after you
299// have already decided what the file says. Only the call-site query is a control.
300func bg_isqrt(v: i64) -> i64 { if v<=0 {return 0} var x: i64=v; var y: i64=(x+1)/2; while y<x { x=y; y=(x+v/x)/2 } return x }
301// ★CATMULL-ROM spline through control values p1..p2 (neighbours p0,p3), t in [0,1000]; returns value*1000.
302// THE Infinigen-gap fix: linear interpolation between sparse rings makes every part read as stacked cones with
303// a crease at each ring -- a cubic through the SAME rings gives C1-smooth organic curvature everywhere.
304// Integer-exact at the ends: t=0 -> p1*1000, t=1000 -> p2*1000.
305func bg_cmr(p0: i64, p1: i64, p2: i64, p3: i64, t: i64) -> i64 {
306 let a: i64 = 2*p1
307 let b: i64 = p2 - p0
308 let c: i64 = 2*p0 - 5*p1 + 4*p2 - p3
309 let d: i64 = 3*p1 - p0 + p3 - 3*p2
310 return (a*BG_PERMIL_CUBE + b*t*BG_PERMIL_SQ + c*t*t*1000 + d*t*t*t)/BG_CATMULL_DEN
311}
312// integer IEEE-754 float32 encoder (NishiLang has no float type -- we pack the bits ourselves)
313func bg_f32(v: i64, scale: i64) -> i64 {
314 if v == 0 { return 0 }
315 var neg: i64 = 0
316 var m: i64 = v
317 if m < 0 { neg = 1; m = 0-m }
318 var e: i64 = 0
319 var num: i64 = m
320 var den: i64 = scale
321 while num >= den*2 { den = den*2; e = e+1 }
322 while num < den { num = num*2; e = e-1 }
323 let frac: i64 = ((num - den)*BG_F32_MANT_SCALE)/den
324 var bits: i64 = ((e+127) << 23) | (frac & BG_F32_MANT_MASK)
325 if neg == 1 { bits = bits | (1<<31) }
326 return bits
327}
328func bg_wr32(b: *u8, o: i64, v: i64) -> i64 {
329 b[o]=(v&255) as u8; b[o+1]=((v>>8)&255) as u8; b[o+2]=((v>>16)&255) as u8; b[o+3]=((v>>24)&255) as u8
330 return 0
331}
332
333// ---- CANON PARSER: the emitter reads its geometry from DATA, it carries none. ----
334// signed-integer token reader: skips leading non-digit/non-minus within [pos,end), reads, advances pos.
335func bg_rdint(b: *u8, pos: *i64, end: i64) -> i64 {
336 var i: i64 = pos[0]
337 var go: i64 = 1
338 while go == 1 {
339 if i >= end { go = 0 } else {
340 let c: i64 = b[i] as i64
341 if c == 45 { go = 0 } else {
342 if c >= 48 { if c <= 57 { go = 0 } else { i = i+1 } } else { i = i+1 }
343 }
344 }
345 }
346 var sg: i64 = 1
347 if i < end { if (b[i] as i64) == 45 { sg = 0-1; i = i+1 } }
348 var v: i64 = 0
349 var g2: i64 = 1
350 while g2 == 1 {
351 if i >= end { g2 = 0 } else {
352 let c: i64 = b[i] as i64
353 if c >= 48 { if c <= 57 { v = v*10 + (c-48); i = i+1 } else { g2 = 0 } } else { g2 = 0 }
354 }
355 }
356 pos[0] = i
357 return v*sg
358}
359// parse a canon buffer: P (part header) / R (control ring) / F (relief feature) lines; '#' = comment.
360// ---- ★★★OPENINGS: THE MECHANISM RELIEF STRUCTURALLY CANNOT PROVIDE (seq1387/seq908) ----
361// An orbit and a nasal aperture are HOLES. Relief modulates a RADIUS, and a radius modulation can dent a
362// surface but can never remove it -- which is why the skull's six declared hollows moved the mesh and
363// moved nx_bodybench by NOTHING (headline 45, detail_head 14). An 'O' row declares a region where the
364// shell is simply ABSENT: the quad is not emitted, so the surface is genuinely gone and what lies behind
365// it is visible. Same geometry fields as an F row (part, y, y-halfwidth, theta, theta-halfwidth) minus
366// the amplitude, because there is no amount -- the surface is there or it is not.
367// ★PARSED SEPARATELY ON PURPOSE: bg_parse_canon already takes 24 arguments, and widening it further is
368// the wrong shape (that row wants a context array on its next touch, D001). This walks the same buffer
369// independently, so the existing signature and all its callers are untouched.
370// ★★ADDITIVE BY CONSTRUCTION: a canon carrying no O rows yields count 0 and every test below is inert,
371// so every existing canon must emit BIT-IDENTICAL output. That is the acceptance proof, not an opinion.
372func bg_parse_open(b: *u8, len: i64, oP: *i64, oY: *i64, oYw: *i64, oT: *i64, oTw: *i64, cnt: *i64) -> i64 {
373 let pos: *i64 = sys_mmap(16) as *i64
374 var n: i64 = 0
375 var i: i64 = 0
376 var bol: i64 = 1
377 while i < len {
378 if bol == 1 {
379 if (b[i] as i64) == 79 {
380 if n < BG_MAXFEAT {
381 pos[0] = i+1
382 oP[n] = bg_rdint(b, pos, len)
383 oY[n] = bg_rdint(b, pos, len)
384 oYw[n] = bg_rdint(b, pos, len)
385 oT[n] = bg_rdint(b, pos, len)
386 oTw[n] = bg_rdint(b, pos, len)
387 i = pos[0]
388 n = n + 1
389 }
390 }
391 }
392 if (b[i] as i64) == 10 { bol = 1 } else { bol = 0 }
393 i = i + 1
394 }
395 cnt[0] = n
396 return n
397}
398// is this (part, station, angle) inside a declared opening? bg_angsep handles the 0/360 wrap.
399func bg_in_open(part: i64, ymil: i64, thd: i64, oP: *i64, oY: *i64, oYw: *i64, oT: *i64, oTw: *i64, n: i64) -> i64 {
400 var k: i64 = 0
401 while k < n {
402 if oP[k] == part {
403 var dy: i64 = ymil - oY[k]
404 if dy < 0 { dy = 0 - dy }
405 if dy <= oYw[k] {
406 if bg_angsep(thd, oT[k]) <= oTw[k] { return 1 }
407 }
408 }
409 k = k + 1
410 }
411 return 0
412}
413
414func bg_parse_canon(b: *u8, len: i64, ry: *i64, rx0: *i64, rz0: *i64, ra: *i64, rb: *i64,
415 pStart: *i64, pCount: *i64, pMirror: *i64, pRot: *i64, pOx: *i64, pOy: *i64, pOz: *i64,
416 pMat: *i64, pRotZ: *i64, pRotY: *i64, fP: *i64, fY: *i64, fYw: *i64, fT: *i64, fTw: *i64, fA: *i64, counts: *i64) -> i64 {
417 var np: i64 = 0; var n: i64 = 0; var nf: i64 = 0
418 let pos: *i64 = sys_mmap(8) as *i64
419 var i: i64 = 0
420 while i < len {
421 var j: i64 = i
422 var sk: i64 = 1
423 while sk == 1 {
424 if j >= len { sk = 0 } else {
425 let c: i64 = b[j] as i64
426 if c == 32 { j = j+1 } else { if c == 9 { j = j+1 } else { sk = 0 } }
427 }
428 }
429 var tag: i64 = 0
430 if j < len { tag = b[j] as i64 }
431 var e: i64 = i
432 var fe: i64 = 1
433 while fe == 1 { if e >= len { fe = 0 } else { if (b[e] as i64) == 10 { fe = 0 } else { e = e+1 } } }
434 if tag == 80 { // 'P' -- part header
435 // GUARD: refuse LOUD rather than write past the part arrays. The canon is EXTERNAL input, so
436 // this is a boundary; an unguarded write here silently overflowed for every canon past the cap.
437 if np >= BG_MAXPART {
438 bg_hw("CANON-REFUSED part count exceeds BG_MAXPART\n" as *u8)
439 sys_exit(4)
440 }
441 if np > 0 { pCount[np-1] = n - pStart[np-1] }
442 pos[0] = j+1
443 pMirror[np] = bg_rdint(b,pos,e); pRot[np] = bg_rdint(b,pos,e)
444 pOx[np] = bg_rdint(b,pos,e); pOy[np] = bg_rdint(b,pos,e); pOz[np] = bg_rdint(b,pos,e)
445 pMat[np] = bg_rdint(b,pos,e) // optional 6th field: material (0=flesh, 1=eye)
446 // ★optional 7th field: ROTATION ABOUT Z, degrees (F1084 prereq 3). The mechanism gap the face
447 // work hit head-on: a brow ridge and a lip run HORIZONTALLY, but a part could only stack rings
448 // along Y and rotate about X, so every horizontal feature came out a vertical blob. rotZ turns
449 // the canonical Y-tube sideways IN the face plane; absent field parses as 0 = exact identity,
450 // so every existing canon is bit-identical (proven by golden md5 on the standing canon).
451 pRotZ[np] = bg_rdint(b,pos,e)
452 // ★optional 8th field: ROTATION ABOUT Y = AZIMUTH, degrees (S1). rotZ turns a part sideways in
453 // its own plane and rotX pitches it; NEITHER can answer "which compass direction does this limb
454 // point". That is the whole reason a wing, a branching antler and a spine-following ribcage were
455 // inexpressible: parts could only fan within one plane. Applied LAST of the three, so it is a
456 // true world azimuth rather than a spin of the cross-section. ZXY is a complete Euler
457 // parameterisation, so any orientation is now reachable. Absent field parses 0 -> pyc=Q14,
458 // pys=0, and x*Q14/Q14 is integer-exact => every existing canon stays BIT-IDENTICAL.
459 pRotY[np] = bg_rdint(b,pos,e)
460 pStart[np] = n; np = np+1
461 }
462 if tag == 82 { // 'R' -- control ring
463 // ★★THE GUARD THAT WAS MISSING FOR AS LONG AS THE PART GUARD HAS EXISTED. The 'P' branch above
464 // was hardened after an unguarded write silently overflowed -- and the fix was applied to ONE of
465 // the three branches. R and F kept writing past their arrays. ★A HARDENING APPLIED TO ONE
466 // BRANCH OF THREE IS NOT A HARDENING; it is a note saying somebody once knew about the problem.
467 // ⚠WHY IT NEVER SHOWED: the ring pool is GLOBAL across parts (256 entries for the whole body)
468 // and the canon has used 110 of them, so the overflow was always one anatomy rung away rather
469 // than absent. A 32-tooth arch at 4 rings each is 128 rings ON ITS OWN. mmap rounds to a page,
470 // so the first few hundred over-writes would have "worked" -- a wrong body with a clean exit.
471 if n >= BG_MAXRING {
472 bg_hw("CANON-REFUSED ring count exceeds BG_MAXRING\n" as *u8)
473 sys_exit(5)
474 }
475 pos[0] = j+1
476 ry[n] = bg_rdint(b,pos,e); rx0[n] = bg_rdint(b,pos,e); rz0[n] = bg_rdint(b,pos,e)
477 ra[n] = bg_rdint(b,pos,e); rb[n] = bg_rdint(b,pos,e); n = n+1
478 }
479 if tag == 70 { // 'F' -- relief feature
480 // the F pool was a bare unnamed sys_mmap(128*8) with no constant and no check -- it now has both
481 if nf >= BG_MAXFEAT {
482 bg_hw("CANON-REFUSED feature count exceeds BG_MAXFEAT\n" as *u8)
483 sys_exit(6)
484 }
485 pos[0] = j+1
486 fP[nf] = bg_rdint(b,pos,e); fY[nf] = bg_rdint(b,pos,e); fYw[nf] = bg_rdint(b,pos,e)
487 fT[nf] = bg_rdint(b,pos,e); fTw[nf] = bg_rdint(b,pos,e); fA[nf] = bg_rdint(b,pos,e); nf = nf+1
488 }
489 i = e+1
490 }
491 if np > 0 { pCount[np-1] = n - pStart[np-1] }
492 counts[0] = np; counts[1] = n; counts[2] = nf
493 return 0
494}
495
496// parse the measured-profile file: 'S <part> <ymil> <ra> <rb> <24 ratios>' rows, ';' comments.
497// ★DECLARED BIN COUNT, READ BEFORE ALLOCATION (2026-08-23) so the PRIOR'S OWN RESOLUTION sizes the
498// array instead of a compile-time ceiling deciding it. Mirrors bg_parse_prof's own line walk so the
499// two can never disagree about what an 'N' row is. Returns 0 when the file declares none.
500func bg_scan_nb(b: *u8, len: i64) -> i64 {
501 let pos: *i64 = sys_mmap(8) as *i64
502 var i: i64 = 0
503 while i < len {
504 var j: i64 = i
505 var sk: i64 = 1
506 while sk == 1 {
507 if j >= len { sk = 0 } else {
508 let c: i64 = b[j] as i64
509 if c == 32 { j = j+1 } else { if c == 9 { j = j+1 } else { sk = 0 } }
510 }
511 }
512 var e: i64 = i
513 var fe: i64 = 1
514 while fe == 1 { if e >= len { fe = 0 } else { if (b[e] as i64) == 10 { fe = 0 } else { e = e+1 } } }
515 if j < len { if (b[j] as i64) == 78 { pos[0] = j+1; return bg_rdint(b,pos,e) } }
516 i = e+1
517 }
518 return 0
519}
520
521func bg_parse_prof(b: *u8, len: i64, sP: *i64, sY: *i64, sR: *i64, nbo: *i64, stride: i64) -> i64 {
522 var ns: i64 = 0
523 var nb: i64 = 0
524 let pos: *i64 = sys_mmap(8) as *i64
525 var i: i64 = 0
526 while i < len {
527 var j: i64 = i
528 var sk: i64 = 1
529 while sk == 1 {
530 if j >= len { sk = 0 } else {
531 let c: i64 = b[j] as i64
532 if c == 32 { j = j+1 } else { if c == 9 { j = j+1 } else { sk = 0 } }
533 }
534 }
535 var tag: i64 = 0
536 if j < len { tag = b[j] as i64 }
537 var e: i64 = i
538 var fe: i64 = 1
539 while fe == 1 { if e >= len { fe = 0 } else { if (b[e] as i64) == 10 { fe = 0 } else { e = e+1 } } }
540 if tag == 78 { // 'N' -- bins per section
541 pos[0] = j+1
542 nb = bg_rdint(b,pos,e)
543 // ⚠THIS USED TO READ `if nb > BG_NBMAX { nb = 0 }` -- a prior declaring MORE bins than the
544 // compile-time ceiling was SILENTLY DISCARDED WHOLE: nb=0 means every S row is skipped, so
545 // the body emitted with NO measured prior at all and said nothing. A cap that deletes the
546 // data it cannot hold, without a word, is the worst shape a cap can take. The stride is now
547 // DERIVED from this same file's declared N, so for a well-formed prior this is unreachable;
548 // it remains as a fail-loud guard and RECORDS the offered count so the caller can announce.
549 if nb > stride { nbo[2] = nb; nb = 0 }
550 }
551 if tag == 83 { // 'S'
552 // ★COUNT WHAT WAS OFFERED, NOT ONLY WHAT FIT. nbo[1] is the row count PRESENT in the file; the
553 // caller compares it to the accepted count so a cap can never pass itself off as the data.
554 if nb > 0 { nbo[1] = nbo[1] + 1 }
555 if ns < BG_MAXPROF { if nb > 0 {
556 pos[0] = j+1
557 sP[ns] = bg_rdint(b,pos,e); sY[ns] = bg_rdint(b,pos,e)
558 bg_rdint(b,pos,e); bg_rdint(b,pos,e) // measured ra/rb are diagnostics; SIZE stays procedural
559 var k: i64 = 0
560 while k < nb { sR[ns*stride+k] = bg_rdint(b,pos,e); k = k+1 }
561 ns = ns+1
562 }}
563 }
564 i = e+1
565 }
566 nbo[0] = nb
567 return ns
568}
569// look up the shape prior for (part, height, parameter angle): linear in height between the two bracketing
570// measured stations, linear in angle between the two bracketing bins, clamped. Parts with no measured rows
571// (the foot, which runs forward and is measured in its own frame) return 1000 = unchanged.
572// ★HIGH-FREQUENCY RESIDUAL (hf != 0). Four measured attempts agreed that transferring the reference's
573// LOW-frequency shape improves silhouettes and WORSENS surface busyness -- and busyness is the binding
574// judge. The information the detail judge wants is the part of the real section that a smooth shape does
575// NOT explain: the residual against the profile's own smoothed self. Same measured data, opposite band.
576// ★stride is nb, not a ceiling: the array is exactly as wide as the prior declared itself to be.
577func bg_prof_at(sR: *i64, row: i64, b: i64, nb: i64) -> i64 { return sR[row*nb + ((b%nb)+nb)%nb] }
578func bg_prof_smooth(sR: *i64, row: i64, b: i64, nb: i64) -> i64 {
579 var acc: i64 = 0
580 var k: i64 = 0-3
581 while k <= 3 { acc = acc + bg_prof_at(sR,row,b+k,nb); k = k+1 }
582 return acc/7
583}
584func bg_prof(part: i64, ymil: i64, dq: i64, sP: *i64, sY: *i64, sR: *i64, ns: i64, nb: i64, hf: i64) -> i64 {
585 var lo: i64 = 0-1
586 var hi: i64 = 0-1
587 var k: i64 = 0
588 // ★★★PART-EDGE FEATHER (seq1466). The prior is looked up PER PART, so two parts that MEET can be
589 // perturbed to DIFFERENT radii at their shared boundary and stop meeting -- the skin then shows a hard
590 // step. RENDERED AND CONFIRMED: at PROF=1000 layer 0 alone (not a layer-superposition artifact -- that
591 // hypothesis was tested and refuted) carries a collar at the neck, a waist band, a knee seam and a
592 // capped head, and PROF=0 is clean, so the prior introduces them.
593 // ★The canon's parts are built to meet EXACTLY; the prior only has to stop pulling them apart. Fading
594 // its influence to zero at each part's own data extremes preserves the join by construction while
595 // leaving the part's INTERIOR fully modulated, which is where the detail lives.
596 let edge: i64 = BG_PROFEDGE
597 var pmin: i64 = BG_PERMIL_SQ
598 var pmax: i64 = 0 - BG_PERMIL_SQ
599 while k < ns {
600 if sP[k] == part {
601 if sY[k] < pmin { pmin = sY[k] }
602 if sY[k] > pmax { pmax = sY[k] }
603 if sY[k] <= ymil { if lo < 0 { lo = k } else { if sY[k] > sY[lo] { lo = k } } }
604 if sY[k] >= ymil { if hi < 0 { hi = k } else { if sY[k] < sY[hi] { hi = k } } }
605 }
606 k = k+1
607 }
608 if lo < 0 { if hi < 0 { return 1000 } lo = hi }
609 if hi < 0 { hi = lo }
610 let a: i64 = bg_wrap(dq)
611 let fb: i64 = a*nb*1000/360
612 let b0: i64 = (fb/1000) % nb
613 let b1: i64 = (b0+1) % nb
614 let bm: i64 = (b0+nb-1) % nb
615 let b2: i64 = (b0+2) % nb
616 let ft: i64 = fb % 1000
617 // ★CIRCULAR CATMULL-ROM around the ring, not linear between bins. Linear interpolation of the prior puts
618 // a CREASE at every one of the 24 bin boundaries -- a normal discontinuity every ~2 vertices at radial 44
619 // -- and the detail judge punishes busy-where-the-oracle-is-smooth exactly as it punishes smooth-where-
620 // detailed, so a C0 prior scored WORSE than no prior at all (measured: detail 360 -> 333). A cubic through
621 // the same measured bins is C1 by construction. Same fix that removed the axial banding in the lofting.
622 let v0: i64 = bg_cmr(sR[lo*nb+bm], sR[lo*nb+b0], sR[lo*nb+b1], sR[lo*nb+b2], ft)/1000
623 let v1: i64 = bg_cmr(sR[hi*nb+bm], sR[hi*nb+b0], sR[hi*nb+b1], sR[hi*nb+b2], ft)/1000
624 var w: i64 = 0
625 if sY[hi] != sY[lo] { w = (ymil - sY[lo])*1000/(sY[hi]-sY[lo]) }
626 if w < 0 { w = 0 }
627 if w > 1000 { w = 1000 }
628 // ★★★THE RINGING, FIXED WITH THE FIX ALREADY IN THIS FUNCTION -- ONE AXIS OVER.
629 // The comment above records killing a CREASE AT EVERY BIN BOUNDARY in the THETA direction by replacing
630 // linear interpolation with a circular Catmull-Rom, because a C0 prior scored WORSE than no prior at
631 // all (360 -> 333). ***THE AXIAL BLEND WAS STILL LINEAR***, so the prior was C1 AROUND the body and C0
632 // ALONG it: the tangent jumps at EVERY one of the 156 profile rows, and at strong PROF those creases
633 // read as hard horizontal bands. RENDERED AND CONFIRMED at PROF=1000: a pronounced collar at the neck
634 // plus seams at waist and knees -- which is exactly the 'it rings the neck' the default-off rationale
635 // cited, and it was never a property of the DATA, only of how the data was blended.
636 // ★SMOOTHSTEP makes dw/dy vanish at w=0 and w=1, so both sides of every row meet with equal tangent =
637 // C1 across the row. Exact at the ends by construction: w=0 -> 0, w=1000 -> 1000, w=500 -> 500.
638 w = w*w*(BG_SMOOTHSTEP_3_PERMIL - 2*w)/BG_PERMIL_SQ
639 var v: i64 = (v0*(1000-w) + v1*w)/1000
640 if hf != 0 {
641 // subtract the profile's own smoothed shape -> keep ONLY what the smooth shape cannot explain
642 let s0: i64 = bg_prof_smooth(sR, lo, b0, nb)
643 let s1: i64 = bg_prof_smooth(sR, hi, b0, nb)
644 let sv: i64 = (s0*(1000-w) + s1*w)/1000
645 // hf is a FLAG here, not a scale -- the caller applies the scale. Using it as a per-mille multiplier
646 // made (v-sv)*1/1000 truncate to exactly ZERO, so the whole band was a silent no-op that still built
647 // and still benched identically. Match the units of every factor before believing a null result.
648 v = 1000 + (v - sv)
649 }
650 // ★APPLY THE EDGE FEATHER: within `edge` of this part's own data extremes, ramp the modulation back
651 // toward neutral so the part meets its neighbour exactly as the canon built it. Linear in distance is
652 // enough here because the endpoints are what must agree; the axial blend is already C1 (smoothstep).
653 if pmax > pmin {
654 var d: i64 = ymil - pmin
655 let d2: i64 = pmax - ymil
656 if d2 < d { d = d2 }
657 if d < 0 { d = 0 }
658 // ⚠FEATHER REMOVED FROM THE PATH 2026-07-30 (my first disable was WRONG and the bench caught it:
659 // writing (v-1000)*0/edge forces v=1000 near the extremes, which is the MAXIMUM feather, not none --
660 // it read headline 332, worse than both the feather 340 and the clean 354. Match the units of every
661 // factor before believing a null result -- this file says exactly that 40 lines down about hf.)
662 // ⚠DISABLED 2026-07-30: feather LOST ON BOTH INSTRUMENTS -- headline 354->340, detail_head 309->288 at PROF=1000, AND the render was visually UNCHANGED (same collar, waist band, knee seam). A change that loses the number AND shows nothing to the eye has no case. Kept as a zeroed term rather than deleted so the next diagnosis can see what was tried. THREE hypotheses now refuted BY LOOKING: axial C0 creasing (smoothstep helped numbers, changed nothing visible), layer superposition (layer 0 ALONE is identical), and this. STOP GUESSING: dump radius-vs-y at fixed theta for PROF 0 vs 1000, diff, and read off the exact stations where the step is.
663 }
664 if v > 1000+BG_PROFCLAMP { v = 1000+BG_PROFCLAMP }
665 if v < 1000-BG_PROFCLAMP { v = 1000-BG_PROFCLAMP }
666 return v
667}
668
669func main(argc: i64, argv: *i64) -> i64 {
670 let outp: *u8 = argv[1] as *u8
671 var H: i64 = BG_DEFAULT_STATURE_MM
672 if argc > 2 { H = bg_satoi(argv[2] as *u8) }
673 var RS: i64 = 28
674 if argc > 3 { RS = bg_satoi(argv[3] as *u8) }
675 var SUB: i64 = 4
676 if argc > 4 { SUB = bg_satoi(argv[4] as *u8) }
677 // relief amplitude scale, per-mille -- makes the anatomical surface relief a CONTROLLED VARIABLE
678 // measurable against the oracle, rather than a change assumed to help (1000 = as authored)
679 var RLF: i64 = 1000
680 if argc > 5 { RLF = bg_satoi(argv[5] as *u8) }
681 // ★SUBCUTANEOUS FAT (argv[7], per-mille): the layer between muscle and skin. It attenuates how much of
682 // the muscle definition reaches the SKIN surface -- lean (fat 0) shows the abs, heavy (fat high) smooths
683 // them -- so "abs hidden under fat" is EMERGENT from the layer stack, not a hack. Default lean-ish.
684 var FAT: i64 = 250
685 if argc > 7 { FAT = bg_satoi(argv[7] as *u8) }
686 // ★PROF (argv[8], per-mille): how much of the MEASURED section prior to apply. A CONTROLLED VARIABLE --
687 // 0 reproduces the pre-GX-31 elliptical body exactly, so the A/B is the same code path and any change in
688 // the bench is attributable to the profiles alone (the relief-scale knob earned this pattern in GX-24).
689 // ★DEFAULT OFF, and it stays off until the prior earns it: MEASURED, applying the section prior LOWERS
690 // the honest headline (361 -> 335) because it transfers low-frequency form while flattening the back,
691 // and it rings the neck. Shipping it on by default would have been a silent regression for every other
692 // caller. It stays available as an opt-in so the next rung can build on the measurement, not repeat it.
693 // ★★★DEFAULT 0 -> 250, EARNED 2026-07-30 BY BOTH INSTRUMENTS (seq1441/1448/1451). The rationale above
694 // was correct FOR THE BODY IT WAS WRITTEN AGAINST -- but that body measured 361 baseline and this one
695 // measures 319, so the emitter moved underneath the decision. Re-swept vs the cadaver oracle
696 // knowledge/skin.nxmesh (self_iou=self_shape=self_detail=1000 every run):
697 // PROF 0 -> headline 319 detail_head 155 shape 934
698 // PROF 250 -> headline 360 detail_head 164 shape 934 <-- INTERIOR OPTIMUM, +41, NO shape cost
699 // PROF 500 -> headline 343 detail_head 196 shape 934
700 // PROF 750 -> headline 338 detail_head 242 shape 923
701 // PROF 1000 -> headline 347 detail_head 289 shape 923
702 // ★★AND THE NECK RINGING IS REAL -- I RENDERED IT AND LOOKED, which is the half a bench cannot do.
703 // At PROF=1000 the body shows a pronounced COLLAR AT THE NECK plus hard seams at waist and knees and
704 // a bulbous seamed head: the original author's word 'rings' is exactly right, and their refusal to
705 // ship it on was CORRECT. At PROF=250 those artifacts are ABSENT and the render is INDISTINGUISHABLE
706 // from PROF=0 by eye, while scoring +41. ★So 250 is number-up AND eye-neutral; 1000 was number-up and
707 // eye-DOWN, which is the Goodhart this lane refuses. A rising number is not permission to ship -- a
708 // rising number WITH AN UNCHANGED EYE is.
709 // ⚠The ringing at high prior is an unfixed defect, not a reason to avoid the prior: fixing it is what
710 // would let the strong end of this curve (detail_head 289, +134) be taken. That is the next rung.
711 var PROF: i64 = 250
712 if argc > 8 { PROF = bg_satoi(argv[8] as *u8) }
713 // ★HF (argv[10], per-mille): apply only the measured HIGH-FREQUENCY residual. Independent of PROF so the
714 // two bands are never confounded -- the whole point of the four measurements that led here.
715 var HF: i64 = 0
716 if argc > 10 { HF = bg_satoi(argv[10] as *u8) }
717 // BAS (argv[11], per-mille): analytic shape-basis weight -- a controlled variable like every knob here
718 var BAS: i64 = 0
719 if argc > 11 { BAS = bg_satoi(argv[11] as *u8) }
720 // ★DEC (argv[12], per-mille): measured-prior vs authored-relief DECONFLICTION. Where a part carries
721 // measured prof rows, attenuate the AUTHORED relief by DEC so the two stop double-modulating the same
722 // radius (triangulated 2026-08-10: head-scale A/Bs 226/249/166 -- each prior helped exactly where its
723 // data was faithful and fought the hand relief elsewhere). DEC=0 -> byte-identical output.
724 var DEC: i64 = 0
725 if argc > 12 { DEC = bg_satoi(argv[12] as *u8) }
726 let sinT: *i64 = sys_mmap(400*8) as *i64
727 bg_sin_fill(sinT)
728
729 // ---- CONTROL RINGS, per-mille of stature: y, xoff, zoff, rx, rz ----
730 let ry: *i64 = sys_mmap(BG_MAXRING*8) as *i64
731 let rx0: *i64 = sys_mmap(BG_MAXRING*8) as *i64
732 let rz0: *i64 = sys_mmap(BG_MAXRING*8) as *i64
733 let ra: *i64 = sys_mmap(BG_MAXRING*8) as *i64
734 let rb: *i64 = sys_mmap(BG_MAXRING*8) as *i64
735 // three consecutive station rings (slot 1 = the station being normalled) -> TRUE surface normals
736 // by CENTRAL difference in both surface parameters
737 let sx: *i64 = sys_mmap(3*BG_MAXRS*8) as *i64
738 let sz: *i64 = sys_mmap(3*BG_MAXRS*8) as *i64
739 let sy: *i64 = sys_mmap(4*8) as *i64
740 let scx: *i64 = sys_mmap(4*8) as *i64
741 let scz: *i64 = sys_mmap(4*8) as *i64
742 // vertex rings: c = current station, pp = previous station (quads are emitted between them)
743 let cpx: *i64 = sys_mmap(BG_MAXRS*8) as *i64
744 let cpy: *i64 = sys_mmap(BG_MAXRS*8) as *i64
745 let cpz: *i64 = sys_mmap(BG_MAXRS*8) as *i64
746 let ppy: *i64 = sys_mmap(BG_MAXRS*8) as *i64
747 let cnx: *i64 = sys_mmap(BG_MAXRS*8) as *i64
748 let cny: *i64 = sys_mmap(BG_MAXRS*8) as *i64
749 let cnz: *i64 = sys_mmap(BG_MAXRS*8) as *i64
750 let ppx: *i64 = sys_mmap(BG_MAXRS*8) as *i64
751 let ppz: *i64 = sys_mmap(BG_MAXRS*8) as *i64
752 let pnx: *i64 = sys_mmap(BG_MAXRS*8) as *i64
753 let pny: *i64 = sys_mmap(BG_MAXRS*8) as *i64
754 let pnz: *i64 = sys_mmap(BG_MAXRS*8) as *i64
755 let pStart: *i64 = sys_mmap(BG_MAXPART*8) as *i64
756 let pCount: *i64 = sys_mmap(BG_MAXPART*8) as *i64
757 let pMirror: *i64 = sys_mmap(BG_MAXPART*8) as *i64
758 // ★PART PLACEMENT. Every part is authored in its own canonical frame as a tube stacked along +Y, then
759 // ROTATED about X and offset into place. Without this a part can only run vertically, which is why the
760 // foot had to be faked as two forward-stretched rings on the end of the leg tube (it read as a blunt
761 // cone, and the error map put the feet among the worst regions). A real foot runs FORWARD, so it is a
762 // Y-tube rotated 90 degrees. Same mechanism gives fingers and toes. Existing parts use rot=0, off=0
763 // and are bit-identical to before.
764 let pRot: *i64 = sys_mmap(BG_MAXPART*8) as *i64
765 let pOx: *i64 = sys_mmap(BG_MAXPART*8) as *i64
766 let pOy: *i64 = sys_mmap(BG_MAXPART*8) as *i64
767 let pOz: *i64 = sys_mmap(BG_MAXPART*8) as *i64
768 let pMat: *i64 = sys_mmap(BG_MAXPART*8) as *i64
769 let pRotZ: *i64 = sys_mmap(BG_MAXPART*8) as *i64
770 let pRotY: *i64 = sys_mmap(BG_MAXPART*8) as *i64
771 let tf3: *i64 = sys_mmap(64) as *i64
772 var pz: i64 = 0
773 while pz < BG_MAXPART { pRot[pz]=0; pOx[pz]=0; pOy[pz]=0; pOz[pz]=0; pMat[pz]=0; pRotZ[pz]=0; pRotY[pz]=0; pz=pz+1 }
774 var n: i64 = 0
775 var np: i64 = 0
776
777 // ---- LOAD THE CANON (DATA-DRIVEN: the emitter carries NO geometry literals; the anthropometric canon --
778 // every ring and every relief feature -- lives in a data file. A different archetype (male, female,
779 // anime, monster) is a different canon fed to the SAME emit algorithm, and the canon itself is produced
780 // by a PROCEDURAL generator, not typed by hand.) ----
781 let fP: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
782 let fY: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
783 let fYw: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
784 let fT: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
785 let fTw: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
786 let fA: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
787 var canonp: *u8 = "knowledge/canon_male.dat" as *u8
788 if argc > 6 { canonp = argv[6] as *u8 }
789 let clen: *i64 = sys_mmap(16) as *i64
790 let cbuf: *u8 = sys_read_file(canonp, clen)
791 // ★FIXED 2026-07-30: this literal had UNESCAPED QUOTES -- bg_hw("{"error":...") -- so nx_cc read
792 // `error` as a bare identifier and REFUSED the whole module. nx_body_gen, the emitter behind every
793 // body AND the skull mesh, was NOT BUILDABLE FROM ITS OWN SOURCE; the live binary predates the line.
794 // The file already had the right idiom 350 lines further down (\x22), it just was not used here.
795 if (cbuf as i64) == 0 { bg_hw("{\x22error\x22:\x22cannot read canon file\x22}\n" as *u8); return 3 }
796 let counts: *i64 = sys_mmap(32) as *i64
797 bg_parse_canon(cbuf, clen[0], ry,rx0,rz0,ra,rb, pStart,pCount,pMirror,pRot,pOx,pOy,pOz, pMat, pRotZ, pRotY, fP,fY,fYw,fT,fTw,fA, counts)
798 // ★OPENINGS (seq1387): parsed from the SAME buffer by its own walker, so bg_parse_canon's 24-arg
799 // signature and every caller of it stay untouched. Zero O rows => nopen[0]=0 => provably inert.
800 let oP: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
801 let oY: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
802 let oYw: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
803 let oT: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
804 let oTw: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
805 let nopen: *i64 = sys_mmap(16) as *i64
806 nopen[0] = 0
807 bg_parse_open(cbuf, clen[0], oP, oY, oYw, oT, oTw, nopen)
808 // ★SHAPE-BASIS CANON, loaded as DATA. Applies to every canon exactly as the hardcoded table did, so it
809 // is one file rather than a copy per canon. REFUSES if absent: a body emitted with no basis rows would
810 // be silently smooth-torsoed and browless, which reads as a rendering fault rather than a missing file.
811 let kP: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
812 let kYlo: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
813 let kYhi: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
814 let kTh: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
815 let kWk: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
816 let kW0: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
817 let kW1: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
818 let kW2: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
819 let kAmp: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
820 let kYk: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
821 let kP0: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
822 let kP1: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
823 let kP2: *i64 = sys_mmap(BG_MAXFEAT*8) as *i64
824 let nbasis: *i64 = sys_mmap(16) as *i64
825 nbasis[0] = 0
826 let blen: *i64 = sys_mmap(16) as *i64
827 let bbuf: *u8 = sys_read_file("knowledge/body_shape_basis.conf" as *u8, blen)
828 if (bbuf as i64) == 0 { bg_hw("{\x22error\x22:\x22cannot read knowledge/body_shape_basis.conf -- the shape-basis canon is REQUIRED; refusing to emit a featureless body\x22}\n" as *u8); return 7 }
829 bg_parse_basis(bbuf, blen[0], kP,kYlo,kYhi,kTh,kWk,kW0,kW1,kW2,kAmp,kYk,kP0,kP1,kP2, nbasis)
830 if nbasis[0] < 1 { bg_hw("{\x22error\x22:\x22body_shape_basis.conf declares no B rows -- refusing to emit a featureless body\x22}\n" as *u8); return 7 }
831 // ★LAYER PALETTE, read from L rows in the SAME buffer -- one file, one read, no second config path.
832 // REFUSES on an incomplete palette for the same reason the B rows do: a body emitted with an unpainted
833 // layer looks like a renderer fault, not a missing row, and would be debugged in the wrong organ.
834 let lyR: *i64 = sys_mmap(BG_NLAYER*8) as *i64
835 let lyG: *i64 = sys_mmap(BG_NLAYER*8) as *i64
836 let lyB: *i64 = sys_mmap(BG_NLAYER*8) as *i64
837 let nlay: *i64 = sys_mmap(16) as *i64
838 nlay[0] = 0
839 bg_parse_layers(bbuf, blen[0], lyR, lyG, lyB, nlay)
840 if nlay[0] < BG_NLAYER { bg_hw("{\x22error\x22:\x22body_shape_basis.conf must declare one L row per layer -- refusing to emit a body with an unpainted layer\x22}\n" as *u8); return 7 }
841 np = counts[0]; n = counts[1]; var nf: i64 = counts[2]
842
843 // ---- MEASURED SECTION PROFILES (optional: absent file -> ns 0 -> every lookup returns 1000) ----
844 let sP: *i64 = sys_mmap(BG_MAXPROF*8) as *i64
845 let sY: *i64 = sys_mmap(BG_MAXPROF*8) as *i64
846 let nbp: *i64 = sys_mmap(32) as *i64
847 nbp[0] = 0
848 nbp[2] = 0
849 var ns: i64 = 0
850 var profp: *u8 = "knowledge/profile_human.dat" as *u8
851 if argc > 9 { profp = argv[9] as *u8 }
852 let plen: *i64 = sys_mmap(16) as *i64
853 let pbuf: *u8 = sys_read_file(profp, plen)
854 // Qualification requires an explicit measured-region contract; diagnostics retain raw data.
855 if PROF > 0 {
856 if (pbuf as i64) == 0 { bg_hw("profile qualification: missing source\n" as *u8); return 5 }
857 let qi: *i64 = sys_mmap(40) as *i64
858 let qv: i64 = profile_contract_scan(pbuf, plen[0], qi)
859 if qv != 0 {
860 bg_hw("profile qualification refused: verdict=" as *u8); bg_pn(qv)
861 bg_hw(" ambiguous_stations=" as *u8); bg_pn(qi[1])
862 bg_hw(" first_y=" as *u8); bg_pn(qi[2])
863 bg_hw(" affected_parts=" as *u8); bg_pn(qi[3]); bg_hw("," as *u8); bg_pn(qi[4])
864 bg_hw(" required=profile-contract-v2 next=map source anatomical regions; retain source and diagnostic captures\n" as *u8)
865 return 5
866 }
867 }
868 // ★★★STRIDE DERIVED FROM THE PRIOR'S OWN DECLARED N (2026-08-23) -- the ceiling is REMOVED, not
869 // raised. BG_NBMAX=96 was a compile-time bound on how finely the measured prior could be carried,
870 // and it was the binding cap the moment PF_NB=48 was lifted in the producer the same day. Worse,
871 // a file declaring MORE bins was silently discarded whole (see bg_parse_prof). Sizing the array
872 // from the file's own N means the consumer can carry ANY resolution the producer can measure, and
873 // there is no number here for anyone to pick. BG_MAXPROF still bounds the ROW count (a different
874 // axis, still a cap, named for the census).
875 var nbdecl: i64 = 0
876 if (pbuf as i64) != 0 { nbdecl = bg_scan_nb(pbuf, plen[0]) }
877 var stride: i64 = nbdecl
878 if stride < 1 { stride = 1 }
879 let sR: *i64 = sys_mmap(BG_MAXPROF*stride*8) as *i64
880 if (pbuf as i64) != 0 { ns = bg_parse_prof(pbuf, plen[0], sP, sY, sR, nbp, stride) }
881 let nbins: i64 = nbp[0]
882 if nbins < 1 { ns = 0 }
883 // per-part prof coverage: which parts the measured prior actually speaks for (drives DEC)
884 let pcov: *i64 = sys_mmap(BG_MAXPART*8) as *i64
885 var pcf: i64 = 0
886 while pcf < ns { if sP[pcf] >= 0 { if sP[pcf] < BG_MAXPART { pcov[sP[pcf]] = 1 } } pcf = pcf + 1 }
887
888 // ---- emit ----
889 let tri: *i64 = sys_mmap(BG_MAXTRI*21*8) as *i64
890 // ★per-triangle MATERIAL colour (0-1000 each). Lets a feature (eyes) carry its OWN colour instead of the
891 // flat per-layer flesh -- the reason eyes were invisible skin-bumps. Written per tri at emit, read at write.
892 let tcR: *i64 = sys_mmap(BG_MAXTRI*8) as *i64
893 let tcG: *i64 = sys_mmap(BG_MAXTRI*8) as *i64
894 let tcB: *i64 = sys_mmap(BG_MAXTRI*8) as *i64
895 var nt: i64 = 0
896 // demand counter: every tri the geometry WANTED to emit, counted whether or not the cap admitted it.
897 // ntoff > nt is the truncation proof; mirrors the prof_rows_offered pattern below.
898 var ntoff: i64 = 0
899 let layCnt: *i64 = sys_mmap(BG_NLAYER*8) as *i64
900
901 // ★LAYER LOOP -- emit the body once per anatomical layer (bone, muscle, skin), nested inside each other.
902 var Lyr: i64 = 0
903 while Lyr < BG_NLAYER {
904 let lstart: i64 = nt
905 // per-layer radius scale + how much of the muscle relief this layer carries
906 // ★SKIN IS LAYER 0 so the renderer's skin shading (wrap-diffuse SSS + sheen, keyed on layer 0) lands
907 // on it; muscle=1, bone=2 sit inside. Intact z-buffers to the outermost (skin) regardless of order.
908 var rmul: i64 = 1000; var relmul: i64 = 1000
909 // ★COLOUR IS INDEXED, NOT LADDERED -- a new layer needs an L row in the canon, not a new branch
910 // here. rmul and relmul stay as branches deliberately: they are SHAPE, not palette (already-named
911 // consts plus a fat-derived value), and folding them into the same table would put two unrelated
912 // kinds of thing in one row.
913 var lcR: i64 = lyR[Lyr]; var lcG: i64 = lyG[Lyr]; var lcB: i64 = lyB[Lyr]
914 if Lyr == 0 { rmul = 1000; relmul = 1000 - FAT } // SKIN: relief attenuated by fat
915 if Lyr == 1 { rmul = BG_MUSCF; relmul = 1000 } // MUSCLE
916 if Lyr == 2 { rmul = BG_BONEF; relmul = 0 } // BONE
917 if relmul < 0 { relmul = 0 }
918 var p: i64 = 0
919 while p < np {
920 var side: i64 = 0
921 var nsides: i64 = 1
922 if pMirror[p] == 1 { nsides = 2 }
923 while side < nsides {
924 var sgn: i64 = 1
925 if side == 1 { sgn = 0-1 }
926 // ★ONE GLOBAL STATION INDEX. Normals are CENTRAL differences in BOTH surface parameters --
927 // across stations as well as around the ring -- so they are shared by the quads either side
928 // and vary continuously. The previous one-sided within-band difference made the vertical
929 // tilt CONSTANT per band and step at every boundary: true normals, but visible bandaging.
930 let maxst: i64 = (pCount[p]-1)*SUB
931 let prc: i64 = sinT[bg_wrap(pRot[p]+90)]
932 let prs: i64 = sinT[bg_wrap(pRot[p])]
933 // ★Z-rotation (F1084): applied BEFORE the X-rotation at every transform site. The MIRRORED side
934 // gets the NEGATED angle so a left feature is the true mirror of the right one (a brow that
935 // tilts up-and-out on the right must tilt up-and-out on the left too). rotZ=0 gives pzc=Q14,
936 // pzs=0, and x*Q14/Q14 is integer-exact, so unrotated parts are BIT-IDENTICAL by construction.
937 let pzc: i64 = sinT[bg_wrap(sgn*pRotZ[p]+90)]
938 let pzs: i64 = sinT[bg_wrap(sgn*pRotZ[p])]
939 // ★AZIMUTH IS NEGATED ON THE MIRRORED SIDE, exactly as rotZ is -- mirroring flips X, so a limb
940 // swept BACK on the right must sweep BACK on the left, not forward. rotX is deliberately NOT
941 // negated: a forward pitch stays forward on both sides. Getting this wrong yields a body whose
942 // two halves rotate opposite ways, which reads as a twist rather than as a mirror.
943 let pyc: i64 = sinT[bg_wrap(sgn*pRotY[p]+90)]
944 let pys: i64 = sinT[bg_wrap(sgn*pRotY[p])]
945 var st: i64 = 0
946 while st <= maxst {
947 // evaluate the station ring at st-1, st, st+1 (clamped at the caps) into slots 0,1,2
948 var q: i64 = 0
949 while q < 3 {
950 var stq: i64 = st + q - 1
951 if stq < 0 { stq = 0 }
952 if stq > maxst { stq = maxst }
953 var cq: i64 = stq/SUB
954 if cq > pCount[p]-2 { cq = pCount[p]-2 }
955 let j0: i64 = pStart[p]+cq
956 let j1: i64 = j0+1
957 let fq: i64 = (stq - cq*SUB)*1000/SUB
958 // ★SUB-UNIT SAMPLING. Every station coordinate is computed to BG_PSUB sub-units with ONE
959 // division, instead of rounding to raw units first. The old code rounded y to whole units
960 // before the central-difference tangent, so on a SMALL part (the head is ~1/8 the body)
961 // where dy/station is only a few units, the rounding made uy alternate 6,8,6,8 -> the
962 // vertical tilt oscillated -> horizontal BANDING (proven in the normal map, and immune to
963 // relief and to raising PSUB, because y never went through PSUB). yri etc are per-mille*1000.
964 // Catmull-Rom through the ring and its neighbours (clamped at part ends) -- see bg_cmr.
965 var jm: i64 = j0-1
966 if jm < pStart[p] { jm = pStart[p] }
967 var jp: i64 = j1+1
968 if jp > pStart[p]+pCount[p]-1 { jp = pStart[p]+pCount[p]-1 }
969 let yri: i64 = bg_cmr(ry[jm], ry[j0], ry[j1], ry[jp], fq)
970 let xri: i64 = sgn*bg_cmr(rx0[jm], rx0[j0], rx0[j1], rx0[jp], fq)
971 let zri: i64 = bg_cmr(rz0[jm], rz0[j0], rz0[j1], rz0[jp], fq)
972 var ari: i64 = bg_cmr(ra[jm], ra[j0], ra[j1], ra[jp], fq)
973 var bri: i64 = bg_cmr(rb[jm], rb[j0], rb[j1], rb[jp], fq)
974 if ari < 0 { ari = 0 } // cubic overshoot must never go negative
975 if bri < 0 { bri = 0 }
976 let ymq: i64 = yri/1000
977 let xqs: i64 = xri*H*BG_PSUB/BG_PERMIL_SQ
978 let zqs: i64 = zri*H*BG_PSUB/BG_PERMIL_SQ
979 sy[q] = yri*H*BG_PSUB/BG_PERMIL_SQ
980 scx[q] = xqs
981 scz[q] = zqs
982 let aqs: i64 = ari*rmul/1000*H*BG_PSUB/BG_PERMIL_SQ
983 let bqs: i64 = bri*rmul/1000*H*BG_PSUB/BG_PERMIL_SQ
984 var i: i64 = 0
985 while i < RS {
986 let dq: i64 = bg_wrap(i*360/RS)
987 let cw: i64 = sinT[bg_wrap(dq+90)]; let sw: i64 = sinT[dq]
988 // anatomical relief modulates the radius per ANGLE as well as height, so the
989 // surface carries real features instead of being an ellipse of revolution. relmul is
990 // the fraction of that relief THIS layer carries (bone 0, muscle full, skin fat-attenuated).
991 var relmul2: i64 = relmul
992 if DEC > 0 { if pcov[p] == 1 { relmul2 = relmul*(1000-DEC)/1000 } }
993 var rq: i64 = 1000 + bg_relief(p, ymq, dq, fP,fY,fYw,fT,fTw,fA, nf)*RLF/1000*relmul2/1000
994 if BAS != 0 { rq = rq + bg_shape_basis(p, ymq, dq, sinT, kP,kYlo,kYhi,kTh,kWk,kW0,kW1,kW2,kAmp,kYk,kP0,kP1,kP2, nbasis[0])*BAS/1000*relmul2/1000 }
995 // ★measured section prior. On a MIRRORED part the ring itself is not mirrored (only its
996 // centre offset is), so theta 0 stays +X and would put the limb's LATERAL profile on the
997 // medial side; flip the angle for side 1 so left and right are true mirrors.
998 if ns > 0 {
999 var pdq: i64 = dq
1000 if sgn < 0 { pdq = bg_wrap(180-dq) }
1001 if PROF != 0 {
1002 let pv: i64 = bg_prof(p, ymq, pdq, sP, sY, sR, ns, nbins, 0)
1003 rq = rq*(1000 + (pv-1000)*PROF/1000)/1000
1004 }
1005 if HF != 0 {
1006 let hv: i64 = bg_prof(p, ymq, pdq, sP, sY, sR, ns, nbins, 1)
1007 rq = rq*(1000 + (hv-1000)*HF/1000)/1000
1008 }
1009 }
1010 sx[q*BG_MAXRS+i] = xqs + (aqs*rq/1000)*cw/BG_Q14
1011 sz[q*BG_MAXRS+i] = zqs + (bqs*rq/1000)*sw/BG_Q14
1012 i = i+1
1013 }
1014 q = q+1
1015 }
1016 let uy: i64 = sy[2]-sy[0]
1017 var i: i64 = 0
1018 while i < RS {
1019 let ip: i64 = (i+1)%RS
1020 let im: i64 = (i+RS-1)%RS
1021 // dP/dtheta and dP/dstation, both central
1022 let vx: i64 = sx[BG_MAXRS+ip]-sx[BG_MAXRS+im]
1023 let vz: i64 = sz[BG_MAXRS+ip]-sz[BG_MAXRS+im]
1024 let ux: i64 = sx[2*BG_MAXRS+i]-sx[i]
1025 let uz: i64 = sz[2*BG_MAXRS+i]-sz[i]
1026 var enx: i64 = uy*vz
1027 var eny: i64 = uz*vx - ux*vz
1028 var enz: i64 = 0-uy*vx
1029 // keep the components squareable without throwing away the fine detail
1030 var mx: i64 = enx; if mx < 0 { mx = 0-mx }
1031 var m2: i64 = eny; if m2 < 0 { m2 = 0-m2 }
1032 if m2 > mx { mx = m2 }
1033 m2 = enz; if m2 < 0 { m2 = 0-m2 }
1034 if m2 > mx { mx = m2 }
1035 while mx > BG_NCAP { enx=enx/2; eny=eny/2; enz=enz/2; mx=mx/2 }
1036 // outward = agrees with the ring-centre-to-vertex direction (relief included)
1037 let ox: i64 = sx[BG_MAXRS+i]-scx[1]
1038 let oz: i64 = sz[BG_MAXRS+i]-scz[1]
1039 if (enx*ox + enz*oz) < 0 { enx = 0-enx; eny = 0-eny; enz = 0-enz }
1040 var enl: i64 = bg_isqrt(enx*enx + eny*eny + enz*enz)
1041 if enl < 1 { enl = 1 }
1042 var wnx: i64 = enx*BG_Q14/enl
1043 var wny: i64 = eny*BG_Q14/enl
1044 var wnz: i64 = enz*BG_Q14/enl
1045 var wpx: i64 = sx[BG_MAXRS+i]/BG_PSUB
1046 var wpy: i64 = sy[1]/BG_PSUB
1047 var wpz: i64 = sz[BG_MAXRS+i]/BG_PSUB
1048 // place the part: rotate about Z, then about X, then offset (see PART PLACEMENT above)
1049 bg_rot3(wpx,wpy,wpz, pzc,pzs,prc,prs,pyc,pys, tf3)
1050 wpx = tf3[0]; wpy = tf3[1]; wpz = tf3[2]
1051 wpy = wpy + pOy[p]*H/1000
1052 wpz = wpz + pOz[p]*H/1000
1053 wpx = wpx + sgn*pOx[p]*H/1000
1054 bg_rot3(wnx,wny,wnz, pzc,pzs,prc,prs,pyc,pys, tf3)
1055 wnx = tf3[0]; wny = tf3[1]; wnz = tf3[2]
1056 cnx[i] = wnx; cny[i] = wny; cnz[i] = wnz
1057 cpx[i] = wpx; cpy[i] = wpy; cpz[i] = wpz
1058 i = i+1
1059 }
1060 let cy: i64 = sy[1]/BG_PSUB
1061 // ★CAP THE TUBE ENDS. An open tube lets the camera see its own inner wall -- that was the
1062 // bright flat trapezoid at the crotch: the torso tube's open bottom, viewed from inside.
1063 // The cap faces along the tube AXIS (from the station-centre difference), so it works for
1064 // the arm and leg tubes too, whose parameter runs downward rather than up.
1065 var capend: i64 = 0
1066 if st == 0 { capend = 1 }
1067 if st == maxst { capend = 2 }
1068 if capend > 0 {
1069 var kx: i64 = scx[1]-scx[2]; var ky: i64 = sy[1]-sy[2]; var kz: i64 = scz[1]-scz[2]
1070 if capend == 2 { kx = scx[1]-scx[0]; ky = sy[1]-sy[0]; kz = scz[1]-scz[0] }
1071 var kl: i64 = bg_isqrt(kx*kx+ky*ky+kz*kz)
1072 if kl < 1 { kl = 1 }
1073 kx = kx*BG_Q14/kl; ky = ky*BG_Q14/kl; kz = kz*BG_Q14/kl
1074 // a station ring is planar in xz, so its face normal is purely +/-y: pick the winding
1075 // that agrees with the axis direction. Decided in the CANONICAL frame, before the
1076 // placement rotation -- a rotation preserves orientation, so the choice still holds.
1077 let kyc: i64 = ky
1078 bg_rot3(kx,ky,kz, pzc,pzs,prc,prs,pyc,pys, tf3)
1079 kx = tf3[0]; ky = tf3[1]; kz = tf3[2]
1080 var ccx: i64 = scx[1]/BG_PSUB
1081 var ccy: i64 = cy
1082 var ccz: i64 = scz[1]/BG_PSUB
1083 bg_rot3(ccx,ccy,ccz, pzc,pzs,prc,prs,pyc,pys, tf3)
1084 ccx = tf3[0]; ccy = tf3[1]; ccz = tf3[2]
1085 ccy = ccy + pOy[p]*H/1000
1086 ccz = ccz + pOz[p]*H/1000
1087 ccx = ccx + sgn*pOx[p]*H/1000
1088 var e2: i64 = 0
1089 while e2 < RS {
1090 var v0: i64 = (e2+1)%RS
1091 var v1: i64 = e2
1092 if kyc < 0 { v0 = e2; v1 = (e2+1)%RS }
1093 ntoff = ntoff + 1
1094 if nt < BG_MAXTRI-2 {
1095 let t3: i64 = nt*21
1096 tri[t3]=ccx; tri[t3+1]=ccy; tri[t3+2]=ccz
1097 tri[t3+3]=cpx[v0]; tri[t3+4]=cpy[v0]; tri[t3+5]=cpz[v0]
1098 tri[t3+6]=cpx[v1]; tri[t3+7]=cpy[v1]; tri[t3+8]=cpz[v1]
1099 tri[t3+9]=kx; tri[t3+10]=ky; tri[t3+11]=kz
1100 tri[t3+12]=kx; tri[t3+13]=ky; tri[t3+14]=kz
1101 tri[t3+15]=kx; tri[t3+16]=ky; tri[t3+17]=kz
1102 var cr3: i64 = lcR; var cg3: i64 = lcG; var cb3: i64 = lcB
1103 if pMat[p] >= 1 { if pMat[p] <= 4 { cr3 = 958; cg3 = 954; cb3 = 942 } } // eye cap = sclera
1104 tcR[nt]=cr3; tcG[nt]=cg3; tcB[nt]=cb3
1105 nt = nt+1
1106 }
1107 e2 = e2+1
1108 }
1109 }
1110 if st > 0 {
1111 var e: i64 = 0
1112 while e < RS {
1113 let ep: i64 = (e+1)%RS
1114 // per-quad material colour (flat per-layer, unless a feature material)
1115 var qr: i64 = lcR; var qg: i64 = lcG; var qb: i64 = lcB
1116 if pMat[p] >= 1 { if pMat[p] <= 4 { // EYE (material = iris colour 1..4)
1117 qr = 958; qg = 954; qb = 942 // sclera white
1118 var af: i64 = e*360/RS - 90; if af < 0 { af = 0-af } // 0 at the FRONT (+Z)
1119 var sf: i64 = st - maxst/2; if sf < 0 { sf = 0-sf }
1120 sf = sf*100/maxst // 0 at the eye equator
1121 if af < 34 { if sf < 17 {
1122 qr = 120; qg = 78; qb = 45 // 1 = brown (default)
1123 if pMat[p] == 2 { qr = 86; qg = 122; qb = 170 } // 2 = blue
1124 if pMat[p] == 3 { qr = 92; qg = 134; qb = 92 } // 3 = green
1125 if pMat[p] == 4 { qr = 150; qg = 116; qb = 66 } // 4 = amber/hazel
1126 }}
1127 if af < 14 { if sf < 7 { qr = 24; qg = 22; qb = 24 } } // pupil (near-black)
1128 }}
1129 if pMat[p] == 5 { // FACE (head): colour by region
1130 let ymil: i64 = cy*1000/H
1131 var af2: i64 = e*360/RS - 90; if af2 < 0 { af2 = 0-af2 } // 0 at the FRONT (+Z)
1132 // ★LIP PAINT RETIRED (F1093), same reasoning as the brow: the lips are now two
1133 // real Z-rotated parts with a genuine groove between them, and a colour band
1134 // calibrated for the HEAD's angular frame lands arbitrarily across them. The
1135 // mouth is now a shadow cast by anatomy, not a rectangle drawn on an ovoid.
1136 // ★BROW PAINT RETIRED (F1084 prereq 2). The brow is now a real Z-ROTATED PART, and
1137 // paint fights geometry: this band is calibrated for the HEAD's angular frame, so
1138 // on a small brow part it landed as black bars that read as goggles. A feature is
1139 // either geometry or paint; once it is geometry the paint is a lie on top of it.
1140 }
1141 // ★★THE OPENING TEST. Skipping the quad removes the surface OUTRIGHT -- this is the
1142 // thing a radius modulation structurally cannot do. Written as a flag rather than a
1143 // wrapping block so the brace structure is UNCHANGED (a stray brace here would be a
1144 // silent scoping change in the emitter's hottest loop).
1145 var emit: i64 = 1
1146 if nopen[0] > 0 { if bg_in_open(p, cy*1000/H, e*360/RS, oP,oY,oYw,oT,oTw, nopen[0]) == 1 { emit = 0 } }
1147 // an OPENING is intentional absence -- only cap refusal counts as truncation demand
1148 if emit == 1 { ntoff = ntoff + 2 }
1149 if nt >= BG_MAXTRI-2 { emit = 0 }
1150 if emit == 1 {
1151 let t1: i64 = nt*21
1152 tri[t1]=ppx[e]; tri[t1+1]=ppy[e]; tri[t1+2]=ppz[e]
1153 tri[t1+3]=cpx[e]; tri[t1+4]=cpy[e]; tri[t1+5]=cpz[e]
1154 tri[t1+6]=cpx[ep];tri[t1+7]=cpy[ep]; tri[t1+8]=cpz[ep]
1155 tri[t1+9]=pnx[e]; tri[t1+10]=pny[e]; tri[t1+11]=pnz[e]
1156 tri[t1+12]=cnx[e]; tri[t1+13]=cny[e]; tri[t1+14]=cnz[e]
1157 tri[t1+15]=cnx[ep];tri[t1+16]=cny[ep]; tri[t1+17]=cnz[ep]
1158 tcR[nt]=qr; tcG[nt]=qg; tcB[nt]=qb
1159 nt = nt+1
1160 let t2: i64 = nt*21
1161 tri[t2]=ppx[e]; tri[t2+1]=ppy[e]; tri[t2+2]=ppz[e]
1162 tri[t2+3]=cpx[ep]; tri[t2+4]=cpy[ep]; tri[t2+5]=cpz[ep]
1163 tri[t2+6]=ppx[ep]; tri[t2+7]=ppy[ep]; tri[t2+8]=ppz[ep]
1164 tri[t2+9]=pnx[e]; tri[t2+10]=pny[e]; tri[t2+11]=pnz[e]
1165 tri[t2+12]=cnx[ep]; tri[t2+13]=cny[ep]; tri[t2+14]=cnz[ep]
1166 tri[t2+15]=pnx[ep]; tri[t2+16]=pny[ep]; tri[t2+17]=pnz[ep]
1167 tcR[nt]=qr; tcG[nt]=qg; tcB[nt]=qb
1168 nt = nt+1
1169 }
1170 e = e+1
1171 }
1172 }
1173 var g: i64 = 0
1174 while g < RS {
1175 ppx[g]=cpx[g]; ppy[g]=cpy[g]; ppz[g]=cpz[g]
1176 pnx[g]=cnx[g]; pny[g]=cny[g]; pnz[g]=cnz[g]
1177 g = g+1
1178 }
1179 st = st+1
1180 }
1181 side = side+1
1182 }
1183 p = p+1
1184 }
1185 layCnt[Lyr] = nt - lstart
1186 Lyr = Lyr+1
1187 }
1188
1189 // (the head is now PART 4 above -- the ellipsoid-of-revolution cranium is gone, replaced by a ring-tube
1190 // that inherits true normals + the facial relief table + the crown cap, just like every other part.)
1191
1192 // ---- write NXMSH2 (3 LAYERS: bone, muscle, skin -- contiguous tri ranges) ----
1193 let hdr: i64 = 16 + BG_NLAYER*24
1194 let bytes: i64 = hdr + nt*84 + nt*4
1195 let buf: *u8 = sys_mmap(bytes + 64)
1196 buf[0]=78 as u8; buf[1]=88 as u8; buf[2]=77 as u8; buf[3]=83 as u8
1197 buf[4]=72 as u8; buf[5]=50 as u8; buf[6]=0 as u8; buf[7]=0 as u8
1198 bg_wr32(buf, 8, BG_NLAYER); bg_wr32(buf, 12, nt)
1199 // layer table: name[16] off4 cnt4, in emit order 0=bone 1=muscle 2=skin
1200 var lo: i64 = 0; var Lw: i64 = 0
1201 while Lw < BG_NLAYER {
1202 let lb: i64 = 16 + Lw*24
1203 var q: i64 = 0
1204 while q < 16 { buf[lb+q]=0 as u8; q=q+1 }
1205 if Lw==0 { buf[lb]=115 as u8; buf[lb+1]=107 as u8; buf[lb+2]=105 as u8; buf[lb+3]=110 as u8 } // "skin"
1206 if Lw==1 { buf[lb]=109 as u8; buf[lb+1]=117 as u8; buf[lb+2]=115 as u8; buf[lb+3]=99 as u8 } // "musc"
1207 if Lw==2 { buf[lb]=98 as u8; buf[lb+1]=111 as u8; buf[lb+2]=110 as u8; buf[lb+3]=101 as u8 } // "bone"
1208 bg_wr32(buf, lb+16, lo); bg_wr32(buf, lb+20, layCnt[Lw])
1209 lo = lo + layCnt[Lw]
1210 Lw = Lw+1
1211 }
1212 // per-tri geometry + per-TRIANGLE material colour (from the emit; carries feature colours like the eyes).
1213 let l0: i64 = layCnt[0]; let l1: i64 = layCnt[0]+layCnt[1]
1214 var t: i64 = 0
1215 while t < nt {
1216 let o: i64 = hdr + t*84
1217 var j: i64 = 0
1218 while j < 9 { bg_wr32(buf, o+j*4, bg_f32(tri[t*21+j], 1)); j=j+1 }
1219 while j < 18 { bg_wr32(buf, o+j*4, bg_f32(tri[t*21+j], BG_Q14)); j=j+1 }
1220 bg_wr32(buf, o+72, bg_f32(tcR[t], 1000)); bg_wr32(buf, o+76, bg_f32(tcG[t], 1000)); bg_wr32(buf, o+80, bg_f32(tcB[t], 1000))
1221 t = t+1
1222 }
1223 // per-tri layer id (0=skin, 1=muscle, 2=bone)
1224 var z: i64 = 0
1225 while z < nt {
1226 var lid: i64 = 2
1227 if z < l0 { lid = 0 } else { if z < l1 { lid = 1 } }
1228 bg_wr32(buf, hdr + nt*84 + z*4, lid); z=z+1
1229 }
1230 let fd: i64 = sys_openat_wr(outp, MODE_0644)
1231 sys_write(fd, buf, bytes)
1232 sys_close(fd)
1233
1234 bg_hw("{\x22organ\x22:\x22nx_body_gen\x22,\x22v\x22:2,\x22source\x22:\x22SOVEREIGN PROCEDURAL -- anthropometric canon, continuous ring profiles, no scanned asset\x22" as *u8)
1235 bg_hw(",\x22height\x22:" as *u8); bg_pn(H)
1236 bg_hw(",\x22parts\x22:" as *u8); bg_pn(np)
1237 bg_hw(",\x22control_rings\x22:" as *u8); bg_pn(n)
1238 bg_hw(",\x22radial\x22:" as *u8); bg_pn(RS)
1239 bg_hw(",\x22sub\x22:" as *u8); bg_pn(SUB)
1240 bg_hw(",\x22tris\x22:" as *u8); bg_pn(nt)
1241 bg_hw(",\x22tris_offered\x22:" as *u8); bg_pn(ntoff)
1242 // ★TRUNCATION MUST BE LOUD (F1083). The two raster guards silently STOP emitting at BG_MAXTRI, which is
1243 // the documented root of the \x22red face\x22 bug: the skin layer is emitted LAST, so a full budget drops the
1244 // head/hands and they render as the muscle layer underneath -- a wrong body with a clean exit code. Same
1245 // silent-failure class as the unguarded part array. Report the headroom always, and FAIL LOUD at the cap.
1246 bg_hw(",\x22tri_cap\x22:" as *u8); bg_pn(BG_MAXTRI)
1247 bg_hw(",\x22tri_headroom\x22:" as *u8); bg_pn(BG_MAXTRI - nt)
1248 var trunc: i64 = 0
1249 if nt >= BG_MAXTRI - 4 { trunc = 1 }
1250 if ntoff > nt { trunc = 1 } // demand-based: ANY refused tri marks the mesh truncated, not just a full budget
1251 bg_hw(",\x22truncated\x22:" as *u8); bg_pn(trunc)
1252 bg_hw(",\x22prof_rows\x22:" as *u8); bg_pn(ns)
1253 // ★OFFERED vs ACCEPTED. Equal = the whole file loaded. Greater = the cap ate rows and every number below
1254 // is measured on PARTIAL data -- publish it rather than let a truncated prior look like a measured one.
1255 bg_hw(",\x22prof_rows_offered\x22:" as *u8); bg_pn(nbp[1])
1256 var proftrunc: i64 = 0
1257 if nbp[1] > ns { proftrunc = 1 }
1258 bg_hw(",\x22prof_truncated\x22:" as *u8); bg_pn(proftrunc)
1259 bg_hw(",\x22prof_scale\x22:" as *u8); bg_pn(PROF)
1260 bg_hw(",\x22dec\x22:" as *u8); bg_pn(DEC)
1261 bg_hw("}\n" as *u8)
1262 return 0
1263}