code wiki / (root) / nx_skullsdf_verified_r4_t333.nx

nx_skullsdf_verified_r4_t333.nx source

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