nx_skullsdf_verified_candidate_t333.nx source
↩ module page · 2831 lines · 148845 B
1// nx_skullsdf.nx -- the skull as a FUSED SHELL WITH OPENINGS, built in the implicit path.
2//
3// ★WHY THIS EXISTS, from two render cycles of evidence rather than preference. nx_skullgen emits the
4// skull as seven LOFTED TUBES. Rendered, that is seven separate objects sharing a bounding box: the
5// nasal bones float clear of the face, the zygomatic arch is a rod passing through nothing, and the
6// braincase is a balloon with a jaw hanging near it. Moving the tubes closer helps a little and cannot
7// fix the class of problem, because A SKULL IS NOT A SET OF TUBES -- it is one continuous fused shell
8// with holes cut in it. Tubes cannot fuse and cannot have holes.
9//
10// ★THE IMPLICIT PATH DOES EXACTLY THOSE TWO THINGS AND WE ALREADY OWN IT: smooth-union joins bones into
11// one surface, subtraction cuts the orbits and the nasal aperture as real openings, and nx_isosurf's
12// surface_nets polygonizes the result into nx_trimesh. The plan reserved SDF for viscera on the grounds
13// that it cannot resolve an eyelash -- true, and irrelevant to bone, whose features are centimetres.
14// ⚠So this does NOT replace the loft path for skin. It claims the skull only.
15//
16// nx_skullsdf <out.nxmesh> [sex 0-1000] [robust 0-1000] [grid]
17// license_tier: ORIGINAL expect_exit: 0 No hw writes (Rule 26).
18import "nx_isosurf.nx"
19import "nx_itoa_lib.nx" // shared MSB-first emitter (zero-alloc)
20import "nx_memfloor.nx" // mf_admit: refuse an O(G^3) grid that would eat the host (2026-07-30 incident)
21import "nx_sdfprim_lib.nx" // the implicit primitives (ellipsoid, capsule, arch, plate, walled cylinder, ring): ONE family for every anatomy field
22import "nx_fieldfit_verified_candidate_t333.nx" // the fit machinery (two-sided region-balanced objective, coordinate descent, prefix fit file): ONE optimiser for every field
23const SS_MAGIC_2026: i64 = 2026
24const SS_MAGIC_1024: i64 = 1024
25const SS_MAGIC_8388608: i64 = 8388608
26const SS_MAGIC_8388607: i64 = 8388607
27const SS_MAGIC_40000: i64 = 40000
28
29const SS_G: i64 = 160 // grid cells per axis
30const SS_EXT: i64 = 120 // world half-extent in MILLIMETRES. A male skull is ~185mm long and
31 // ~145mm broad, so 260mm of grid covers it with no wasted resolution
32 // (the first version sampled 600mm and spent most of the grid on air)
33// ★THE PRIMITIVES ARE AUTHORED IN AN ARBITRARY ~90-UNIT SPACE, NOT MILLIMETRES. Assuming otherwise
34// produced a skull measuring 84x75x93mm against the reference's 151x209x215 -- roughly half scale and
35// wrongly proportioned. This factor maps the authored space onto real millimetres, and the three
36// reference dimensions are named so the gate can check the result against them instead of my eye.
37// Derived from the measurement, not guessed: at 1850 the emitted skull stood 348mm against a 209mm
38// reference, so the factor is 1850 x 209/348. Each correction here is now driven by the bbox the organ
39// prints, which is the whole reason that check exists.
40// ★IDENTITY. The field below is now authored in REAL MILLIMETRES against the reference's measured box,
41// so there is no unit-space to get wrong. The previous arbitrary ~90-unit space needed a fudge factor
42// that could correct overall size but never proportion -- the skull came out 176x256x210 where the
43// reference is 151x209x215: too tall AND too shallow, which no single multiplier can fix.
44const SS_SCALE: i64 = 1000
45const SS_REF_W: i64 = 151 // reference bounding box, mm, measured off BodyParts3D: x lateral
46const SS_REF_H: i64 = 215 // HEIGHT = the file's z extent (BodyParts3D is a floor-origin z-UP body frame)
47const SS_REF_D: i64 = 209 // DEPTH = the file's y extent (antero-posterior, face at -y). Until 2026-09-18 the two
48 // were swapped, because every reader below took the file as y-up: see ss_ref_map
49const SS_TOL: i64 = 25 // mm each dimension may differ before the build is called wrong
50const SS_Q: i64 = SP_Q // fixed point for the distance functions
51const SS_NQ: i64 = 4096 // the scale surface_nets emits gradient normals in (nx_isosurf.nx:68)
52const SS_ISO: i64 = 0
53const SS_BONE: i64 = 0xe8e0d8
54// ***REDISTANCE (argv[8]) -- REBUILD |grad f| = 1 ON THE SAMPLED GRID, the fix this file's own tissue
55// diagnosis names (see the DISABLED gradient-normalisation block): chained ss_smin leaves the field up
56// to 40 percent off a true SDF near the surface, so an iso-offset of depth d moves the skin by
57// d/|grad| instead of d (measured 3-6mm scatter), and dividing by |grad| downstream AMPLIFIES flat
58// cells (measured 62mm chins). The standard remedy is an eikonal pass over the grid we already build:
59// SEED every node adjacent to a zero crossing with its exact sub-cell distance to that crossing (so
60// the bone surface CANNOT move -- linear interpolation between two seeds reproduces the crossing at
61// exactly the raw field's own position), then FAST-SWEEP the upwind eikonal update in all 8 diagonal
62// orders until distances are true everywhere. The redistanced field is carried at SS_RDQ fixed point
63// so sub-cell seeds survive integer storage; surface_nets only ever interpolates zero crossings and
64// normalises gradients, so a uniformly scaled field polygonizes identically.
65// ADDITIVE: argv[8] absent or 0 leaves the old path byte-identical.
66const SS_RDQ: i64 = 256 // fixed-point units per millimetre in the redistanced field
67const SS_RD_INF: i64 = 76800 // 300mm x SS_RDQ -- farther than any point in the sampled box
68// ---- M2 SUB-MM RAW FIELD (debt 1786406737, 2026-08-12): the raw grid stored INTEGER-MILLIMETRE
69// distances, so every iso-crossing snapped to coarse fractions of a cell and the redistance seeds
70// inherited those mm crossings -- the onion-ring terraces that SURVIVE redistancing (proven 08-10:
71// "redistance seeds inherit the RAW field's integer-mm zero crossings; the only cure is fixed-point
72// evaluation of the primitive field itself"). The _q lanes below evaluate the SAME authored-mm
73// geometry but carry the RESULT at SS_FQ units per millimetre. SS_FQ == SS_RDQ so the raw and
74// redistanced grids share ONE fixed point and every ratio-based consumer (seed crossing t=af/(af+ag),
75// sign restore, surface_nets at SS_ISO=0) is scale-invariant by construction -- no downstream change.
76// The mm lane (ss_field/ss_field_p/ss_field_world) stays for the tuner/bench/grad verbs unchanged.
77const SS_FQ: i64 = SP_FQ
78const SS_RD_NEAR: i64 = 3 // near-band half-width, cells, for the printed |grad| A/B
79const SS_RD_LO: i64 = 800 // |grad| per-mille below this counts under (same bar as ss_grad)
80const SS_RD_HI: i64 = 1200 // |grad| per-mille above this counts over (same bar as ss_grad)
81static SS_REDIST: i64
82// ★★SMOOTH-UNION RADIUS -- AND WHY IT IS NOW ZERO. ss_smin subtracts h^2/(4k) from the result, so every
83// chained call pushes the field further negative. Chaining eleven of them means the value at a point
84// depends on how many bones are near it, and the result is NOT a distance field -- gradient magnitude
85// drifts far from 1. surface_nets places each vertex by LINEAR INTERPOLATION along a cell edge, which
86// assumes the field is locally linear in distance; feed it a distorted field and vertices land in
87// inconsistent places, giving a jagged self-intersecting shell that renders as speckle.
88// ★Plain min() is the exact union of two SDFs and cannot distort anything. It is also anatomically
89// right: bones meet at SUTURES, which are sharp, not blended.
90// Restored to a real millimetre blend. At 0 (plain union) the mandible and face floated as separate
91// lumps with visible seams; bones do meet at sutures, but a 6mm blend at 2mm sampling is what makes
92// adjacent masses read as ONE bone rather than a pile of touching balls.
93// ★2026-08-10: default 6 -> 3, the value every measured run shipped with today (redistancing repairs
94// the field distortion smin causes, so the old reason to hold 6 is gone; 3 keeps fusion w/ sharper form)
95const SS_K: i64 = 3
96// ***SS_K IS NOW RUNTIME-SETTABLE (argv[7]) SO THE SMOOTH-UNION/DISTANCE-FIDELITY TRADE CAN BE A/B'd
97// WITHOUT A REBUILD. This file already records setting K to ZERO once, for exactly the reason that
98// matters here -- plain min() is the EXACT union of two SDFs and cannot distort anything, whereas every
99// chained ss_smin subtracts h*h/(4k) and pushes the field away from a true distance function. K=0 gives
100// honest distances with visible sutures; K=6 gives one fused shell with a distorted field. Until now that
101// trade was a recompile, so nobody measured it. Default is unchanged, so every existing caller is
102// byte-identical.
103static SS_KSET: i64
104static SS_KVAL: i64
105func ss_k() -> i64 { if SS_KSET == 1 { return SS_KVAL } return SS_K }
106
107func ss_puts(s: *u8) -> i64 { var n: i64=0; while s[n]!=(0 as u8){n=n+1} sys_write(1,s,n); return 0 }
108// MIGRATED to nxi_out (debt 1785563586). The old body mmapped 32 bytes per call and never freed it,
109// across 33 call sites. THIS ORGAN ALREADY IMPORTS nx_memfloor mf_admit after the 2026-07-30
110// incident where it took 27.7GB of 36GB and froze every seat -- the GUARD was added, the CAUSE
111// was not. nxi_out is MSB-first, allocates NOTHING, and emits identical bytes including the sign.
112func ss_pn(v: i64) -> i64 { nxi_out(v); return 0 }
113func ss_atoi(s: *u8) -> i64 {
114 var i: i64=0; var n: i64=0; var sg: i64=1
115 if s[0]==(45 as u8) { sg=0-1; i=1 }
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 }
117 return n*sg
118}
119func ss_streq(a: *u8, b: *u8) -> i64 {
120 var i: i64=0; var go: i64=1; var eq: i64=1
121 while go==1 { if a[i]!=b[i] { eq=0; go=0 } else { if a[i]==(0 as u8) { go=0 } else { i=i+1 } } }
122 return eq
123}
124func ss_isqrt(v: i64) -> i64 { return sp_isqrt(v) }
125func ss_abs(v: i64) -> i64 { if v<0 { return 0-v } return v }
126func ss_min(a: i64, b: i64) -> i64 { if a<b { return a } return b }
127func ss_max(a: i64, b: i64) -> i64 { if a>b { return a } return b }
128
129// ---- primitives. All return a signed distance in world units: negative inside.
130// An ellipsoid's exact SDF has no closed form; the standard cheap bound (scaled radial distance times
131// the smallest semi-axis) is used, which is what every SDF modeller uses and is accurate near the
132// surface -- the only place the polygonizer looks.
133// ★★TRUE ELLIPSOID DISTANCE, not a radial bound. The previous version returned
134// (radial-1) x smallest-semi-axis, which is only correct on a sphere and drifts badly off-axis. Alone
135// that is invisible; SMOOTH-UNIONED a dozen times it produced grid-scale ripples in the field, and
136// surface nets faithfully polygonized the ripples into a lumpy self-intersecting shell that z-fought
137// against itself. ★The error was in the PRIMITIVE and only became visible under COMPOSITION.
138// This is the standard first-order approximation d = k0(k0-1)/k1, exact on a sphere and accurate near
139// the surface of an ellipsoid -- which is the only region the polygonizer samples.
140// integer Bhaskara sine: degrees in, per-mille out; exact at 0/90/180, <2 permil error between.
141// The estate's emitter already carries one for the body; the field needs its own because a
142// STRUCTURED primitive places instances around an arc and a table lookup cannot be tuned smoothly.
143// ---- rule-11 named constants: each is a DOMAIN FACT, not a dial (2026-08-14) ----
144// Bhaskara I's 7th-century sine approximation: sin(x) ~ 4x(180-x) / (40500 - x(180-x)).
145// The numerator's 4 is scaled by 1000 so the result is PER-MILLE, matching ss_isin's contract
146// above; 40500 = 5 * 90^2 belongs to the closed form itself and is not tunable.
147const SS_BHASKARA_NUM_PERMILLE: i64 = 4000
148const SS_BHASKARA_DEN: i64 = 40500
149// Trilinear interpolation carries fractions as 0..SS_LERP_ONE (Q10 fixed point).
150const SS_LERP_ONE: i64 = 1024
151// Per-mille denominator. A UNIT, not a dial: sexf/robust arrive as 0..1000 and the policy is the
152// NUMERATOR (`3*sexf/SS_PERMILLE` says three per-mille per unit of sex). Hoisted ONLY at the 23
153// sites proven by enumeration to be divisors -- 47 of the 70 occurrences of 1000 are NOT (spans,
154// coordinates, argv), and folding those in would move the skull, not rename a unit.
155const SS_PERMILLE: i64 = 1000
156// Min/max accumulators start at +/- this and are replaced by the first real sample. A
157// SENTINEL, not a limit -- no value is ever clamped to it.
158const SS_EXTENT_SENTINEL: i64 = 999999
159// |grad SDF| must be ~1000 per-mille (unit) for a true signed-distance field; the probe counts
160// samples outside a +/-20% band around unit. LO and HI are ONE fact in two halves -- nx_magic's
161// 1024 threshold flags only HI, so naming HI alone would leave the pair half-told.
162const SS_GRAD_BAND_LO: i64 = 800
163const SS_GRAD_BAND_HI: i64 = 1200
164// Marching-cubes cell budget: the argv[7] default and the floor it is clamped up to.
165const SS_MARCH_CELLS_DEFAULT: i64 = 2000
166const SS_MARCH_CELLS_MIN: i64 = 1000
167// ---- THE SKULL FIELD. Every dimension is a function of the sex/robusticity knobs, as in nx_skullgen;
168// the difference is purely that these compose by union and subtraction instead of standing apart.
169// ★AUTHORED IN MILLIMETRES, in a frame centred on the cranium: +y up, +z forward (toward the face),
170// x lateral. Every figure is a real skull dimension, so the emitted bounding box can be compared
171// directly against the reference's 151 x 209 x 215 instead of through a fudge factor.
172// ★★THE SKULL AS A PARAMETER VECTOR. Hand-placing coordinates got the bounding box to 5mm and left the
173// SHAPE at 8mm mean error, because a person adjusting numbers by eye cannot search twenty dimensions.
174// Exposing the dimensions as data lets the fit metric DRIVE them instead: `tune` runs coordinate
175// descent against the real scanned reference and keeps only changes that lower the measured error.
176const SP_N: i64 = 87
177const SS_FIT_MIN: i64 = 58 // the v1 vector length: a fit file carrying at least this many ints
178 // applies as a PREFIX (structured params added later keep their
179 // defaults until the next tune saves the full vector) -- growing the
180 // parametrization must never discard banked convergence
181const P_VW: i64 = 0 // vault half-width
182const P_VH: i64 = 1 // vault half-height
183const P_VD: i64 = 2 // vault half-depth
184const P_VY: i64 = 3 // vault centre y
185const P_VZ: i64 = 4 // vault centre z
186const P_FY: i64 = 5 // frontal centre y
187const P_FZ: i64 = 6 // frontal centre z
188const P_FH: i64 = 7 // frontal half-height
189const P_FD: i64 = 8 // frontal half-depth
190const P_MY: i64 = 9 // maxilla centre y
191const P_MZ: i64 = 10 // maxilla centre z
192const P_MW: i64 = 11 // maxilla half-width
193const P_MH: i64 = 12 // maxilla half-height
194const P_MD: i64 = 13 // maxilla half-depth
195const P_JY: i64 = 14 // mandible chin y
196const P_JZ: i64 = 15 // mandible chin z
197const P_RX: i64 = 16 // ramus x offset
198const P_RY: i64 = 17 // ramus centre y
199const P_OR: i64 = 18 // orbit radius
200const P_OX: i64 = 19 // orbit centre x
201// ***THE REST OF THE SKULL'S STATIONS, PARAMETERISED (2026-08-09, operator: "the tooling should be
202// able to see pixel by pixel why our emitter is emitting shit compared to the benchmark and get us
203// to pixel to pixel emission -- not manual"). Coordinate descent can only move what is a parameter;
204// everything below was a frozen literal, which is why the measured-wrong stations (orbit depth,
205// nasal position, arch endpoints) could never converge no matter how good the objective was.
206const P_BX: i64 = 20 // brow bar half-span
207const P_BY: i64 = 21 // brow bar y
208const P_BZ: i64 = 22 // brow bar z
209const P_ZAX: i64 = 23 // zygomatic arch face-end x
210const P_ZAY: i64 = 24 // zygomatic arch face-end y
211const P_ZAZ: i64 = 25 // zygomatic arch face-end z
212const P_ZBX: i64 = 26 // zygomatic arch ear-end x
213const P_ZBY: i64 = 27 // zygomatic arch ear-end y
214const P_ZBZ: i64 = 28 // zygomatic arch ear-end z
215const P_ZR: i64 = 29 // zygomatic arch radius
216const P_NY: i64 = 30 // nasal bones centre y
217const P_NZ: i64 = 31 // nasal bones centre z
218const P_NRX: i64 = 32 // nasal radius x
219const P_NRY: i64 = 33 // nasal radius y
220const P_NRZ: i64 = 34 // nasal radius z
221const P_JAX: i64 = 35 // jaw body chin-end x
222const P_JAZ: i64 = 36 // jaw body chin-end z offset from P_JZ
223const P_JBX: i64 = 37 // jaw body angle-end x
224const P_JBY: i64 = 38 // jaw body angle-end y offset from P_JY
225const P_JBZ: i64 = 39 // jaw body angle-end z
226const P_JR: i64 = 40 // jaw body radius
227const P_RZ: i64 = 41 // ramus centre z
228const P_RRX: i64 = 42 // ramus radius x
229const P_RRY: i64 = 43 // ramus radius y
230const P_RRZ: i64 = 44 // ramus radius z
231const P_OAY: i64 = 45 // orbit opening y
232const P_OAZ: i64 = 46 // orbit opening z
233const P_OBX: i64 = 47 // orbit apex x
234const P_OBY: i64 = 48 // orbit apex y
235const P_OBZ: i64 = 49 // orbit apex z
236const P_PAY: i64 = 50 // nasal aperture opening y
237const P_PAZ: i64 = 51 // nasal aperture opening z
238const P_PBY: i64 = 52 // nasal aperture back y
239const P_PBZ: i64 = 53 // nasal aperture back z
240const P_PR: i64 = 54 // nasal aperture radius
241const P_CRX: i64 = 55 // chin ellipsoid radius x
242const P_CRY: i64 = 56 // chin ellipsoid radius y
243const P_CRZ: i64 = 57 // chin ellipsoid radius z
244// ***THE FIRST STRUCTURED PRIMITIVE: A REPEATED ELEMENT ALONG A CURVE (operator 2026-08-09: "you
245// cant even make teeth in a jaw... how are you going to emit a tree"). A flat list of blobs cannot
246// express teeth; ~9 knobs per ARCH drive N instances of one tooth rule along an elliptical arc.
247// This construct IS the seed of tree emission: a tree is elements-along-a-curve RECURSED.
248const P_UY: i64 = 58 // upper arch: occlusal centre y
249const P_UZ: i64 = 59 // upper arch: arc centre z
250const P_UAX: i64 = 60 // upper arch: lateral semi-axis
251const P_UAZ: i64 = 61 // upper arch: anterior semi-axis
252const P_UTH: i64 = 62 // upper arch: half arc span, degrees
253const P_UN: i64 = 63 // upper arch: tooth count
254const P_UTW: i64 = 64 // upper arch: tooth width
255const P_UTHT: i64 = 65 // upper arch: tooth height
256const P_UPR: i64 = 66 // upper arch: molar widening, permil at the arc ends
257const P_LY: i64 = 67 // lower arch: occlusal centre y
258const P_LZ: i64 = 68 // lower arch: arc centre z
259const P_LAX: i64 = 69 // lower arch: lateral semi-axis
260const P_LAZ: i64 = 70 // lower arch: anterior semi-axis
261const P_LTH: i64 = 71 // lower arch: half arc span, degrees
262const P_LN: i64 = 72 // lower arch: tooth count
263const P_LTW: i64 = 73 // lower arch: tooth width
264const P_LTHT: i64 = 74 // lower arch: tooth height
265const P_LPR: i64 = 75 // lower arch: molar widening, permil at the arc ends
266// ---- AN17 primitive rungs (2026-09-19): the openings as SHAPES the ruler can read, appended so a 76-int fit file still
267// loads as a prefix. RETIRED stations (kept in the vector for file compatibility, skipped by the tuner, unread by the
268// field): P_OR P_OBX P_OBY P_OBZ (the orbit was a drilled capsule to an apex), P_PBY P_PBZ P_PR (the aperture was a
269// capsule tunnel), P_NRZ (the nasal bones are a plate with P_NTH), P_JAX (the body is one arc through the chin),
270// P_RX P_RY P_RZ P_RRY (the ramus stands between the body's angle and the arch's ear end, derived, never placed).
271const P_OSW: i64 = 76 // orbit socket semi-width x (the rim's lateral half-span)
272const P_OSH: i64 = 77 // orbit socket semi-height y
273const P_OSD: i64 = 78 // orbit socket semi-depth z (the back wall sits at P_OCZ - P_OSD, inside the bone)
274const P_OCZ: i64 = 79 // orbit socket centre z; the front pokes through the face at P_OCZ + P_OSD
275const P_PAW: i64 = 80 // piriform aperture width (rim to rim)
276const P_PAH: i64 = 81 // piriform aperture height (rhinion to nasospinale)
277const P_PAD: i64 = 82 // piriform aperture depth: the nasal floor wall sits P_PAD behind the rim at P_PAZ
278const P_NTILT: i64 = 83 // nasal plate pitch, degrees: the rhinion end forward of the nasion end
279const P_NTH: i64 = 84 // nasal plate half-thickness
280const P_AAR: i64 = 85 // alveolar process radius: the U-arch of bone the upper teeth stand in
281const P_FPR: i64 = 86 // maxillary frontal process radius (the bone either side of the aperture, up to the orbits)
282// also RETIRED: P_PAY P_PAZ -- the aperture hangs from the nasal plate's lower edge (the rhinion), derived in the field
283// the tuner's population: 1 for a station the field reads, 0 for a retired one (an evaluation spent on a dead
284// parameter is a pass that cannot move anything)
285func ss_param_live(k: i64) -> i64 {
286 if k == P_PAY { return 0 }
287 if k == P_PAZ { return 0 }
288 if k == P_OR { return 0 }
289 if k == P_OBX { return 0 }
290 if k == P_OBY { return 0 }
291 if k == P_OBZ { return 0 }
292 if k == P_PBY { return 0 }
293 if k == P_PBZ { return 0 }
294 if k == P_PR { return 0 }
295 if k == P_NRZ { return 0 }
296 if k == P_JAX { return 0 }
297 if k == P_RX { return 0 }
298 if k == P_RY { return 0 }
299 if k == P_RZ { return 0 }
300 if k == P_RRY { return 0 }
301 return 1
302}
303// ★FITTED, NOT TYPED. These are the output of `tune` -- coordinate descent against the 171k-triangle
304// scanned reference, which took the mean surface error from 8.37mm to 5.06mm in one run. Every value
305// here was accepted only because it LOWERED a measured number, which is the opposite of how the
306// previous eight rounds of hand-placed coordinates were chosen.
307func ss_defaults(P: *i64) -> i64 {
308 P[P_VW]=81; P[P_VH]=71; P[P_VD]=75; P[P_VY]=24; P[P_VZ]=0-33
309 P[P_FY]=46; P[P_FZ]=15; P[P_FH]=34; P[P_FD]=33
310 P[P_MY]=0-45; P[P_MZ]=58; P[P_MW]=30; P[P_MH]=13; P[P_MD]=53
311 P[P_JY]=0-78; P[P_JZ]=60; P[P_RX]=57; P[P_RY]=0-46
312 P[P_OR]=8; P[P_OX]=30
313 // every remaining primitive station, extracted verbatim from the field's former literals so the
314 // TUNER can reach them -- the orbit stations, nasal position and arch endpoints were frozen
315 // literals no optimizer could move, which is why the gamed 8mm orbit could never recover
316 P[P_BX]=52; P[P_BY]=22; P[P_BZ]=62
317 P[P_ZAX]=52; P[P_ZAY]=6; P[P_ZAZ]=52; P[P_ZBX]=62; P[P_ZBY]=8; P[P_ZBZ]=0-30; P[P_ZR]=7
318 P[P_NY]=8; P[P_NZ]=76; P[P_NRX]=9; P[P_NRY]=18; P[P_NRZ]=12
319 P[P_JAX]=22; P[P_JAZ]=0-4; P[P_JBX]=46; P[P_JBY]=10; P[P_JBZ]=10; P[P_JR]=17
320 P[P_RZ]=0-6; P[P_RRX]=9; P[P_RRY]=34; P[P_RRZ]=26
321 P[P_OAY]=18; P[P_OAZ]=80; P[P_OBX]=20; P[P_OBY]=12; P[P_OBZ]=18
322 P[P_PAY]=0-8; P[P_PAZ]=92; P[P_PBY]=0-2; P[P_PBZ]=40; P[P_PR]=13
323 P[P_CRX]=26; P[P_CRY]=18; P[P_CRZ]=22
324 // DENTAL ARCHES: placement DERIVES from the parent bones (never type a placement the parent
325 // already knows -- the maxilla and jaw rows above are the parents); the structural dims (arch
326 // radii, tooth size/count, published human dental anatomy) are STARTING values the tuner owns.
327 P[P_UY]=P[P_MY]-24; P[P_UZ]=P[P_MZ]-10; P[P_UAX]=26; P[P_UAZ]=30
328 P[P_UTH]=75; P[P_UN]=14; P[P_UTW]=9; P[P_UTHT]=11; P[P_UPR]=400
329 P[P_LY]=P[P_JY]+16; P[P_LZ]=P[P_JZ]-12; P[P_LAX]=25; P[P_LAZ]=28
330 P[P_LTH]=75; P[P_LN]=14; P[P_LTW]=9; P[P_LTHT]=11; P[P_LPR]=400
331 // AN17 primitive rungs: the openings START at the oracle's own ruler readings (nx_skull_canon_gate, 2026-09-18, mm:
332 // aperture 23.1 wide, 22.4 high, 10.7 deep; orbit width 28.3) and the tuner owns them from there
333 P[P_OSW]=16; P[P_OSH]=14; P[P_OSD]=22; P[P_OCZ]=P[P_OAZ]-8
334 P[P_PAW]=23; P[P_PAH]=22; P[P_PAD]=11
335 P[P_NTILT]=25; P[P_NTH]=3; P[P_AAR]=8; P[P_FPR]=6
336 return 0
337}
338
339// the millimetre lane is the SS_FQ lane divided down: ONE definition of the skull's geometry (until 2026-09-19 the two
340// lanes carried the same twenty-two primitives twice, and a primitive changed in one and not the other is half a skull)
341func ss_field_p(px: i64, py: i64, pz: i64, sexf: i64, robust: i64, P: *i64) -> i64 {
342 return ss_field_p_q(px, py, pz, sexf, robust, P)/SS_FQ
343}
344// ss_field_p at SS_FQ output: same geometry, same composition order, sub-mm result. ss_smin/ss_sub
345// are scale-invariant so only the primitive outputs and the smoothing radius change units.
346func ss_field_p_q(px: i64, py: i64, pz: i64, sexf: i64, robust: i64, P: *i64) -> i64 {
347 let vw: i64 = P[P_VW] - 3*sexf/SS_PERMILLE
348 let vh: i64 = P[P_VH] - 2*sexf/SS_PERMILLE
349 let vd: i64 = P[P_VD] - 2*sexf/SS_PERMILLE
350 let brow: i64 = 10 - 3*sexf/SS_PERMILLE + 5*robust/SS_PERMILLE
351 let kq: i64 = ss_k()*SS_FQ
352 var d: i64 = sp_ellipsoid_q(px,py,pz, 0, P[P_VY], P[P_VZ], vw, vh, vd)
353 d = sp_smin(d, sp_ellipsoid_q(px,py,pz, 0, P[P_FY], P[P_FZ], vw*78/100, P[P_FH], P[P_FD]), kq)
354 d = sp_smin(d, sp_capsule_q(px,py,pz, 0-P[P_BX],P[P_BY],P[P_BZ], P[P_BX],P[P_BY],P[P_BZ], brow), kq)
355 d = sp_smin(d, sp_ellipsoid_q(px,py,pz, 0, P[P_MY], P[P_MZ], P[P_MW], P[P_MH], P[P_MD]), kq)
356 // (d) the alveolar process: a U-arch of bone standing on the upper dental arc; its front at the midline is the prosthion
357 d = sp_smin(d, sp_arch_q(px,py,pz, P[P_UY]+P[P_UTHT]/2+P[P_AAR]*2/3, P[P_UZ], P[P_UAX], P[P_UAZ], P[P_UTH], 0, P[P_AAR]), kq)
358 d = sp_smin(d, sp_ring_q(px,py,pz, P[P_UY], P[P_UZ], P[P_UAX], P[P_UAZ], P[P_UTH], P[P_UN], P[P_UTW], P[P_UTHT], P[P_UPR]), kq)
359 d = sp_smin(d, sp_ring_q(px,py,pz, P[P_LY], P[P_LZ], P[P_LAX], P[P_LAZ], P[P_LTH], P[P_LN], P[P_LTW], P[P_LTHT], P[P_LPR]), kq)
360 d = sp_smin(d, sp_capsule_q(px,py,pz, 0-P[P_ZAX],P[P_ZAY],P[P_ZAZ], 0-P[P_ZBX],P[P_ZBY],P[P_ZBZ], P[P_ZR]), kq)
361 d = sp_smin(d, sp_capsule_q(px,py,pz, P[P_ZAX],P[P_ZAY],P[P_ZAZ], P[P_ZBX],P[P_ZBY],P[P_ZBZ], P[P_ZR]), kq)
362 // (c) the nasal bones as a pitched PLATE from the nasion down and forward to the rhinion, never a peg
363 d = sp_smin(d, sp_ellipsoid_tiltx_q(px,py,pz, 0, P[P_NY], P[P_NZ], P[P_NRX], P[P_NRY], P[P_NTH], P[P_NTILT]), kq)
364 d = sp_smin(d, sp_ellipsoid_q(px,py,pz, 0, P[P_JY], P[P_JZ], P[P_CRX], P[P_CRY], P[P_CRZ]), kq)
365 // (e) the mandibular body as ONE arc from angle to angle through the chin, rising P_JBY toward the angles
366 d = sp_smin(d, sp_arch_q(px,py,pz, P[P_JY], P[P_JBZ], P[P_JBX], P[P_JZ]+P[P_JAZ]-P[P_JBZ], 90, P[P_JBY], P[P_JR]), kq)
367 // the ramus stands between the body's angle end and the arch's ear end (the condyle under the arch root): DERIVED
368 // from the two structures it joins, so the angle and the condyle cannot drift apart
369 let cdy: i64 = P[P_ZBY] - 2*P[P_ZR]
370 let rcy: i64 = (P[P_JY]+P[P_JBY] + cdy)/2
371 let rcz: i64 = (P[P_JBZ] + P[P_ZBZ])/2
372 let rcx: i64 = (P[P_JBX] + P[P_ZBX])/2
373 var rhy: i64 = (cdy - (P[P_JY]+P[P_JBY]))/2 + P[P_RRX]
374 if rhy < P[P_RRX] { rhy = P[P_RRX] }
375 d = sp_smin(d, sp_ellipsoid_q(px,py,pz, 0-rcx, rcy, rcz, P[P_RRX], rhy, P[P_RRZ]), kq)
376 d = sp_smin(d, sp_ellipsoid_q(px,py,pz, rcx, rcy, rcz, P[P_RRX], rhy, P[P_RRZ]), kq)
377 // the rhinion: the nasal plate's lower edge, where the aperture's top rim is by definition. The aperture is placed
378 // FROM it (a typed aperture station drifted 20 mm in front of the bone the moment the peg became a plate: an
379 // opening carved into air is not an opening)
380 let nts: i64 = sp_isin(P[P_NTILT])
381 let ntc: i64 = sp_icos(P[P_NTILT])
382 let yrh: i64 = P[P_NY] - P[P_NRY]*ntc/SS_PERMILLE
383 let zrh: i64 = P[P_NZ] + P[P_NRY]*nts/SS_PERMILLE
384 // the maxilla's FRONTAL PROCESSES: the bone either side of the aperture, rising from its lateral rims to the medial
385 // orbital rims, so the opening has rims to be walked and the maxilla joins the brow instead of floating under it
386 let fpx: i64 = P[P_PAW]/2 + P[P_FPR]
387 let fpy: i64 = yrh - P[P_PAH]/2
388 let fpz: i64 = zrh - P[P_FPR]
389 let fqx: i64 = P[P_OX] - P[P_OSW] - P[P_FPR]/2
390 let fqy: i64 = P[P_OAY] - P[P_OSH]/2
391 d = sp_smin(d, sp_capsule_q(px,py,pz, 0-fpx,fpy,fpz, 0-fqx,fqy,P[P_OCZ], P[P_FPR]), kq)
392 d = sp_smin(d, sp_capsule_q(px,py,pz, fpx,fpy,fpz, fqx,fqy,P[P_OCZ], P[P_FPR]), kq)
393 // (b) the orbits as SOCKETS: an ellipsoid carved with its back wall inside the bone and its front through the face
394 d = sp_sub(d, sp_ellipsoid_q(px,py,pz, 0-P[P_OX], P[P_OAY], P[P_OCZ], P[P_OSW], P[P_OSH], P[P_OSD]))
395 d = sp_sub(d, sp_ellipsoid_q(px,py,pz, P[P_OX], P[P_OAY], P[P_OCZ], P[P_OSW], P[P_OSH], P[P_OSD]))
396 // (c) the piriform aperture as an OPENING hanging from the rhinion, its nasal floor P_PAD behind the rim
397 d = sp_sub(d, sp_cylz_q(px,py,pz, 0, yrh - P[P_PAH]/2, P[P_PAW]/2, P[P_PAH]/2, zrh - P[P_PAD]))
398 return d
399}
400
401// THE DEFAULT PARAMETER VECTOR IS MAPPED ONCE, NOT ONCE PER SAMPLE -- the organ's single largest
402// defect, not a tuning matter. ss_field is the hot path of the whole program: the polygonizer
403// evaluates it at every one of (G+1)^3 grid corners. It used to sys_mmap(SP_N*8) on EVERY call, and
404// sys_mmap is PAGE-GRANULAR -- a 160-byte request costs a whole 4096-byte page, nothing here frees,
405// so THE FIELD LEAKED ONE PAGE PER SAMPLE.
406// MEASURED, and it reproduces the 2026-07-30 incident to the digit: G=224 is 225^3 = 11,390,625
407// samples x 4096 B = 46.6 GB of anonymous pages; the box OOM-killed it at total-vm 33.8 GB /
408// anon-rss 28.0 GB partway through. The grid array at that size is only 91 MB and cv another 90 MB,
409// so 2,966 bytes per cell was never the grid -- it was this line. It is also why G=1500 mapped 27 GB
410// and froze every other seat's builds.
411// THE BANKED DIAGNOSIS -- 'the knob allocates on the RAW argument while computing on a CAPPED one' --
412// WAS WRONG, and the memory arithmetic refutes it: the raw-argument allocation is O(G^3)x8 = 91 MB at
413// G=224, three orders of magnitude short of the observed kill. The cost was per-EVALUATION, not
414// per-cell-of-storage.
415// A static POINTER lazily mapped once is the sanctioned shape here (a static ARRAY in BSS is the
416// banked crash-on-startup hazard, and this is the idiom nx_fluid/nx_genome/nx_ghash already use). The
417// vector is immutable after ss_defaults, so ONE copy is correct for every caller and ss_field stays a
418// pure function of its arguments -- the property the tuner and the polygonizer both rely on.
419// ---- THE FIT FILE: the tuner's output is DATA the emitter loads, never a source edit. If
420// knowledge/skull_fit.dat exists and carries a COMPLETE SP_N integer vector it overrides the
421// builtin defaults; short or absent files change nothing (parsed into a temp, applied only when
422// complete, so a truncated write cannot half-poison the skull). `tune ... <savepath>` writes it,
423// every emit reports fit_src, and the optimize->emit->measure loop closes with no hand in the numbers.
424static SS_FITSRC: i64
425static SS_FITN: i64
426// the fit file through the ONE loader (nx_fieldfit_lib.ff_load_prefix): a prefix of at least SS_FIT_MIN ints applies,
427// anything shorter changes nothing; SS_FITN carries how many stations the file governed for the emit receipt
428func ss_load_fit(P: *i64) -> i64 {
429 let got: i64 = ff_load_prefix("knowledge/skull_fit.dat" as *u8, P, SP_N, SS_FIT_MIN)
430 if got >= SS_FIT_MIN { SS_FITN = got; return 1 }
431 return 0
432}
433static SS_PDEF: i64
434func ss_pdef() -> *i64 {
435 if SS_PDEF == 0 {
436 SS_PDEF = sys_mmap(SP_N*8) as i64
437 ss_defaults(SS_PDEF as *i64)
438 SS_FITSRC = ss_load_fit(SS_PDEF as *i64)
439 }
440 return SS_PDEF as *i64
441}
442func ss_field(px: i64, py: i64, pz: i64, sexf: i64, robust: i64) -> i64 {
443 // delegates to the parameterised field with the default vector, so every existing caller is
444 // unchanged and there is exactly ONE definition of the skull's geometry
445 return ss_field_p(px, py, pz, sexf, robust, ss_pdef())
446}
447
448// Evaluate the authored field at a WORLD millimetre point: map the point back into authored space,
449// then scale the returned distance forward again so the field stays a true SDF in world units.
450func ss_field_world(px: i64, py: i64, pz: i64, sexf: i64, robust: i64) -> i64 {
451 let d: i64 = ss_field(px*1000/SS_SCALE, py*1000/SS_SCALE, pz*1000/SS_SCALE, sexf, robust)
452 return d * SS_SCALE / 1000
453}
454// world-space field at SS_FQ units per world-unit -- the sub-mm raw lane (see the SS_FQ block)
455func ss_field_world_q(px: i64, py: i64, pz: i64, sexf: i64, robust: i64) -> i64 {
456 let d: i64 = ss_field_p_q(px*1000/SS_SCALE, py*1000/SS_SCALE, pz*1000/SS_SCALE, sexf, robust, ss_pdef())
457 return d * SS_SCALE / 1000
458}
459
460// ★★★SKIN AS A TRUE ENVELOPE -- THE ANSWER THE OFFSET FAILURE HANDED US. nx_skinwrap displaced every
461// bone vertex outward along its own normal by the forensic tissue depth, and it LOWERED the binding judge
462// 99 -> 88 against the cadaver skin. The reason was structural, not tuning: AN OFFSET ALONG A NORMAL
463// CANNOT BRIDGE A CAVITY, and a face is largely defined by the cavities its skin bridges -- the orbits,
464// the nasal aperture, the temporal fossa. A per-vertex offset reproduces every opening and pushes its rim
465// outward, so a socket becomes a bulging crater. That is the exact inverse of this lane's banked law that
466// relief modulates a radius and cannot CUT a hole: a normal offset cannot FILL one.
467// ★THE IMPLICIT PATH DOES IT FOR FREE, and that is why this belongs here and not in a new organ. The skull
468// is already a distance FIELD. Subtracting a depth from the distance before polygonizing moves the zero
469// level OUTWARD by that depth, and AN ISO-SURFACE AT DISTANCE d NATURALLY BRIDGES ANY OPENING NARROWER
470// THAN 2d -- which is precisely the eyelid-over-orbit and skin-over-aperture behaviour we want, arising
471// from the representation rather than from a special case.
472// ★DEPTH IS KEYED ON THE FIELD'S OWN AUTHORED STATIONS, not on a per-mille of some bounding box, because
473// the field already places every landmark in millimetres in a frame centred on the cranium. These are the
474// published forensic depths (Rhine/De Greef class) this codebase carries in knowledge/face_tissue.dat.
475// ⚠HONEST v1 LIMIT, declared here rather than discovered later: this varies with HEIGHT only. The temple
476// is 3mm while the cheekbone at nearly the same height is 7, so a height-keyed table cannot express a
477// lateral difference. The nasion dip at 3mm between brow 7 and nasal 6 IS expressible, and it is the one
478// that makes a nose read as a nose.
479static SS_TISSUE: i64
480// ★★★DENSE-ER TISSUE MAP: DEPTH IS A FUNCTION OF (HEIGHT, LATERAL DISTANCE), NOT HEIGHT ALONE.
481// ★WHY, from the 2026 literature rather than from taste: the state of the art in anatomy-guided face
482// generation (Skull-to-Face, arXiv 2403.16207; SCULPTOR skeleton-consistent parametric generator; and the
483// PLOS One automatic forensic reconstruction from DENSE STATISTICS OF SOFT TISSUE THICKNESS) does not use
484// a sparse landmark list -- it fits a DENSE MAP of tissue thickness over the skull surface. Our v1 was a
485// 9-band table keyed on height only, and I declared its limit when I shipped it: the temple is ~3mm while
486// the zygion sits at ~7mm at nearly the SAME HEIGHT, so a 1-D table structurally cannot express either
487// without corrupting the other. Adding the lateral axis is the smallest honest step toward a dense map,
488// and it is the axis that carries the largest published disagreement.
489// ★THE LATERAL STRUCTURE IS REAL ANATOMY, NOT SMOOTHING. Two rows invert with distance from the midline
490// and they are the reason this matters: at the BROW LINE the midline glabella is thick (7) while the
491// TEMPLE is the thinnest soft tissue on the whole head (3); at the JAW the midline chin is 11 but the
492// GONION is thicker still going outward (11) because the MASSETER inserts there. A height-only table gets
493// the temple and the gonion wrong in OPPOSITE directions, which is exactly the kind of error that shows up
494// as a wrong silhouette rather than a wrong number.
495// ⚠STILL NOT A DENSE MAP: this is 9 height bands x 3 lateral bands = 27 cells, against a literature
496// standard of a per-vertex statistical field. It is a strict superset of v1's information, not parity.
497const SS_LAT_MID: i64 = 25 // |x| under this is the midline column
498const SS_LAT_FAR: i64 = 55 // |x| over this is the far-lateral column (temple / zygomatic arch / gonion)
499func ss_tdepth2(y: i64, ax: i64) -> i64 {
500 var col: i64 = 0
501 if ax >= SS_LAT_MID { col = 1 }
502 if ax >= SS_LAT_FAR { col = 2 }
503 if y < 0-78 { if col==0 { return 11 } if col==1 { return 10 } return 8 } // chin / mental
504 if y < 0-60 { if col==0 { return 9 } if col==1 { return 10 } return 11 } // jaw -- THICKENS outward (masseter)
505 if y < 0-38 { if col==0 { return 11 } if col==1 { return 9 } return 8 } // lower lip
506 if y < 0-30 { if col==0 { return 10 } if col==1 { return 8 } return 7 } // upper lip
507 if y < 0 { if col==0 { return 7 } if col==1 { return 7 } return 6 } // maxilla / zygion
508 if y < 8 { if col==0 { return 6 } if col==1 { return 7 } return 6 } // nasal
509 if y < 22 { if col==0 { return 3 } if col==1 { return 6 } return 5 } // nasion DIP on the midline only
510 if y < 30 { if col==0 { return 7 } if col==1 { return 6 } return 4 } // brow: glabella thick, temple thin
511 if col==0 { return 5 }
512 if col==1 { return 4 }
513 return 3 // temple -- thinnest on the head
514}
515// v1 kept as the midline column so the 1-D behaviour is still reachable and comparable
516func ss_tdepth(y: i64) -> i64 { return ss_tdepth2(y, 0) }
517// ***TABLE VALUES ARE LANDMARK MEASUREMENTS, NOT STEP FUNCTIONS. On the distorted field the band
518// steps were accidentally BLURRED by the field error; the redistanced field reproduces them
519// faithfully, as visible horizontal shelves at every band boundary (rendered proof:
520// /world/mh_skin_env_redist.png). The honest reading of a forensic depth table is depth AT a
521// landmark station, interpolated BETWEEN stations. Only the REDIST path consumes this, so the
522// shipped band behaviour is byte-identical.
523const SS_TD_N: i64 = 9
524static SS_TD_Y: i64
525static SS_TD_D: i64
526func ss_td_tab() -> i64 {
527 if SS_TD_Y == 0 {
528 SS_TD_Y = sys_mmap(SS_TD_N*8) as i64
529 SS_TD_D = sys_mmap(SS_TD_N*8) as i64
530 let Y: *i64 = SS_TD_Y as *i64
531 let D: *i64 = SS_TD_D as *i64
532 Y[0]=0-88; D[0]=11
533 Y[1]=0-69; D[1]=9
534 Y[2]=0-49; D[2]=11
535 Y[3]=0-34; D[3]=10
536 Y[4]=0-15; D[4]=7
537 Y[5]=4; D[5]=6
538 Y[6]=15; D[6]=3
539 Y[7]=26; D[7]=7
540 Y[8]=45; D[8]=5
541 }
542 return 0
543}
544// depth at height y in mm x SS_RDQ, piecewise-linear between the landmark stations (band centres of
545// ss_tdepth, same forensic values), clamped at both ends
546func ss_tdepth_q(y: i64) -> i64 {
547 ss_td_tab()
548 let Y: *i64 = SS_TD_Y as *i64
549 let D: *i64 = SS_TD_D as *i64
550 if y <= Y[0] { return D[0]*SS_RDQ }
551 if y >= Y[SS_TD_N-1] { return D[SS_TD_N-1]*SS_RDQ }
552 var i: i64 = 0
553 while i < SS_TD_N-1 {
554 if y <= Y[i+1] {
555 let c0: i64 = Y[i]
556 let c1: i64 = Y[i+1]
557 return (D[i]*(c1-y) + D[i+1]*(y-c0))*SS_RDQ/(c1-c0)
558 }
559 i = i + 1
560 }
561 return D[SS_TD_N-1]*SS_RDQ
562}
563func ss_f32(v: i64, scale: i64) -> i64 {
564 // integer -> IEEE-754 single bits, value = v/scale
565 if v == 0 { return 0 }
566 var neg: i64 = 0
567 var m: i64 = v
568 if m < 0 { neg = 1; m = 0 - m }
569 var e: i64 = 127
570 // normalise m/scale into [1,2)
571 var num: i64 = m
572 var den: i64 = scale
573 while num >= den*2 { den = den*2; e = e + 1 }
574 while num < den { num = num*2; e = e - 1 }
575 // mantissa = (num/den - 1) * 2^23
576 let frac: i64 = ((num - den) * SS_MAGIC_8388608) / den
577 var bits: i64 = (e << 23) | (frac & SS_MAGIC_8388607)
578 if neg == 1 { bits = bits | (1 << 31) }
579 return bits
580}
581func ss_wr32(b: *u8, o: i64, v: i64) -> i64 {
582 b[o] = (v & 255) as u8
583 b[o+1] = ((v >> 8) & 255) as u8
584 b[o+2] = ((v >> 16) & 255) as u8
585 b[o+3] = ((v >> 24) & 255) as u8
586 return 0
587}
588
589// ***REALISED THICKNESS -- THE OBJECTIVE THE DENSE-MAP LITERATURE ACTUALLY NEEDS, AND IT IS FREE HERE.
590// The 2-D table failed because writing depths into a FIELD is not the same as getting them on the
591// SURFACE: surface_nets redistributes them. So the thing to build is not a better table, it is a
592// MEASUREMENT OF WHAT THE SURFACE ACTUALLY REALISED. Our skull IS a distance function, so |field| at an
593// envelope vertex IS that vertex's realised tissue thickness over the bone -- no ray cast, no nearest-
594// triangle search. Same trick ss_fit already uses against the scanned reference.
595// Simultaneously the diagnostic (how much does the field-to-surface step redistribute a requested
596// depth) and the objective a coordinate descent would minimise.
597func ss_bandix(y: i64) -> i64 {
598 if y < 0-78 { return 0 }
599 if y < 0-60 { return 1 }
600 if y < 0-38 { return 2 }
601 if y < 0-30 { return 3 }
602 if y < 0 { return 4 }
603 if y < 8 { return 5 }
604 if y < 22 { return 6 }
605 if y < 30 { return 7 }
606 return 8
607}
608func ss_band_req(ix: i64) -> i64 {
609 if ix == 0 { return 11 }
610 if ix == 1 { return 9 }
611 if ix == 2 { return 11 }
612 if ix == 3 { return 10 }
613 if ix == 4 { return 7 }
614 if ix == 5 { return 6 }
615 if ix == 6 { return 3 }
616 if ix == 7 { return 7 }
617 return 5
618}
619func ss_rd32(b: *u8, o: i64) -> i64 {
620 return (b[o] as i64) | ((b[o+1] as i64)<<8) | ((b[o+2] as i64)<<16) | ((b[o+3] as i64)<<24)
621}
622func ss_r_f32(bits: i64, scale: i64) -> i64 {
623 let s: i64 = (bits >> 31) & 1
624 let e: i64 = (bits >> 23) & 255
625 let m: i64 = bits & SS_MAGIC_8388607
626 if e == 0 { return 0 }
627 if e == 255 { return 0 }
628 let mant: i64 = SS_MAGIC_8388608 | m
629 let sh: i64 = e - 127 - 23
630 var v: i64 = 0
631 if sh >= 0 { if sh > 30 { return 0 } v = (mant*scale) << sh }
632 else { let rs: i64 = 0 - sh; if rs > 62 { return 0 } v = (mant*scale) >> rs }
633 if s == 1 { return 0 - v }
634 return v
635}
636// ★SCORE AGAINST THE REAL SCANNED REFERENCE, IN MILLIMETRES -- and the metric is FREE because our skull
637// IS a distance function: |field| at a reference vertex is the error there. No registration search, no
638// closest-triangle hunt. Eight rounds of hand-placing primitives matched the bounding box to 5mm while
639// the SHAPE stayed a cluster of lumps; a bounding box cannot see shape and an eyeball cannot be
640// optimized against. This can.
641// ⚠FRAME: the reference faces -z in a full-body frame, ours faces +z centred on the cranium. The
642// transform is DERIVED from the reference's own bbox, and z is negated -- without that we would be
643// scoring our face against the back of its skull.
644// THE ORACLE'S FRAME, READ ONCE, CORRECTLY (anatomy AN17, 2026-09-18). knowledge/skull.nxmesh is BodyParts3D, and
645// BodyParts3D is a FLOOR-ORIGIN, z-UP body frame: the head sits at z 1.42..1.64 m, y runs antero-posterior with the
646// face at -y, x lateral (first triangle: x 18.7, y -156.9, z 1457.4 mm; bbox x 151, y 209, z 215 mm). Every reader in
647// this file took it as y-up and merely negated z, so the tuner fitted an upright field to a skull LYING ON ITS BACK
648// since the first tune: the trend's "vault 4 mm" was measured against that pose and knowledge/skull_fit.dat converged
649// to the egg that best matches a supine skull (vault half-height 92, a negative nasal radius). Measured by the AN17
650// canon ruler's midline profile dump: read as x, z, -y the profile from the front IS a skull (forehead receding 110 mm
651// over 126 mm to a glabella, an aperture floor 26 mm behind it, a chin 53 mm below the prosthion); read as y-up it is
652// the skull base seen from below, its 36 mm see-through the foramen magnum.
653// x_a = x - cx ; y_a = z - cz ; z_a = -(y - cy) -- a proper rotation of a quarter turn about x, applied to positions
654// (out3, integer mm at scale units) and to normals (ss_ref_map_normal). ONE mapper for every reader below.
655func ss_ref_map(buf: *u8, o: i64, cx: i64, cy: i64, cz: i64, scale: i64, out3: *i64) -> i64 {
656 out3[0] = ss_r_f32(ss_rd32(buf, o), scale) - cx
657 out3[1] = ss_r_f32(ss_rd32(buf, o+8), scale) - cz
658 out3[2] = 0 - (ss_r_f32(ss_rd32(buf, o+4), scale) - cy)
659 return 0
660}
661func ss_ref_map_normal(buf: *u8, o: i64, scale: i64, out3: *i64) -> i64 {
662 out3[0] = ss_r_f32(ss_rd32(buf, o), scale)
663 out3[1] = ss_r_f32(ss_rd32(buf, o+8), scale)
664 out3[2] = 0 - ss_r_f32(ss_rd32(buf, o+4), scale)
665 return 0
666}
667func ss_fit(path: *u8, sexf: i64, robust: i64, stride: i64) -> i64 {
668 let ln: *i64 = sys_mmap(16) as *i64
669 let buf: *u8 = sys_read_file(path, ln)
670 if (buf as i64) == 0 { ss_puts("{\x22error\x22:\x22cannot read reference\x22}\n" as *u8); return 3 }
671 let nlayer: i64 = ss_rd32(buf, 8)
672 let nt: i64 = ss_rd32(buf, 12)
673 let hdr: i64 = 16 + nlayer*24
674 if nt <= 0 { ss_puts("{\x22error\x22:\x22no triangles\x22}\n" as *u8); return 4 }
675 var lox: i64 = 0; var hix: i64 = 0
676 var loy: i64 = 0; var hiy: i64 = 0
677 var loz: i64 = 0; var hiz: i64 = 0
678 var first: i64 = 1
679 var t: i64 = 0
680 while t < nt {
681 let o: i64 = hdr + t*84
682 var j: i64 = 0
683 while j < 3 {
684 let x: i64 = ss_r_f32(ss_rd32(buf,o+j*12), 1)
685 let y: i64 = ss_r_f32(ss_rd32(buf,o+j*12+4), 1)
686 let z: i64 = ss_r_f32(ss_rd32(buf,o+j*12+8), 1)
687 if first == 1 { lox=x; hix=x; loy=y; hiy=y; loz=z; hiz=z; first=0 } else {
688 if x<lox {lox=x}
689 if x>hix {hix=x}
690 if y<loy {loy=y}
691 if y>hiy {hiy=y}
692 if z<loz {loz=z}
693 if z>hiz {hiz=z}
694 }
695 j = j + 1
696 }
697 t = t + 1
698 }
699 let cx: i64 = (lox+hix)/2
700 let cy: i64 = (loy+hiy)/2
701 let cz: i64 = (loz+hiz)/2
702 var sum: i64 = 0
703 var n: i64 = 0
704 var worst: i64 = 0
705 var over: i64 = 0
706 t = 0
707 while t < nt {
708 if t % stride == 0 {
709 let o: i64 = hdr + t*84
710 let m3: *i64 = sys_mmap(24) as *i64
711 ss_ref_map(buf, o, cx, cy, cz, 1, m3)
712 let x: i64 = m3[0]
713 let y: i64 = m3[1]
714 let z: i64 = m3[2]
715 var d: i64 = ss_field(x, y, z, sexf, robust)
716 if d < 0 { d = 0 - d }
717 sum = sum + d
718 n = n + 1
719 if d > worst { worst = d }
720 if d > 10 { over = over + 1 }
721 }
722 t = t + 1
723 }
724 if n == 0 { ss_puts("{\x22error\x22:\x22no samples\x22}\n" as *u8); return 5 }
725 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22fit\x22,\x22mean_err_mm\x22:" as *u8); ss_pn(sum/n)
726 ss_puts(",\x22worst_err_mm\x22:" as *u8); ss_pn(worst)
727 ss_puts(",\x22over_10mm_permil\x22:" as *u8); ss_pn(over*1000/n)
728 ss_puts(",\x22samples\x22:" as *u8); ss_pn(n)
729 ss_puts(",\x22ref_bbox_mm\x22:[" as *u8); ss_pn(hix-lox)
730 ss_puts("," as *u8); ss_pn(hiy-loy); ss_puts("," as *u8); ss_pn(hiz-loz)
731 ss_puts("]}\n" as *u8)
732 return 0
733}
734
735// load reference vertices once into flat arrays, already transformed into our frame
736func ss_load_ref(path: *u8, RX: *i64, RY: *i64, RZ: *i64, cap: i64, stride: i64) -> i64 {
737 let ln: *i64 = sys_mmap(16) as *i64
738 let buf: *u8 = sys_read_file(path, ln)
739 if (buf as i64) == 0 { return 0-1 }
740 let nlayer: i64 = ss_rd32(buf, 8)
741 let nt: i64 = ss_rd32(buf, 12)
742 let hdr: i64 = 16 + nlayer*24
743 var lox: i64 = 0; var hix: i64 = 0
744 var loy: i64 = 0; var hiy: i64 = 0
745 var loz: i64 = 0; var hiz: i64 = 0
746 var first: i64 = 1
747 var t: i64 = 0
748 while t < nt {
749 let o: i64 = hdr + t*84
750 // all three vertices: the gapmap and voxref centre by the same bbox, and a centre read off vertex 0 alone
751 // (as this loop did until 2026-09-18) registered the two readers a fraction of a cell apart
752 var vj: i64 = 0
753 while vj < 3 {
754 let x: i64 = ss_r_f32(ss_rd32(buf,o+vj*12), 1)
755 let y: i64 = ss_r_f32(ss_rd32(buf,o+vj*12+4), 1)
756 let z: i64 = ss_r_f32(ss_rd32(buf,o+vj*12+8), 1)
757 if first == 1 { lox=x; hix=x; loy=y; hiy=y; loz=z; hiz=z; first=0 } else {
758 if x<lox {lox=x}
759 if x>hix {hix=x}
760 if y<loy {loy=y}
761 if y>hiy {hiy=y}
762 if z<loz {loz=z}
763 if z>hiz {hiz=z}
764 }
765 vj = vj + 1
766 }
767 t = t + 1
768 }
769 let cx: i64 = (lox+hix)/2
770 let cy: i64 = (loy+hiy)/2
771 let cz: i64 = (loz+hiz)/2
772 var n: i64 = 0
773 let m3: *i64 = sys_mmap(24) as *i64
774 t = 0
775 while t < nt {
776 if t % stride == 0 {
777 if n < cap {
778 let o: i64 = hdr + t*84
779 ss_ref_map(buf, o, cx, cy, cz, 1, m3)
780 RX[n] = m3[0]
781 RY[n] = m3[1]
782 RZ[n] = m3[2]
783 n = n + 1
784 }
785 }
786 t = t + 1
787 }
788 return n
789}
790// ★★THE OBJECTIVE IS SYMMETRIC, AND IT HAS TO BE. A one-directional score -- "how far is each REFERENCE
791// point from my surface" -- is trivially gamed by DELETING GEOMETRY: the first tuning run shrank the
792// orbits from 22mm to 8mm and flattened the maxilla from 30mm to 13mm, improving the number 40% by
793// filling in the eye sockets, because surface that does not exist cannot be wrong.
794// The reverse term fixes that by construction: sample points on OUR surface and measure how far they
795// are from the REFERENCE. A filled orbit puts our surface where the reference has a hole, and the
796// reverse term charges for it. Together they are a two-sided (Hausdorff-style) distance.
797// ⚠We have no distance function for the reference MESH, so the reverse term uses the nearest reference
798// VERTEX from a spatial grid. That is an upper bound on the true point-to-surface distance -- it can
799// overstate, never understate, which is the safe direction for a penalty.
800// the oracle box the reverse term's spatial hash covers: the scanned skull's own extent, in the field's frame
801const SG_DIM: i64 = 24 // spatial hash grid, cells per axis
802const SG_EXT: i64 = 140 // half-extent covered, mm
803const SS_TUNE_LAT: i64 = 6 // reverse-term lattice spacing, mm (the objective's sampling of OUR surface)
804const SS_GR_N: i64 = 7 // the named regions of ss_gap_region (vault, base, brow-orbits, nasal, zygomatic, mandible, maxilla)
805// ★THE LANDMARK TERM (AN17, 2026-09-19). MEASURED FIRST: with the two surface terms alone, region-balanced, the descent
806// closed the orbit sockets to 2 mm slits and deepened the aperture to a 35 mm tunnel while the objective fell 445 -> 413,
807// because a surface objective cannot see an opening. This term is the third error mean the fit library folds in: where
808// the field PLACES its features (from its own stations, closed-form) against where the ruler FOUND the oracle's
809// landmarks (knowledge/status/skull_oracle_q.dat, written by nx_skull_canon_gate from its own measurement, never typed
810// here). It is a SURROGATE of the ruler on our mesh -- the beat still runs the real ruler on the emitted mesh and gates
811// the pass on its in-band count -- and its predicted quantities are printed so the surrogate's error is readable beside
812// the ruler's reading. Quantities the ruler seeds from its own conf (orbit depth at the eye seed, the vault chord pitch)
813// are not predicted. Absent file = term OFF, announced.
814const SS_LMQ_N: i64 = 18 // the ruler's quantity count, in skc_qname order (15 + the three of 2026-09-19)
815const SS_LMQ_PRED: i64 = 16 // the quantities this field can place from its stations
816const SS_LMQ_BYTES: i64 = 4096
817const SS_LMQ_NONE: i64 = 0 - 999999999 // "this quantity is not predicted from the stations" -- a value no landmark can reach
818static SS_LMQ: i64 // *i64: oracle_u10 per quantity, or 0 when the file is absent
819static SS_LM_SEXF: i64
820static SS_LM_ROBUST: i64
821func ss_lm_load() -> i64 {
822 if SS_LMQ != 0 { return 1 }
823 let ln: *i64 = sys_mmap(16) as *i64
824 let buf: *u8 = sys_read_file("knowledge/status/skull_oracle_q.dat" as *u8, ln)
825 if (buf as i64) == 0 { return 0 }
826 let n: i64 = ln[0]
827 let T: *i64 = sys_mmap(SS_LMQ_N*8) as *i64
828 // each row: <name> <oracle_u10> <band_u10>; the second field of each line is the target. Flag-exited scans: a loop
829 // that clobbers its cursor to break cannot report where it stopped (the estate's cursor-sentinel law)
830 var i: i64 = 0
831 var row: i64 = 0
832 while i < n {
833 var go: i64 = 1
834 while go == 1 { if i >= n { go = 0 } else { if buf[i] == (32 as u8) { go = 0 } else { i = i + 1 } } }
835 if i < n { i = i + 1 }
836 var neg: i64 = 0
837 if i < n { if buf[i] == (45 as u8) { neg = 1; i = i + 1 } }
838 var v: i64 = 0
839 var any: i64 = 0
840 go = 1
841 while go == 1 {
842 if i >= n { go = 0 } else {
843 let c: i64 = buf[i] as i64
844 if c >= 48 { if c <= 57 { v = v*10 + (c-48); any = 1; i = i + 1 } else { go = 0 } } else { go = 0 }
845 }
846 }
847 if any == 1 { if row < SS_LMQ_N { if neg == 1 { v = 0 - v } T[row] = v; row = row + 1 } }
848 go = 1
849 while go == 1 { if i >= n { go = 0 } else { if buf[i] == (10 as u8) { go = 0 } else { i = i + 1 } } }
850 if i < n { i = i + 1 }
851 }
852 if row < SS_LMQ_N { return 0 }
853 SS_LMQ = T as i64
854 return 1
855}
856// the field's own placement of the ruler's quantities, u10, from the stations (index = skc_qname order; -1 = not predicted)
857func ss_lm_predict(P: *i64, Q: *i64) -> i64 {
858 let brow: i64 = 10 - 3*SS_LM_SEXF/SS_PERMILLE + 5*SS_LM_ROBUST/SS_PERMILLE
859 // the ruler's glabella is the MOST ANTERIOR midline point above the aperture floor: the brow bar's front or the
860 // frontal ellipsoid's front, whichever leads (measured 2026-09-19: the surrogate read the bar, the ruler the bulge)
861 var glab_z: i64 = P[P_BZ] + brow
862 if P[P_FZ] + P[P_FD] > glab_z { glab_z = P[P_FZ] + P[P_FD] }
863 let glab_y: i64 = P[P_BY]
864 let nts: i64 = sp_isin(P[P_NTILT])
865 let ntc: i64 = sp_icos(P[P_NTILT])
866 let nasion_y: i64 = P[P_NY] + P[P_NRY]*ntc/SS_PERMILLE
867 let yrh: i64 = P[P_NY] - P[P_NRY]*ntc/SS_PERMILLE
868 let nasosp_y: i64 = yrh - P[P_PAH]
869 let pog_z: i64 = P[P_JZ] + P[P_CRZ]
870 let gnath_y: i64 = P[P_JY] - P[P_CRY]
871 let pros_z: i64 = P[P_UZ] + P[P_UAZ] + P[P_AAR]
872 let pros_y: i64 = P[P_UY] + P[P_UTHT]/2 + P[P_AAR]*2/3
873 let k: i64 = ss_k()
874 Q[0] = (pog_z - glab_z)*10
875 Q[1] = (nasion_y - nasosp_y)*10
876 Q[2] = P[P_PAH]*10
877 Q[3] = P[P_PAW]*10 // the ruler's crest walk stops at the cylinder's own rim, not the process crest (measured)
878 Q[4] = 2*P[P_OX]*10
879 Q[5] = (glab_y - P[P_OAY])*10
880 Q[6] = 2*(P[P_OSW] + k)*10
881 Q[7] = 2*(P[P_ZBX] + P[P_ZR])*10
882 Q[8] = 2*(P[P_JBX] + P[P_JR])*10
883 Q[9] = (pros_z - glab_z)*10
884 Q[10] = (nasion_y - pros_y)*10
885 Q[11] = ((glab_y - nasosp_y) - (nasosp_y - gnath_y))*10
886 Q[12] = P[P_PAD]*10
887 Q[13] = SS_LMQ_NONE
888 Q[14] = SS_LMQ_NONE
889 // the three the ruler grew for the tuner's blind spots: the socket's rim height, the dip at the nasion (the plate's
890 // front face at its top end against the glabella), the nasal bones' projection (the plate's slope times its length)
891 let nasion_z: i64 = P[P_NZ] - P[P_NRY]*nts/SS_PERMILLE + P[P_NTH]
892 let rhinion_z: i64 = P[P_NZ] + P[P_NRY]*nts/SS_PERMILLE + P[P_NTH]
893 Q[15] = 2*(P[P_OSH] + k)*10
894 Q[16] = (glab_z - nasion_z)*10
895 Q[17] = (rhinion_z - nasion_z)*10
896 return SS_LMQ_PRED
897}
898// the third error mean, centi-mm: mean |predicted - oracle| over the predicted quantities. The scratch vector is mapped
899// ONCE (this runs per descent move; a page per call is the leak this file measured in ss_field)
900static SS_LMSCR: i64
901func ss_lm_term(P: *i64) -> i64 {
902 if SS_LMQ == 0 { return 0 }
903 let O: *i64 = SS_LMQ as *i64
904 if SS_LMSCR == 0 { SS_LMSCR = sys_mmap(SS_LMQ_N*8) as i64 }
905 let Q: *i64 = SS_LMSCR as *i64
906 ss_lm_predict(P, Q)
907 var sum: i64 = 0
908 var cnt: i64 = 0
909 var q: i64 = 0
910 while q < SS_LMQ_N {
911 if Q[q] != SS_LMQ_NONE {
912 var d: i64 = Q[q] - O[q]
913 if d < 0 { d = 0 - d }
914 sum = sum + d
915 cnt = cnt + 1
916 }
917 q = q + 1
918 }
919 if cnt == 0 { return 0 }
920 return sum*10/cnt
921}
922// ★THE TUNE COMPOSES nx_fieldfit_lib (AN17, 2026-09-19): the two-sided region-balanced objective, the coordinate descent
923// and the fit file are the library's; this organ supplies its field, its region classifier and its live-station mask
924// as function values, and keeps only what is the skull's -- the oracle reader, the parameter vector, the receipt.
925func ss_params_valid(P: *i64, np: i64) -> i64 {
926 if np != SP_N { return 0 }
927 if P[P_VW] <= 0 { return 0 }
928 if P[P_VH] <= 0 { return 0 }
929 if P[P_VD] <= 0 { return 0 }
930 if P[P_FH] <= 0 { return 0 }
931 if P[P_FD] <= 0 { return 0 }
932 if P[P_MW] <= 0 { return 0 }
933 if P[P_MH] <= 0 { return 0 }
934 if P[P_MD] <= 0 { return 0 }
935 if P[P_OX] <= 0 { return 0 }
936 if P[P_BX] <= 0 { return 0 }
937 if P[P_ZR] <= 0 { return 0 }
938 if P[P_NRX] <= 0 { return 0 }
939 if P[P_NRY] <= 0 { return 0 }
940 if P[P_JBX] <= 0 { return 0 }
941 if P[P_JR] <= 0 { return 0 }
942 if P[P_RRX] <= 0 { return 0 }
943 if P[P_RRZ] <= 0 { return 0 }
944 if P[P_CRX] <= 0 { return 0 }
945 if P[P_CRY] <= 0 { return 0 }
946 if P[P_CRZ] <= 0 { return 0 }
947 if P[P_UAX] <= 0 { return 0 }
948 if P[P_UAZ] <= 0 { return 0 }
949 if P[P_UTW] <= 0 { return 0 }
950 if P[P_UTHT] <= 0 { return 0 }
951 if P[P_LAX] <= 0 { return 0 }
952 if P[P_LAZ] <= 0 { return 0 }
953 if P[P_LTW] <= 0 { return 0 }
954 if P[P_LTHT] <= 0 { return 0 }
955 if P[P_OSW] <= 0 { return 0 }
956 if P[P_OSH] <= 0 { return 0 }
957 if P[P_OSD] <= 0 { return 0 }
958 if P[P_PAW] <= 0 { return 0 }
959 if P[P_PAH] <= 0 { return 0 }
960 if P[P_PAD] <= 0 { return 0 }
961 if P[P_NTH] <= 0 { return 0 }
962 if P[P_AAR] <= 0 { return 0 }
963 if P[P_FPR] <= 0 { return 0 }
964 if P[P_UN] < SP_RING_N_MIN { return 0 } if P[P_UN] > SP_RING_N_MAX { return 0 }
965 if P[P_LN] < SP_RING_N_MIN { return 0 } if P[P_LN] > SP_RING_N_MAX { return 0 }
966 if P[P_UTH] < SP_RING_TH_MIN { return 0 } if P[P_UTH] > SP_RING_TH_MAX { return 0 }
967 if P[P_LTH] < SP_RING_TH_MIN { return 0 } if P[P_LTH] > SP_RING_TH_MAX { return 0 }
968 return 1
969}
970func ss_fit_contract() -> *FfFitContract {
971 let C: *FfFitContract = sys_mmap(32) as *FfFitContract
972 C.header="NXFFIT2 schema=4bef6d72830e61efa67c0ca4f0a1887fb596f8ae1d7c93b25b7f2d30275fd7f4 frame=bodyparts3d-x-z-negative-y-mm-v1 producer=89f60e488da4ff5bbafc86d42c8d1baa5b97abd47bd1b71faa16afeb605f9c0b reference=0022db41aa5d1f741e75f4a19c0163c5febbc025f16feeea068616d1a6b913c2 objective=region-balanced-two-sided-no-extra residual=none\n" as *u8
973 C.header_bytes=327; C.np=SP_N; C.valid=ss_params_valid
974 return C
975}
976
977func ss_tune(path: *u8, sexf: i64, robust: i64, stride: i64, passes: i64, step0: i64, save: *u8) -> i64 {
978 let cap: i64 = SS_MAGIC_40000
979 let C: *FfCtx = ff_ctx_new(SP_N, SS_GR_N, cap, SG_EXT, SG_DIM, SS_TUNE_LAT, SS_FQ)
980 C.field = ss_field_p_q
981 C.region = ss_gap_region
982 C.live = ss_param_live
983 C.a = sexf
984 C.b = robust
985 SS_LM_SEXF = sexf
986 SS_LM_ROBUST = robust
987 C.extra = ss_lm_term
988 C.has_extra = 0 // explicit two-sided objective; no optional unbound landmark file
989 let n: i64 = ss_load_ref(path, C.RX, C.RY, C.RZ, cap, stride)
990 if n <= 0 { ss_puts("{\x22error\x22:\x22cannot load reference\x22}\n" as *u8); return 3 }
991 C.n = n
992 ff_bin(C)
993 ff_regions(C)
994 let P: *i64 = sys_mmap(SP_N*8) as *i64
995 ss_defaults(P)
996 // iterate FROM the current fit so successive tune runs converge instead of restarting
997 let seeded: i64 = 0
998 ss_puts("FIT-MODE explicit-new-from-named-source-defaults legacy-not-applied residual-none\n" as *u8)
999 if ss_params_valid(P, SP_N) != 1 { ss_puts("FIT-REFUSED invalid named defaults\n" as *u8); return 6 }
1000 let start: i64 = ff_score2(C, P)
1001 let best: i64 = ff_descend_checked(C, P, passes, step0, 1, ss_params_valid)
1002 // persist the fit as DATA (the emitter loads it; no source edit carries these numbers)
1003 if best < 0 { return 6 }
1004 if (save as i64) != 0 { if ff_save_verified(save, P, ss_fit_contract()) < 0 { return 6 } }
1005 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22tune\x22,\x22samples\x22:" as *u8); ss_pn(n)
1006 ss_puts(",\x22start_err_mm\x22:" as *u8); ss_pn(start/100)
1007 ss_puts(",\x22final_err_mm\x22:" as *u8); ss_pn(best/100)
1008 ss_puts(",\x22start_centi\x22:" as *u8); ss_pn(start)
1009 ss_puts(",\x22final_centi\x22:" as *u8); ss_pn(best)
1010 ss_puts(",\x22objective\x22:\x22region-balanced\x22,\x22regions\x22:" as *u8); ss_pn(SS_GR_N)
1011 ss_puts(",\x22live_params\x22:" as *u8); ss_pn(ff_live_count(C))
1012 ss_puts(",\x22seeded\x22:" as *u8); ss_pn(seeded)
1013 ss_puts(",\x22landmark_term\x22:" as *u8); ss_pn(C.has_extra)
1014 if C.has_extra == 1 {
1015 // the surrogate's own prediction, u10, in the ruler's quantity order (-1 = not predicted): read it beside the
1016 // canon gate's `q ... ours=` line to know the surrogate's error
1017 let LQ: *i64 = sys_mmap(SS_LMQ_N*8) as *i64
1018 ss_lm_predict(P, LQ)
1019 ss_puts(",\x22landmark_term_centi\x22:" as *u8); ss_pn(ss_lm_term(P))
1020 ss_puts(",\x22predicted_u10\x22:[" as *u8)
1021 var lq: i64 = 0
1022 while lq < SS_LMQ_N {
1023 if lq > 0 { ss_puts("," as *u8) }
1024 ss_pn(LQ[lq])
1025 lq = lq + 1
1026 }
1027 ss_puts("]" as *u8)
1028 }
1029 ss_puts(",\x22params\x22:[" as *u8)
1030 var q: i64 = 0
1031 while q < SP_N {
1032 if q > 0 { ss_puts("," as *u8) }
1033 ss_pn(P[q])
1034 q = q + 1
1035 }
1036 ss_puts("]}\n" as *u8)
1037 return 0
1038}
1039
1040// THE `thick` VERB: report, per height band, the depth we REQUESTED versus the thickness the emitted
1041// envelope ACTUALLY realised over the bone. A gap between them is the field-to-surface redistribution
1042// made visible, and its mean absolute error is the number a fit would drive to zero.
1043func ss_thick(path: *u8, sexf: i64, robust: i64, stride: i64) -> i64 {
1044 let ln: *i64 = sys_mmap(16) as *i64
1045 let buf: *u8 = sys_read_file(path, ln)
1046 if (buf as i64) == 0 { ss_puts("{\x22error\x22:\x22cannot read envelope mesh\x22}\n" as *u8); return 3 }
1047 let nlayer: i64 = ss_rd32(buf, 8)
1048 let nt: i64 = ss_rd32(buf, 12)
1049 if nt <= 0 { ss_puts("{\x22error\x22:\x22no triangles\x22}\n" as *u8); return 4 }
1050 let hdr: i64 = 16 + nlayer*24
1051 let cnt: *i64 = sys_mmap(9*8) as *i64
1052 let sm: *i64 = sys_mmap(9*8) as *i64
1053 let mn: *i64 = sys_mmap(9*8) as *i64
1054 let mx: *i64 = sys_mmap(9*8) as *i64
1055 var b: i64 = 0
1056 while b < 9 { cnt[b]=0; sm[b]=0; mn[b]=SS_EXTENT_SENTINEL; mx[b]=0-SS_EXTENT_SENTINEL; b=b+1 }
1057 var abserr: i64 = 0
1058 var n: i64 = 0
1059 var t: i64 = 0
1060 while t < nt {
1061 if t % stride == 0 {
1062 var j: i64 = 0
1063 while j < 3 {
1064 let o: i64 = hdr + t*84 + j*12
1065 let px: i64 = ss_r_f32(ss_rd32(buf,o), 1)
1066 let py: i64 = ss_r_f32(ss_rd32(buf,o+4), 1)
1067 let pz: i64 = ss_r_f32(ss_rd32(buf,o+8), 1)
1068 let d: i64 = ss_field(px, py, pz, sexf, robust)
1069 let ix: i64 = ss_bandix(py)
1070 cnt[ix] = cnt[ix] + 1
1071 sm[ix] = sm[ix] + d
1072 if d < mn[ix] { mn[ix] = d }
1073 if d > mx[ix] { mx[ix] = d }
1074 var e: i64 = d - ss_band_req(ix)
1075 if e < 0 { e = 0 - e }
1076 abserr = abserr + e
1077 n = n + 1
1078 j = j + 1
1079 }
1080 }
1081 t = t + 1
1082 }
1083 if n == 0 { ss_puts("{\x22error\x22:\x22no samples\x22}\n" as *u8); return 5 }
1084 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22thick\x22,\x22samples\x22:" as *u8); ss_pn(n)
1085 ss_puts(",\x22mean_abs_err_mm\x22:" as *u8); ss_pn(abserr/n)
1086 ss_puts(",\x22bands\x22:[" as *u8)
1087 b = 0
1088 while b < 9 {
1089 if b > 0 { ss_puts("," as *u8) }
1090 ss_puts("{\x22band\x22:" as *u8); ss_pn(b)
1091 ss_puts(",\x22req\x22:" as *u8); ss_pn(ss_band_req(b))
1092 ss_puts(",\x22mean\x22:" as *u8)
1093 if cnt[b] > 0 { ss_pn(sm[b]/cnt[b]) } else { ss_pn(0-1) }
1094 ss_puts(",\x22min\x22:" as *u8)
1095 if cnt[b] > 0 { ss_pn(mn[b]) } else { ss_pn(0-1) }
1096 ss_puts(",\x22max\x22:" as *u8)
1097 if cnt[b] > 0 { ss_pn(mx[b]) } else { ss_pn(0-1) }
1098 ss_puts(",\x22n\x22:" as *u8); ss_pn(cnt[b])
1099 ss_puts("}" as *u8)
1100 b = b + 1
1101 }
1102 ss_puts("]}\n" as *u8)
1103 return 0
1104}
1105
1106// ***THE `grad` VERB -- MEASURE |grad f| DIRECTLY INSTEAD OF INFERRING IT FROM SCATTER.
1107// Every remaining hypothesis about the tissue-thickness scatter is a claim about how far this field is
1108// from a TRUE distance function, where |grad f| = 1 everywhere. Rather than argue, sample it: walk a
1109// coarse lattice, keep the points NEAR THE SURFACE (the only region that matters for an offset), and
1110// report the distribution of |grad f| in per-mille. A true SDF reads 1000.
1111// ***READ IT LIKE THIS: spread around 1000 is the offset error budget. If a requested 7mm offset lands
1112// where |grad| is 700, the surface moves 10mm; at 1400 it moves 5mm. That IS the 3-6mm scatter, and this
1113// verb says so directly instead of by inference. It also discriminates the two surviving suspects --
1114// ss_smin composition (already exonerated by K=0) versus ss_ellipsoid's first-order approximation --
1115// because you can re-run it with argv[5]=0 for a plain union and compare the SAME distribution.
1116func ss_grad(sexf: i64, robust: i64, step: i64, near: i64) -> i64 {
1117 var lo: i64 = SS_EXTENT_SENTINEL
1118 var hi: i64 = 0-SS_EXTENT_SENTINEL
1119 var sum: i64 = 0
1120 var n: i64 = 0
1121 var under: i64 = 0
1122 var over: i64 = 0
1123 var x: i64 = 0 - SS_EXT
1124 while x <= SS_EXT {
1125 var y: i64 = 0 - SS_EXT
1126 while y <= SS_EXT {
1127 var z: i64 = 0 - SS_EXT
1128 while z <= SS_EXT {
1129 let f: i64 = ss_field(x, y, z, sexf, robust)
1130 var af: i64 = f
1131 if af < 0 { af = 0 - af }
1132 if af <= near {
1133 let gx: i64 = (ss_field(x+1,y,z,sexf,robust) - ss_field(x-1,y,z,sexf,robust)) * 1000 / 2
1134 let gy: i64 = (ss_field(x,y+1,z,sexf,robust) - ss_field(x,y-1,z,sexf,robust)) * 1000 / 2
1135 let gz: i64 = (ss_field(x,y,z+1,sexf,robust) - ss_field(x,y,z-1,sexf,robust)) * 1000 / 2
1136 let g: i64 = ss_isqrt(gx*gx + gy*gy + gz*gz)
1137 if g < lo { lo = g }
1138 if g > hi { hi = g }
1139 sum = sum + g
1140 n = n + 1
1141 if g < SS_GRAD_BAND_LO { under = under + 1 }
1142 if g > SS_GRAD_BAND_HI { over = over + 1 }
1143 }
1144 z = z + step
1145 }
1146 y = y + step
1147 }
1148 x = x + step
1149 }
1150 if n == 0 { ss_puts("{\x22error\x22:\x22no near-surface samples\x22}\n" as *u8); return 5 }
1151 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22grad\x22,\x22samples\x22:" as *u8); ss_pn(n)
1152 ss_puts(",\x22true_sdf_is\x22:1000,\x22mean\x22:" as *u8); ss_pn(sum/n)
1153 ss_puts(",\x22min\x22:" as *u8); ss_pn(lo)
1154 ss_puts(",\x22max\x22:" as *u8); ss_pn(hi)
1155 ss_puts(",\x22under_800_permil\x22:" as *u8); ss_pn(under*1000/n)
1156 ss_puts(",\x22over_1200_permil\x22:" as *u8); ss_pn(over*1000/n)
1157 ss_puts(",\x22smooth_union_k\x22:" as *u8); ss_pn(ss_k())
1158 ss_puts("}\n" as *u8)
1159 return 0
1160}
1161
1162// ---- GAP MAP (the `gapmap` verb): WHERE and HOW MUCH we deviate from the scanned oracle ----
1163// The redistance pass makes OUR field a true SDF; the same sweep machinery run over the ORACLE'S
1164// VERTICES gives the ORACLE'S distance field on the SAME grid. Comparing the two turns "ours is
1165// wrong" into a RANKED PER-REGION WORKLIST (which primitive to fix first, by measured millimetres)
1166// and TWO HEAT MESHES the eye can read: our surface coloured by distance-to-oracle (where our
1167// geometry is wrong) and the oracle's surface coloured by distance-to-ours (what real anatomy we
1168// are MISSING -- sockets, teeth, arches glow). The oracle stays a RULER: nothing here feeds oracle
1169// geometry back into the generator.
1170// ⚠DECLARED BOUND: the oracle field is seeded from VERTICES, not triangles, so it OVERSTATES
1171// distance by at most half the oracle's vertex spacing (~1mm on the 171k-tri skull) -- safe
1172// direction for a gap report, and printed in the JSON.
1173// ***THE RESIDUAL LAYER (operator 2026-08-09: "not until you actually can emit the benchmark skull
1174// can you claim any of this"). The parametric base B is the CONTROLLABLE layer and converges near
1175// ~4.5mm -- blobs cannot carry identity. The industry decomposition is base + DISPLACEMENT: gapmap
1176// already builds B and the ingested input's own SDF O on the same grid, so the ideal correction is
1177// their pointwise difference, downsampled to a lattice and stored as DATA. Emission = B + trilinear(R)
1178// -- the input-derived residual carries identity, the base stays controllable, and a scale knob
1179// slides between the generic parametric skull (0) and the ingested benchmark (1000). R is DERIVED
1180// FROM THE INGESTED INPUT by construction: that IS the match half of the ingest->match->exceed
1181// circle, and it involves no hand-typed number anywhere.
1182const SS_RES_MAGIC: i64 = 0x4e585253 // 'NXRS'
1183const SS_RES_MAXN: i64 = 256 // lattice nodes per axis, upper bound (256^3 x 8 = 134MB;
1184 // raised 128->256 2026-08-10: a 2mm-lattice residual over a
1185 // 1mm grid blurs sub-2mm bone walls into speckle -- MEASURED
1186 // as the ghost-shell emission; identity needs lattice = grid)
1187static SS_RESP: i64 // loaded residual values (Q units)
1188static SS_RESN: i64 // lattice nodes per axis
1189static SS_RESORG: i64 // lattice origin, mm
1190static SS_RESSP: i64 // lattice spacing, mm
1191static SS_RESSC: i64 // application scale, permil
1192// load a residual file: [magic n org sp q] then n^3 i64 values; complete-or-nothing
1193func ss_res_load(path: *u8) -> i64 {
1194 let ln: *i64 = sys_mmap(16) as *i64
1195 let buf: *u8 = sys_read_file(path, ln)
1196 if (buf as i64) == 0 { return 0 }
1197 let hdr: *i64 = buf as *i64
1198 if hdr[0] != SS_RES_MAGIC { return 0 }
1199 let n: i64 = hdr[1]
1200 if n < 2 { return 0 }
1201 if n > SS_RES_MAXN { return 0 }
1202 if ln[0] < 40 + n*n*n*8 { return 0 }
1203 SS_RESN = n
1204 SS_RESORG = hdr[2]
1205 SS_RESSP = hdr[3]
1206 SS_RESP = (buf as i64) + 40
1207 return 1
1208}
1209// trilinear sample of the residual at a world-mm point, in Q units; zero outside the lattice
1210func ss_res_at(x: i64, y: i64, z: i64) -> i64 {
1211 if SS_RESP == 0 { return 0 }
1212 let R: *i64 = SS_RESP as *i64
1213 let n: i64 = SS_RESN
1214 let sp: i64 = SS_RESSP
1215 var ux: i64 = x - SS_RESORG
1216 var uy: i64 = y - SS_RESORG
1217 var uz: i64 = z - SS_RESORG
1218 if ux < 0 { return 0 }
1219 if uy < 0 { return 0 }
1220 if uz < 0 { return 0 }
1221 var i0: i64 = ux/sp
1222 var j0: i64 = uy/sp
1223 var k0: i64 = uz/sp
1224 if i0 >= n-1 { return 0 }
1225 if j0 >= n-1 { return 0 }
1226 if k0 >= n-1 { return 0 }
1227 let fx: i64 = (ux - i0*sp)*SS_LERP_ONE/sp
1228 let fy: i64 = (uy - j0*sp)*SS_LERP_ONE/sp
1229 let fz: i64 = (uz - k0*sp)*SS_LERP_ONE/sp
1230 let c000: i64 = R[(i0*n+j0)*n+k0]
1231 let c100: i64 = R[((i0+1)*n+j0)*n+k0]
1232 let c010: i64 = R[(i0*n+(j0+1))*n+k0]
1233 let c110: i64 = R[((i0+1)*n+(j0+1))*n+k0]
1234 let c001: i64 = R[(i0*n+j0)*n+(k0+1)]
1235 let c101: i64 = R[((i0+1)*n+j0)*n+(k0+1)]
1236 let c011: i64 = R[(i0*n+(j0+1))*n+(k0+1)]
1237 let c111: i64 = R[((i0+1)*n+(j0+1))*n+(k0+1)]
1238 let x00: i64 = c000 + (c100-c000)*fx/SS_LERP_ONE
1239 let x10: i64 = c010 + (c110-c010)*fx/SS_LERP_ONE
1240 let x01: i64 = c001 + (c101-c001)*fx/SS_LERP_ONE
1241 let x11: i64 = c011 + (c111-c011)*fx/SS_LERP_ONE
1242 let y0: i64 = x00 + (x10-x00)*fy/SS_LERP_ONE
1243 let y1: i64 = x01 + (x11-x01)*fy/SS_LERP_ONE
1244 return y0 + (y1-y0)*fz/SS_LERP_ONE
1245}
1246// ***THE ORACLE FIELD, DONE RIGHT (2026-08-10, operator: "nothing still looks close to a skull do
1247// you actually know what you are doing"). Honest answer: the vertex-cloud + flood + normal-heuristic
1248// construction of O was improvised through every classic mesh-to-SDF pitfall in sequence (beads,
1249// leaks, dead signs). The robust textbook construction, which the redistance pass ALREADY uses for
1250// OUR field, is: exact SURFACE CROSSINGS + PARITY. Intersect each grid column (x-ray at fixed y,z)
1251// with the actual TRIANGLES: a 2D point-in-triangle test in (y,z) selects hits, barycentric
1252// interpolation gives the exact crossing x in Q units, the two flanking nodes seed with exact
1253// distances, and CROSSING PARITY gives inside/outside -- no normals, no flood, no beads possible.
1254// The control verb `voxref` emits surface_nets(O) ALONE so the render answers one question first:
1255// is O the skull?
1256// ***NO CAPACITY CONSTANTS (rule 11, operator 2026-08-10: "stop doing these magic number bullshit
1257// things"). Bucket granularity = the GRID CELL (derived, not chosen); insertion storage is sized by a
1258// COUNTING pass, so there is no cap to hit and nothing to silently drop; the per-column hit buffer is
1259// sized by the longest measured bucket. Every bound is the population's own, computed per run.
1260// counting pass: how many (triangle, bucket-cell) insertions will the build make?
1261func ss_vb_count(rbuf: *u8, rhdr: i64, rnt: i64, cy: i64, cz: i64, ocy: i64, ocz: i64,
1262 org: i64, nb: i64, bcell: i64) -> i64 {
1263 var ins: i64 = 0
1264 var t: i64 = 0
1265 while t < rnt {
1266 let o: i64 = rhdr + t*84
1267 var loy: i64 = 0
1268 var hiy: i64 = 0
1269 var loz: i64 = 0
1270 var hiz: i64 = 0
1271 var vj: i64 = 0
1272 while vj < 3 {
1273 let wy: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+8), 1) - cz + ocy
1274 let wz: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+vj*12+4), 1) - cy) + ocz
1275 if vj == 0 { loy=wy; hiy=wy; loz=wz; hiz=wz } else {
1276 if wy<loy {loy=wy}
1277 if wy>hiy {hiy=wy}
1278 if wz<loz {loz=wz}
1279 if wz>hiz {hiz=wz}
1280 }
1281 vj = vj + 1
1282 }
1283 var bj: i64 = (loy - org)/bcell
1284 let bj1: i64 = (hiy - org)/bcell
1285 while bj <= bj1 {
1286 if bj >= 0 { if bj < nb {
1287 var bk: i64 = (loz - org)/bcell
1288 let bk1: i64 = (hiz - org)/bcell
1289 while bk <= bk1 {
1290 if bk >= 0 { if bk < nb { ins = ins + 1 } }
1291 bk = bk + 1
1292 }
1293 } }
1294 bj = bj + 1
1295 }
1296 t = t + 1
1297 }
1298 return ins
1299}
1300// fill pass: identical walk; capacity is the counting pass's own number, so overflow is impossible
1301func ss_vb_build(rbuf: *u8, rhdr: i64, rnt: i64, cx: i64, cy: i64, cz: i64, ocx: i64, ocy: i64, ocz: i64,
1302 org: i64, nb: i64, bcell: i64, head: *i64, nxt: *i64, tref: *i64, cap: i64) -> i64 {
1303 var c: i64 = 0
1304 while c < nb*nb { head[c] = 0-1; c = c + 1 }
1305 var ins: i64 = 0
1306 var t: i64 = 0
1307 while t < rnt {
1308 let o: i64 = rhdr + t*84
1309 var loy: i64 = 0
1310 var hiy: i64 = 0
1311 var loz: i64 = 0
1312 var hiz: i64 = 0
1313 var vj: i64 = 0
1314 while vj < 3 {
1315 let wy: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+8), 1) - cz + ocy
1316 let wz: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+vj*12+4), 1) - cy) + ocz
1317 if vj == 0 { loy=wy; hiy=wy; loz=wz; hiz=wz } else {
1318 if wy<loy {loy=wy}
1319 if wy>hiy {hiy=wy}
1320 if wz<loz {loz=wz}
1321 if wz>hiz {hiz=wz}
1322 }
1323 vj = vj + 1
1324 }
1325 var bj: i64 = (loy - org)/bcell
1326 let bj1: i64 = (hiy - org)/bcell
1327 while bj <= bj1 {
1328 if bj >= 0 { if bj < nb {
1329 var bk: i64 = (loz - org)/bcell
1330 let bk1: i64 = (hiz - org)/bcell
1331 while bk <= bk1 {
1332 if bk >= 0 { if bk < nb {
1333 if ins < cap {
1334 tref[ins] = t
1335 nxt[ins] = head[bj*nb+bk]
1336 head[bj*nb+bk] = ins
1337 ins = ins + 1
1338 }
1339 } }
1340 bk = bk + 1
1341 }
1342 } }
1343 bj = bj + 1
1344 }
1345 t = t + 1
1346 }
1347 return ins
1348}
1349func ss_gap_region(x: i64, y: i64, z: i64) -> i64 {
1350 // coarse NAMED boxes in the field's own authored frame (mm, +y up, +z face); priority order.
1351 // THE NASAL BOX IS DERIVED FROM THE FIELD'S OWN NASAL PRIMITIVES (AN17, 2026-09-18): the typed box below (|x|<20,
1352 // z>=55, -15<=y<30) read n_ours=0 n_oracle=0 on every trend row since 2026-08-14 -- it was authored for the default
1353 // nasal station (y 8, z 76) while the tuned station had drifted (y -28, z 34), and the oracle's nose, read supine,
1354 // was never where any box expected it. The region is now wherever the nasal-bone ellipsoid and the piriform capsule
1355 // stand in the CURRENT vector: y from the aperture's lowest rim to the top of the nasal bones, |x| within the wider
1356 // of the two radii, z no further back than the nasal ellipsoid's back face. It moves with the tune.
1357 let P: *i64 = ss_pdef()
1358 var ax: i64 = x
1359 if ax < 0 { ax = 0-ax }
1360 if y < 0-55 { return 5 }
1361 var nxr: i64 = P[P_NRX]
1362 if P[P_PAW]/2 > nxr { nxr = P[P_PAW]/2 }
1363 // the aperture hangs from the rhinion (the plate's lower edge), so its lowest rim is one aperture height below it
1364 let nylo: i64 = P[P_NY] - P[P_NRY]*sp_icos(P[P_NTILT])/SS_PERMILLE - P[P_PAH]
1365 let nyhi: i64 = P[P_NY] + P[P_NRY]
1366 let nzlo: i64 = P[P_NZ] - P[P_NRY]
1367 if ax <= nxr { if z >= nzlo { if y >= nylo { if y <= nyhi { return 3 } } } }
1368 if ax < 20 { if z >= 55 { if y >= 0-15 { if y < 30 { return 3 } } } }
1369 if ax < 45 { if z >= 25 { if y >= 5 { if y < 40 { return 2 } } } }
1370 if ax >= 42 { if y >= 0-10 { if y < 25 { if z >= 0-35 { return 4 } } } }
1371 if y >= 0-55 { if y < 0-20 { if z >= 25 { return 6 } } }
1372 if y >= 18 { return 0 }
1373 return 1
1374}
1375func ss_gap_regname(i: i64) -> i64 {
1376 if i == 0 { ss_puts("vault" as *u8); return 0 }
1377 if i == 1 { ss_puts("base_other" as *u8); return 0 }
1378 if i == 2 { ss_puts("brow_orbits" as *u8); return 0 }
1379 if i == 3 { ss_puts("nasal" as *u8); return 0 }
1380 if i == 4 { ss_puts("zygomatic" as *u8); return 0 }
1381 if i == 5 { ss_puts("mandible" as *u8); return 0 }
1382 ss_puts("maxilla" as *u8)
1383 return 0
1384}
1385// heat ramp: green 0mm -> yellow 3mm -> red 8mm+, written as the tri's 3 colour floats
1386func ss_gap_wrcol(b: *u8, o: i64, gq: i64) -> i64 {
1387 let g3: i64 = 3*SS_RDQ
1388 let g8: i64 = 8*SS_RDQ
1389 var r: i64 = 0
1390 var g: i64 = 750
1391 var bl: i64 = 250
1392 if gq <= g3 {
1393 r = 200 + 650*gq/g3
1394 } else {
1395 var t: i64 = (gq-g3)*1000/(g8-g3)
1396 if t > 1000 { t = 1000 }
1397 r = 850 + 50*t/SS_PERMILLE
1398 g = 750 - 500*t/SS_PERMILLE
1399 bl = 250 - 50*t/SS_PERMILLE
1400 }
1401 ss_wr32(b, o, ss_f32(r,1000))
1402 ss_wr32(b, o+4, ss_f32(g,1000))
1403 ss_wr32(b, o+8, ss_f32(bl,1000))
1404 return 0
1405}
1406// nearest grid node index for a world-mm point; wx-org >= 0 always (org is the negative bound)
1407func ss_gap_node(w: i64, org: i64, cell: i64, n1: i64) -> i64 {
1408 var i: i64 = (w - org + cell/2)/cell
1409 if i < 0 { i = 0 }
1410 if i > n1-1 { i = n1-1 }
1411 return i
1412}
1413// write one NXMSH2 header + layer table (single "bone" layer covering nt tris)
1414func ss_gap_wrhdr(buf: *u8, nt: i64) -> i64 {
1415 buf[0]=78 as u8; buf[1]=88 as u8; buf[2]=77 as u8; buf[3]=83 as u8
1416 buf[4]=72 as u8; buf[5]=50 as u8; buf[6]=0 as u8; buf[7]=0 as u8
1417 ss_wr32(buf, 8, 3)
1418 ss_wr32(buf, 12, nt)
1419 var L: i64 = 0
1420 while L < 3 {
1421 let lb: i64 = 16 + L*24
1422 var q: i64 = 0
1423 while q < 16 { buf[lb+q]=0 as u8; q=q+1 }
1424 if L==2 { buf[lb]=98 as u8; buf[lb+1]=111 as u8; buf[lb+2]=110 as u8; buf[lb+3]=101 as u8 }
1425 if L==2 { ss_wr32(buf, lb+16, 0); ss_wr32(buf, lb+20, nt) } else { ss_wr32(buf, lb+16, 0); ss_wr32(buf, lb+20, 0) }
1426 L = L + 1
1427 }
1428 return 0
1429}
1430func ss_gapmap(ref: *u8, oursout: *u8, oraout: *u8, sexf: i64, robust: i64, cum: i64, resout: *u8, latmm: i64) -> i64 {
1431 var G: i64 = (SS_EXT*2*1000 + cum - 1)/cum
1432 if G > SS_EXT*2 { G = SS_EXT*2 }
1433 let cell: i64 = (SS_EXT*2 + G - 1)/G
1434 let org: i64 = 0 - (G*cell)/2
1435 let n1: i64 = G+1
1436 if mf_admit("nx_skullsdf gapmap grids" as *u8, n1*n1*n1*8*3) == 0 { return 8 }
1437 let grid: *i64 = sys_mmap(n1*n1*n1*8) as *i64
1438 let dist: *i64 = sys_mmap(n1*n1*n1*8) as *i64
1439 let odist: *i64 = sys_mmap(n1*n1*n1*8) as *i64
1440 let hq: i64 = cell*SS_RDQ
1441 // ---- OUR true SDF (fill raw, seed, sweep, sign -- the proven redistance recipe) ----
1442 var i: i64 = 0
1443 while i < n1 {
1444 let x: i64 = org + i*cell
1445 var j: i64 = 0
1446 while j < n1 {
1447 let y: i64 = org + j*cell
1448 var k: i64 = 0
1449 while k < n1 {
1450 let z: i64 = org + k*cell
1451 grid[(i*n1+j)*n1+k] = ss_field_world(x, y, z, sexf, robust)
1452 k = k + 1
1453 }
1454 j = j + 1
1455 }
1456 i = i + 1
1457 }
1458 var si: i64 = 0
1459 while si < n1 {
1460 var sj: i64 = 0
1461 while sj < n1 {
1462 var sk: i64 = 0
1463 while sk < n1 {
1464 let ix: i64 = (si*n1+sj)*n1+sk
1465 let f: i64 = grid[ix]
1466 var best: i64 = SS_RD_INF
1467 if si > 0 { best = ss_rd_try(f, grid[((si-1)*n1+sj)*n1+sk], cell, best) }
1468 if si < n1-1 { best = ss_rd_try(f, grid[((si+1)*n1+sj)*n1+sk], cell, best) }
1469 if sj > 0 { best = ss_rd_try(f, grid[(si*n1+(sj-1))*n1+sk], cell, best) }
1470 if sj < n1-1 { best = ss_rd_try(f, grid[(si*n1+(sj+1))*n1+sk], cell, best) }
1471 if sk > 0 { best = ss_rd_try(f, grid[(si*n1+sj)*n1+(sk-1)], cell, best) }
1472 if sk < n1-1 { best = ss_rd_try(f, grid[(si*n1+sj)*n1+(sk+1)], cell, best) }
1473 dist[ix] = best
1474 sk = sk + 1
1475 }
1476 sj = sj + 1
1477 }
1478 si = si + 1
1479 }
1480 var it: i64 = 0
1481 while it < 2 {
1482 var sw: i64 = 0
1483 while sw < 8 {
1484 var di: i64 = 1
1485 if (sw & 1) == 1 { di = 0-1 }
1486 var dj: i64 = 1
1487 if ((sw>>1) & 1) == 1 { dj = 0-1 }
1488 var dk: i64 = 1
1489 if ((sw>>2) & 1) == 1 { dk = 0-1 }
1490 let sd0: i64 = ss_rd_sweep(dist, n1, hq, di, dj, dk)
1491 sw = sw + 1
1492 }
1493 it = it + 1
1494 }
1495 // ---- OUR surface's own bbox centre, then sign restore ----
1496 // The oracle below is centred by ITS bbox; without centring OURS the same way, the authored
1497 // frame's off-centre z biases every gap (first run: nasal read 25mm with n_oracle=0 from
1498 // exactly this). And surface_nets needs the SIGNED field -- polygonizing the unsigned one
1499 // emits a doubled shell (first run: 177,120 tris where the skull has 97,660).
1500 var obx0: i64 = 0; var obx1: i64 = 0
1501 var oby0: i64 = 0; var oby1: i64 = 0
1502 var obz0: i64 = 0; var obz1: i64 = 0
1503 var obfirst: i64 = 1
1504 var bi2: i64 = 0
1505 while bi2 < n1 {
1506 var bj2: i64 = 0
1507 while bj2 < n1 {
1508 var bk2: i64 = 0
1509 while bk2 < n1 {
1510 var ad2: i64 = dist[(bi2*n1+bj2)*n1+bk2]
1511 if ad2 < 0 { ad2 = 0-ad2 }
1512 if ad2 <= hq {
1513 let wx2: i64 = org + bi2*cell
1514 let wy2: i64 = org + bj2*cell
1515 let wz2: i64 = org + bk2*cell
1516 if obfirst == 1 { obx0=wx2; obx1=wx2; oby0=wy2; oby1=wy2; obz0=wz2; obz1=wz2; obfirst=0 } else {
1517 if wx2<obx0 {obx0=wx2}
1518 if wx2>obx1 {obx1=wx2}
1519 if wy2<oby0 {oby0=wy2}
1520 if wy2>oby1 {oby1=wy2}
1521 if wz2<obz0 {obz0=wz2}
1522 if wz2>obz1 {obz1=wz2}
1523 }
1524 }
1525 bk2 = bk2 + 1
1526 }
1527 bj2 = bj2 + 1
1528 }
1529 bi2 = bi2 + 1
1530 }
1531 let ocx: i64 = (obx0+obx1)/2
1532 let ocy: i64 = (oby0+oby1)/2
1533 let ocz: i64 = (obz0+obz1)/2
1534 var sgi: i64 = 0
1535 while sgi < n1*n1*n1 {
1536 if grid[sgi] <= 0 { dist[sgi] = 0 - dist[sgi] }
1537 sgi = sgi + 1
1538 }
1539 // ---- ORACLE distance field on the SAME grid, seeded from its vertices ----
1540 let ln: *i64 = sys_mmap(16) as *i64
1541 let rbuf: *u8 = sys_read_file(ref, ln)
1542 if (rbuf as i64) == 0 { ss_puts("{\x22error\x22:\x22cannot read reference\x22}\n" as *u8); return 3 }
1543 let rlayer: i64 = ss_rd32(rbuf, 8)
1544 let rnt: i64 = ss_rd32(rbuf, 12)
1545 let rhdr: i64 = 16 + rlayer*24
1546 if rnt <= 0 { ss_puts("{\x22error\x22:\x22no reference triangles\x22}\n" as *u8); return 4 }
1547 var lox: i64 = 0; var hix: i64 = 0
1548 var loy: i64 = 0; var hiy: i64 = 0
1549 var loz: i64 = 0; var hiz: i64 = 0
1550 var first: i64 = 1
1551 var t: i64 = 0
1552 while t < rnt {
1553 let o: i64 = rhdr + t*84
1554 var vj: i64 = 0
1555 while vj < 3 {
1556 let x: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12), 1)
1557 let y: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+4), 1)
1558 let z: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+8), 1)
1559 if first == 1 { lox=x; hix=x; loy=y; hiy=y; loz=z; hiz=z; first=0 } else {
1560 if x<lox {lox=x}
1561 if x>hix {hix=x}
1562 if y<loy {loy=y}
1563 if y>hiy {hiy=y}
1564 if z<loz {loz=z}
1565 if z>hiz {hiz=z}
1566 }
1567 vj = vj + 1
1568 }
1569 t = t + 1
1570 }
1571 let cx: i64 = (lox+hix)/2
1572 let cy: i64 = (loy+hiy)/2
1573 let cz: i64 = (loz+hiz)/2
1574 // ***SEEDS CARRY THE SIGN OF THE ORACLE'S OWN VERTEX NORMALS. The first version signed the whole
1575 // near-band negative (flood barrier), and a point-cloud distance field touches zero AT every seed
1576 // -- surface_nets then emitted ONE BEAD PER ORACLE VERTEX (measured: ~380K verts ~ the 171K-vertex
1577 // benchmark, rendered as skull-shaped filigree). A node signed by the side of the surface its
1578 // seeding vertex's normal says it is on crosses zero ONCE.
1579 if mf_admit("nx_skullsdf gapmap seed-signs" as *u8, n1*n1*n1) == 0 { return 8 }
1580 let osgn: *u8 = sys_mmap(n1*n1*n1)
1581 var oi: i64 = 0
1582 while oi < n1*n1*n1 { odist[oi] = SS_RD_INF; osgn[oi] = 0 as u8; oi = oi + 1 }
1583 t = 0
1584 while t < rnt {
1585 let o: i64 = rhdr + t*84
1586 var vj: i64 = 0
1587 while vj < 3 {
1588 let wx: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12), 1) - cx + ocx
1589 let wy: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+8), 1) - cz + ocy
1590 let wz: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+vj*12+4), 1) - cy) + ocz
1591 let nvx: i64 = ss_r_f32(ss_rd32(rbuf,o+36+vj*12), 1000)
1592 let nvy: i64 = ss_r_f32(ss_rd32(rbuf,o+36+vj*12+8), 1000)
1593 let nvz: i64 = 0 - ss_r_f32(ss_rd32(rbuf,o+36+vj*12+4), 1000)
1594 let ni: i64 = ss_gap_node(wx, org, cell, n1)
1595 let nj: i64 = ss_gap_node(wy, org, cell, n1)
1596 let nk: i64 = ss_gap_node(wz, org, cell, n1)
1597 let dxq: i64 = (wx - (org + ni*cell))*SS_RDQ
1598 let dyq: i64 = (wy - (org + nj*cell))*SS_RDQ
1599 let dzq: i64 = (wz - (org + nk*cell))*SS_RDQ
1600 let dq: i64 = ss_isqrt(dxq*dxq + dyq*dyq + dzq*dzq)
1601 let nix: i64 = (ni*n1+nj)*n1+nk
1602 if dq < odist[nix] {
1603 odist[nix] = dq
1604 // node minus vertex, dotted with the outward normal: positive = outside
1605 let dt: i64 = (0-dxq)*nvx + (0-dyq)*nvy + (0-dzq)*nvz
1606 if dt >= 0 { osgn[nix] = 1 as u8 } else { osgn[nix] = 2 as u8 }
1607 }
1608 // ***SEED THE SIX NEIGHBOURS TOO, SIGNED. MEASURED MOTIVE: the benchmark's vertices are
1609 // INTEGER MILLIMETRES, so at cell=1 they land EXACTLY on nodes -- offset zero, sign moot
1610 // (+-0 is 0: the counters read 47,529 outside / 0 inside and both residuals hashed
1611 // identical), and an isolated zero-node beads by construction. A signed +-cell seed on
1612 // each neighbour puts the crossing THROUGH the vertex node instead of islanding it.
1613 var nbi: i64 = 0
1614 while nbi < 6 {
1615 var oi2: i64 = 0
1616 var oj2: i64 = 0
1617 var ok2: i64 = 0
1618 if nbi == 0 { oi2 = 1 }
1619 if nbi == 1 { oi2 = 0-1 }
1620 if nbi == 2 { oj2 = 1 }
1621 if nbi == 3 { oj2 = 0-1 }
1622 if nbi == 4 { ok2 = 1 }
1623 if nbi == 5 { ok2 = 0-1 }
1624 let mi: i64 = ni + oi2
1625 let mj: i64 = nj + oj2
1626 let mk3: i64 = nk + ok2
1627 var inr: i64 = 1
1628 if mi < 0 { inr = 0 }
1629 if mi > n1-1 { inr = 0 }
1630 if mj < 0 { inr = 0 }
1631 if mj > n1-1 { inr = 0 }
1632 if mk3 < 0 { inr = 0 }
1633 if mk3 > n1-1 { inr = 0 }
1634 if inr == 1 {
1635 let vxq: i64 = (org + mi*cell - wx)*SS_RDQ
1636 let vyq: i64 = (org + mj*cell - wy)*SS_RDQ
1637 let vzq: i64 = (org + mk3*cell - wz)*SS_RDQ
1638 let nd2: i64 = ss_isqrt(vxq*vxq + vyq*vyq + vzq*vzq)
1639 let mix: i64 = (mi*n1+mj)*n1+mk3
1640 if nd2 < odist[mix] {
1641 odist[mix] = nd2
1642 let dt2: i64 = vxq*nvx + vyq*nvy + vzq*nvz
1643 if dt2 >= 0 { osgn[mix] = 1 as u8 } else { osgn[mix] = 2 as u8 }
1644 }
1645 }
1646 nbi = nbi + 1
1647 }
1648 vj = vj + 1
1649 }
1650 t = t + 1
1651 }
1652 // instrument the sign seeding itself: a fix whose counters read zero is dead code, not a fix
1653 var sgn_out: i64 = 0
1654 var sgn_in: i64 = 0
1655 var sgi2: i64 = 0
1656 while sgi2 < n1*n1*n1 {
1657 if osgn[sgi2] == (1 as u8) { sgn_out = sgn_out + 1 }
1658 if osgn[sgi2] == (2 as u8) { sgn_in = sgn_in + 1 }
1659 sgi2 = sgi2 + 1
1660 }
1661 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22seedsign\x22,\x22outside\x22:" as *u8); ss_pn(sgn_out)
1662 ss_puts(",\x22inside\x22:" as *u8); ss_pn(sgn_in)
1663 ss_puts("}\n" as *u8)
1664 it = 0
1665 while it < 2 {
1666 var sw2: i64 = 0
1667 while sw2 < 8 {
1668 var di2: i64 = 1
1669 if (sw2 & 1) == 1 { di2 = 0-1 }
1670 var dj2: i64 = 1
1671 if ((sw2>>1) & 1) == 1 { dj2 = 0-1 }
1672 var dk2: i64 = 1
1673 if ((sw2>>2) & 1) == 1 { dk2 = 0-1 }
1674 let sd1: i64 = ss_rd_sweep(odist, n1, hq, di2, dj2, dk2)
1675 sw2 = sw2 + 1
1676 }
1677 it = it + 1
1678 }
1679 // ---- per-region two-sided tallies over both near-bands ----
1680 let fsum: *i64 = sys_mmap(SS_GR_N*8) as *i64
1681 let fmax: *i64 = sys_mmap(SS_GR_N*8) as *i64
1682 let fn: *i64 = sys_mmap(SS_GR_N*8) as *i64
1683 let rsum: *i64 = sys_mmap(SS_GR_N*8) as *i64
1684 let rmax: *i64 = sys_mmap(SS_GR_N*8) as *i64
1685 let rn: *i64 = sys_mmap(SS_GR_N*8) as *i64
1686 var gi: i64 = 0
1687 while gi < SS_GR_N { fsum[gi]=0; fmax[gi]=0; fn[gi]=0; rsum[gi]=0; rmax[gi]=0; rn[gi]=0; gi=gi+1 }
1688 var pi: i64 = 0
1689 while pi < n1 {
1690 let px: i64 = org + pi*cell
1691 var pj: i64 = 0
1692 while pj < n1 {
1693 let py: i64 = org + pj*cell
1694 var pk: i64 = 0
1695 while pk < n1 {
1696 let pz: i64 = org + pk*cell
1697 let ix2: i64 = (pi*n1+pj)*n1+pk
1698 var ao: i64 = dist[ix2]
1699 if ao < 0 { ao = 0-ao }
1700 let r: i64 = ss_gap_region(px, py, pz)
1701 if ao <= hq {
1702 let gv: i64 = odist[ix2]
1703 fsum[r] = fsum[r] + gv
1704 if gv > fmax[r] { fmax[r] = gv }
1705 fn[r] = fn[r] + 1
1706 }
1707 if odist[ix2] <= hq {
1708 rsum[r] = rsum[r] + ao
1709 if ao > rmax[r] { rmax[r] = ao }
1710 rn[r] = rn[r] + 1
1711 }
1712 pk = pk + 1
1713 }
1714 pj = pj + 1
1715 }
1716 pi = pi + 1
1717 }
1718 // ---- heat mesh 1: OUR surface coloured by distance-to-oracle ----
1719 tm_reset()
1720 surface_nets(dist, G, G, G, org, org, org, cell, SS_ISO, SS_BONE)
1721 let nt1: i64 = tm_nt()
1722 if nt1 > 0 {
1723 let h1: i64 = 16 + 3*24
1724 let by1: i64 = h1 + nt1*84 + nt1*4
1725 let b1: *u8 = sys_mmap(by1 + 64)
1726 ss_gap_wrhdr(b1, nt1)
1727 var t1: i64 = 0
1728 while t1 < nt1 {
1729 let o: i64 = h1 + t1*84
1730 let ia: i64 = tm_ta(t1); let ib: i64 = tm_tb(t1); let ic: i64 = tm_tc(t1)
1731 ss_wr32(b1, o, ss_f32(tm_vx(ia),1)); ss_wr32(b1, o+4, ss_f32(tm_vy(ia),1)); ss_wr32(b1, o+8, ss_f32(tm_vz(ia),1))
1732 ss_wr32(b1, o+12, ss_f32(tm_vx(ib),1)); ss_wr32(b1, o+16, ss_f32(tm_vy(ib),1)); ss_wr32(b1, o+20, ss_f32(tm_vz(ib),1))
1733 ss_wr32(b1, o+24, ss_f32(tm_vx(ic),1)); ss_wr32(b1, o+28, ss_f32(tm_vy(ic),1)); ss_wr32(b1, o+32, ss_f32(tm_vz(ic),1))
1734 ss_wr32(b1, o+36, ss_f32(tm_vnx(ia),SS_NQ)); ss_wr32(b1, o+40, ss_f32(tm_vny(ia),SS_NQ)); ss_wr32(b1, o+44, ss_f32(tm_vnz(ia),SS_NQ))
1735 ss_wr32(b1, o+48, ss_f32(tm_vnx(ib),SS_NQ)); ss_wr32(b1, o+52, ss_f32(tm_vny(ib),SS_NQ)); ss_wr32(b1, o+56, ss_f32(tm_vnz(ib),SS_NQ))
1736 ss_wr32(b1, o+60, ss_f32(tm_vnx(ic),SS_NQ)); ss_wr32(b1, o+64, ss_f32(tm_vny(ic),SS_NQ)); ss_wr32(b1, o+68, ss_f32(tm_vnz(ic),SS_NQ))
1737 let mx: i64 = (tm_vx(ia)+tm_vx(ib)+tm_vx(ic))/3
1738 let my: i64 = (tm_vy(ia)+tm_vy(ib)+tm_vy(ic))/3
1739 let mz: i64 = (tm_vz(ia)+tm_vz(ib)+tm_vz(ic))/3
1740 let hi1: i64 = ss_gap_node(mx, org, cell, n1)
1741 let hj1: i64 = ss_gap_node(my, org, cell, n1)
1742 let hk1: i64 = ss_gap_node(mz, org, cell, n1)
1743 ss_gap_wrcol(b1, o+72, odist[(hi1*n1+hj1)*n1+hk1])
1744 ss_wr32(b1, h1 + nt1*84 + t1*4, 2)
1745 t1 = t1 + 1
1746 }
1747 let fd1: i64 = sys_openat_wr(oursout, 420)
1748 sys_write(fd1, b1, by1)
1749 sys_close(fd1)
1750 }
1751 // ---- heat mesh 2: ORACLE surface coloured by distance-to-ours (what we are MISSING) ----
1752 let h2: i64 = 16 + 3*24
1753 let by2: i64 = h2 + rnt*84 + rnt*4
1754 let b2: *u8 = sys_mmap(by2 + 64)
1755 ss_gap_wrhdr(b2, rnt)
1756 t = 0
1757 while t < rnt {
1758 let so: i64 = rhdr + t*84
1759 let dsto: i64 = h2 + t*84
1760 var vj: i64 = 0
1761 var mx2: i64 = 0
1762 var my2: i64 = 0
1763 var mz2: i64 = 0
1764 while vj < 3 {
1765 let wx: i64 = ss_r_f32(ss_rd32(rbuf,so+vj*12), 1) - cx + ocx
1766 let wy: i64 = ss_r_f32(ss_rd32(rbuf,so+vj*12+8), 1) - cz + ocy
1767 let wz: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,so+vj*12+4), 1) - cy) + ocz
1768 ss_wr32(b2, dsto+vj*12, ss_f32(wx,1))
1769 ss_wr32(b2, dsto+vj*12+4, ss_f32(wy,1))
1770 ss_wr32(b2, dsto+vj*12+8, ss_f32(wz,1))
1771 // normals: copy with z negated (decode at mille scale, re-encode negated -- no new
1772 // bit-twiddling operator, and a unit normal loses nothing at 1/SS_PERMILLE resolution)
1773 // normals through the same quarter turn: authored ny = file nz, authored nz = -file ny
1774 ss_wr32(b2, dsto+36+vj*12, ss_rd32(rbuf, so+36+vj*12))
1775 ss_wr32(b2, dsto+36+vj*12+4, ss_rd32(rbuf, so+36+vj*12+8))
1776 let nzv: i64 = ss_r_f32(ss_rd32(rbuf, so+36+vj*12+4), 1000)
1777 ss_wr32(b2, dsto+36+vj*12+8, ss_f32(0-nzv, 1000))
1778 mx2 = mx2 + wx
1779 my2 = my2 + wy
1780 mz2 = mz2 + wz
1781 vj = vj + 1
1782 }
1783 mx2 = mx2/3
1784 my2 = my2/3
1785 mz2 = mz2/3
1786 let hi2: i64 = ss_gap_node(mx2, org, cell, n1)
1787 let hj2: i64 = ss_gap_node(my2, org, cell, n1)
1788 let hk2: i64 = ss_gap_node(mz2, org, cell, n1)
1789 var av: i64 = dist[(hi2*n1+hj2)*n1+hk2]
1790 if av < 0 { av = 0-av }
1791 ss_gap_wrcol(b2, dsto+72, av)
1792 ss_wr32(b2, h2 + rnt*84 + t*4, 2)
1793 t = t + 1
1794 }
1795 let fd2: i64 = sys_openat_wr(oraout, 420)
1796 sys_write(fd2, b2, by2)
1797 sys_close(fd2)
1798 // ---- optional RESIDUAL LAYER: R = O_signed - B at lattice nodes, written as DATA ----
1799 if (resout as i64) != 0 {
1800 // sign the oracle field by flooding OUTSIDE-ness from the box boundary; the near-surface
1801 // band is the barrier. Enclosed cavities (sinuses) stay INSIDE, which is correct anatomy.
1802 if mf_admit("nx_skullsdf gapmap oracle-sign" as *u8, n1*n1*n1*8) == 0 { return 8 }
1803 let mk: *i64 = sys_mmap(n1*n1*n1*8) as *i64
1804 let thr: i64 = hq
1805 var fi: i64 = 0
1806 while fi < n1 {
1807 var fj: i64 = 0
1808 while fj < n1 {
1809 var fk: i64 = 0
1810 while fk < n1 {
1811 let ixf: i64 = (fi*n1+fj)*n1+fk
1812 mk[ixf] = 0
1813 var onb: i64 = 0
1814 if fi == 0 { onb = 1 }
1815 if fi == n1-1 { onb = 1 }
1816 if fj == 0 { onb = 1 }
1817 if fj == n1-1 { onb = 1 }
1818 if fk == 0 { onb = 1 }
1819 if fk == n1-1 { onb = 1 }
1820 if onb == 1 { if odist[ixf] > thr { mk[ixf] = 1 } }
1821 fk = fk + 1
1822 }
1823 fj = fj + 1
1824 }
1825 fi = fi + 1
1826 }
1827 var chg: i64 = 1
1828 var itc: i64 = 0
1829 while chg == 1 {
1830 if itc >= 8 { chg = 0 } else {
1831 chg = 0
1832 var pi2: i64 = 0
1833 while pi2 < n1 {
1834 var pj2: i64 = 0
1835 while pj2 < n1 {
1836 var pk2: i64 = 0
1837 while pk2 < n1 {
1838 let ixp: i64 = (pi2*n1+pj2)*n1+pk2
1839 if mk[ixp] == 0 { if odist[ixp] > thr {
1840 var nb: i64 = 0
1841 if pi2 > 0 { if mk[((pi2-1)*n1+pj2)*n1+pk2] == 1 { nb = 1 } }
1842 if pi2 < n1-1 { if mk[((pi2+1)*n1+pj2)*n1+pk2] == 1 { nb = 1 } }
1843 if pj2 > 0 { if mk[(pi2*n1+(pj2-1))*n1+pk2] == 1 { nb = 1 } }
1844 if pj2 < n1-1 { if mk[(pi2*n1+(pj2+1))*n1+pk2] == 1 { nb = 1 } }
1845 if pk2 > 0 { if mk[(pi2*n1+pj2)*n1+(pk2-1)] == 1 { nb = 1 } }
1846 if pk2 < n1-1 { if mk[(pi2*n1+pj2)*n1+(pk2+1)] == 1 { nb = 1 } }
1847 if nb == 1 { mk[ixp] = 1; chg = 1 }
1848 } }
1849 pk2 = pk2 + 1
1850 }
1851 pj2 = pj2 + 1
1852 }
1853 pi2 = pi2 + 1
1854 }
1855 var qi2: i64 = n1-1
1856 while qi2 >= 0 {
1857 var qj2: i64 = n1-1
1858 while qj2 >= 0 {
1859 var qk2: i64 = n1-1
1860 while qk2 >= 0 {
1861 let ixq: i64 = (qi2*n1+qj2)*n1+qk2
1862 if mk[ixq] == 0 { if odist[ixq] > thr {
1863 var nb2: i64 = 0
1864 if qi2 > 0 { if mk[((qi2-1)*n1+qj2)*n1+qk2] == 1 { nb2 = 1 } }
1865 if qi2 < n1-1 { if mk[((qi2+1)*n1+qj2)*n1+qk2] == 1 { nb2 = 1 } }
1866 if qj2 > 0 { if mk[(qi2*n1+(qj2-1))*n1+qk2] == 1 { nb2 = 1 } }
1867 if qj2 < n1-1 { if mk[(qi2*n1+(qj2+1))*n1+qk2] == 1 { nb2 = 1 } }
1868 if qk2 > 0 { if mk[(qi2*n1+qj2)*n1+(qk2-1)] == 1 { nb2 = 1 } }
1869 if qk2 < n1-1 { if mk[(qi2*n1+qj2)*n1+(qk2+1)] == 1 { nb2 = 1 } }
1870 if nb2 == 1 { mk[ixq] = 1; chg = 1 }
1871 } }
1872 qk2 = qk2 - 1
1873 }
1874 qj2 = qj2 - 1
1875 }
1876 qi2 = qi2 - 1
1877 }
1878 itc = itc + 1
1879 }
1880 }
1881 var lat: i64 = latmm
1882 if lat < cell { lat = cell }
1883 var n2: i64 = (G*cell)/lat + 1
1884 // REFUSE, never clamp: a clamped lattice would silently cover part of the box and be read
1885 // as the whole -- the exact silent-cap class this organ refuses one layer down (grid finer
1886 // than the field). Caught in my own first version, 2026-08-09.
1887 if n2 > SS_RES_MAXN {
1888 ss_puts("{\x22error\x22:\x22residual lattice finer than the bound allows\x22,\x22requested_n\x22:" as *u8); ss_pn(n2)
1889 ss_puts(",\x22max_n\x22:" as *u8); ss_pn(SS_RES_MAXN)
1890 ss_puts(",\x22finest_allowed_lat_mm\x22:" as *u8); ss_pn((G*cell)/(SS_RES_MAXN-1) + 1)
1891 ss_puts("}\n" as *u8)
1892 return 9
1893 }
1894 let rby: i64 = 40 + n2*n2*n2*8
1895 let rb: *u8 = sys_mmap(rby + 64)
1896 let rh: *i64 = rb as *i64
1897 rh[0] = SS_RES_MAGIC
1898 rh[1] = n2
1899 rh[2] = org
1900 rh[3] = lat
1901 rh[4] = SS_RDQ
1902 let rv: *i64 = ((rb as i64) + 40) as *i64
1903 var li: i64 = 0
1904 while li < n2 {
1905 var gi2: i64 = li*lat/cell
1906 if gi2 > n1-1 { gi2 = n1-1 }
1907 var lj: i64 = 0
1908 while lj < n2 {
1909 var gj2: i64 = lj*lat/cell
1910 if gj2 > n1-1 { gj2 = n1-1 }
1911 var lk: i64 = 0
1912 while lk < n2 {
1913 var gk2: i64 = lk*lat/cell
1914 if gk2 > n1-1 { gk2 = n1-1 }
1915 let ixr: i64 = (gi2*n1+gj2)*n1+gk2
1916 var osg: i64 = odist[ixr]
1917 // a normal-signed seed overrides the flood; unseeded nodes fall back to it
1918 var oneg: i64 = 0
1919 if osgn[ixr] == (2 as u8) { oneg = 1 }
1920 if osgn[ixr] == (0 as u8) { if mk[ixr] == 0 { oneg = 1 } }
1921 if oneg == 1 { osg = 0 - osg }
1922 rv[(li*n2+lj)*n2+lk] = osg - dist[ixr]
1923 lk = lk + 1
1924 }
1925 lj = lj + 1
1926 }
1927 li = li + 1
1928 }
1929 let rfd: i64 = sys_openat_wr(resout, 420)
1930 sys_write(rfd, rb, rby)
1931 sys_close(rfd)
1932 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22fitres\x22,\x22lattice_n\x22:" as *u8); ss_pn(n2)
1933 ss_puts(",\x22spacing_mm\x22:" as *u8); ss_pn(lat)
1934 ss_puts(",\x22flood_iters\x22:" as *u8); ss_pn(itc)
1935 ss_puts(",\x22bytes\x22:" as *u8); ss_pn(rby)
1936 ss_puts(",\x22derived_from\x22:\x22the ingested reference -- this file IS the match half of the circle, benchmark evidence, not a product asset\x22}\n" as *u8)
1937 }
1938 // ---- the ranked worklist ----
1939 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22gapmap\x22,\x22cell_mm\x22:" as *u8); ss_pn(cell)
1940 ss_puts(",\x22ours_centre_mm\x22:[" as *u8); ss_pn(ocx)
1941 ss_puts("," as *u8); ss_pn(ocy)
1942 ss_puts("," as *u8); ss_pn(ocz)
1943 ss_puts("]" as *u8)
1944 ss_puts(",\x22bound\x22:\x22vertex-seeded oracle field OVERSTATES gaps by at most half the oracle vertex spacing (~1mm); ours near-band = our surface, oracle near-band = its surface\x22" as *u8)
1945 ss_puts(",\x22regions\x22:[" as *u8)
1946 gi = 0
1947 while gi < SS_GR_N {
1948 if gi > 0 { ss_puts("," as *u8) }
1949 ss_puts("{\x22region\x22:\x22" as *u8)
1950 ss_gap_regname(gi)
1951 ss_puts("\x22,\x22ours_to_oracle_mean_mm\x22:" as *u8)
1952 if fn[gi] > 0 { ss_pn(fsum[gi]/fn[gi]/SS_RDQ) } else { ss_pn(0-1) }
1953 ss_puts(",\x22ours_to_oracle_worst_mm\x22:" as *u8); ss_pn(fmax[gi]/SS_RDQ)
1954 ss_puts(",\x22missing_anatomy_mean_mm\x22:" as *u8)
1955 if rn[gi] > 0 { ss_pn(rsum[gi]/rn[gi]/SS_RDQ) } else { ss_pn(0-1) }
1956 ss_puts(",\x22missing_anatomy_worst_mm\x22:" as *u8); ss_pn(rmax[gi]/SS_RDQ)
1957 ss_puts(",\x22n_ours\x22:" as *u8); ss_pn(fn[gi])
1958 ss_puts(",\x22n_oracle\x22:" as *u8); ss_pn(rn[gi])
1959 ss_puts("}" as *u8)
1960 gi = gi + 1
1961 }
1962 ss_puts("]}\n" as *u8)
1963 return 0
1964}
1965
1966// ---- VOXREF: the oracle voxelized by exact triangle crossings + parity (derived bounds, no caps) ----
1967func ss_voxref(ref: *u8, outp: *u8, cum: i64) -> i64 {
1968 var G: i64 = (SS_EXT*2*1000 + cum - 1)/cum
1969 if G > SS_EXT*2 { G = SS_EXT*2 }
1970 let cell: i64 = (SS_EXT*2 + G - 1)/G
1971 let org: i64 = 0 - (G*cell)/2
1972 let n1: i64 = G+1
1973 let ln: *i64 = sys_mmap(16) as *i64
1974 let rbuf: *u8 = sys_read_file(ref, ln)
1975 if (rbuf as i64) == 0 { ss_puts("{\x22error\x22:\x22cannot read reference\x22}\n" as *u8); return 3 }
1976 let rlayer: i64 = ss_rd32(rbuf, 8)
1977 let rnt: i64 = ss_rd32(rbuf, 12)
1978 let rhdr: i64 = 16 + rlayer*24
1979 if rnt <= 0 { ss_puts("{\x22error\x22:\x22no reference triangles\x22}\n" as *u8); return 4 }
1980 // bbox centre (mm)
1981 var lox: i64 = 0; var hix: i64 = 0
1982 var loy: i64 = 0; var hiy: i64 = 0
1983 var loz: i64 = 0; var hiz: i64 = 0
1984 var first: i64 = 1
1985 var t: i64 = 0
1986 while t < rnt {
1987 let o: i64 = rhdr + t*84
1988 var vj: i64 = 0
1989 while vj < 3 {
1990 let x: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12), 1)
1991 let y: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+4), 1)
1992 let z: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+8), 1)
1993 if first == 1 { lox=x; hix=x; loy=y; hiy=y; loz=z; hiz=z; first=0 } else {
1994 if x<lox {lox=x}
1995 if x>hix {hix=x}
1996 if y<loy {loy=y}
1997 if y>hiy {hiy=y}
1998 if z<loz {loz=z}
1999 if z>hiz {hiz=z}
2000 }
2001 vj = vj + 1
2002 }
2003 t = t + 1
2004 }
2005 let cx: i64 = (lox+hix)/2
2006 let cy: i64 = (loy+hiy)/2
2007 let cz: i64 = (loz+hiz)/2
2008 // buckets over (y,z) AT GRID RESOLUTION -- granularity derived from the grid, storage sized by
2009 // the counting pass: no capacity constant exists to hit
2010 let nb: i64 = G + 2
2011 let nins: i64 = ss_vb_count(rbuf, rhdr, rnt, cy, cz, 0, 0, org, nb, cell)
2012 if nins <= 0 { ss_puts("{\x22error\x22:\x22no triangles land in the grid\x22}\n" as *u8); return 4 }
2013 if mf_admit("nx_skullsdf voxref" as *u8, n1*n1*n1*8 + nb*nb*8 + nins*16) == 0 { return 8 }
2014 let head: *i64 = sys_mmap(nb*nb*8) as *i64
2015 let nxt: *i64 = sys_mmap(nins*8) as *i64
2016 let tref: *i64 = sys_mmap(nins*8) as *i64
2017 let ins: i64 = ss_vb_build(rbuf, rhdr, rnt, cx, cy, cz, 0, 0, 0, org, nb, cell, head, nxt, tref, nins)
2018 if ins != nins {
2019 // the two passes walk identical loops; disagreement is an internal defect, never tolerable
2020 ss_puts("{\x22error\x22:\x22count/fill mismatch\x22,\x22counted\x22:" as *u8); ss_pn(nins)
2021 ss_puts(",\x22filled\x22:" as *u8); ss_pn(ins)
2022 ss_puts("}\n" as *u8)
2023 return 9
2024 }
2025 // per-column hit buffer sized by the longest measured bucket (the exact upper bound)
2026 var maxlist: i64 = 0
2027 var bc2: i64 = 0
2028 while bc2 < nb*nb {
2029 var ll: i64 = 0
2030 var p2: i64 = head[bc2]
2031 while p2 >= 0 { ll = ll + 1; p2 = nxt[p2] }
2032 if ll > maxlist { maxlist = ll }
2033 bc2 = bc2 + 1
2034 }
2035 // signed field, Q units; parity signs every node, crossings seed exact flank distances
2036 let fld: *i64 = sys_mmap(n1*n1*n1*8) as *i64
2037 let hits: *i64 = sys_mmap((maxlist+1)*8) as *i64
2038 let orgq: i64 = org*SS_RDQ
2039 let cellq: i64 = cell*SS_RDQ
2040 var totalhits: i64 = 0
2041 var repaired: i64 = 0
2042 var maxnd: i64 = 0
2043 var j: i64 = 0
2044 while j < n1 {
2045 let y0q: i64 = (org + j*cell)*SS_RDQ
2046 var k: i64 = 0
2047 while k < n1 {
2048 let z0q: i64 = (org + k*cell)*SS_RDQ
2049 let bj: i64 = j
2050 let bk: i64 = k
2051 var nh: i64 = 0
2052 if bj >= 0 { if bj < nb { if bk >= 0 { if bk < nb {
2053 var p: i64 = head[bj*nb+bk]
2054 while p >= 0 {
2055 let tt: i64 = tref[p]
2056 let o: i64 = rhdr + tt*84
2057 let xa: i64 = ss_r_f32(ss_rd32(rbuf,o), SS_RDQ) - cx*SS_RDQ
2058 let ya: i64 = ss_r_f32(ss_rd32(rbuf,o+8), SS_RDQ) - cz*SS_RDQ
2059 let za: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+4), SS_RDQ) - cy*SS_RDQ)
2060 let xb: i64 = ss_r_f32(ss_rd32(rbuf,o+12), SS_RDQ) - cx*SS_RDQ
2061 let yb: i64 = ss_r_f32(ss_rd32(rbuf,o+20), SS_RDQ) - cz*SS_RDQ
2062 let zb: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+16), SS_RDQ) - cy*SS_RDQ)
2063 let xc: i64 = ss_r_f32(ss_rd32(rbuf,o+24), SS_RDQ) - cx*SS_RDQ
2064 let yc: i64 = ss_r_f32(ss_rd32(rbuf,o+32), SS_RDQ) - cz*SS_RDQ
2065 let zc: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+28), SS_RDQ) - cy*SS_RDQ)
2066 // edge functions in the (y,z) plane at (y0q,z0q)
2067 let e0: i64 = (yb-ya)*(z0q-za) - (zb-za)*(y0q-ya)
2068 let e1: i64 = (yc-yb)*(z0q-zb) - (zc-zb)*(y0q-yb)
2069 let e2: i64 = (ya-yc)*(z0q-zc) - (za-zc)*(y0q-yc)
2070 var hit: i64 = 0
2071 if e0 >= 0 { if e1 >= 0 { if e2 >= 0 { hit = 1 } } }
2072 if e0 <= 0 { if e1 <= 0 { if e2 <= 0 { hit = 1 } } }
2073 if hit == 1 {
2074 let den: i64 = e0 + e1 + e2
2075 if den != 0 {
2076 // barycentric: e1 weights vertex a, e2 weights b, e0 weights c
2077 // nh is bounded by this bucket's own length <= maxlist: no cap exists
2078 let xq: i64 = (e1*xa + e2*xb + e0*xc)/den
2079 hits[nh] = xq
2080 nh = nh + 1
2081 }
2082 }
2083 p = nxt[p]
2084 }
2085 } } } }
2086 // insertion sort + dedup within 2 Q (shared-edge doubles)
2087 var s1: i64 = 1
2088 while s1 < nh {
2089 let v: i64 = hits[s1]
2090 var s2: i64 = s1
2091 var go2: i64 = 1
2092 while go2 == 1 {
2093 if s2 <= 0 { go2 = 0 } else {
2094 if hits[s2-1] > v { hits[s2] = hits[s2-1]; s2 = s2 - 1 } else { go2 = 0 }
2095 }
2096 }
2097 hits[s2] = v
2098 s1 = s1 + 1
2099 }
2100 var nd: i64 = 0
2101 var s3: i64 = 0
2102 while s3 < nh {
2103 var keep: i64 = 1
2104 // shared-edge duplicates coincide geometrically; each crossing rounds ONCE in the
2105 // barycentric integer division, so duplicates differ by at most 2 quanta -- the
2106 // tolerance is the arithmetic's own bound, not a tuned number
2107 if nd > 0 { if hits[s3] - hits[nd-1] <= 2 { keep = 0 } }
2108 if keep == 1 { hits[nd] = hits[s3]; nd = nd + 1 }
2109 s3 = s3 + 1
2110 }
2111 // parity repair: an ODD count means this ray passed through a hole in the scan; the
2112 // unpaired crossing would flip parity for the rest of the column and extrude a streak to
2113 // the box edge (rendered, measured). Drop the deepest crossing so parity closes; COUNT it.
2114 if (nd & 1) == 1 { nd = nd - 1; repaired = repaired + 1 }
2115 if nd > maxnd { maxnd = nd }
2116 totalhits = totalhits + nd
2117 // walk nodes: parity sign everywhere, exact seeds at crossing flanks
2118 var hi2: i64 = 0
2119 var i: i64 = 0
2120 while i < n1 {
2121 let nxq: i64 = orgq + i*cellq
2122 var go3: i64 = 1
2123 while go3 == 1 {
2124 if hi2 >= nd { go3 = 0 } else {
2125 if hits[hi2] <= nxq { hi2 = hi2 + 1 } else { go3 = 0 }
2126 }
2127 }
2128 var fv: i64 = SS_RD_INF
2129 // distance to nearest crossing on this column (exact near the surface)
2130 if hi2 > 0 {
2131 let dl: i64 = nxq - hits[hi2-1]
2132 if dl < fv { fv = dl }
2133 }
2134 if hi2 < nd {
2135 let dr: i64 = hits[hi2] - nxq
2136 if dr < fv { fv = dr }
2137 }
2138 // parity: odd crossings passed = inside
2139 if (hi2 & 1) == 1 { fv = 0 - fv }
2140 fld[(i*n1+j)*n1+k] = fv
2141 i = i + 1
2142 }
2143 k = k + 1
2144 }
2145 j = j + 1
2146 }
2147 // polygonize O alone -- the control: is O the skull?
2148 tm_reset()
2149 surface_nets(fld, G, G, G, org, org, org, cell, SS_ISO, SS_BONE)
2150 let nv: i64 = tm_nv()
2151 let nt2: i64 = tm_nt()
2152 if nt2 <= 0 { ss_puts("{\x22error\x22:\x22no surface\x22}\n" as *u8); return 5 }
2153 let h1: i64 = 16 + 3*24
2154 let by1: i64 = h1 + nt2*84 + nt2*4
2155 let b1: *u8 = sys_mmap(by1 + 64)
2156 ss_gap_wrhdr(b1, nt2)
2157 var t2: i64 = 0
2158 while t2 < nt2 {
2159 let o: i64 = h1 + t2*84
2160 let ia: i64 = tm_ta(t2); let ib: i64 = tm_tb(t2); let ic: i64 = tm_tc(t2)
2161 ss_wr32(b1, o, ss_f32(tm_vx(ia),1)); ss_wr32(b1, o+4, ss_f32(tm_vy(ia),1)); ss_wr32(b1, o+8, ss_f32(tm_vz(ia),1))
2162 ss_wr32(b1, o+12, ss_f32(tm_vx(ib),1)); ss_wr32(b1, o+16, ss_f32(tm_vy(ib),1)); ss_wr32(b1, o+20, ss_f32(tm_vz(ib),1))
2163 ss_wr32(b1, o+24, ss_f32(tm_vx(ic),1)); ss_wr32(b1, o+28, ss_f32(tm_vy(ic),1)); ss_wr32(b1, o+32, ss_f32(tm_vz(ic),1))
2164 ss_wr32(b1, o+36, ss_f32(tm_vnx(ia),SS_NQ)); ss_wr32(b1, o+40, ss_f32(tm_vny(ia),SS_NQ)); ss_wr32(b1, o+44, ss_f32(tm_vnz(ia),SS_NQ))
2165 ss_wr32(b1, o+48, ss_f32(tm_vnx(ib),SS_NQ)); ss_wr32(b1, o+52, ss_f32(tm_vny(ib),SS_NQ)); ss_wr32(b1, o+56, ss_f32(tm_vnz(ib),SS_NQ))
2166 ss_wr32(b1, o+60, ss_f32(tm_vnx(ic),SS_NQ)); ss_wr32(b1, o+64, ss_f32(tm_vny(ic),SS_NQ)); ss_wr32(b1, o+68, ss_f32(tm_vnz(ic),SS_NQ))
2167 ss_wr32(b1, o+72, ss_f32(910,1000)); ss_wr32(b1, o+76, ss_f32(890,1000)); ss_wr32(b1, o+80, ss_f32(845,1000))
2168 ss_wr32(b1, h1 + nt2*84 + t2*4, 2)
2169 t2 = t2 + 1
2170 }
2171 let fd1: i64 = sys_openat_wr(outp, MODE_0644)
2172 sys_write(fd1, b1, by1)
2173 sys_close(fd1)
2174 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22voxref\x22,\x22cell_mm\x22:" as *u8); ss_pn(cell)
2175 ss_puts(",\x22crossings\x22:" as *u8); ss_pn(totalhits)
2176 ss_puts(",\x22parity_repaired_columns\x22:" as *u8); ss_pn(repaired)
2177 ss_puts(",\x22max_crossings_per_column\x22:" as *u8); ss_pn(maxnd)
2178 ss_puts(",\x22max_bucket_len\x22:" as *u8); ss_pn(maxlist)
2179 ss_puts(",\x22bucket_insertions\x22:" as *u8); ss_pn(ins)
2180 ss_puts(",\x22verts\x22:" as *u8); ss_pn(nv)
2181 ss_puts(",\x22tris\x22:" as *u8); ss_pn(nt2)
2182 ss_puts(",\x22overflow\x22:" as *u8); ss_pn(tm_ovf())
2183 ss_puts(",\x22method\x22:\x22exact triangle crossings per grid column + parity sign -- the control: this is O alone, no base, no residual\x22}\n" as *u8)
2184 return 0
2185}
2186
2187// ---- REDISTANCE HELPERS (argv[8]; see the SS_RDQ const block for why this pass exists) ----
2188// one seed candidate: if f and g straddle the iso level, the crossing sits |f|/(|f|+|g|) along the
2189// edge; the distance from this node to it, in SS_RDQ units, competes for the seed minimum
2190func ss_rd_try(f: i64, g: i64, cell: i64, best: i64) -> i64 {
2191 var fin: i64 = 0
2192 if f <= 0 { fin = 1 }
2193 var gin: i64 = 0
2194 if g <= 0 { gin = 1 }
2195 if fin == gin { return best }
2196 var af: i64 = f
2197 if af < 0 { af = 0-af }
2198 var ag: i64 = g
2199 if ag < 0 { ag = 0-ag }
2200 var den: i64 = af+ag
2201 if den < 1 { den = 1 }
2202 let t: i64 = af*cell*SS_RDQ/den
2203 if t < best { return t }
2204 return best
2205}
2206// upwind eikonal update from the per-axis neighbour minima with grid spacing h (all SS_RDQ units).
2207// Sequential form: try 1D, then 2D, then 3D. Each discriminant is positive when its case is reached
2208// (reaching 2D means a+h > b so (a-b)^2 < h^2 < 2h^2), but both are still guarded.
2209func ss_rd_solve(a0: i64, b0: i64, c0: i64, h: i64) -> i64 {
2210 var a: i64 = a0
2211 var b: i64 = b0
2212 var c: i64 = c0
2213 var tv: i64 = 0
2214 if a > b { tv=a; a=b; b=tv }
2215 if b > c { tv=b; b=c; c=tv }
2216 if a > b { tv=a; a=b; b=tv }
2217 if a >= SS_RD_INF { return SS_RD_INF }
2218 var d: i64 = a + h
2219 if d <= b { return d }
2220 let s2: i64 = 2*h*h - (a-b)*(a-b)
2221 if s2 > 0 { d = (a + b + ss_isqrt(s2))/2 }
2222 if d <= c { return d }
2223 let s: i64 = a+b+c
2224 let s3: i64 = s*s - 3*(a*a + b*b + c*c - h*h)
2225 if s3 > 0 { return (s + ss_isqrt(s3))/3 }
2226 return d
2227}
2228// one directional sweep; returns the largest single-node improvement so convergence is a PRINTED
2229// number rather than an assumption. Min-update only ever lowers a value, and an eikonal update from
2230// true-distance neighbours can never undercut the true distance (triangle inequality), so the exact
2231// sub-cell seeds survive every sweep without a freeze flag.
2232func ss_rd_sweep(dist: *i64, n1: i64, h: i64, di: i64, dj: i64, dk: i64) -> i64 {
2233 var maxd: i64 = 0
2234 var sa: i64 = 0
2235 while sa < n1 {
2236 var i: i64 = sa
2237 if di < 0 { i = n1-1-sa }
2238 var sb: i64 = 0
2239 while sb < n1 {
2240 var j: i64 = sb
2241 if dj < 0 { j = n1-1-sb }
2242 var sc: i64 = 0
2243 while sc < n1 {
2244 var k: i64 = sc
2245 if dk < 0 { k = n1-1-sc }
2246 let ix: i64 = (i*n1+j)*n1+k
2247 let cur: i64 = dist[ix]
2248 if cur > 0 {
2249 var ax: i64 = SS_RD_INF
2250 if i > 0 { ax = dist[((i-1)*n1+j)*n1+k] }
2251 if i < n1-1 {
2252 let wx: i64 = dist[((i+1)*n1+j)*n1+k]
2253 if wx < ax { ax = wx }
2254 }
2255 var ay: i64 = SS_RD_INF
2256 if j > 0 { ay = dist[(i*n1+(j-1))*n1+k] }
2257 if j < n1-1 {
2258 let wy: i64 = dist[(i*n1+(j+1))*n1+k]
2259 if wy < ay { ay = wy }
2260 }
2261 var az: i64 = SS_RD_INF
2262 if k > 0 { az = dist[(i*n1+j)*n1+(k-1)] }
2263 if k < n1-1 {
2264 let wz: i64 = dist[(i*n1+j)*n1+(k+1)]
2265 if wz < az { az = wz }
2266 }
2267 let nd: i64 = ss_rd_solve(ax, ay, az, h)
2268 if nd < cur {
2269 dist[ix] = nd
2270 let dl: i64 = cur - nd
2271 if dl > maxd { maxd = dl }
2272 }
2273 }
2274 sc = sc + 1
2275 }
2276 sb = sb + 1
2277 }
2278 sa = sa + 1
2279 }
2280 return maxd
2281}
2282// near-band |grad| distribution of a SAMPLED field, per-mille of a true SDF -- the same statistic
2283// ss_grad reports for the analytic field, taken here on the grid so the pass can be A/B'd in-run.
2284// q = field units per millimetre (1 for the raw grid, SS_RDQ for the redistanced one).
2285func ss_rd_gradstat(F: *i64, n1: i64, cell: i64, q: i64, tag: *u8) -> i64 {
2286 var lo: i64 = SS_EXTENT_SENTINEL
2287 var hi: i64 = 0-SS_EXTENT_SENTINEL
2288 var sum: i64 = 0
2289 var n: i64 = 0
2290 var under: i64 = 0
2291 var over: i64 = 0
2292 let band: i64 = SS_RD_NEAR*cell*q
2293 var i: i64 = 1
2294 while i < n1-1 {
2295 var j: i64 = 1
2296 while j < n1-1 {
2297 var k: i64 = 1
2298 while k < n1-1 {
2299 let f: i64 = F[(i*n1+j)*n1+k]
2300 var af: i64 = f
2301 if af < 0 { af = 0-af }
2302 if af <= band {
2303 let gx: i64 = F[((i+1)*n1+j)*n1+k] - F[((i-1)*n1+j)*n1+k]
2304 let gy: i64 = F[(i*n1+(j+1))*n1+k] - F[(i*n1+(j-1))*n1+k]
2305 let gz: i64 = F[(i*n1+j)*n1+(k+1)] - F[(i*n1+j)*n1+(k-1)]
2306 let g: i64 = ss_isqrt(gx*gx + gy*gy + gz*gz)*1000/(2*cell*q)
2307 if g < lo { lo = g }
2308 if g > hi { hi = g }
2309 sum = sum + g
2310 n = n + 1
2311 if g < SS_RD_LO { under = under + 1 }
2312 if g > SS_RD_HI { over = over + 1 }
2313 }
2314 k = k + 1
2315 }
2316 j = j + 1
2317 }
2318 i = i + 1
2319 }
2320 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22redist_gradstat\x22,\x22field\x22:\x22" as *u8)
2321 ss_puts(tag)
2322 ss_puts("\x22,\x22true_sdf_is\x22:1000,\x22samples\x22:" as *u8); ss_pn(n)
2323 if n > 0 {
2324 ss_puts(",\x22mean\x22:" as *u8); ss_pn(sum/n)
2325 ss_puts(",\x22min\x22:" as *u8); ss_pn(lo)
2326 ss_puts(",\x22max\x22:" as *u8); ss_pn(hi)
2327 ss_puts(",\x22under_800_permil\x22:" as *u8); ss_pn(under*1000/n)
2328 ss_puts(",\x22over_1200_permil\x22:" as *u8); ss_pn(over*1000/n)
2329 }
2330 ss_puts("}\n" as *u8)
2331 return 0
2332}
2333
2334func main(argc: i64, argv: *i64) -> i64 {
2335 if argc < 2 { return 2 }
2336 if ss_streq(argv[1] as *u8, "tune" as *u8) != 1 { ss_puts("CANDIDATE: explicit new fit only; emission not installed\n" as *u8); return 2 }
2337 if argc < 2 { ss_puts("usage: nx_skullsdf <out.nxmesh> [sex] [robust] [grid] [cell_um] [tissue_permil] [k_mm] [redist] | fit <ref> | tune <ref> | gapmap <ref> <heat_ours> <heat_oracle>\n" as *u8); return 2 }
2338 if ss_streq(argv[1] as *u8, "tune" as *u8) == 1 {
2339 if argc < 3 { ss_puts("usage: nx_skullsdf tune <ref.nxmesh> [sex] [robust] [stride] [passes] [step0] [save_dat]\n" as *u8); return 2 }
2340 var ts: i64 = 0
2341 if argc > 3 { ts = ss_atoi(argv[3] as *u8) }
2342 var tr: i64 = 500
2343 if argc > 4 { tr = ss_atoi(argv[4] as *u8) }
2344 var tst: i64 = 31
2345 if argc > 5 { tst = ss_atoi(argv[5] as *u8) }
2346 if tst < 1 { tst = 1 }
2347 var tp: i64 = 5
2348 if argc > 6 { tp = ss_atoi(argv[6] as *u8) }
2349 var tstep: i64 = 8
2350 if argc > 7 { tstep = ss_atoi(argv[7] as *u8) }
2351 var tsv: i64 = 0
2352 if argc > 8 { tsv = argv[8] }
2353 return ss_tune(argv[2] as *u8, ts, tr, tst, tp, tstep, tsv as *u8)
2354 }
2355 if ss_streq(argv[1] as *u8, "grad" as *u8) == 1 {
2356 var gs: i64 = 0
2357 if argc > 2 { gs = ss_atoi(argv[2] as *u8) }
2358 var gr: i64 = 500
2359 if argc > 3 { gr = ss_atoi(argv[3] as *u8) }
2360 var gp: i64 = 4
2361 if argc > 4 { gp = ss_atoi(argv[4] as *u8) }
2362 if gp < 1 { gp = 1 }
2363 if argc > 5 {
2364 SS_KVAL = ss_atoi(argv[5] as *u8)
2365 if SS_KVAL >= 0 { SS_KSET = 1 }
2366 }
2367 return ss_grad(gs, gr, gp, 3)
2368 }
2369 if ss_streq(argv[1] as *u8, "thick" as *u8) == 1 {
2370 if argc < 3 { ss_puts("usage: nx_skullsdf thick <envelope.nxmesh> [sex] [robust] [stride]\n" as *u8); return 2 }
2371 var ks: i64 = 0
2372 if argc > 3 { ks = ss_atoi(argv[3] as *u8) }
2373 var kr: i64 = 500
2374 if argc > 4 { kr = ss_atoi(argv[4] as *u8) }
2375 var kt: i64 = 7
2376 if argc > 5 { kt = ss_atoi(argv[5] as *u8) }
2377 if kt < 1 { kt = 1 }
2378 return ss_thick(argv[2] as *u8, ks, kr, kt)
2379 }
2380 if ss_streq(argv[1] as *u8, "voxref" as *u8) == 1 {
2381 if argc < 4 { ss_puts("usage: nx_skullsdf voxref <ref.nxmesh> <out.nxmesh> [cell_um]\n" as *u8); return 2 }
2382 var vc: i64 = 1000
2383 if argc > 4 { vc = ss_atoi(argv[4] as *u8) }
2384 if vc < 1000 { vc = 1000 }
2385 return ss_voxref(argv[2] as *u8, argv[3] as *u8, vc)
2386 }
2387 if ss_streq(argv[1] as *u8, "gapmap" as *u8) == 1 {
2388 if argc < 5 { ss_puts("usage: nx_skullsdf gapmap <ref.nxmesh> <heat_ours.nxmesh> <heat_oracle.nxmesh> [sex] [robust] [cell_um]\n" as *u8); return 2 }
2389 var ms: i64 = 0
2390 if argc > 5 { ms = ss_atoi(argv[5] as *u8) }
2391 var mr: i64 = 500
2392 if argc > 6 { mr = ss_atoi(argv[6] as *u8) }
2393 var mc: i64 = SS_MARCH_CELLS_DEFAULT
2394 if argc > 7 { mc = ss_atoi(argv[7] as *u8) }
2395 if mc < SS_MARCH_CELLS_MIN { mc = SS_MARCH_CELLS_MIN }
2396 var mres: i64 = 0
2397 if argc > 8 { mres = argv[8] }
2398 var mlat: i64 = 4
2399 if argc > 9 { mlat = ss_atoi(argv[9] as *u8) }
2400 return ss_gapmap(argv[2] as *u8, argv[3] as *u8, argv[4] as *u8, ms, mr, mc, mres as *u8, mlat)
2401 }
2402 if ss_streq(argv[1] as *u8, "fit" as *u8) == 1 {
2403 if argc < 3 { ss_puts("usage: nx_skullsdf fit <ref.nxmesh> [sex] [robust] [stride]\n" as *u8); return 2 }
2404 var fs: i64 = 0
2405 if argc > 3 { fs = ss_atoi(argv[3] as *u8) }
2406 var fr: i64 = 500
2407 if argc > 4 { fr = ss_atoi(argv[4] as *u8) }
2408 var st: i64 = 7
2409 if argc > 5 { st = ss_atoi(argv[5] as *u8) }
2410 if st < 1 { st = 1 }
2411 return ss_fit(argv[2] as *u8, fs, fr, st)
2412 }
2413 var sexf: i64 = 0
2414 if argc > 2 { sexf = ss_atoi(argv[2] as *u8) }
2415 var robust: i64 = 500
2416 if argc > 3 { robust = ss_atoi(argv[3] as *u8) }
2417 var G: i64 = SS_G
2418 if argc > 4 { G = ss_atoi(argv[4] as *u8) }
2419 // ★★CELL-SIZE-DRIVEN RESOLUTION (argv[5], MICROMETRES) -- the honest dial, additive so argv[4] still
2420 // means G for every existing caller.
2421 // WHY: `cell` below is INTEGER MILLIMETRES, so with a 320mm extent EVERY G from 161 to 319 yields
2422 // cell=2. Raising G in that range buys ZERO resolution while GROWING THE BOX (G=224 covers 448mm at
2423 // the SAME 2mm) and the allocation with it -- the dial is actively harmful in its dead zone.
2424 // MEASURED: G=160, 176 and 192 emit BYTE-IDENTICAL geometry (cell 2, verts 48814, tris 97660).
2425 // Asking for a CELL SIZE makes resolution monotonic and the box exactly the extent, with no waste.
2426 if argc > 5 {
2427 let cum: i64 = ss_atoi(argv[5] as *u8)
2428 if cum > 0 { G = (SS_EXT*2*1000 + cum - 1)/cum }
2429 }
2430
2431 // ★TISSUE ENVELOPE (argv[6], per-mille of the published depths). ADDITIVE by construction: absent or 0
2432 // means SS_TISSUE stays 0 and the bone surface is emitted exactly as before.
2433 if argc > 6 {
2434 let tp: i64 = ss_atoi(argv[6] as *u8)
2435 if tp > 0 { SS_TISSUE = tp }
2436 }
2437 // SMOOTH-UNION RADIUS (argv[7], mm). Set 0 for a TRUE distance field with visible sutures.
2438 if argc > 7 {
2439 SS_KVAL = ss_atoi(argv[7] as *u8)
2440 if SS_KVAL >= 0 { SS_KSET = 1 }
2441 }
2442 // REDISTANCE (argv[8]). ★DEFAULT NOW 1 (2026-08-10, shipped winners: a plain call gets the true
2443 // SDF; pass 0 explicitly for the legacy raw field).
2444 SS_REDIST = 1
2445 if argc > 8 {
2446 SS_REDIST = ss_atoi(argv[8] as *u8)
2447 }
2448 // RESIDUAL (argv[9] scale permil, argv[10] path): the input-derived identity layer on top of the
2449 // parametric base. ★DEFAULT NOW 250 PERMIL (2026-08-10, operator: a bug to not ship): measured ladder
2450 // 0->73, 250->125 with silhouettes held and the onion-ring class dead by eye, 1000->bead cloud.
2451 // Explicit argv[9] overrides (0 disables). A missing/invalid residual file FAILS OPEN to the
2452 // parametric base on the DEFAULT path -- only an EXPLICIT request errors loudly.
2453 if argc <= 9 { SS_RESSC = 250 }
2454 if argc > 9 { SS_RESSC = ss_atoi(argv[9] as *u8) }
2455 if SS_RESSC > 0 {
2456 var rp: *u8 = "knowledge/skull_res.dat" as *u8
2457 if argc > 10 { rp = argv[10] as *u8 }
2458 if ss_res_load(rp) == 0 {
2459 if argc > 9 {
2460 ss_puts("{\x22error\x22:\x22residual requested but the file did not load (magic/size/bounds)\x22}\n" as *u8)
2461 return 6
2462 }
2463 SS_RESSC = 0
2464 }
2465 if SS_RESSC > 0 { if SS_REDIST != 1 {
2466 if argc > 9 {
2467 ss_puts("{\x22error\x22:\x22residual requires redist=1 (argv[8]): the base must be a true SDF\x22}\n" as *u8)
2468 return 6
2469 }
2470 SS_RESSC = 0
2471 }}
2472 }
2473
2474 // ⚠CEILING, not truncation. SS_EXT*2/G with 260mm over 144 cells gives cell=1, so the grid covered
2475 // only 144mm and CLIPPED the skull at its own boundary -- which is why width and depth both came
2476 // back as 142: they were not measurements of the skull, they were measurements of the box.
2477 let cell: i64 = (SS_EXT*2 + G - 1)/G
2478 if cell*G < SS_EXT*2 { ss_puts("{\x22error\x22:\x22grid does not cover the extent\x22}\n" as *u8); return 7 }
2479 // THE DIAL'S OTHER DEAD ZONE, AND IT IS THE SAME DEFECT ONE LEVEL DOWN. `cell` is an INTEGER
2480 // NUMBER OF MILLIMETRES, so the finest resolution this field can be sampled at is 1mm, reached at
2481 // G = SS_EXT*2. Every G ABOVE that still yields cell=1 -- but G*cell then EXCEEDS the extent, so the
2482 // grid silently covers a LARGER BOX at the SAME resolution: G=480 sampled 480mm instead of 240mm,
2483 // costing 8x the memory and 8x the time for ZERO extra detail, while still printing a `grid` field
2484 // that implies the caller got what they asked for.
2485 // That is exactly the failure the micrometre dial above was added to cure, so silently tolerating
2486 // it here would leave the cure with the disease inside it. REFUSE, and NAME the finest cell that is
2487 // actually expressible -- an honest non-answer beats a wrong mesh (the nx_memfloor law, applied to
2488 // over-resolution rather than over-allocation).
2489 if G > SS_EXT*2 {
2490 ss_puts("{\x22error\x22:\x22grid finer than the field can be sampled\x22,\x22requested_grid\x22:" as *u8); ss_pn(G)
2491 ss_puts(",\x22max_grid\x22:" as *u8); ss_pn(SS_EXT*2)
2492 ss_puts(",\x22finest_cell_mm\x22:1,\x22why\x22:\x22cell size is integer millimetres, so G above 2*SS_EXT grows the sampled box without adding resolution\x22}\n" as *u8)
2493 return 9
2494 }
2495 // ⚠CENTRE THE GRID ON THE SPAN IT ACTUALLY HAS. Ceiling division makes G*cell LARGER than 2*EXT, so
2496 // an origin of -EXT put the extra span entirely on the positive side and clipped the mandible off
2497 // the bottom -- which made the measured height depend on the grid rather than on the skull.
2498 let org: i64 = 0 - (G*cell)/2
2499 let n1: i64 = G+1
2500 // UPPER BOUND. The check above guards G being too SMALL; nothing guarded it being too LARGE, and
2501 // this allocation is O(G^3). On 2026-07-30 a G of ~1500 mapped 1501^3*8 = 27.06 GB on a 36 GB host
2502 // in under three minutes: swap hit 98%, load hit 41, and the mgmt API began refusing builds for
2503 // every other seat. seq1547 was the same shape in nx_ssdf and took mgmt, tools and sshd down.
2504 // Ask BEFORE mapping, and REFUSE rather than silently shrinking -- a caller who asked for 1500 and
2505 // quietly got 160 would get a wrong mesh, which is worse than an honest non-answer.
2506 if mf_admit("nx_skullsdf sdf grid" as *u8, n1*n1*n1*8) == 0 { return 8 }
2507 let grid: *i64 = sys_mmap(n1*n1*n1*8) as *i64
2508 var i: i64 = 0
2509 while i < n1 {
2510 let x: i64 = org + i*cell
2511 var j: i64 = 0
2512 while j < n1 {
2513 let y: i64 = org + j*cell
2514 var k: i64 = 0
2515 while k < n1 {
2516 let z: i64 = org + k*cell
2517 // M2: the raw grid now carries SS_FQ units/mm -- seeds, signs and surface_nets are
2518 // ratio/sign-based so nothing downstream changes; the tissue subtract below becomes
2519 // unit-CONSISTENT (ss_tdepth is already mm x SS_RDQ and SS_FQ == SS_RDQ).
2520 var fv: i64 = ss_field_world_q(x, y, z, sexf, robust)
2521 // SS_TISSUE = 0 leaves the bone iso-surface EXACTLY as it was, so every existing caller
2522 // is byte-identical; > 0 moves the zero level outward by the forensic depth at this height.
2523 // depth now varies with BOTH height and lateral distance (|x|), per the dense-map
2524 // literature; ss_tdepth2 at ax=0 reproduces the old midline column exactly.
2525 // ★★★MEASURED AND REVERTED TO THE MIDLINE COLUMN. The 2-D (height x lateral) table above is
2526 // RETAINED UNUSED, the GX-34 emitLimbTube precedent, because it MADE THE FACE WORSE on the
2527 // judge built to catch exactly this. A/B at grid 80 vs the cadaver skin oracle:
2528 // variance headline 128 -> 129 (noise), but PLACEMENT 135 -> 123 with recall 306 -> 278 and
2529 // precision unchanged at 444. For positional work this lane trusts PLACEMENT over variance.
2530 // ★★AND THE REASON IS STRUCTURAL, worth more than the revert: the midline depths in ss_tdepth2
2531 // are IDENTICAL to v1 by construction, yet the MIDLINE PROFILE STILL CHANGED. In an
2532 // ISO-SURFACE formulation the depths are NOT independent per-vertex knobs -- subtracting a
2533 // different depth off-midline moves the field in a neighbourhood, and surface_nets
2534 // interpolates that across cells, so a LATERAL edit propagates onto the MIDLINE SURFACE.
2535 // ★That is the difference from the offset formulation, where every vertex moved alone, and it
2536 // means the literature's DENSE TISSUE MAP cannot be transplanted cell-by-cell onto an SDF
2537 // envelope: the map must be fitted AGAINST THE RESULTING SURFACE, not applied to the field.
2538 // ***THE PER-POINT SUBTRACTION IS THE ONE THAT MEASURES BEST. I moved this into a
2539 // gradient-normalised second pass and it was WORSE BY A LOT -- see the disabled pass below.
2540 // under REDIST the offset moves to a separate pass AFTER redistancing, so the raw
2541 // bone field survives for seeding; without it this line is the exact old behaviour
2542 if SS_TISSUE > 0 { if SS_REDIST == 0 { fv = fv - ss_tdepth(y)*SS_TISSUE/SS_PERMILLE } }
2543 grid[(i*n1+j)*n1+k] = fv
2544 k = k + 1
2545 }
2546 j = j + 1
2547 }
2548 i = i + 1
2549 }
2550 // ***GRADIENT-NORMALISED TISSUE OFFSET -- THE FIX THE MEASUREMENT DEMANDED, NOT THE ONE I EXPECTED.
2551 // MEASURED: requesting a depth d realised 3-6mm of SCATTER around it, and that scatter barely moved
2552 // when the cell went 3mm -> 2mm (total spread 37 -> 34, 8 percent for 2.25x the cells). So it is NOT a
2553 // sampling artifact. THE CAUSE IS IN THIS FILE'S OWN HEADER: ss_smin subtracts h*h/(4k) on every
2554 // chained call, and 'the result is NOT a distance field -- gradient magnitude drifts far from 1'.
2555 // SUBTRACTING d FROM A FIELD WHOSE GRADIENT MAGNITUDE IS NOT 1 MOVES THE SURFACE BY d/|grad f|, NOT d.
2556 // With ~16 chained unions the drift is worst exactly where primitives overlap, which is why the nasal
2557 // and upper-lip bands scattered most and why everything came out systematically THIN (chained smin
2558 // pushes the field negative, so |grad| > 1 and d/|grad| lands short).
2559 // ***THE REMEDY IS THE STANDARD SDF ONE: divide the requested depth by the LOCAL GRADIENT MAGNITUDE,
2560 // estimated by central differences on the grid we have already built. It costs one extra pass and no
2561 // extra field evaluations. This also subsumes the -1mm bias, which was the same cause, not a second.
2562 // Gradient is carried in PER-MILLE so a true distance field reads 1000 and integer division stays exact.
2563 // ***DISABLED AND RETAINED (GX-34 precedent). MEASURED AT 3mm, normalised vs per-point:
2564 // chin req 11 realised 14 with range 8..62 (was 10, range 9..13); cheek 7 -> 8 range 4..24 (was 6,
2565 // range 5..8); mean_abs_err 0 -> 2. DIVIDING BY |grad f| MADE IT MUCH WORSE.
2566 // ***WHY, and it sharpens the diagnosis rather than excusing it: the gradient does not merely drift
2567 // ABOVE 1, it drifts BOTH WAYS, and where it drifts LOW the division AMPLIFIES -- a 62mm chin came
2568 // from a near-flat cell. My guard only caught g < 0.1; a g of 0.2 still multiplies the requested
2569 // depth by five. So the field is not slightly distorted, it is distorted enough that neither naive
2570 // remedy works: IGNORING |grad| scatters by 3-6mm, DIVIDING BY IT scatters by 50.
2571 // ***THE REAL FIX IS TO MAKE THE FIELD A TRUE SDF, not to compensate downstream: either drop SS_K to 0
2572 // (this file records having done exactly that once, for exactly this reason, before restoring 6mm for
2573 // appearance) and accept sutured seams, or REDISTANCE the grid -- an eikonal/fast-sweeping pass that
2574 // rebuilds |grad| = 1 everywhere before any offset is taken. Redistancing is the standard answer and
2575 // it operates on the grid we already build.
2576 if SS_TISSUE < 0 {
2577 let gm: *i64 = sys_mmap(n1*n1*n1*8) as *i64
2578 var gi: i64 = 0
2579 while gi < n1 {
2580 var gj: i64 = 0
2581 while gj < n1 {
2582 var gk: i64 = 0
2583 while gk < n1 {
2584 var ai: i64 = gi+1
2585 if ai > n1-1 { ai = n1-1 }
2586 var bi: i64 = gi-1
2587 if bi < 0 { bi = 0 }
2588 var aj: i64 = gj+1
2589 if aj > n1-1 { aj = n1-1 }
2590 var bj: i64 = gj-1
2591 if bj < 0 { bj = 0 }
2592 var ak: i64 = gk+1
2593 if ak > n1-1 { ak = n1-1 }
2594 var bk: i64 = gk-1
2595 if bk < 0 { bk = 0 }
2596 let dx: i64 = (grid[(ai*n1+gj)*n1+gk] - grid[(bi*n1+gj)*n1+gk]) * 1000 / ((ai-bi)*cell*SS_FQ)
2597 let dy: i64 = (grid[(gi*n1+aj)*n1+gk] - grid[(gi*n1+bj)*n1+gk]) * 1000 / ((aj-bj)*cell*SS_FQ)
2598 let dz: i64 = (grid[(gi*n1+gj)*n1+ak] - grid[(gi*n1+gj)*n1+bk]) * 1000 / ((ak-bk)*cell*SS_FQ)
2599 var g: i64 = ss_isqrt(dx*dx + dy*dy + dz*dz)
2600 // a degenerate gradient (flat field, e.g. deep inside a solid) carries no direction
2601 // information; fall back to the unnormalised depth rather than dividing by ~0
2602 if g < 100 { g = 1000 }
2603 gm[(gi*n1+gj)*n1+gk] = g
2604 gk = gk + 1
2605 }
2606 gj = gj + 1
2607 }
2608 gi = gi + 1
2609 }
2610 gi = 0
2611 while gi < n1 {
2612 let gx: i64 = org + gi*cell
2613 var gj: i64 = 0
2614 while gj < n1 {
2615 let gy: i64 = org + gj*cell
2616 var gk: i64 = 0
2617 while gk < n1 {
2618 let ix: i64 = (gi*n1+gj)*n1+gk
2619 let d: i64 = ss_tdepth(gy)*SS_TISSUE/SS_PERMILLE
2620 grid[ix] = grid[ix] - d*1000/gm[ix]
2621 gk = gk + 1
2622 }
2623 gj = gj + 1
2624 }
2625 gi = gi + 1
2626 }
2627 }
2628 // ---- REDISTANCE PASS (argv[8]; mechanism at the SS_RDQ const block) ----
2629 var FLD: *i64 = grid
2630 if SS_REDIST == 1 {
2631 // its own array: grid keeps the raw signed field (for seeds, signs and the printed A/B),
2632 // dist receives true unsigned distances at SS_RDQ fixed point. Ask before mapping (memfloor law).
2633 if mf_admit("nx_skullsdf redistance grid" as *u8, n1*n1*n1*8) == 0 { return 8 }
2634 let dist: *i64 = sys_mmap(n1*n1*n1*8) as *i64
2635 let hq: i64 = cell*SS_RDQ
2636 var seeded: i64 = 0
2637 var si: i64 = 0
2638 while si < n1 {
2639 var sj: i64 = 0
2640 while sj < n1 {
2641 var sk: i64 = 0
2642 while sk < n1 {
2643 let ix: i64 = (si*n1+sj)*n1+sk
2644 let f: i64 = grid[ix]
2645 var best: i64 = SS_RD_INF
2646 if si > 0 { best = ss_rd_try(f, grid[((si-1)*n1+sj)*n1+sk], cell, best) }
2647 if si < n1-1 { best = ss_rd_try(f, grid[((si+1)*n1+sj)*n1+sk], cell, best) }
2648 if sj > 0 { best = ss_rd_try(f, grid[(si*n1+(sj-1))*n1+sk], cell, best) }
2649 if sj < n1-1 { best = ss_rd_try(f, grid[(si*n1+(sj+1))*n1+sk], cell, best) }
2650 if sk > 0 { best = ss_rd_try(f, grid[(si*n1+sj)*n1+(sk-1)], cell, best) }
2651 if sk < n1-1 { best = ss_rd_try(f, grid[(si*n1+sj)*n1+(sk+1)], cell, best) }
2652 dist[ix] = best
2653 if best < SS_RD_INF { seeded = seeded + 1 }
2654 sk = sk + 1
2655 }
2656 sj = sj + 1
2657 }
2658 si = si + 1
2659 }
2660 // 8 diagonal sweep orders, run twice; the second set's largest improvement is printed as the
2661 // convergence evidence (0 = fully converged after the first set)
2662 var lastd: i64 = 0
2663 var it: i64 = 0
2664 while it < 2 {
2665 var setd: i64 = 0
2666 var sw: i64 = 0
2667 while sw < 8 {
2668 var di: i64 = 1
2669 if (sw & 1) == 1 { di = 0-1 }
2670 var dj: i64 = 1
2671 if ((sw>>1) & 1) == 1 { dj = 0-1 }
2672 var dk: i64 = 1
2673 if ((sw>>2) & 1) == 1 { dk = 0-1 }
2674 let sd: i64 = ss_rd_sweep(dist, n1, hq, di, dj, dk)
2675 if sd > setd { setd = sd }
2676 sw = sw + 1
2677 }
2678 lastd = setd
2679 it = it + 1
2680 }
2681 // restore the sign from the raw field BEFORE measuring: on an unsigned field a central
2682 // difference straddling the surface reads ~0 and the statistic would convict its own input
2683 var pi: i64 = 0
2684 while pi < n1 {
2685 var pj: i64 = 0
2686 while pj < n1 {
2687 var pk: i64 = 0
2688 while pk < n1 {
2689 let ix2: i64 = (pi*n1+pj)*n1+pk
2690 if grid[ix2] <= 0 { dist[ix2] = 0 - dist[ix2] }
2691 pk = pk + 1
2692 }
2693 pj = pj + 1
2694 }
2695 pi = pi + 1
2696 }
2697 // the in-run A/B: same statistic, same band, raw grid versus redistanced grid
2698 ss_rd_gradstat(grid, n1, cell, SS_FQ, "raw" as *u8)
2699 ss_rd_gradstat(dist, n1, cell, SS_RDQ, "redistanced" as *u8)
2700 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22redist\x22,\x22seeded\x22:" as *u8); ss_pn(seeded)
2701 ss_puts(",\x22last_sweep_delta_q\x22:" as *u8); ss_pn(lastd)
2702 ss_puts(",\x22q_per_mm\x22:" as *u8); ss_pn(SS_RDQ)
2703 ss_puts("}\n" as *u8)
2704 // the identity layer rides ON TOP of the honest base: F = B + trilinear(R) x scale
2705 if SS_RESSC > 0 {
2706 var ri: i64 = 0
2707 while ri < n1 {
2708 let rx: i64 = org + ri*cell
2709 var rj: i64 = 0
2710 while rj < n1 {
2711 let ry: i64 = org + rj*cell
2712 var rk: i64 = 0
2713 while rk < n1 {
2714 let rix: i64 = (ri*n1+rj)*n1+rk
2715 dist[rix] = dist[rix] + ss_res_at(rx, ry, org + rk*cell)*SS_RESSC/SS_PERMILLE
2716 rk = rk + 1
2717 }
2718 rj = rj + 1
2719 }
2720 ri = ri + 1
2721 }
2722 }
2723 // tissue offset on the TRUE distance field: an iso-offset of depth d now moves the surface by
2724 // exactly d, which is the whole point of the pass
2725 if SS_TISSUE > 0 {
2726 var ti: i64 = 0
2727 while ti < n1 {
2728 var tj: i64 = 0
2729 while tj < n1 {
2730 let ty: i64 = org + tj*cell
2731 // interpolated landmark depths (ss_tdepth_q) rather than the band steps: on an
2732 // honest field the steps render as literal shelves; see the function's comment
2733 let toff: i64 = ss_tdepth_q(ty)*SS_TISSUE/SS_PERMILLE
2734 var tk: i64 = 0
2735 while tk < n1 {
2736 let ix3: i64 = (ti*n1+tj)*n1+tk
2737 dist[ix3] = dist[ix3] - toff
2738 tk = tk + 1
2739 }
2740 tj = tj + 1
2741 }
2742 ti = ti + 1
2743 }
2744 }
2745 FLD = dist
2746 }
2747 tm_reset()
2748 surface_nets(FLD, G, G, G, org, org, org, cell, SS_ISO, SS_BONE)
2749 let nv: i64 = tm_nv()
2750 let nt: i64 = tm_nt()
2751 if nt <= 0 { ss_puts("{\x22error\x22:\x22no surface -- field never crosses the iso level\x22}\n" as *u8); return 5 }
2752
2753 // ---- write NXMSH2, one layer ("bone"), so the existing viewer and benches read it unchanged
2754 let hdr: i64 = 16 + 3*24
2755 let bytes: i64 = hdr + nt*84 + nt*4
2756 let buf: *u8 = sys_mmap(bytes + 64)
2757 buf[0]=78 as u8; buf[1]=88 as u8; buf[2]=77 as u8; buf[3]=83 as u8
2758 buf[4]=72 as u8; buf[5]=50 as u8; buf[6]=0 as u8; buf[7]=0 as u8
2759 ss_wr32(buf, 8, 3); ss_wr32(buf, 12, nt)
2760 var L: i64 = 0
2761 while L < 3 {
2762 let lb: i64 = 16 + L*24
2763 var q: i64 = 0
2764 while q < 16 { buf[lb+q]=0 as u8; q=q+1 }
2765 if L==2 { buf[lb]=98 as u8; buf[lb+1]=111 as u8; buf[lb+2]=110 as u8; buf[lb+3]=101 as u8 }
2766 if L==2 { ss_wr32(buf, lb+16, 0); ss_wr32(buf, lb+20, nt) } else { ss_wr32(buf, lb+16, 0); ss_wr32(buf, lb+20, 0) }
2767 L = L + 1
2768 }
2769 var t: i64 = 0
2770 while t < nt {
2771 let o: i64 = hdr + t*84
2772 let ia: i64 = tm_ta(t); let ib: i64 = tm_tb(t); let ic: i64 = tm_tc(t)
2773 ss_wr32(buf, o, ss_f32(tm_vx(ia),1)); ss_wr32(buf, o+4, ss_f32(tm_vy(ia),1)); ss_wr32(buf, o+8, ss_f32(tm_vz(ia),1))
2774 ss_wr32(buf, o+12, ss_f32(tm_vx(ib),1)); ss_wr32(buf, o+16, ss_f32(tm_vy(ib),1)); ss_wr32(buf, o+20, ss_f32(tm_vz(ib),1))
2775 ss_wr32(buf, o+24, ss_f32(tm_vx(ic),1)); ss_wr32(buf, o+28, ss_f32(tm_vy(ic),1)); ss_wr32(buf, o+32, ss_f32(tm_vz(ic),1))
2776 // ⚠surface_nets writes gradient normals at 4096 scale (nx_isosurf.nx:68), NOT the Q14 16384 the
2777 // mesh format uses elsewhere. Reading them as Q14 made every normal a QUARTER length, so the
2778 // lambert term collapsed and the whole surface rendered dark and mottled -- which I spent three
2779 // passes blaming on the ellipsoid, the rasterizer and the z-buffer in turn.
2780 ss_wr32(buf, o+36, ss_f32(tm_vnx(ia),SS_NQ)); ss_wr32(buf, o+40, ss_f32(tm_vny(ia),SS_NQ)); ss_wr32(buf, o+44, ss_f32(tm_vnz(ia),SS_NQ))
2781 ss_wr32(buf, o+48, ss_f32(tm_vnx(ib),SS_NQ)); ss_wr32(buf, o+52, ss_f32(tm_vny(ib),SS_NQ)); ss_wr32(buf, o+56, ss_f32(tm_vnz(ib),SS_NQ))
2782 ss_wr32(buf, o+60, ss_f32(tm_vnx(ic),SS_NQ)); ss_wr32(buf, o+64, ss_f32(tm_vny(ic),SS_NQ)); ss_wr32(buf, o+68, ss_f32(tm_vnz(ic),SS_NQ))
2783 ss_wr32(buf, o+72, ss_f32(910,1000)); ss_wr32(buf, o+76, ss_f32(890,1000)); ss_wr32(buf, o+80, ss_f32(845,1000))
2784 ss_wr32(buf, hdr + nt*84 + t*4, 2)
2785 t = t + 1
2786 }
2787 let fd: i64 = sys_openat_wr(argv[1] as *u8, 420)
2788 sys_write(fd, buf, bytes)
2789 sys_close(fd)
2790
2791 // ★MEASURE THE RESULT AGAINST THE REFERENCE, in the organ, every run. The scale defect shipped to a
2792 // published page because nothing compared the emitted skull to the 151x209x215mm it is meant to be.
2793 var lox: i64 = 0; var hix: i64 = 0
2794 var loy: i64 = 0; var hiy: i64 = 0
2795 var loz: i64 = 0; var hiz: i64 = 0
2796 var vi: i64 = 0
2797 while vi < nv {
2798 let X: i64 = tm_vx(vi); let Y: i64 = tm_vy(vi); let Z: i64 = tm_vz(vi)
2799 if vi == 0 { lox=X; hix=X; loy=Y; hiy=Y; loz=Z; hiz=Z } else {
2800 if X < lox { lox = X }
2801 if X > hix { hix = X }
2802 if Y < loy { loy = Y }
2803 if Y > hiy { hiy = Y }
2804 if Z < loz { loz = Z }
2805 if Z > hiz { hiz = Z }
2806 }
2807 vi = vi + 1
2808 }
2809 let bw: i64 = hix-lox
2810 let bh: i64 = hiy-loy
2811 let bd: i64 = hiz-loz
2812 var fit: i64 = 1
2813 if ss_abs(bw - SS_REF_W) > SS_TOL { fit = 0 }
2814 if ss_abs(bh - SS_REF_H) > SS_TOL { fit = 0 }
2815 if ss_abs(bd - SS_REF_D) > SS_TOL { fit = 0 }
2816 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22bbox_mm\x22:[" as *u8); ss_pn(bw)
2817 ss_puts("," as *u8); ss_pn(bh); ss_puts("," as *u8); ss_pn(bd)
2818 ss_puts("],\x22reference_mm\x22:[" as *u8); ss_pn(SS_REF_W)
2819 ss_puts("," as *u8); ss_pn(SS_REF_H); ss_puts("," as *u8); ss_pn(SS_REF_D)
2820 ss_puts("],\x22dims_within_tolerance\x22:" as *u8); ss_pn(fit)
2821 ss_puts(",\x22grid\x22:" as *u8); ss_pn(G)
2822 ss_puts(",\x22cell\x22:" as *u8); ss_pn(cell)
2823 ss_puts(",\x22verts\x22:" as *u8); ss_pn(nv)
2824 ss_puts(",\x22tris\x22:" as *u8); ss_pn(nt)
2825 ss_puts(",\x22overflow\x22:" as *u8); ss_pn(tm_ovf())
2826 ss_puts(",\x22fit_src\x22:" as *u8); ss_pn(SS_FITSRC)
2827 ss_puts(",\x22fit_n\x22:" as *u8); ss_pn(SS_FITN)
2828 ss_puts(",\x22res_scale\x22:" as *u8); ss_pn(SS_RESSC)
2829 ss_puts(",\x22method\x22:\x22smooth-union of bone primitives, orbits and nasal aperture SUBTRACTED as real openings, polygonized by surface_nets\x22}\n" as *u8)
2830 return 0
2831}