turn-fixed.mjs 144 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800
  1. const T3_ROOT = Math.sqrt(1.6);
  2. const T3_TAU = Math.PI * 2;
  3. const T3_RAD = Math.PI / 180;
  4. const T3_LB = [0, 0.2, 0.42, 0.62];
  5. const T3_EB = [0.25, 0.5, 0.75];
  6. const T3_SOFT = 0.035;
  7. const T3_LEVELS = 32;
  8. const T3_Q = 64;
  9. const t3State = { detail: 1, exact: false };
  10. function t3Num(v) {
  11. if (t3State.exact) return String(Math.round(v * 1e6) / 1e6);
  12. let t = Math.round(v * 100);
  13. if (t === 0) return "0";
  14. let sign = "";
  15. if (t < 0) {
  16. sign = "-";
  17. t = -t;
  18. }
  19. const whole = Math.floor(t / 100);
  20. const part = t - whole * 100;
  21. if (part === 0) return sign + whole;
  22. if (part < 10) return sign + whole + ".0" + part;
  23. return sign + whole + "." + (part % 10 === 0 ? part / 10 : part);
  24. }
  25. function t3Fix(v, scale) {
  26. const t = Math.round(v * scale) / scale;
  27. return t === 0 ? "0" : String(t);
  28. }
  29. const t3Arena = { on: false, f: null };
  30. function t3Token(get, count, closed) {
  31. const f = t3Arena.f;
  32. const at = f.arenaN;
  33. let arena = f.arena;
  34. if (!arena || arena.length < 2 * (at + count)) {
  35. const next = new Float64Array(Math.max(512, 2 * (at + count) * 2));
  36. if (arena) next.set(arena.subarray(0, 2 * at));
  37. arena = f.arena = next;
  38. }
  39. const unit = t3State.exact ? 1e6 : 100;
  40. for (let i = 0; i < count; i++) {
  41. arena[2 * (at + i)] = Math.round(get(2 * i) * unit) / unit;
  42. arena[2 * (at + i) + 1] = Math.round(get(2 * i + 1) * unit) / unit;
  43. }
  44. f.arenaN = at + count;
  45. return "\u0001" + String.fromCharCode(at & 0xffff, at >>> 16, count, closed ? 1 : 0);
  46. }
  47. function t3Matrix(f, role, a, b, c, d, e, g) {
  48. const list = f.tm || (f.tm = []);
  49. const m = list[role] || (list[role] = new Float64Array(6));
  50. m[0] = Math.round(a * 1e5) / 1e5;
  51. m[1] = Math.round(b * 1e5) / 1e5;
  52. m[2] = Math.round(c * 1e5) / 1e5;
  53. m[3] = Math.round(d * 1e5) / 1e5;
  54. m[4] = Math.round(e * 100) / 100;
  55. m[5] = Math.round(g * 100) / 100;
  56. return "\u0002";
  57. }
  58. function t3Path(buf, count, closed) {
  59. if (count < 2) return "";
  60. if (t3Arena.on) return t3Token((i) => buf[i], count, closed);
  61. let s = "M" + t3Num(buf[0]) + " " + t3Num(buf[1]);
  62. for (let i = 1; i < count; i++) s += "L" + t3Num(buf[2 * i]) + " " + t3Num(buf[2 * i + 1]);
  63. return closed ? s + "Z" : s;
  64. }
  65. const t3Step = (a, b, x) => {
  66. const t = Math.min(1, Math.max(0, (x - a) / (b - a)));
  67. return t * t * (3 - 2 * t);
  68. };
  69. function t3Level(score, bands) {
  70. let u = 0;
  71. for (let i = 0; i < bands.length; i++) u += t3Step(bands[i] - T3_SOFT, bands[i] + T3_SOFT, score);
  72. return Math.round(u * T3_Q);
  73. }
  74. function t3Grow(f, name, size, Kind) {
  75. if (!f[name] || f[name].length < size) f[name] = new Kind(Math.max(size, f[name] ? f[name].length * 2 : 16));
  76. return f[name];
  77. }
  78. function t3Box(buf, count, box) {
  79. let x0 = Infinity;
  80. let y0 = Infinity;
  81. let x1 = -Infinity;
  82. let y1 = -Infinity;
  83. for (let i = 0; i < count; i++) {
  84. const x = buf[2 * i];
  85. const y = buf[2 * i + 1];
  86. if (x < x0) x0 = x;
  87. if (x > x1) x1 = x;
  88. if (y < y0) y0 = y;
  89. if (y > y1) y1 = y;
  90. }
  91. box[0] = x0;
  92. box[1] = y0;
  93. box[2] = x1;
  94. box[3] = y1;
  95. }
  96. function t3Unit(v) {
  97. const l = Math.hypot(v[0], v[1], v[2]) || 1;
  98. return [v[0] / l, v[1] / l, v[2] / l];
  99. }
  100. function t3Rot(axis, degrees) {
  101. const [x, y, z] = t3Unit(axis);
  102. const c = Math.cos(degrees * T3_RAD);
  103. const s = Math.sin(degrees * T3_RAD);
  104. const C = 1 - c;
  105. return new Float64Array([c + x * x * C, x * y * C - z * s, x * z * C + y * s, y * x * C + z * s, c + y * y * C, y * z * C - x * s, z * x * C - y * s, z * y * C + x * s, c + z * z * C]);
  106. }
  107. function t3Mul(A, B) {
  108. const out = new Float64Array(9);
  109. for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) out[r * 3 + c] = A[r * 3] * B[c] + A[r * 3 + 1] * B[3 + c] + A[r * 3 + 2] * B[6 + c];
  110. return out;
  111. }
  112. const t3Apply = (R, v) => [R[0] * v[0] + R[1] * v[1] + R[2] * v[2], R[3] * v[0] + R[4] * v[1] + R[5] * v[2], R[6] * v[0] + R[7] * v[1] + R[8] * v[2]];
  113. const T3_EYE = new Float64Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  114. function t3Camera(P, pose) {
  115. const a = (P.azimuth ?? 45) * T3_RAD;
  116. const e = (P.elevation ?? 30) * T3_RAD;
  117. const k = P.scale * T3_ROOT;
  118. const sa = Math.sin(a);
  119. const ca = Math.cos(a);
  120. const se = Math.sin(e);
  121. const ce = Math.cos(e);
  122. const cam = { m: new Float64Array(6), ox: 0, oy: 0, V: [0, 0, 0], L: [0, 0, 0], k, turn: 0, R: T3_EYE, t: [0, 0, 0], lx: 0, ly: 1, sa, ca, se, ce, origin: P.origin };
  123. const lw = Math.hypot(sa, ca, 1.2);
  124. if (pose && pose.R && !(pose.turn !== undefined && pose.root)) {
  125. const R = pose.R;
  126. const t = pose.t ?? [0, 0, 0];
  127. const r0 = [sa * k, -ca * k, 0];
  128. const r1 = [ca * se * k, sa * se * k, -ce * k];
  129. for (let c = 0; c < 3; c++) {
  130. cam.m[c] = r0[0] * R[c] + r0[1] * R[3 + c] + r0[2] * R[6 + c];
  131. cam.m[3 + c] = r1[0] * R[c] + r1[1] * R[3 + c] + r1[2] * R[6 + c];
  132. }
  133. cam.ox = P.origin[0] + r0[0] * t[0] + r0[1] * t[1] + r0[2] * t[2];
  134. cam.oy = P.origin[1] + r1[0] * t[0] + r1[1] * t[1] + r1[2] * t[2];
  135. const V = [ca * ce, sa * ce, se];
  136. const L = [-sa / lw, ca / lw, 1.2 / lw];
  137. for (let c = 0; c < 3; c++) {
  138. cam.V[c] = R[c] * V[0] + R[3 + c] * V[1] + R[6 + c] * V[2];
  139. cam.L[c] = R[c] * L[0] + R[3 + c] * L[1] + R[6 + c] * L[2];
  140. }
  141. cam.R = R;
  142. cam.t = t;
  143. } else {
  144. const turn = pose ? pose.turn ?? 0 : 0;
  145. const pivot = pose && pose.pivot ? pose.pivot : [0, 0];
  146. const b = a - turn * T3_RAD;
  147. const sb = Math.sin(b);
  148. const cb = Math.cos(b);
  149. cam.m[0] = sb * k;
  150. cam.m[1] = -cb * k;
  151. cam.m[2] = 0;
  152. cam.m[3] = cb * se * k;
  153. cam.m[4] = sb * se * k;
  154. cam.m[5] = -ce * k;
  155. cam.ox = P.origin[0] + (pivot[0] * sa - pivot[1] * ca) * k;
  156. cam.oy = P.origin[1] + (pivot[0] * ca + pivot[1] * sa) * se * k;
  157. cam.V = [cb * ce, sb * ce, se];
  158. cam.L = [-sb / lw, cb / lw, 1.2 / lw];
  159. cam.turn = turn;
  160. const c = Math.cos(turn * T3_RAD);
  161. const s = Math.sin(turn * T3_RAD);
  162. cam.R = new Float64Array([c, -s, 0, s, c, 0, 0, 0, 1]);
  163. cam.t = [pivot[0], pivot[1], 0];
  164. }
  165. const lh = Math.hypot(cam.L[0], cam.L[1]) || 1;
  166. cam.lx = cam.L[0] / lh;
  167. cam.ly = cam.L[1] / lh;
  168. return cam;
  169. }
  170. function t3Quat(q) {
  171. const l = Math.hypot(q[0], q[1], q[2], q[3]) || 1;
  172. const x = q[0] / l;
  173. const y = q[1] / l;
  174. const z = q[2] / l;
  175. const w = q[3] / l;
  176. return new Float64Array([1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w), 2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w), 2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]);
  177. }
  178. function t3FreeRot(v) {
  179. if (v.R) return v.R instanceof Float64Array ? v.R : Float64Array.from(v.R);
  180. if (v.q) return t3Quat(v.q);
  181. if (v.axis) return t3Rot(v.axis, v.angle ?? 0);
  182. return T3_EYE;
  183. }
  184. function t3Poses(groups, values) {
  185. const get = (name) => (values instanceof Map ? values.get(name) : values ? values[name] : undefined) ?? 0;
  186. const list = [];
  187. for (let index = 0; index < groups.length; index++) {
  188. const g = groups[index];
  189. const v = get(g.name);
  190. let parent = g.parent === undefined || g.parent === null || g.parent < 0 ? null : list[g.parent];
  191. let po = parent ? groups[g.parent].origin : [0, 0, 0];
  192. let R = T3_EYE;
  193. let t = [g.origin[0] - po[0], g.origin[1] - po[1], g.origin[2] - po[2]];
  194. if (g.kind === "turn") R = t3Rot([0, 0, 1], v);
  195. else if (g.kind === "hinge") R = t3Rot(g.axis, v);
  196. else if (g.kind === "slide") {
  197. const d = t3Unit(g.direction);
  198. t[0] += d[0] * v;
  199. t[1] += d[1] * v;
  200. t[2] += d[2] * v;
  201. } else if (g.kind === "free" && v && typeof v === "object") {
  202. R = t3FreeRot(v);
  203. if (v.world) {
  204. parent = null;
  205. po = [0, 0, 0];
  206. t = [g.origin[0], g.origin[1], g.origin[2]];
  207. }
  208. if (v.t) {
  209. t[0] += v.t[0];
  210. t[1] += v.t[1];
  211. t[2] += v.t[2];
  212. }
  213. }
  214. if (!parent) {
  215. const pose = { R, t, value: v };
  216. if (g.kind === "turn") Object.assign(pose, { turn: v, pivot: [g.origin[0], g.origin[1]], root: true });
  217. list.push(pose);
  218. continue;
  219. }
  220. const tw = t3Apply(parent.R, t);
  221. list.push({ R: t3Mul(parent.R, R), t: [tw[0] + parent.t[0], tw[1] + parent.t[1], tw[2] + parent.t[2]], value: v });
  222. }
  223. return list;
  224. }
  225. function t3PosesMap(groups, values) {
  226. const list = t3Poses(groups, values);
  227. return new Map(groups.map((g, index) => [g.name, list[index]]));
  228. }
  229. function t3Roles(part) {
  230. const roles = [];
  231. const spec = part.spec;
  232. const details = part.details ?? {};
  233. const add = (name, type, extra = {}) => roles.push({ name, type, ...extra });
  234. const tone = part.tone ?? "hi";
  235. const crease = part.crease ?? "faint";
  236. const fadedSlots = (prefix, count, cls, lineTone) => {
  237. for (let j = 0; j < count; j++) add(`${prefix}${j}`, "slot", { cls, tone: lineTone });
  238. };
  239. const planes = () => (part.planes ?? []).forEach((_, j) => add(`plane${j}`, "plane"));
  240. const dots = () => (part.dots ?? []).forEach((dot, j) => add(`c${j}`, "dot", { tone: dot.tone ?? "mid", size: dot.size ?? 0.5 }));
  241. const sheets = (top) => {
  242. for (let t = 0; t < 4; t++) add(`s${t}`, "path", { cls: "iso-shade", shade: t });
  243. if (top) add("s4", "path", { cls: "iso-top" });
  244. };
  245. const inner = () => {
  246. if ((details.seams && details.seams.length) || (details.ribs && details.ribs.seams)) add("inner", "path", { cls: "iso-line", tone: "faint" });
  247. };
  248. const ribs = () => {
  249. if (details.ribs) fadedSlots("r", spec.slots?.ribs ?? 6, "iso-line", details.ribs.tone ?? "lo");
  250. };
  251. if (part.kind === "prism") {
  252. add("fill", "path", { cls: "iso-fill" });
  253. const faces = spec.ring.length / 2 + (spec.up ? 0 : 2);
  254. for (let j = 0; j < faces; j++) add(`f${j}`, "face");
  255. if (spec.up) add("top", "xform", { cls: "iso-top" });
  256. if (crease !== "none") add("crease", "path", { cls: "iso-line iso-crease", tone: crease });
  257. if (spec.bevel && crease !== "none") fadedSlots("v", spec.slots?.bevel ?? 6, "iso-line iso-bevel", crease);
  258. if (details.seams && details.seams.length) add("inner", "path", { cls: "iso-line", tone: "faint" });
  259. planes();
  260. add("edge", "path", { cls: "iso-line iso-edge", tone });
  261. dots();
  262. } else if (part.kind === "round" || part.kind === "lathe") {
  263. add("fill", "path", { cls: "iso-fill" });
  264. sheets(true);
  265. const ends = part.kind === "round" ? spec.ends : spec.caps.map((cap) => (cap ? "flat" : "open"));
  266. ends.forEach((end, j) => end === "flat" && add(`k${j}`, "face"));
  267. if (crease !== "none") add("crease", "path", { cls: "iso-line iso-crease", tone: crease });
  268. inner();
  269. ribs();
  270. planes();
  271. add("edge", "path", { cls: "iso-line iso-edge", tone });
  272. dots();
  273. } else if (part.kind === "ball") {
  274. add("fill", "path", { cls: "iso-fill" });
  275. sheets(false);
  276. spec.flats.forEach((_, j) => add(`f${j}`, "face"));
  277. if (crease !== "none") add("crease", "path", { cls: "iso-line iso-crease", tone: crease });
  278. planes();
  279. add("edge", "path", { cls: "iso-line iso-edge", tone });
  280. dots();
  281. } else if (part.kind === "tube") {
  282. add("body", "path", { cls: "tb-body" });
  283. if (spec.wide) {
  284. add("shine", "path", { cls: "tb-shine" });
  285. add("shade", "path", { cls: "tb-shade" });
  286. }
  287. if (spec.rings) fadedSlots("r", spec.slots?.ribs ?? 6, "tb-ring", spec.rings.tone ?? "lo");
  288. add("edges", "path", { cls: "iso-line tb-edge", tone });
  289. } else if (part.kind === "item") {
  290. return roles;
  291. } else if (part.kind === "fixed") {
  292. add("move", "self");
  293. ribs();
  294. planes();
  295. dots();
  296. }
  297. return roles;
  298. }
  299. function t3Planes(list) {
  300. return (list ?? []).map((plane) => ({ o: plane.o, u: plane.u, v: plane.v, n: plane.n, fade: plane.fade ?? [0.04, 0.3], billboard: Boolean(plane.billboard) }));
  301. }
  302. function t3Dots(list) {
  303. return (list ?? []).map((dot) => ({ p: dot.p, n: dot.n ?? null, size: dot.size ?? 0.5, fade: dot.fade ?? [0.04, 0.42] }));
  304. }
  305. function t3PreparePrism(run, part) {
  306. const spec = part.spec;
  307. const n = spec.ring.length / 2;
  308. run.n = n;
  309. run.up = Boolean(spec.up);
  310. const ring = Float64Array.from(spec.ring);
  311. run.ring = ring;
  312. const nx = new Float64Array(n);
  313. const ny = new Float64Array(n);
  314. for (let i = 0; i < n; i++) {
  315. const j = (i + 1) % n;
  316. const dx = ring[2 * j] - ring[2 * i];
  317. const dy = ring[2 * j + 1] - ring[2 * i + 1];
  318. const l = Math.hypot(dx, dy) || 1;
  319. nx[i] = dy / l;
  320. ny[i] = -dx / l;
  321. }
  322. run.nx = nx;
  323. run.ny = ny;
  324. const F = spec.up ? { o: [0, 0, 0], a: [0, 0, 1], u: [1, 0, 0], v: [0, 1, 0] } : spec.F;
  325. run.F = F;
  326. run.s0 = spec.up ? spec.z0 : spec.s0;
  327. run.s1 = spec.up ? spec.z1 : spec.s1;
  328. const lo = new Float64Array(3 * n);
  329. const hi = new Float64Array(3 * n);
  330. const N3 = new Float64Array(3 * n);
  331. for (let i = 0; i < n; i++) {
  332. const x = ring[2 * i];
  333. const y = ring[2 * i + 1];
  334. for (let c = 0; c < 3; c++) {
  335. const base = F.o[c] + F.u[c] * x + F.v[c] * y;
  336. lo[3 * i + c] = base + F.a[c] * run.s0;
  337. hi[3 * i + c] = base + F.a[c] * run.s1;
  338. N3[3 * i + c] = F.u[c] * nx[i] + F.v[c] * ny[i];
  339. }
  340. }
  341. run.lo = lo;
  342. run.hi = hi;
  343. run.N3 = N3;
  344. run.sharp = new Uint8Array(n);
  345. for (let i = 0; i < n; i++) {
  346. const p = (i - 1 + n) % n;
  347. run.sharp[i] = nx[p] * nx[i] + ny[p] * ny[i] < Math.cos(0.35) ? 1 : 0;
  348. }
  349. if (spec.bevel) {
  350. const inset = new Float64Array(2 * n);
  351. for (let i = 0; i < n; i++) {
  352. const p = (i - 1 + n) % n;
  353. const mx = nx[p] + nx[i];
  354. const my = ny[p] + ny[i];
  355. const l = Math.hypot(mx, my) || 1;
  356. inset[2 * i] = ring[2 * i] - (mx / l) * spec.bevel;
  357. inset[2 * i + 1] = ring[2 * i + 1] - (my / l) * spec.bevel;
  358. }
  359. run.inset = inset;
  360. }
  361. run.seams = part.details && part.details.seams ? part.details.seams.slice() : null;
  362. run.cut = spec.cuts && spec.cuts.length ? spec.cuts : null;
  363. }
  364. function t3Axes(run, part) {
  365. if (run.kind === "ball") return run.flats.map((flat) => flat.n);
  366. if (run.kind === "tube") return run.tips.slice();
  367. if (run.kind === "prism") {
  368. const out = [run.F.a];
  369. for (let i = 0; i < run.n; i++) {
  370. const n = [run.N3[3 * i], run.N3[3 * i + 1], run.N3[3 * i + 2]];
  371. if (out.every((m) => Math.abs(m[0] * n[0] + m[1] * n[1] + m[2] * n[2]) < 0.9995)) out.push(n);
  372. }
  373. return out;
  374. }
  375. if (run.F) return [run.F.a];
  376. if (part.spec && part.spec.F) return [part.spec.F.a];
  377. return [];
  378. }
  379. function t3Cloud(run, part) {
  380. const out = [];
  381. const ring = (F, s, r, count) => {
  382. for (let j = 0; j < count; j++) {
  383. const c = Math.cos((j / count) * T3_TAU);
  384. const n = Math.sin((j / count) * T3_TAU);
  385. out.push(F.o[0] + F.a[0] * s + r * (c * F.u[0] + n * F.v[0]), F.o[1] + F.a[1] * s + r * (c * F.u[1] + n * F.v[1]), F.o[2] + F.a[2] * s + r * (c * F.u[2] + n * F.v[2]));
  386. }
  387. };
  388. if (run.kind === "prism") {
  389. for (let i = 0; i < 3 * run.n; i++) out.push(run.lo[i]);
  390. for (let i = 0; i < 3 * run.n; i++) out.push(run.hi[i]);
  391. } else if (run.kind === "round") {
  392. ring(run.F, run.s0, run.r0, 24);
  393. ring(run.F, run.s1, run.r1, 24);
  394. for (const [end, s, r] of [[0, run.s0, run.r0], [1, run.s1, run.r1]]) {
  395. if (run.ends[end] !== "dome") continue;
  396. const sign = end ? 1 : -1;
  397. for (const b of [0.5, 1.0, 1.35]) ring(run.F, s + sign * r * Math.sin(b), r * Math.cos(b), 6);
  398. out.push(run.F.o[0] + run.F.a[0] * (s + sign * r), run.F.o[1] + run.F.a[1] * (s + sign * r), run.F.o[2] + run.F.a[2] * (s + sign * r));
  399. }
  400. } else if (run.kind === "ball") {
  401. const golden = Math.PI * (3 - Math.sqrt(5));
  402. for (let i = 0; i < 64; i++) {
  403. const y = 1 - (2 * (i + 0.5)) / 64;
  404. const rad = Math.sqrt(1 - y * y);
  405. const w = [Math.cos(golden * i) * rad, Math.sin(golden * i) * rad, y];
  406. const p = [run.c[0] + run.r * w[0], run.c[1] + run.r * w[1], run.c[2] + run.r * w[2]];
  407. let inside = true;
  408. for (const flat of run.flats) if ((p[0] - run.c[0]) * flat.n[0] + (p[1] - run.c[1]) * flat.n[1] + (p[2] - run.c[2]) * flat.n[2] > flat.d + 1e-9) inside = false;
  409. if (inside) out.push(p[0], p[1], p[2]);
  410. }
  411. for (const flat of run.flats)
  412. for (let j = 0; j < 12; j++) {
  413. const c = Math.cos((j / 12) * T3_TAU) * flat.rho;
  414. const n = Math.sin((j / 12) * T3_TAU) * flat.rho;
  415. out.push(run.c[0] + flat.n[0] * flat.d + c * flat.u[0] + n * flat.v[0], run.c[1] + flat.n[1] * flat.d + c * flat.u[1] + n * flat.v[1], run.c[2] + flat.n[2] * flat.d + c * flat.u[2] + n * flat.v[2]);
  416. }
  417. } else if (run.kind === "lathe") {
  418. const lv = run.levels;
  419. const step = Math.max(4, Math.floor(lv.length / 4 / 8)) * 4;
  420. for (let i = 0; i < lv.length; i += step) ring(run.F, lv[i], lv[i + 1], 8);
  421. ring(run.F, lv[lv.length - 4], lv[lv.length - 3], 8);
  422. } else if (run.kind === "tube") {
  423. const b = run.body;
  424. const stride = Math.max(1, Math.floor(b.count / 8));
  425. for (let i = 0; i < b.count; i += stride) {
  426. const T = t3Unit([b.D3[3 * i], b.D3[3 * i + 1], b.D3[3 * i + 2]]);
  427. const [u, v] = t3Basis(T);
  428. ring({ o: [b.P3[3 * i], b.P3[3 * i + 1], b.P3[3 * i + 2]], a: T, u, v }, 0, run.r, 8);
  429. }
  430. } else if (part.cloud) for (const v of part.cloud) out.push(v);
  431. return Float64Array.from(out);
  432. }
  433. function t3Unpack(value, grouped) {
  434. if (!value) return new Float64Array(0);
  435. if (typeof value !== "string") return Float64Array.from(value);
  436. const text = atob(value);
  437. const bytes = new Uint8Array(text.length);
  438. for (let i = 0; i < text.length; i++) bytes[i] = text.charCodeAt(i);
  439. const view = new DataView(bytes.buffer);
  440. const size = grouped ? 10 : 8;
  441. const stride = grouped ? 6 : 5;
  442. const count = bytes.length / size;
  443. const out = new Float64Array(count * stride);
  444. for (let e = 0; e < count; e++) {
  445. let o = e * size;
  446. const at = e * stride;
  447. out[at] = view.getUint16(o);
  448. out[at + 1] = view.getUint16(o + 2);
  449. o += 4;
  450. if (grouped) {
  451. out[at + 2] = view.getUint16(o) - 1;
  452. o += 2;
  453. }
  454. let x = (view.getUint16(o) / 65535) * 2 - 1;
  455. let y = (view.getUint16(o + 2) / 65535) * 2 - 1;
  456. const z = 1 - Math.abs(x) - Math.abs(y);
  457. if (z < 0) {
  458. const ox = (1 - Math.abs(y)) * (x >= 0 ? 1 : -1);
  459. const oy = (1 - Math.abs(x)) * (y >= 0 ? 1 : -1);
  460. x = ox;
  461. y = oy;
  462. }
  463. const l = Math.hypot(x, y, z) || 1;
  464. out[at + stride - 3] = x / l;
  465. out[at + stride - 2] = y / l;
  466. out[at + stride - 1] = z / l;
  467. }
  468. return out;
  469. }
  470. function t3Prepare(data, { unit = 1 } = {}) {
  471. const P = data.P;
  472. const runs = data.parts.map((part, index) => {
  473. const run = { index, name: part.name, kind: part.kind, group: part.group ?? -1, layer: part.layer, part, roles: t3Roles(part), planes: t3Planes(part.planes), dots: t3Dots(part.dots), unit };
  474. run.role = Object.fromEntries(run.roles.map((role, j) => [role.name, j]));
  475. if (part.kind === "prism") t3PreparePrism(run, part);
  476. else if (part.kind === "round") t3PrepareRound(run, part, P, unit);
  477. else if (part.kind === "ball") t3PrepareBall(run, part, P, unit);
  478. else if (part.kind === "lathe") t3PrepareLathe(run, part, P, unit);
  479. else if (part.kind === "tube") t3PrepareTube(run, part, data);
  480. else if (part.kind === "item") {
  481. run.version = 0;
  482. run.itemBox = new Float64Array([1e9, 1e9, -1e9, -1e9]);
  483. run.itemHull = new Float64Array(0);
  484. } else if (part.kind === "fixed") {
  485. run.anchor = part.spec.anchor;
  486. run.home = part.spec.home;
  487. run.box0 = part.spec.box;
  488. run.hull0 = Float64Array.from(part.spec.hull);
  489. run.F = part.spec.F ?? null;
  490. run.ribs = part.details && part.details.ribs ? part.details.ribs : null;
  491. }
  492. run.slots = part.spec.slots ?? {};
  493. run.cloud = t3Cloud(run, part);
  494. run.axes = t3Axes(run, part);
  495. const cn = run.cloud.length / 3;
  496. run.centroid = [0, 0, 0];
  497. for (let i = 0; i < cn; i++) for (let c = 0; c < 3; c++) run.centroid[c] += run.cloud[3 * i + c] / Math.max(1, cn);
  498. return run;
  499. });
  500. const layers = data.layers.map((layer, index) => {
  501. const parts = Int32Array.from(layer.parts);
  502. const local = new Map();
  503. parts.forEach((global, at) => local.set(global, at));
  504. const planar = t3Unpack(data.planes && data.planes[layer.name], false);
  505. const dynamic = Int32Array.from((data.dynamic && data.dynamic[layer.name]) ?? []);
  506. const free = Int32Array.from((data.free && data.free[layer.name]) ?? []);
  507. const framed = t3Unpack(data.framed && data.framed[layer.name], true);
  508. const groupPairs = [];
  509. const raw = (data.groupPairs && data.groupPairs[layer.name]) ?? [];
  510. const members = new Map();
  511. for (const global of parts) {
  512. const g = runs[global].group;
  513. if (!members.has(g)) members.set(g, []);
  514. members.get(g).push(global);
  515. }
  516. for (let p = 0; p < raw.length; p += 6) groupPairs.push({ a: Int32Array.from(members.get(raw[p]) ?? []), b: Int32Array.from(members.get(raw[p + 1]) ?? []), frame: raw[p + 2], n: [raw[p + 3], raw[p + 4], raw[p + 5]], boxA: new Float64Array(4), boxB: new Float64Array(4) });
  517. const looseAt = new Uint8Array(parts.length);
  518. for (const global of free) looseAt[local.get(global)] = 1;
  519. return { index, name: layer.name, parts, local, rest: Int32Array.from(layer.rest ?? layer.parts), planar, framed, groupPairs, dynamic, free, looseAt, warm: new Map() };
  520. });
  521. return { P, data, unit, groups: data.groups, runs, layers };
  522. }
  523. function t3Frame(run) {
  524. const count = run.roles.length;
  525. return { d: new Array(count).fill(""), q: new Int32Array(count), w: new Float64Array(count).fill(-1), t: new Array(count).fill(""), o: new Float64Array(count).fill(1), box: new Float64Array(4), hull: new Float64Array(64), hullN: 0, cx: new Float64Array(count), cy: new Float64Array(count), quads: null, quadN: 0 };
  526. }
  527. const t3Buf = { a: new Float64Array(1024), b: new Float64Array(1024), c: new Float64Array(1024) };
  528. function t3Scratch(name, size) {
  529. if (t3Buf[name].length < size) t3Buf[name] = new Float64Array(size * 2);
  530. return t3Buf[name];
  531. }
  532. function t3SetHull(f, buf, count) {
  533. const hull = t3Grow(f, "hull", 2 * count, Float64Array);
  534. for (let i = 0; i < 2 * count; i++) hull[i] = buf[i];
  535. f.hullN = count;
  536. }
  537. function t3Faded(f, run, prefix, lines, count) {
  538. if (!f.fade) f.fade = {};
  539. const detail = t3State.detail;
  540. if (detail < 1) for (let i = 0; i < count; i++) lines.alpha[i] *= detail;
  541. if (detail < 0.01) count = 0;
  542. f.fade[prefix] = { key: lines.key.slice(0, count), alpha: lines.alpha.slice(0, count) };
  543. const slots = run.slots[prefix === "v" ? "bevel" : "ribs"] ?? 6;
  544. const levels = run._levels ?? (run._levels = new Array(T3_LEVELS + 1));
  545. for (let l = 0; l <= T3_LEVELS; l++) levels[l] = "";
  546. for (let i = 0; i < count; i++) {
  547. const alpha = lines.alpha[i];
  548. const level = Math.min(T3_LEVELS, Math.round(alpha * T3_LEVELS));
  549. if (level <= 0) continue;
  550. levels[level] += lines.d[i];
  551. }
  552. const present = [];
  553. for (let l = T3_LEVELS; l >= 1; l--) if (levels[l]) present.push([l, levels[l]]);
  554. while (present.length > slots) {
  555. let best = 1;
  556. let gap = Infinity;
  557. for (let i = 1; i < present.length; i++) {
  558. const g = present[i - 1][0] - present[i][0];
  559. if (g < gap) {
  560. gap = g;
  561. best = i;
  562. }
  563. }
  564. const [a, da] = present[best - 1];
  565. const [b, db] = present[best];
  566. present.splice(best - 1, 2, [(a + b) / 2, da + db]);
  567. }
  568. for (let j = 0; j < slots; j++) {
  569. const role = run.role[`${prefix}${j}`];
  570. if (role === undefined) continue;
  571. if (j < present.length) {
  572. f.d[role] = present[j][1];
  573. f.o[role] = present[j][0] / T3_LEVELS;
  574. } else {
  575. f.d[role] = "";
  576. f.o[role] = 0;
  577. }
  578. }
  579. return present.length;
  580. }
  581. const t3Lines = { d: [], alpha: [], key: [] };
  582. const t3None = { d: [], alpha: [], key: [] };
  583. function t3EmitPrism(run, cam, f) {
  584. const n = run.n;
  585. const m = cam.m;
  586. const ox = cam.ox;
  587. const oy = cam.oy;
  588. const V = cam.V;
  589. const L = cam.L;
  590. const lo = run.lo;
  591. const hi = run.hi;
  592. const N3 = run.N3;
  593. const bot = t3Scratch("a", 2 * n);
  594. const top = t3Scratch("b", 2 * n);
  595. for (let i = 0; i < n; i++) {
  596. const a = 3 * i;
  597. bot[2 * i] = ox + m[0] * lo[a] + m[1] * lo[a + 1] + m[2] * lo[a + 2];
  598. bot[2 * i + 1] = oy + m[3] * lo[a] + m[4] * lo[a + 1] + m[5] * lo[a + 2];
  599. top[2 * i] = ox + m[0] * hi[a] + m[1] * hi[a + 1] + m[2] * hi[a + 2];
  600. top[2 * i + 1] = oy + m[3] * hi[a] + m[4] * hi[a + 1] + m[5] * hi[a + 2];
  601. }
  602. const F = run.F;
  603. const aV = F.a[0] * V[0] + F.a[1] * V[1] + F.a[2] * V[2];
  604. const near = aV >= 0 ? top : bot;
  605. const far = aV >= 0 ? bot : top;
  606. const facing = run._facing ?? (run._facing = new Float64Array(n));
  607. for (let i = 0; i < n; i++) facing[i] = N3[3 * i] * V[0] + N3[3 * i + 1] * V[1] + N3[3 * i + 2] * V[2];
  608. const on = (i) => facing[((i % n) + n) % n] > 1e-9;
  609. let i0 = -1;
  610. for (let i = 0; i < n; i++)
  611. if (on(i) && !on(i - 1)) {
  612. i0 = i;
  613. break;
  614. }
  615. const sil = t3Scratch("c", 4 * n + 8);
  616. const silAt = run._silAt ?? (run._silAt = new Int32Array(2 * n + 4));
  617. let count = 0;
  618. let i1 = i0;
  619. const nearSet = aV >= 0 ? hi : lo;
  620. const farSet = aV >= 0 ? lo : hi;
  621. if (i0 < 0) {
  622. for (let i = 0; i < n; i++) {
  623. sil[2 * count] = near[2 * i];
  624. sil[2 * count + 1] = near[2 * i + 1];
  625. silAt[count] = i;
  626. count++;
  627. }
  628. } else {
  629. while (on(i1)) i1++;
  630. for (let j = i0; j <= i1; j++) {
  631. const i = j % n;
  632. sil[2 * count] = far[2 * i];
  633. sil[2 * count + 1] = far[2 * i + 1];
  634. silAt[count] = -1 - i;
  635. count++;
  636. }
  637. for (let j = i1; j <= i0 + n; j++) {
  638. const i = j % n;
  639. sil[2 * count] = near[2 * i];
  640. sil[2 * count + 1] = near[2 * i + 1];
  641. silAt[count] = i;
  642. count++;
  643. }
  644. if (count > 2 && Math.abs(sil[0] - sil[2 * count - 2]) < 1e-9 && Math.abs(sil[1] - sil[2 * count - 1]) < 1e-9) count--;
  645. }
  646. const outline = t3Path(sil, count, true);
  647. f.d[run.role.fill] = outline;
  648. if (run.cut) {
  649. const inPlane = (index) => {
  650. const at = silAt[index];
  651. const set = at < 0 ? farSet : nearSet;
  652. const v = at < 0 ? -1 - at : at;
  653. return run.cut.some((cut) => Math.abs(cut.n[0] * set[3 * v] + cut.n[1] * set[3 * v + 1] + cut.n[2] * set[3 * v + 2] - cut.d) < 1e-3);
  654. };
  655. const flags = new Uint8Array(count);
  656. const onSame = (i, j) => {
  657. const at = (index) => {
  658. const a = silAt[index];
  659. const set = a < 0 ? farSet : nearSet;
  660. const v = a < 0 ? -1 - a : a;
  661. return [set[3 * v], set[3 * v + 1], set[3 * v + 2]];
  662. };
  663. const p = at(i);
  664. const q = at(j);
  665. return run.cut.some((cut) => Math.abs(cut.n[0] * p[0] + cut.n[1] * p[1] + cut.n[2] * p[2] - cut.d) < 1e-3 && Math.abs(cut.n[0] * q[0] + cut.n[1] * q[1] + cut.n[2] * q[2] - cut.d) < 1e-3);
  666. };
  667. for (let j = 0; j < count; j++) flags[j] = inPlane(j) && onSame(j, (j + 1) % count) ? 1 : 0;
  668. f.d[run.role.edge] = t3Broken(sil, count, flags);
  669. } else f.d[run.role.edge] = outline;
  670. t3Box(sil, count, f.box);
  671. t3SetHull(f, sil, count);
  672. const quad = new Float64Array(8);
  673. for (let i = 0; i < n; i++) {
  674. const role = run.role[`f${i}`];
  675. if (!(facing[i] > 1e-6)) {
  676. f.d[role] = "";
  677. continue;
  678. }
  679. const j = (i + 1) % n;
  680. quad[0] = top[2 * i];
  681. quad[1] = top[2 * i + 1];
  682. quad[2] = top[2 * j];
  683. quad[3] = top[2 * j + 1];
  684. quad[4] = bot[2 * j];
  685. quad[5] = bot[2 * j + 1];
  686. quad[6] = bot[2 * i];
  687. quad[7] = bot[2 * i + 1];
  688. f.d[role] = t3Path(quad, 4, true);
  689. let score;
  690. if (run.up) {
  691. score = (run.nx[i] * cam.lx + run.ny[i] * cam.ly + 1) / 2;
  692. f.q[role] = t3Level(score, T3_EB);
  693. } else {
  694. score = N3[3 * i] * L[0] + N3[3 * i + 1] * L[1] + N3[3 * i + 2] * L[2];
  695. f.q[role] = t3Level(score, T3_LB);
  696. }
  697. const e1 = Math.hypot(quad[2] - quad[0], quad[3] - quad[1]);
  698. const e2 = Math.hypot(quad[6] - quad[0], quad[7] - quad[1]);
  699. const area = Math.abs((quad[2] - quad[0]) * (quad[7] - quad[1]) - (quad[3] - quad[1]) * (quad[6] - quad[0]));
  700. const wide = area / (Math.max(e1, e2) || 1);
  701. f.w[role] = wide < 0.4 ? Math.round(wide * 100) / 100 : -1;
  702. }
  703. if (run.up) {
  704. const z = run.s1;
  705. f.t[run.role.top] = t3Arena.on ? t3Matrix(f, run.role.top, m[0], m[3], m[1], m[4], ox + m[2] * z, oy + m[5] * z) : `matrix(${t3Fix(m[0], 1e5)} ${t3Fix(m[3], 1e5)} ${t3Fix(m[1], 1e5)} ${t3Fix(m[4], 1e5)} ${t3Fix(ox + m[2] * z, 100)} ${t3Fix(oy + m[5] * z, 100)})`;
  706. } else {
  707. for (let side = 0; side < 2; side++) {
  708. const role = run.role[`f${n + side}`];
  709. const sign = side ? 1 : -1;
  710. const face = sign * aV;
  711. if (!(face > 1e-6)) {
  712. f.d[role] = "";
  713. continue;
  714. }
  715. const ring = side ? top : bot;
  716. f.d[role] = t3Path(ring, n, true);
  717. f.q[role] = t3Level(sign * (F.a[0] * L[0] + F.a[1] * L[1] + F.a[2] * L[2]), T3_LB);
  718. let minor = Infinity;
  719. let x0 = Infinity;
  720. let x1 = -Infinity;
  721. for (let i = 0; i < n; i++) {
  722. const j = (i + 1) % n;
  723. const ex = ring[2 * j] - ring[2 * i];
  724. const ey = ring[2 * j + 1] - ring[2 * i + 1];
  725. const l = Math.hypot(ex, ey);
  726. if (l < 1e-9) continue;
  727. let lo2 = Infinity;
  728. let hi2 = -Infinity;
  729. for (let q = 0; q < n; q++) {
  730. const v = ((ring[2 * q] - ring[2 * i]) * ey - (ring[2 * q + 1] - ring[2 * i + 1]) * ex) / l;
  731. if (v < lo2) lo2 = v;
  732. if (v > hi2) hi2 = v;
  733. }
  734. minor = Math.min(minor, hi2 - lo2);
  735. x0 = Math.min(x0, lo2);
  736. x1 = Math.max(x1, hi2);
  737. }
  738. f.w[role] = minor < 0.4 ? Math.round(minor * 100) / 100 : -1;
  739. }
  740. }
  741. if (run.role.crease !== undefined) {
  742. let crease = "";
  743. if (run.up) {
  744. if (i0 >= 0) {
  745. const buf = t3Scratch("a", 0);
  746. let c = 0;
  747. const rim = t3Scratch("c", 2 * n + 4);
  748. for (let j = i0; j <= i1; j++) {
  749. const i = j % n;
  750. rim[2 * c] = top[2 * i];
  751. rim[2 * c + 1] = top[2 * i + 1];
  752. c++;
  753. }
  754. crease = t3Path(rim, c, false);
  755. void buf;
  756. }
  757. } else {
  758. const capOn = [-aV > 1e-6, aV > 1e-6];
  759. const seg = new Float64Array(4);
  760. for (let i = 0; i < n; i++) {
  761. const p = (i - 1 + n) % n;
  762. if (run.sharp[i] && facing[i] > 1e-6 && facing[p] > 1e-6) {
  763. seg[0] = bot[2 * i];
  764. seg[1] = bot[2 * i + 1];
  765. seg[2] = top[2 * i];
  766. seg[3] = top[2 * i + 1];
  767. crease += t3Path(seg, 2, false);
  768. }
  769. }
  770. for (let side = 0; side < 2; side++) {
  771. if (!capOn[side] || i0 < 0) continue;
  772. const ring = side ? top : bot;
  773. const rim = t3Scratch("c", 2 * n + 4);
  774. let c = 0;
  775. for (let j = i0; j <= i1; j++) {
  776. const i = j % n;
  777. rim[2 * c] = ring[2 * i];
  778. rim[2 * c + 1] = ring[2 * i + 1];
  779. c++;
  780. }
  781. crease += t3Path(rim, c, false);
  782. }
  783. }
  784. f.d[run.role.crease] = crease;
  785. }
  786. if (run.inset && run.role.v0 !== undefined && t3State.detail < 0.01) f.levels = t3Faded(f, run, "v", t3None, 0);
  787. else if (run.inset && run.role.v0 !== undefined) {
  788. const lines = t3Lines;
  789. lines.d.length = 0;
  790. lines.alpha.length = 0;
  791. lines.key.length = 0;
  792. lines.key.length = 0;
  793. const capSide = aV >= 0 ? 1 : 0;
  794. const s = capSide ? run.s1 : run.s0;
  795. const capAlpha = run.up ? 1 : t3Step(0.02, 0.2, Math.abs(aV));
  796. const ins = t3Scratch("c", 2 * n);
  797. for (let i = 0; i < n; i++) {
  798. const x = run.inset[2 * i];
  799. const y = run.inset[2 * i + 1];
  800. const px = F.o[0] + F.a[0] * s + F.u[0] * x + F.v[0] * y;
  801. const py = F.o[1] + F.a[1] * s + F.u[1] * x + F.v[1] * y;
  802. const pz = F.o[2] + F.a[2] * s + F.u[2] * x + F.v[2] * y;
  803. ins[2 * i] = ox + m[0] * px + m[1] * py + m[2] * pz;
  804. ins[2 * i + 1] = oy + m[3] * px + m[4] * py + m[5] * pz;
  805. }
  806. const rim = capSide ? top : bot;
  807. const seg = new Float64Array(4);
  808. for (let i = 0; i < n; i++) {
  809. const p = (i - 1 + n) % n;
  810. const ai = capAlpha * t3Step(0, 0.14, facing[i]);
  811. const ap = capAlpha * t3Step(0, 0.14, facing[p]);
  812. if (ai > 0.01) {
  813. const j = (i + 1) % n;
  814. seg[0] = ins[2 * i];
  815. seg[1] = ins[2 * i + 1];
  816. seg[2] = ins[2 * j];
  817. seg[3] = ins[2 * j + 1];
  818. lines.d.push(t3Path(seg, 2, false));
  819. lines.alpha.push(ai);
  820. lines.key.push(2 * i);
  821. }
  822. const corner = ai * (1 - ap) + ap * (1 - ai);
  823. if (corner > 0.01) {
  824. seg[0] = ins[2 * i];
  825. seg[1] = ins[2 * i + 1];
  826. seg[2] = rim[2 * i];
  827. seg[3] = rim[2 * i + 1];
  828. lines.d.push(t3Path(seg, 2, false));
  829. lines.alpha.push(corner);
  830. lines.key.push(2 * i + 1);
  831. }
  832. }
  833. f.levels = t3Faded(f, run, "v", lines, lines.d.length);
  834. }
  835. if (run.seams && run.role.inner !== undefined) {
  836. let inner = "";
  837. if (i0 >= 0) {
  838. const rim = t3Scratch("c", 2 * n + 4);
  839. for (const s of run.seams) {
  840. let c = 0;
  841. for (let j = i0; j <= i1; j++) {
  842. const i = j % n;
  843. const x = run.ring[2 * i];
  844. const y = run.ring[2 * i + 1];
  845. const px = F.o[0] + F.a[0] * s + F.u[0] * x + F.v[0] * y;
  846. const py = F.o[1] + F.a[1] * s + F.u[1] * x + F.v[1] * y;
  847. const pz = F.o[2] + F.a[2] * s + F.u[2] * x + F.v[2] * y;
  848. rim[2 * c] = ox + m[0] * px + m[1] * py + m[2] * pz;
  849. rim[2 * c + 1] = oy + m[3] * px + m[4] * py + m[5] * pz;
  850. c++;
  851. }
  852. inner += t3Path(rim, c, false);
  853. }
  854. }
  855. f.d[run.role.inner] = inner;
  856. }
  857. }
  858. function t3Broken(buf, count, skip) {
  859. let start = -1;
  860. for (let j = 0; j < count; j++)
  861. if (skip[(j - 1 + count) % count] && !skip[j]) {
  862. start = j;
  863. break;
  864. }
  865. if (start < 0) return skip[0] ? "" : t3Path(buf, count, true);
  866. let out = "";
  867. let run = [];
  868. for (let step = 0; step < count; step++) {
  869. const j = (start + step) % count;
  870. if (skip[j]) {
  871. if (run.length) {
  872. run.push((j + 0) % count);
  873. out += t3PathOf(run.map((i) => [buf[2 * i], buf[2 * i + 1]]), false);
  874. run = [];
  875. }
  876. continue;
  877. }
  878. run.push(j);
  879. }
  880. if (run.length) {
  881. run.push((start + count) % count);
  882. out += t3PathOf(run.map((i) => [buf[2 * i], buf[2 * i + 1]]), false);
  883. }
  884. return out;
  885. }
  886. function t3EmitPlanes(run, cam, f, sx = 0, sy = 0) {
  887. const m = cam.m;
  888. const V = cam.V;
  889. for (let j = 0; j < run.planes.length; j++) {
  890. const plane = run.planes[j];
  891. const role = run.role[`plane${j}`];
  892. const o = plane.o;
  893. const X = cam.ox - sx + m[0] * o[0] + m[1] * o[1] + m[2] * o[2];
  894. const Y = cam.oy - sy + m[3] * o[0] + m[4] * o[1] + m[5] * o[2];
  895. const facing = plane.n[0] * V[0] + plane.n[1] * V[1] + plane.n[2] * V[2];
  896. const alpha = Math.round(t3Step(plane.fade[0], plane.fade[1], facing) * 100) / 100;
  897. f.o[role] = alpha;
  898. if (plane.billboard) {
  899. f.t[role] = t3Arena.on ? t3Matrix(f, role, 1, 0, 0, 1, X, Y) : `translate(${t3Num(X)} ${t3Num(Y)})`;
  900. continue;
  901. }
  902. const u = plane.u;
  903. const v = plane.v;
  904. const a = m[0] * u[0] + m[1] * u[1] + m[2] * u[2];
  905. const b = m[3] * u[0] + m[4] * u[1] + m[5] * u[2];
  906. const c = m[0] * v[0] + m[1] * v[1] + m[2] * v[2];
  907. const d = m[3] * v[0] + m[4] * v[1] + m[5] * v[2];
  908. f.t[role] = t3Arena.on ? t3Matrix(f, role, a, b, c, d, X, Y) : `matrix(${t3Fix(a, 1e5)} ${t3Fix(b, 1e5)} ${t3Fix(c, 1e5)} ${t3Fix(d, 1e5)} ${t3Fix(X, 100)} ${t3Fix(Y, 100)})`;
  909. }
  910. }
  911. function t3EmitDots(run, cam, f, sx = 0, sy = 0) {
  912. const m = cam.m;
  913. const V = cam.V;
  914. for (let j = 0; j < run.dots.length; j++) {
  915. const dot = run.dots[j];
  916. const role = run.role[`c${j}`];
  917. const p = dot.p;
  918. f.cx[role] = cam.ox - sx + m[0] * p[0] + m[1] * p[1] + m[2] * p[2];
  919. f.cy[role] = cam.oy - sy + m[3] * p[0] + m[4] * p[1] + m[5] * p[2];
  920. const alpha = (dot.n ? t3Step(dot.fade[0], dot.fade[1], dot.n[0] * V[0] + dot.n[1] * V[1] + dot.n[2] * V[2]) : 1) * t3State.detail;
  921. f.o[role] = alpha < 0.005 ? 0 : Math.round(alpha * 100) / 100;
  922. }
  923. }
  924. function t3EmitFixed(run, cam, f) {
  925. const a = run.anchor;
  926. const m = cam.m;
  927. const X = cam.ox + m[0] * a[0] + m[1] * a[1] + m[2] * a[2];
  928. const Y = cam.oy + m[3] * a[0] + m[4] * a[1] + m[5] * a[2];
  929. const dx = X - run.home[0];
  930. const dy = Y - run.home[1];
  931. const rx = Math.round(dx * 100) / 100;
  932. const ry = Math.round(dy * 100) / 100;
  933. f.t[run.role.move] = t3Arena.on ? t3Matrix(f, run.role.move, 1, 0, 0, 1, rx, ry) : rx || ry ? `translate(${t3Num(rx)} ${t3Num(ry)})` : "";
  934. f.shiftX = rx;
  935. f.shiftY = ry;
  936. const b = run.box0;
  937. f.box[0] = b[0] + rx;
  938. f.box[1] = b[1] + ry;
  939. f.box[2] = b[2] + rx;
  940. f.box[3] = b[3] + ry;
  941. const count = run.hull0.length / 2;
  942. const hull = t3Grow(f, "hull", 2 * count, Float64Array);
  943. for (let i = 0; i < count; i++) {
  944. hull[2 * i] = run.hull0[2 * i] + rx;
  945. hull[2 * i + 1] = run.hull0[2 * i + 1] + ry;
  946. }
  947. f.hullN = count;
  948. if (run.ribs && run.F) t3EmitRibs(run, cam, f, run.F, run.ribs, rx, ry);
  949. t3EmitPlanes(run, cam, f, rx, ry);
  950. t3EmitDots(run, cam, f, rx, ry);
  951. }
  952. function t3EmitRibs(run, cam, f, F, ribs, sx, sy) {
  953. if (t3State.detail < 0.01) {
  954. f.levels = t3Faded(f, run, "r", t3None, 0);
  955. return;
  956. }
  957. const m = cam.m;
  958. const V = cam.V;
  959. const lines = t3Lines;
  960. lines.d.length = 0;
  961. lines.alpha.length = 0;
  962. lines.key.length = 0;
  963. const { s0, s1, count, phase = 0, twist = 0, fade = [0.1, 0.55] } = ribs;
  964. const r0 = ribs.r0 ?? ribs.r;
  965. const r1 = ribs.r1 ?? r0;
  966. const slope = (r1 - r0) / (s1 - s0 || 1);
  967. const norm = Math.hypot(1, slope);
  968. const aV = F.a[0] * V[0] + F.a[1] * V[1] + F.a[2] * V[2];
  969. const uV = F.u[0] * V[0] + F.u[1] * V[1] + F.u[2] * V[2];
  970. const vV = F.v[0] * V[0] + F.v[1] * V[1] + F.v[2] * V[2];
  971. const seg = new Float64Array(4);
  972. const at = (s, r, t, out, index) => {
  973. const c = Math.cos(t);
  974. const n = Math.sin(t);
  975. const px = F.o[0] + F.a[0] * s + r * (c * F.u[0] + n * F.v[0]);
  976. const py = F.o[1] + F.a[1] * s + r * (c * F.u[1] + n * F.v[1]);
  977. const pz = F.o[2] + F.a[2] * s + r * (c * F.u[2] + n * F.v[2]);
  978. out[index] = cam.ox - sx + m[0] * px + m[1] * py + m[2] * pz;
  979. out[index + 1] = cam.oy - sy + m[3] * px + m[4] * py + m[5] * pz;
  980. };
  981. for (let i = 0; i < count; i++) {
  982. const t = phase + (i / count) * T3_TAU;
  983. const tm = t + twist / 2;
  984. const facing = (Math.cos(tm) * uV + Math.sin(tm) * vV - slope * aV) / norm;
  985. const alpha = t3Step(fade[0], fade[1], facing);
  986. if (alpha * T3_LEVELS < 0.5) continue;
  987. at(s0, r0, t, seg, 0);
  988. at(s1, r1, t + twist, seg, 2);
  989. lines.d.push(t3Path(seg, 2, false));
  990. lines.alpha.push(alpha);
  991. lines.key.push(i);
  992. }
  993. f.levels = t3Faded(f, run, "r", lines, lines.d.length);
  994. }
  995. function t3Geo(F, cam) {
  996. const m = cam.m;
  997. const V = cam.V;
  998. const L = cam.L;
  999. const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  1000. const lin = (w) => [m[0] * w[0] + m[1] * w[1] + m[2] * w[2], m[3] * w[0] + m[4] * w[1] + m[5] * w[2]];
  1001. const O = [cam.ox + m[0] * F.o[0] + m[1] * F.o[1] + m[2] * F.o[2], cam.oy + m[3] * F.o[0] + m[4] * F.o[1] + m[5] * F.o[2]];
  1002. const aV = dot(F.a, V);
  1003. const uV = dot(F.u, V);
  1004. const vV = dot(F.v, V);
  1005. const aL = dot(F.a, L);
  1006. const uL = dot(F.u, L);
  1007. const vL = dot(F.v, L);
  1008. return { O, SA: lin(F.a), SU: lin(F.u), SV: lin(F.v), aV, aL, view: { a: aV, flat: Math.hypot(uV, vV), phi: Math.atan2(vV, uV) }, light: { a: aL, flat: Math.hypot(uL, vL), phi: Math.atan2(vL, uL) } };
  1009. }
  1010. function t3At(geo, s, r, t, buf, index) {
  1011. const c = Math.cos(t);
  1012. const n = Math.sin(t);
  1013. buf[index] = geo.O[0] + s * geo.SA[0] + r * (c * geo.SU[0] + n * geo.SV[0]);
  1014. buf[index + 1] = geo.O[1] + s * geo.SA[1] + r * (c * geo.SU[1] + n * geo.SV[1]);
  1015. }
  1016. function t3Arcs(nr, na, view, light) {
  1017. const cuts = [];
  1018. if (Math.abs(nr) > 1e-9) {
  1019. const visibleCut = -(na * view.a) / (nr * view.flat);
  1020. if (visibleCut > -1 && visibleCut < 1) {
  1021. const d = Math.acos(visibleCut);
  1022. cuts.push(view.phi - d, view.phi + d);
  1023. }
  1024. for (let b = 0; b < T3_LB.length; b++) {
  1025. const c = (T3_LB[b] - na * light.a) / (nr * light.flat);
  1026. if (c > -1 && c < 1) {
  1027. const d = Math.acos(c);
  1028. cuts.push(light.phi - d, light.phi + d);
  1029. }
  1030. }
  1031. }
  1032. for (let i = 0; i < cuts.length; i++) {
  1033. const w = ((cuts[i] % T3_TAU) + T3_TAU) % T3_TAU;
  1034. cuts[i] = Math.round(w * 1e9) / 1e9;
  1035. }
  1036. cuts.sort((a, b) => a - b);
  1037. const sorted = [];
  1038. for (let i = 0; i < cuts.length; i++) if (!sorted.length || cuts[i] !== sorted[sorted.length - 1]) sorted.push(cuts[i]);
  1039. const label = (angle) => {
  1040. const facing = nr * view.flat * Math.cos(angle - view.phi) + na * view.a;
  1041. if (facing <= 1e-9) return -1;
  1042. const score = nr * light.flat * Math.cos(angle - light.phi) + na * light.a;
  1043. let tone = 0;
  1044. while (tone < T3_LB.length && score >= T3_LB[tone]) tone++;
  1045. return tone;
  1046. };
  1047. if (!sorted.length) {
  1048. const tone = label(0);
  1049. return tone < 0 ? [] : [{ tone, from: 0, to: T3_TAU, full: true }];
  1050. }
  1051. const merged = [];
  1052. for (let index = 0; index < sorted.length; index++) {
  1053. const from = sorted[index];
  1054. const to = index + 1 < sorted.length ? sorted[index + 1] : sorted[0] + T3_TAU;
  1055. const tone = label((from + to) / 2);
  1056. const last = merged[merged.length - 1];
  1057. if (last && last.tone === tone && Math.abs(last.to - from) < 1e-9) last.to = to;
  1058. else merged.push({ tone, from, to });
  1059. }
  1060. if (merged.length > 1 && merged[0].tone === merged[merged.length - 1].tone && Math.abs(merged[merged.length - 1].to - T3_TAU - merged[0].from) < 1e-9) {
  1061. const last = merged.pop();
  1062. merged[0].from = last.from - T3_TAU;
  1063. }
  1064. const out = [];
  1065. for (const arc of merged) if (arc.tone >= 0) out.push(arc);
  1066. return out;
  1067. }
  1068. function t3Strip(geo, s0, r0, s1, r1, from, to, step) {
  1069. const count = Math.max(1, Math.ceil((to - from) / step));
  1070. const buf = t3Scratch("c", 4 * count + 8);
  1071. for (let j = 0; j <= count; j++) {
  1072. const t = from + ((to - from) * j) / count;
  1073. t3At(geo, s0, r0, t, buf, 2 * j);
  1074. t3At(geo, s1, r1, t, buf, 2 * (2 * count + 1 - j));
  1075. }
  1076. return t3Path(t3Oriented(buf, 2 * count + 2), 2 * count + 2, true);
  1077. }
  1078. function t3Oriented(buf, count) {
  1079. let area = 0;
  1080. for (let i = 0; i < count; i++) {
  1081. const j = (i + 1) % count;
  1082. area += buf[2 * i] * buf[2 * j + 1] - buf[2 * j] * buf[2 * i + 1];
  1083. }
  1084. if (area >= 0) return buf;
  1085. for (let i = 0, j = count - 1; i < j; i++, j--) {
  1086. const x = buf[2 * i];
  1087. const y = buf[2 * i + 1];
  1088. buf[2 * i] = buf[2 * j];
  1089. buf[2 * i + 1] = buf[2 * j + 1];
  1090. buf[2 * j] = x;
  1091. buf[2 * j + 1] = y;
  1092. }
  1093. return buf;
  1094. }
  1095. function t3Hull(points) {
  1096. const sorted = points.slice().sort((a, b) => a[0] - b[0] || a[1] - b[1]);
  1097. if (sorted.length < 3) return sorted;
  1098. const cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
  1099. const lower = [];
  1100. for (const p of sorted) {
  1101. while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 1e-12) lower.pop();
  1102. lower.push(p);
  1103. }
  1104. const upper = [];
  1105. for (let i = sorted.length - 1; i >= 0; i--) {
  1106. const p = sorted[i];
  1107. while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 1e-12) upper.pop();
  1108. upper.push(p);
  1109. }
  1110. return lower.slice(0, -1).concat(upper.slice(0, -1));
  1111. }
  1112. function t3PathOf(points, closed) {
  1113. if (points.length < 2) return "";
  1114. if (t3Arena.on) return t3Token((i) => points[i >> 1][i & 1], points.length, closed);
  1115. let s = "M" + t3Num(points[0][0]) + " " + t3Num(points[0][1]);
  1116. for (let i = 1; i < points.length; i++) s += "L" + t3Num(points[i][0]) + " " + t3Num(points[i][1]);
  1117. return closed ? s + "Z" : s;
  1118. }
  1119. function t3Basis(w) {
  1120. const helper = Math.abs(w[2]) > 0.9 ? [1, 0, 0] : [0, 0, 1];
  1121. const u = t3Unit([helper[1] * w[2] - helper[2] * w[1], helper[2] * w[0] - helper[0] * w[2], helper[0] * w[1] - helper[1] * w[0]]);
  1122. return [u, [w[1] * u[2] - w[2] * u[1], w[2] * u[0] - w[0] * u[2], w[0] * u[1] - w[1] * u[0]]];
  1123. }
  1124. function t3Meet(A, a, B, b) {
  1125. const ab = A[0] * B[0] + A[1] * B[1] + A[2] * B[2];
  1126. const det = 1 - ab * ab;
  1127. if (det < 1e-12) return [];
  1128. const alpha = (a - b * ab) / det;
  1129. const beta = (b - a * ab) / det;
  1130. const base = [A[0] * alpha + B[0] * beta, A[1] * alpha + B[1] * beta, A[2] * alpha + B[2] * beta];
  1131. const rest = 1 - (base[0] * base[0] + base[1] * base[1] + base[2] * base[2]);
  1132. if (rest < 0) return [];
  1133. const cr = [A[1] * B[2] - A[2] * B[1], A[2] * B[0] - A[0] * B[2], A[0] * B[1] - A[1] * B[0]];
  1134. const k = Math.sqrt(rest / det);
  1135. return [
  1136. [base[0] + cr[0] * k, base[1] + cr[1] * k, base[2] + cr[2] * k],
  1137. [base[0] - cr[0] * k, base[1] - cr[1] * k, base[2] - cr[2] * k],
  1138. ];
  1139. }
  1140. const t3Tables = new Map();
  1141. function t3Table(count) {
  1142. let table = t3Tables.get(count);
  1143. if (!table) {
  1144. table = new Float64Array(2 * count);
  1145. for (let j = 0; j < count; j++) {
  1146. table[2 * j] = Math.cos((j / count) * T3_TAU);
  1147. table[2 * j + 1] = Math.sin((j / count) * T3_TAU);
  1148. }
  1149. t3Tables.set(count, table);
  1150. }
  1151. return table;
  1152. }
  1153. function t3Dome(cam, C, e, r, count, sheets) {
  1154. const m = cam.m;
  1155. const V = cam.V;
  1156. const L = cam.L;
  1157. const Sx = cam.ox + m[0] * C[0] + m[1] * C[1] + m[2] * C[2];
  1158. const Sy = cam.oy + m[3] * C[0] + m[4] * C[1] + m[5] * C[2];
  1159. const flat = (n) => [Sx + r * (m[0] * n[0] + m[1] * n[1] + m[2] * n[2]), Sy + r * (m[3] * n[0] + m[4] * n[1] + m[5] * n[2])];
  1160. const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  1161. const table = t3Table(count);
  1162. const circle = (W, value, keep) => {
  1163. const [U, Q] = t3Basis(W);
  1164. const rad = Math.sqrt(Math.max(0, 1 - value * value));
  1165. const out = [];
  1166. for (let j = 0; j < count; j++) {
  1167. const cs = table[2 * j] * rad;
  1168. const sn = table[2 * j + 1] * rad;
  1169. const n = [W[0] * value + U[0] * cs + Q[0] * sn, W[1] * value + U[1] * cs + Q[1] * sn, W[2] * value + U[2] * cs + Q[2] * sn];
  1170. if (keep(n)) out.push(n);
  1171. }
  1172. return out;
  1173. };
  1174. const rim = circle(V, 0, (n) => dot(n, e) >= -1e-9).map((n) => [flat(n), dot(n, L)]);
  1175. const base = circle(e, 0, (n) => dot(n, V) >= -1e-9).map((n) => [flat(n), dot(n, L)]);
  1176. const corners = t3Meet(V, 0, e, 0).map((n) => [flat(n), dot(n, L)]);
  1177. for (let tone = 0; tone < 5; tone++) {
  1178. const tau = tone === 0 ? -Infinity : T3_LB[tone - 1];
  1179. const candidates = [];
  1180. for (const list of [rim, base, corners]) for (const [p, lit] of list) if (lit >= tau - 1e-9) candidates.push(p);
  1181. if (tone > 0) {
  1182. for (const n of circle(L, tau, (n) => dot(n, V) >= -1e-9 && dot(n, e) >= -1e-9)) candidates.push(flat(n));
  1183. for (const n of t3Meet(L, tau, V, 0)) if (dot(n, e) >= -1e-9) candidates.push(flat(n));
  1184. for (const n of t3Meet(L, tau, e, 0)) if (dot(n, V) >= -1e-9) candidates.push(flat(n));
  1185. }
  1186. if (candidates.length < 3) continue;
  1187. const region = t3Hull(candidates);
  1188. if (region.length >= 3) sheets[tone] += t3PathOf(region, true);
  1189. }
  1190. }
  1191. function t3BoxOf(pts, box) {
  1192. let x0 = Infinity;
  1193. let y0 = Infinity;
  1194. let x1 = -Infinity;
  1195. let y1 = -Infinity;
  1196. for (const [x, y] of pts) {
  1197. if (x < x0) x0 = x;
  1198. if (x > x1) x1 = x;
  1199. if (y < y0) y0 = y;
  1200. if (y > y1) y1 = y;
  1201. }
  1202. box[0] = x0;
  1203. box[1] = y0;
  1204. box[2] = x1;
  1205. box[3] = y1;
  1206. }
  1207. function t3Thin(points, most) {
  1208. if (points.length <= most) return points;
  1209. const n = points.length;
  1210. const picks = [];
  1211. for (let i = 0; i < most; i++) picks.push(Math.floor((i * n) / most));
  1212. const thin = picks.map((i) => points[i]);
  1213. let err = 0;
  1214. for (let j = 0; j < most; j++) {
  1215. const a = thin[j];
  1216. const b = thin[(j + 1) % most];
  1217. const dx = b[0] - a[0];
  1218. const dy = b[1] - a[1];
  1219. const l = Math.hypot(dx, dy) || 1;
  1220. const end = j + 1 < most ? picks[j + 1] : picks[0] + n;
  1221. for (let i = picks[j] + 1; i < end; i++) {
  1222. const p = points[i % n];
  1223. const out = ((p[0] - a[0]) * dy - (p[1] - a[1]) * dx) / l;
  1224. if (Math.abs(out) > err) err = Math.abs(out);
  1225. }
  1226. }
  1227. return t3Grown(thin, err);
  1228. }
  1229. function t3Grown(poly, by) {
  1230. if (!(by > 0)) return poly;
  1231. let area = 0;
  1232. for (let i = 0; i < poly.length; i++) {
  1233. const a = poly[i];
  1234. const b = poly[(i + 1) % poly.length];
  1235. area += a[0] * b[1] - b[0] * a[1];
  1236. }
  1237. const sign = area >= 0 ? 1 : -1;
  1238. const n = poly.length;
  1239. const normals = poly.map((a, i) => {
  1240. const b = poly[(i + 1) % n];
  1241. const l = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
  1242. return [(sign * (b[1] - a[1])) / l, (-sign * (b[0] - a[0])) / l];
  1243. });
  1244. return poly.map((p, i) => {
  1245. const na = normals[(i - 1 + n) % n];
  1246. const nb = normals[i];
  1247. const mx = na[0] + nb[0];
  1248. const my = na[1] + nb[1];
  1249. const dd = (mx * mx + my * my) / 2 || 1;
  1250. return [p[0] + (mx * by) / dd, p[1] + (my * by) / dd];
  1251. });
  1252. }
  1253. function t3HullOut(f, points, most = 32) {
  1254. const thin = t3Thin(points, most);
  1255. const hull = t3Grow(f, "hull", 2 * thin.length, Float64Array);
  1256. for (let i = 0; i < thin.length; i++) {
  1257. hull[2 * i] = thin[i][0];
  1258. hull[2 * i + 1] = thin[i][1];
  1259. }
  1260. f.hullN = thin.length;
  1261. }
  1262. function t3SupportHull(geo, cam, components, dirs) {
  1263. const table = t3Table(dirs);
  1264. const pts = [];
  1265. const { O, SA, SU, SV } = geo;
  1266. for (let j = 0; j < dirs; j++) {
  1267. const dx = table[2 * j];
  1268. const dy = table[2 * j + 1];
  1269. const pa = SA[0] * dx + SA[1] * dy;
  1270. const pu = SU[0] * dx + SU[1] * dy;
  1271. const pv = SV[0] * dx + SV[1] * dy;
  1272. const w = Math.hypot(pu, pv);
  1273. let best = -Infinity;
  1274. let px = 0;
  1275. let py = 0;
  1276. for (let c = 0; c < components.length; c += 3) {
  1277. const kind = components[c];
  1278. const s = components[c + 1];
  1279. const r = components[c + 2];
  1280. if (kind === 0) {
  1281. const value = s * pa + r * w;
  1282. if (value > best) {
  1283. best = value;
  1284. const cs = w > 1e-12 ? pu / w : 1;
  1285. const sn = w > 1e-12 ? pv / w : 0;
  1286. px = O[0] + s * SA[0] + r * (cs * SU[0] + sn * SV[0]);
  1287. py = O[1] + s * SA[1] + r * (cs * SU[1] + sn * SV[1]);
  1288. }
  1289. } else {
  1290. const rk = r * cam.k;
  1291. const value = s * pa + rk;
  1292. if (value > best) {
  1293. best = value;
  1294. px = O[0] + s * SA[0] + rk * dx;
  1295. py = O[1] + s * SA[1] + rk * dy;
  1296. }
  1297. }
  1298. }
  1299. const last = pts[pts.length - 1];
  1300. if (!last || Math.abs(last[0] - px) + Math.abs(last[1] - py) > 0.02) pts.push([px, py]);
  1301. }
  1302. if (pts.length > 2) {
  1303. const a = pts[0];
  1304. const b = pts[pts.length - 1];
  1305. if (Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]) <= 0.02) pts.pop();
  1306. }
  1307. return pts;
  1308. }
  1309. function t3ArcPoints(geo, s, r, from, to, k, out, cut = false) {
  1310. const count = Math.max(2, Math.ceil((Math.abs(to - from) * 48) / T3_TAU), Math.ceil((Math.abs(to - from) * Math.max(r, 1e-6) * k) / 1.5));
  1311. for (let j = 0; j <= count; j++) {
  1312. const t = from + ((to - from) * j) / count;
  1313. const c = Math.cos(t);
  1314. const n = Math.sin(t);
  1315. const p = [geo.O[0] + s * geo.SA[0] + r * (c * geo.SU[0] + n * geo.SV[0]), geo.O[1] + s * geo.SA[1] + r * (c * geo.SU[1] + n * geo.SV[1])];
  1316. if (cut) p.cut = true;
  1317. out.push(p);
  1318. }
  1319. }
  1320. function t3RoundOutline(run, geo, cam) {
  1321. const k = cam.k;
  1322. const { s0, s1, r0, r1, ends } = run;
  1323. const domes = (ends[0] === "dome" ? 1 : 0) + (ends[1] === "dome" ? 1 : 0);
  1324. if (domes === 2) {
  1325. const c0 = [geo.O[0] + s0 * geo.SA[0], geo.O[1] + s0 * geo.SA[1]];
  1326. const c1 = [geo.O[0] + s1 * geo.SA[0], geo.O[1] + s1 * geo.SA[1]];
  1327. const rk = r0 * k;
  1328. const dx = c1[0] - c0[0];
  1329. const dy = c1[1] - c0[1];
  1330. const l = Math.hypot(dx, dy);
  1331. const count = Math.max(24, Math.ceil((Math.PI * rk) / 1.5));
  1332. const out = [];
  1333. if (l < 1e-6) {
  1334. for (let j = 0; j < 2 * count; j++) {
  1335. const t = (j / (2 * count)) * T3_TAU;
  1336. out.push([c1[0] + rk * Math.cos(t), c1[1] + rk * Math.sin(t)]);
  1337. }
  1338. return out;
  1339. }
  1340. const beta = Math.atan2(dy, dx);
  1341. for (let j = 0; j <= count; j++) {
  1342. const t = beta - Math.PI / 2 + (Math.PI * j) / count;
  1343. out.push([c1[0] + rk * Math.cos(t), c1[1] + rk * Math.sin(t)]);
  1344. }
  1345. for (let j = 0; j <= count; j++) {
  1346. const t = beta + Math.PI / 2 + (Math.PI * j) / count;
  1347. out.push([c0[0] + rk * Math.cos(t), c0[1] + rk * Math.sin(t)]);
  1348. }
  1349. return out;
  1350. }
  1351. if (domes === 1) {
  1352. const pts = [];
  1353. for (const [end, s, r] of [[0, s0, r0], [1, s1, r1]]) {
  1354. t3ArcPoints(geo, s, r, 0, T3_TAU, k, pts);
  1355. if (ends[end] !== "dome") continue;
  1356. const sign = end ? 1 : -1;
  1357. const c = [geo.O[0] + s * geo.SA[0], geo.O[1] + s * geo.SA[1]];
  1358. const rk = r * k;
  1359. const beta = Math.atan2(sign * geo.SA[1], sign * geo.SA[0]);
  1360. const count = Math.max(24, Math.ceil((Math.PI * rk) / 1.5));
  1361. for (let j = 0; j <= count; j++) {
  1362. const t = beta - Math.PI / 2 + (Math.PI * j) / count;
  1363. pts.push([c[0] + rk * Math.cos(t), c[1] + rk * Math.sin(t)]);
  1364. }
  1365. }
  1366. return t3Hull(pts);
  1367. }
  1368. const view = geo.view;
  1369. const out = [];
  1370. let c;
  1371. if (view.flat < 1e-9) c = run.na * view.a > 0 ? -2 : 2;
  1372. else c = -(run.na * view.a) / (run.nr * view.flat);
  1373. if (c <= -1 || c >= 1) {
  1374. const side = c <= -1;
  1375. const capFirst = -geo.aV > 0;
  1376. const keepFirst = side ? !capFirst : capFirst;
  1377. const s = keepFirst ? s0 : s1;
  1378. const r = keepFirst ? r0 : r1;
  1379. t3ArcPoints(geo, s, r, 0, T3_TAU, k, out, run.cutS !== null && Math.abs(run.cutS - s) < 1e-6);
  1380. out.pop();
  1381. return out;
  1382. }
  1383. const d = Math.acos(c);
  1384. const lo = view.phi - d;
  1385. const hi = view.phi + d;
  1386. const cut0 = run.cutS !== null && Math.abs(run.cutS - s0) < 1e-6;
  1387. const cut1 = run.cutS !== null && Math.abs(run.cutS - s1) < 1e-6;
  1388. if (-geo.aV > 0) t3ArcPoints(geo, s0, r0, hi, lo + T3_TAU, k, out, cut0);
  1389. else t3ArcPoints(geo, s0, r0, lo, hi, k, out, cut0);
  1390. const tail = [];
  1391. if (geo.aV > 0) t3ArcPoints(geo, s1, r1, hi, lo + T3_TAU, k, tail, cut1);
  1392. else t3ArcPoints(geo, s1, r1, lo, hi, k, tail, cut1);
  1393. const first = out[out.length - 1];
  1394. const a = tail[0];
  1395. const b = tail[tail.length - 1];
  1396. if (Math.hypot(a[0] - first[0], a[1] - first[1]) > Math.hypot(b[0] - first[0], b[1] - first[1])) tail.reverse();
  1397. for (const p of tail) out.push(p);
  1398. return out;
  1399. }
  1400. function t3LatheMid(a, b) {
  1401. const h = b.s - a.s;
  1402. const ga = -a.na / a.nr;
  1403. const gb = -b.na / b.nr;
  1404. const nr = a.nr + b.nr;
  1405. const na = a.na + b.na;
  1406. const l = Math.hypot(nr, na) || 1;
  1407. return { s: (a.s + b.s) / 2, r: (a.r + b.r) / 2 + (h * (ga - gb)) / 8, nr: nr / l, na: na / l };
  1408. }
  1409. function t3LatheOutline(run, geo, cam) {
  1410. const k = cam.k;
  1411. const view = geo.view;
  1412. const lv = run.levels;
  1413. const pts = [];
  1414. const cut = (L) => (view.flat < 1e-9 ? Infinity : -(L.na * view.a) / (L.nr * view.flat));
  1415. const inside = (L) => L.r <= 1e-9 || Math.abs(cut(L)) < 1;
  1416. const sides = (L) => {
  1417. if (L.r <= 1e-9) {
  1418. const p = [geo.O[0] + L.s * geo.SA[0], geo.O[1] + L.s * geo.SA[1]];
  1419. return [p, p];
  1420. }
  1421. const c = Math.max(-1, Math.min(1, cut(L)));
  1422. const d = Math.acos(c);
  1423. return [view.phi - d, view.phi + d].map((t) => {
  1424. const cs = Math.cos(t);
  1425. const sn = Math.sin(t);
  1426. return [geo.O[0] + L.s * geo.SA[0] + L.r * (cs * geo.SU[0] + sn * geo.SV[0]), geo.O[1] + L.s * geo.SA[1] + L.r * (cs * geo.SU[1] + sn * geo.SV[1])];
  1427. });
  1428. };
  1429. const span = (a, b) => {
  1430. const pa = sides(a);
  1431. const pb = sides(b);
  1432. return Math.max(Math.hypot(pa[0][0] - pb[0][0], pa[0][1] - pb[0][1]), Math.hypot(pa[1][0] - pb[1][0], pa[1][1] - pb[1][1]));
  1433. };
  1434. const refine = (a, b, depth) => {
  1435. if (depth >= 10 || span(a, b) < 1.2) return;
  1436. const mid = t3LatheMid(a, b);
  1437. refine(a, mid, depth + 1);
  1438. pts.push(...sides(mid));
  1439. refine(mid, b, depth + 1);
  1440. };
  1441. let previous = null;
  1442. for (let i = 0; i < lv.length; i += 4) {
  1443. const L = { s: lv[i], r: lv[i + 1], nr: lv[i + 2], na: lv[i + 3] };
  1444. if (inside(L)) pts.push(...sides(L));
  1445. if (previous) {
  1446. const pin = inside(previous);
  1447. const lin = inside(L);
  1448. if (pin && lin) refine(previous, L, 0);
  1449. else if (pin !== lin) {
  1450. let a = pin ? previous : L;
  1451. let b = pin ? L : previous;
  1452. const start = a;
  1453. for (let it = 0; it < 14; it++) {
  1454. const mid = t3LatheMid(a.s < b.s ? a : b, a.s < b.s ? b : a);
  1455. if (inside(mid)) a = mid;
  1456. else b = mid;
  1457. }
  1458. pts.push(...sides(a));
  1459. refine(start.s < a.s ? start : a, start.s < a.s ? a : start, 0);
  1460. }
  1461. }
  1462. previous = L;
  1463. }
  1464. for (const i of [0, lv.length - 4]) if (lv[i + 1] > 1e-9) t3ArcPoints(geo, lv[i], lv[i + 1], 0, T3_TAU, k, pts);
  1465. return t3Hull(pts);
  1466. }
  1467. function t3SeamArc(geo, s, r, slope, k, trim = 0.3) {
  1468. const view = geo.view;
  1469. const norm = Math.hypot(1, slope);
  1470. let lo;
  1471. let hi;
  1472. if (view.flat < 1e-9) {
  1473. if (!((-slope * view.a) / norm > 0)) return "";
  1474. lo = view.phi;
  1475. hi = view.phi + T3_TAU;
  1476. } else {
  1477. const cc = (slope * view.a) / view.flat;
  1478. if (cc >= 1) return "";
  1479. if (cc <= -1) {
  1480. lo = view.phi;
  1481. hi = view.phi + T3_TAU;
  1482. } else {
  1483. const d = Math.acos(cc);
  1484. lo = view.phi - d;
  1485. hi = view.phi + d;
  1486. }
  1487. }
  1488. const full = hi - lo >= T3_TAU - 1e-9;
  1489. const buf = t3Scratch("c", 2 * 520);
  1490. if (!full) {
  1491. const span = hi - lo;
  1492. const cutAt = (from, sign) => {
  1493. t3At(geo, s, r, from, buf, 0);
  1494. const px = buf[0];
  1495. const py = buf[1];
  1496. let a = 0;
  1497. let b = span * 0.25;
  1498. t3At(geo, s, r, from + sign * b, buf, 0);
  1499. if (Math.hypot(buf[0] - px, buf[1] - py) <= trim) return b;
  1500. for (let it = 0; it < 18; it++) {
  1501. const mid = (a + b) / 2;
  1502. t3At(geo, s, r, from + sign * mid, buf, 0);
  1503. if (Math.hypot(buf[0] - px, buf[1] - py) < trim) a = mid;
  1504. else b = mid;
  1505. }
  1506. return (a + b) / 2;
  1507. };
  1508. const d0 = cutAt(lo, 1);
  1509. const d1 = cutAt(hi, -1);
  1510. lo += d0;
  1511. hi -= d1;
  1512. }
  1513. const count = Math.min(512, Math.max(4, Math.ceil(((hi - lo) * r * k) / 1.5)));
  1514. for (let j = 0; j <= count; j++) t3At(geo, s, r, lo + ((hi - lo) * j) / count, buf, 2 * j);
  1515. return t3Path(buf, full ? count : count + 1, full);
  1516. }
  1517. function t3RibLines(geo, F, cam, ribs, sx, sy) {
  1518. const lines = t3Lines;
  1519. lines.d.length = 0;
  1520. lines.alpha.length = 0;
  1521. lines.key.length = 0;
  1522. const { s0, s1, count, phase = 0, twist = 0, fade = [0.1, 0.55] } = ribs;
  1523. const r0 = ribs.r0 ?? ribs.r;
  1524. const r1 = ribs.r1 ?? r0;
  1525. const slope = (r1 - r0) / (s1 - s0 || 1);
  1526. const norm = Math.hypot(1, slope);
  1527. const view = geo.view;
  1528. const seg = new Float64Array(4);
  1529. for (let i = 0; i < count; i++) {
  1530. const t = phase + (i / count) * T3_TAU;
  1531. const tm = t + twist / 2;
  1532. const facing = (view.flat * Math.cos(tm - view.phi) - slope * view.a) / norm;
  1533. const alpha = t3Step(fade[0], fade[1], facing);
  1534. if (alpha * T3_LEVELS < 0.5) continue;
  1535. t3At(geo, s0, r0, t, seg, 0);
  1536. t3At(geo, s1, r1, t + twist, seg, 2);
  1537. seg[0] -= sx;
  1538. seg[1] -= sy;
  1539. seg[2] -= sx;
  1540. seg[3] -= sy;
  1541. lines.d.push(t3Path(seg, 2, false));
  1542. lines.alpha.push(alpha);
  1543. lines.key.push(i);
  1544. }
  1545. return lines;
  1546. }
  1547. function t3PrepareRound(run, part, P, unit) {
  1548. const spec = part.spec;
  1549. const k = P.scale * T3_ROOT;
  1550. run.F = spec.F;
  1551. run.s0 = spec.s0;
  1552. run.s1 = spec.s1;
  1553. run.r0 = spec.r0;
  1554. run.r1 = spec.r1;
  1555. run.ends = spec.ends;
  1556. const g = (spec.r1 - spec.r0) / (spec.s1 - spec.s0 || 1);
  1557. const norm = Math.hypot(1, g);
  1558. run.nr = 1 / norm;
  1559. run.na = -g / norm;
  1560. run.g = g;
  1561. const rmax = Math.max(spec.r0, spec.r1);
  1562. const around = T3_TAU * rmax * k * unit;
  1563. run.fine = Math.max(around < 30 ? 16 : 24, Math.min(96, Math.ceil(around / 2.2)));
  1564. run.dirs = Math.max(around < 30 ? 16 : 32, Math.min(256, Math.ceil(around / 1.5)));
  1565. run.capCount = Math.max(around < 30 ? 16 : 24, Math.min(160, Math.ceil(around / 1.5)));
  1566. run.domeCount = Math.max(around < 30 ? 12 : 16, Math.min(48, Math.round(run.fine * 0.75)));
  1567. const comps = [];
  1568. for (const [end, s, r] of [[0, spec.s0, spec.r0], [1, spec.s1, spec.r1]]) comps.push(spec.ends[end] === "dome" ? 1 : 0, s, r);
  1569. run.components = comps;
  1570. const details = part.details ?? {};
  1571. run.seams = (details.seams ?? []).map((s) => ({ s, r: spec.r0 + g * (s - spec.s0), slope: g }));
  1572. run.ribs = details.ribs ? { ...details.ribs, r0: details.ribs.r0 ?? spec.r0 + g * (details.ribs.s0 - spec.s0), r1: details.ribs.r1 ?? spec.r0 + g * (details.ribs.s1 - spec.s0) } : null;
  1573. run.cutS = null;
  1574. for (const cut of spec.cuts ?? []) {
  1575. const along = cut.n[0] * spec.F.a[0] + cut.n[1] * spec.F.a[1] + cut.n[2] * spec.F.a[2];
  1576. const sCut = (cut.d - (cut.n[0] * spec.F.o[0] + cut.n[1] * spec.F.o[1] + cut.n[2] * spec.F.o[2])) / along;
  1577. if (Math.abs(sCut - spec.s0) < 1e-6 || Math.abs(sCut - spec.s1) < 1e-6) run.cutS = sCut;
  1578. }
  1579. }
  1580. function t3EmitRound(run, cam, f) {
  1581. const geo = t3Geo(run.F, cam);
  1582. const k = cam.k;
  1583. const step = T3_TAU / run.fine;
  1584. const sheets = ["", "", "", "", ""];
  1585. const { s0, s1, r0, r1 } = run;
  1586. for (const arc of t3Arcs(run.nr, run.na, geo.view, geo.light)) sheets[arc.tone] += t3Strip(geo, s0, r0, s1, r1, arc.from, arc.to, step);
  1587. const F = run.F;
  1588. for (let end = 0; end < 2; end++) {
  1589. if (run.ends[end] !== "dome") continue;
  1590. const s = end ? s1 : s0;
  1591. const sign = end ? 1 : -1;
  1592. const C = [F.o[0] + F.a[0] * s, F.o[1] + F.a[1] * s, F.o[2] + F.a[2] * s];
  1593. t3Dome(cam, C, [F.a[0] * sign, F.a[1] * sign, F.a[2] * sign], end ? r1 : r0, run.domeCount, sheets);
  1594. }
  1595. for (let t = 0; t < 5; t++) f.d[run.role[`s${t}`]] = sheets[t];
  1596. const pts = t3RoundOutline(run, geo, cam);
  1597. const outline = t3PathOf(pts, true);
  1598. f.d[run.role.fill] = outline;
  1599. if (run.cutS !== null) {
  1600. const buf = new Float64Array(2 * pts.length);
  1601. const skip = new Uint8Array(pts.length);
  1602. pts.forEach((p, j) => {
  1603. buf[2 * j] = p[0];
  1604. buf[2 * j + 1] = p[1];
  1605. });
  1606. for (let j = 0; j < pts.length; j++) skip[j] = pts[j].cut && pts[(j + 1) % pts.length].cut ? 1 : 0;
  1607. f.d[run.role.edge] = t3Broken(buf, pts.length, skip);
  1608. } else f.d[run.role.edge] = outline;
  1609. t3BoxOf(pts, f.box);
  1610. t3HullOut(f, pts);
  1611. const view = geo.view;
  1612. let crease = "";
  1613. for (let end = 0; end < 2; end++) {
  1614. if (run.ends[end] !== "flat") continue;
  1615. const role = run.role[`k${end}`];
  1616. const sign = end ? 1 : -1;
  1617. const s = end ? s1 : s0;
  1618. const r = end ? r1 : r0;
  1619. const face = sign * geo.aV;
  1620. if (!(face > 1e-9)) {
  1621. f.d[role] = "";
  1622. continue;
  1623. }
  1624. const n = run.capCount;
  1625. const buf = t3Scratch("c", 2 * n);
  1626. const table = t3Table(n);
  1627. for (let j = 0; j < n; j++) {
  1628. const c = table[2 * j];
  1629. const q = table[2 * j + 1];
  1630. buf[2 * j] = geo.O[0] + s * geo.SA[0] + r * (c * geo.SU[0] + q * geo.SV[0]);
  1631. buf[2 * j + 1] = geo.O[1] + s * geo.SA[1] + r * (c * geo.SU[1] + q * geo.SV[1]);
  1632. }
  1633. f.d[role] = t3Path(buf, n, true);
  1634. f.q[role] = t3Level(sign * geo.aL, T3_LB);
  1635. const minor = 2 * r * k * Math.abs(face);
  1636. f.w[role] = minor < 0.4 ? Math.round(minor * 100) / 100 : -1;
  1637. if (run.role.crease === undefined) continue;
  1638. let lo;
  1639. let hi;
  1640. if (view.flat < 1e-9) {
  1641. if (!(run.na * view.a > 1e-9)) continue;
  1642. lo = 0;
  1643. hi = T3_TAU;
  1644. } else {
  1645. const cc = -(run.na * view.a) / (run.nr * view.flat);
  1646. if (cc >= 1) continue;
  1647. if (cc <= -1) {
  1648. lo = view.phi;
  1649. hi = view.phi + T3_TAU;
  1650. } else {
  1651. const d = Math.acos(cc);
  1652. lo = view.phi - d;
  1653. hi = view.phi + d;
  1654. }
  1655. }
  1656. const count = Math.min(400, Math.max(4, Math.ceil(((hi - lo) * r * k) / 1.5)));
  1657. const arc = t3Scratch("c", 2 * count + 2);
  1658. for (let j = 0; j <= count; j++) t3At(geo, s, r, lo + ((hi - lo) * j) / count, arc, 2 * j);
  1659. crease += t3Path(arc, count + 1, false);
  1660. }
  1661. if (run.role.crease !== undefined) f.d[run.role.crease] = crease;
  1662. if (run.role.inner !== undefined) {
  1663. let inner = "";
  1664. for (const seam of run.seams) inner += t3SeamArc(geo, seam.s, seam.r, seam.slope, k);
  1665. if (run.ribs && run.ribs.seams) {
  1666. const rs = run.ribs;
  1667. const slope = (rs.r1 - rs.r0) / (rs.s1 - rs.s0 || 1);
  1668. if (rs.seams !== "last") inner += t3SeamArc(geo, rs.s0, rs.r0, slope, k);
  1669. if (rs.seams !== "first") inner += t3SeamArc(geo, rs.s1, rs.r1, slope, k);
  1670. }
  1671. f.d[run.role.inner] = inner;
  1672. }
  1673. if (run.ribs) {
  1674. const lines = t3State.detail < 0.01 ? t3None : t3RibLines(geo, run.F, cam, run.ribs, 0, 0);
  1675. f.levels = t3Faded(f, run, "r", lines, lines.d.length);
  1676. }
  1677. }
  1678. function t3PrepareBall(run, part, P, unit) {
  1679. const spec = part.spec;
  1680. const k = P.scale * T3_ROOT;
  1681. run.c = spec.c;
  1682. run.r = spec.r;
  1683. run.flats = spec.flats.map((flat) => {
  1684. const n = t3Unit(flat.n);
  1685. const rho = Math.sqrt(Math.max(0, spec.r * spec.r - flat.d * flat.d));
  1686. const [u, v] = t3Basis(n);
  1687. return { n, d: flat.d, rho, u, v };
  1688. });
  1689. run.limb = Math.max(32, Math.min(160, Math.ceil((T3_TAU * spec.r * k * unit) / 1.5)));
  1690. run.rimCount = run.flats.map((flat) => Math.max(20, Math.min(120, Math.ceil((T3_TAU * flat.rho * k * unit) / 1.5))));
  1691. }
  1692. function t3ClipConvex(subject, clip) {
  1693. if (subject.length < 3 || clip.length < 3) return [];
  1694. let area = 0;
  1695. for (let i = 0; i < clip.length; i++) {
  1696. const a = clip[i];
  1697. const b = clip[(i + 1) % clip.length];
  1698. area += a[0] * b[1] - b[0] * a[1];
  1699. }
  1700. const sign = area >= 0 ? 1 : -1;
  1701. let out = subject;
  1702. for (let i = 0; i < clip.length && out.length; i++) {
  1703. const a = clip[i];
  1704. const b = clip[(i + 1) % clip.length];
  1705. const side = (p) => sign * ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]));
  1706. const input = out;
  1707. out = [];
  1708. for (let j = 0; j < input.length; j++) {
  1709. const p = input[j];
  1710. const q = input[(j + 1) % input.length];
  1711. const sp = side(p);
  1712. const sq = side(q);
  1713. if (sp >= 0) out.push(p);
  1714. if ((sp >= 0) !== (sq >= 0)) {
  1715. const t = sp / (sp - sq);
  1716. out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]);
  1717. }
  1718. }
  1719. }
  1720. return out;
  1721. }
  1722. function t3EmitBall(run, cam, f) {
  1723. const m = cam.m;
  1724. const V = cam.V;
  1725. const L = cam.L;
  1726. const { c, r, flats } = run;
  1727. const Cx = cam.ox + m[0] * c[0] + m[1] * c[1] + m[2] * c[2];
  1728. const Cy = cam.oy + m[3] * c[0] + m[4] * c[1] + m[5] * c[2];
  1729. const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  1730. const flat = (w) => [Cx + r * (m[0] * w[0] + m[1] * w[1] + m[2] * w[2]), Cy + r * (m[3] * w[0] + m[4] * w[1] + m[5] * w[2])];
  1731. const inside = (w, skip = -1) => {
  1732. for (let i = 0; i < flats.length; i++) if (i !== skip && dot(w, flats[i].n) * r > flats[i].d + 1e-7) return false;
  1733. return true;
  1734. };
  1735. const [U, W] = t3Basis(V);
  1736. const n = run.limb;
  1737. const table = t3Table(n);
  1738. const limb = [];
  1739. for (let j = 0; j < n; j++) limb.push([U[0] * table[2 * j] + W[0] * table[2 * j + 1], U[1] * table[2 * j] + W[1] * table[2 * j + 1], U[2] * table[2 * j] + W[2] * table[2 * j + 1]]);
  1740. const sil = [];
  1741. for (const w of limb) if (inside(w)) sil.push(flat(w));
  1742. const rims = flats.map((cut, ci) => {
  1743. const count = run.rimCount[ci];
  1744. const t = t3Table(count);
  1745. const list = [];
  1746. for (let j = 0; j < count; j++) {
  1747. const w = [(cut.n[0] * cut.d + cut.rho * (cut.u[0] * t[2 * j] + cut.v[0] * t[2 * j + 1])) / r, (cut.n[1] * cut.d + cut.rho * (cut.u[1] * t[2 * j] + cut.v[1] * t[2 * j + 1])) / r, (cut.n[2] * cut.d + cut.rho * (cut.u[2] * t[2 * j] + cut.v[2] * t[2 * j + 1])) / r];
  1748. list.push({ w, keep: inside(w, ci), p: flat(w) });
  1749. }
  1750. return list;
  1751. });
  1752. flats.forEach((cut, ci) => {
  1753. for (const w of t3Meet(V, 0, cut.n, cut.d / r)) if (inside(w, ci)) sil.push(flat(w));
  1754. rims[ci].forEach(({ keep, p }) => keep && sil.push(p));
  1755. });
  1756. const hull = t3Hull(sil);
  1757. const outline = t3PathOf(hull, true);
  1758. f.d[run.role.fill] = outline;
  1759. f.d[run.role.edge] = outline;
  1760. f.d[run.role.s0] = outline;
  1761. const capOf = (threshold) => {
  1762. const points = [];
  1763. for (const w of limb) if (dot(w, L) >= threshold && inside(w)) points.push(flat(w));
  1764. const radius = Math.sqrt(Math.max(0, 1 - threshold * threshold));
  1765. const [LU, LW] = t3Basis(L);
  1766. for (let j = 0; j < n; j++) {
  1767. const w = [L[0] * threshold + radius * (LU[0] * table[2 * j] + LW[0] * table[2 * j + 1]), L[1] * threshold + radius * (LU[1] * table[2 * j] + LW[1] * table[2 * j + 1]), L[2] * threshold + radius * (LU[2] * table[2 * j] + LW[2] * table[2 * j + 1])];
  1768. if (dot(w, V) >= -1e-9) points.push(flat(w));
  1769. }
  1770. if (dot(L, V) > threshold) points.push(flat(V));
  1771. for (const w of t3Meet(L, threshold, V, 0)) if (inside(w)) points.push(flat(w));
  1772. flats.forEach((cut, ci) => {
  1773. for (const w of t3Meet(V, 0, cut.n, cut.d / r)) if (inside(w, ci) && dot(w, L) >= threshold) points.push(flat(w));
  1774. for (const w of t3Meet(L, threshold, cut.n, cut.d / r)) if (inside(w, ci) && dot(w, V) >= -1e-9) points.push(flat(w));
  1775. for (const { w, keep, p } of rims[ci]) if (keep && dot(w, L) >= threshold && dot(w, V) >= -1e-9) points.push(p);
  1776. });
  1777. if (points.length < 3) return "";
  1778. const region = t3ClipConvex(t3Hull(points), hull);
  1779. return region.length >= 3 ? t3PathOf(region, true) : "";
  1780. };
  1781. f.d[run.role.s1] = capOf(T3_LB[1]);
  1782. f.d[run.role.s2] = capOf(T3_LB[2]);
  1783. f.d[run.role.s3] = capOf(T3_LB[3]);
  1784. let crease = "";
  1785. flats.forEach((cut, ci) => {
  1786. const role = run.role[`f${ci}`];
  1787. const face = dot(cut.n, V);
  1788. if (!(face > 1e-9)) {
  1789. f.d[role] = "";
  1790. return;
  1791. }
  1792. const pts = t3ClipConvex(rims[ci].map(({ p }) => p), hull);
  1793. f.d[role] = t3PathOf(pts, true);
  1794. f.q[role] = t3Level(dot(cut.n, L), T3_LB);
  1795. const minor = 2 * cut.rho * cam.k * face;
  1796. f.w[role] = minor < 0.4 ? Math.round(minor * 100) / 100 : -1;
  1797. const list = rims[ci];
  1798. const seen = list.map(({ w, keep }) => keep && dot(w, V) > 0);
  1799. const start = seen.indexOf(false);
  1800. if (start < 0) {
  1801. crease += t3PathOf(list.map(({ p }) => p), true);
  1802. return;
  1803. }
  1804. let cur = null;
  1805. for (let s = 1; s <= list.length; s++) {
  1806. const i = (start + s) % list.length;
  1807. if (seen[i]) (cur ??= []).push(list[i].p);
  1808. else if (cur) {
  1809. if (cur.length > 1) crease += t3PathOf(cur, false);
  1810. cur = null;
  1811. }
  1812. }
  1813. if (cur && cur.length > 1) crease += t3PathOf(cur, false);
  1814. });
  1815. if (run.role.crease !== undefined) f.d[run.role.crease] = crease;
  1816. let x0 = Infinity;
  1817. let y0 = Infinity;
  1818. let x1 = -Infinity;
  1819. let y1 = -Infinity;
  1820. for (const [x, y] of hull) {
  1821. if (x < x0) x0 = x;
  1822. if (x > x1) x1 = x;
  1823. if (y < y0) y0 = y;
  1824. if (y > y1) y1 = y;
  1825. }
  1826. f.box[0] = x0;
  1827. f.box[1] = y0;
  1828. f.box[2] = x1;
  1829. f.box[3] = y1;
  1830. t3HullOut(f, hull);
  1831. }
  1832. function t3PrepareLathe(run, part, P, unit) {
  1833. const spec = part.spec;
  1834. const k = P.scale * T3_ROOT;
  1835. run.F = spec.F;
  1836. run.levels = spec.levels;
  1837. run.caps = spec.caps;
  1838. let rmax = 0;
  1839. for (let i = 0; i < spec.levels.length; i += 4) rmax = Math.max(rmax, spec.levels[i + 1]);
  1840. run.fine = Math.max(24, Math.min(96, Math.ceil((T3_TAU * rmax * k * unit) / 2.2)));
  1841. run.dirs = Math.max(32, Math.min(256, Math.ceil((T3_TAU * rmax * k * unit) / 1.5)));
  1842. run.capCount = Math.max(24, Math.min(160, Math.ceil((T3_TAU * rmax * k * unit) / 1.5)));
  1843. const comps = [];
  1844. for (let i = 0; i < spec.levels.length; i += 4) comps.push(0, spec.levels[i], spec.levels[i + 1]);
  1845. run.components = comps;
  1846. const details = part.details ?? {};
  1847. run.seams = (details.seams ?? []).map((seam) => (typeof seam === "number" ? t3LatheSeam(spec.levels, seam) : seam));
  1848. run.ribs = details.ribs ?? null;
  1849. }
  1850. function t3LatheSeam(levels, s) {
  1851. for (let i = 0; i + 4 < levels.length; i += 4) {
  1852. const sa = levels[i];
  1853. const sb = levels[i + 4];
  1854. if ((s - sa) * (s - sb) <= 0 && sa !== sb) {
  1855. const t = (s - sa) / (sb - sa);
  1856. const r = levels[i + 1] + (levels[i + 5] - levels[i + 1]) * t;
  1857. const slope = (levels[i + 5] - levels[i + 1]) / (sb - sa);
  1858. return { s, r, slope };
  1859. }
  1860. }
  1861. return { s, r: levels[1], slope: 0 };
  1862. }
  1863. function t3LatheSheets(levels, geo, step, buckets) {
  1864. const at = (L, t) => {
  1865. const c = Math.cos(t);
  1866. const n = Math.sin(t);
  1867. return [geo.O[0] + L.s * geo.SA[0] + L.r * (c * geo.SU[0] + n * geo.SV[0]), geo.O[1] + L.s * geo.SA[1] + L.r * (c * geo.SU[1] + n * geo.SV[1])];
  1868. };
  1869. const arcPoints = (L, from, to) => {
  1870. const count = Math.max(1, Math.ceil((to - from) / step));
  1871. const out = new Array(count + 1);
  1872. for (let index = 0; index <= count; index++) out[index] = at(L, from + ((to - from) * index) / count);
  1873. return out;
  1874. };
  1875. const oriented = (points) => {
  1876. let area = 0;
  1877. for (let i = 0; i < points.length; i++) {
  1878. const a = points[i];
  1879. const b = points[(i + 1) % points.length];
  1880. area += a[0] * b[1] - b[0] * a[1];
  1881. }
  1882. return area < 0 ? points.reverse() : points;
  1883. };
  1884. const centreOf = (arc, reference) => {
  1885. let mid = (arc.from + arc.to) / 2 - reference;
  1886. mid = ((mid % T3_TAU) + T3_TAU) % T3_TAU;
  1887. return mid;
  1888. };
  1889. const present = [false, false, false, false, false];
  1890. for (const L of levels) {
  1891. const groups = [null, null, null, null, null];
  1892. for (const arc of L.arcs) {
  1893. if (!groups[arc.tone]) groups[arc.tone] = [];
  1894. groups[arc.tone].push(arc);
  1895. present[arc.tone] = true;
  1896. }
  1897. for (const list of groups) if (list && list.length > 1) list.sort((x, y) => centreOf(x, geo.light.phi) - centreOf(y, geo.light.phi));
  1898. L.groups = groups;
  1899. }
  1900. const align = (reference, arc) => {
  1901. const out = { ...arc };
  1902. const centre = (reference.from + reference.to) / 2;
  1903. while ((out.from + out.to) / 2 - centre > Math.PI) {
  1904. out.from -= T3_TAU;
  1905. out.to -= T3_TAU;
  1906. }
  1907. while (centre - (out.from + out.to) / 2 > Math.PI) {
  1908. out.from += T3_TAU;
  1909. out.to += T3_TAU;
  1910. }
  1911. return out;
  1912. };
  1913. const overlap = (x, y) => Math.min(x.to, y.to) - Math.max(x.from, y.from);
  1914. const sheet = (tone, run) => {
  1915. const chains = run[0].groups[tone].map((arc) => [arc]);
  1916. for (let q = 1; q < run.length; q++) {
  1917. const next = run[q].groups[tone];
  1918. const used = new Uint8Array(next.length);
  1919. for (const chain of chains) {
  1920. const prev = chain[q - 1];
  1921. let best = -1;
  1922. let score = -Infinity;
  1923. for (let j = 0; j < next.length; j++) {
  1924. if (used[j]) continue;
  1925. const value = overlap(prev, align(prev, next[j]));
  1926. if (value > score) {
  1927. score = value;
  1928. best = j;
  1929. }
  1930. }
  1931. used[best] = 1;
  1932. chain.push(align(prev, next[best]));
  1933. }
  1934. }
  1935. chains.forEach((chain) => {
  1936. const last = run.length - 1;
  1937. const points = arcPoints(run[0], chain[0].from, chain[0].to);
  1938. for (let q = 1; q < last; q++) points.push(at(run[q], chain[q].to));
  1939. points.push(...arcPoints(run[last], chain[last].from, chain[last].to).reverse());
  1940. for (let q = last - 1; q >= 1; q--) points.push(at(run[q], chain[q].from));
  1941. buckets[tone] += t3PathOf(oriented(points), true);
  1942. });
  1943. };
  1944. const strip = (tone, a, b) => {
  1945. const below = a.groups[tone] ?? [];
  1946. const above = b.groups[tone] ?? [];
  1947. const whole = (arc) => arc.to - arc.from >= T3_TAU - 1e-6;
  1948. const seat = (ring, arc) => {
  1949. const gap = T3_TAU - (arc.to - arc.from);
  1950. return { from: arc.from - gap / 2, to: arc.to + gap / 2 };
  1951. };
  1952. const quad = (lo, hi) => {
  1953. if (whole(hi) && !whole(lo)) hi = seat(hi, lo);
  1954. else if (whole(lo) && !whole(hi)) lo = seat(lo, hi);
  1955. const points = [...arcPoints(a, lo.from, lo.to), ...arcPoints(b, hi.from, hi.to).reverse()];
  1956. buckets[tone] += t3PathOf(oriented(points), true);
  1957. };
  1958. const links = below.map(() => []);
  1959. const back = above.map(() => []);
  1960. below.forEach((lo, i) =>
  1961. above.forEach((hi, j) => {
  1962. if (overlap(lo, align(lo, hi)) > -0.05) {
  1963. links[i].push(j);
  1964. back[j].push(i);
  1965. }
  1966. }),
  1967. );
  1968. const doneLo = new Uint8Array(below.length);
  1969. const doneHi = new Uint8Array(above.length);
  1970. const share = (span, parts, flip) => {
  1971. if (whole(span)) {
  1972. const base = parts[0].from;
  1973. const sorted = parts.map((arc) => {
  1974. const shift = T3_TAU * Math.floor((arc.from - base) / T3_TAU);
  1975. return { from: arc.from - shift, to: arc.to - shift };
  1976. }).sort((x, y) => x.from - y.from);
  1977. const n = sorted.length;
  1978. const cuts = sorted.map((arc, q) => {
  1979. const next = q + 1 < n ? sorted[q + 1].from : sorted[0].from + T3_TAU;
  1980. return (arc.to + next) / 2;
  1981. });
  1982. sorted.forEach((arc, q) => {
  1983. const piece = { from: q ? cuts[q - 1] : cuts[n - 1] - T3_TAU, to: cuts[q] };
  1984. if (flip) quad(arc, piece);
  1985. else quad(piece, arc);
  1986. });
  1987. return;
  1988. }
  1989. const sorted = parts.map((arc) => align(span, arc)).sort((x, y) => x.from - y.from);
  1990. const cuts = [span.from];
  1991. for (let q = 1; q < sorted.length; q++) cuts.push(Math.min(span.to, Math.max(span.from, (sorted[q - 1].to + sorted[q].from) / 2)));
  1992. cuts.push(span.to);
  1993. sorted.forEach((arc, q) => {
  1994. const piece = { from: cuts[q], to: cuts[q + 1] };
  1995. if (flip) quad(arc, piece);
  1996. else quad(piece, arc);
  1997. });
  1998. };
  1999. for (let j = 0; j < above.length; j++) {
  2000. if (back[j].length < 2 || back[j].some((i) => links[i].length !== 1)) continue;
  2001. share(above[j], back[j].map((i) => below[i]), false);
  2002. doneHi[j] = 1;
  2003. for (const i of back[j]) doneLo[i] = 1;
  2004. }
  2005. for (let i = 0; i < below.length; i++) {
  2006. if (doneLo[i] || links[i].length < 2 || links[i].some((j) => back[j].length !== 1)) continue;
  2007. share(below[i], links[i].map((j) => above[j]), true);
  2008. doneLo[i] = 1;
  2009. for (const j of links[i]) doneHi[j] = 1;
  2010. }
  2011. for (let i = 0; i < below.length; i++) {
  2012. if (doneLo[i]) continue;
  2013. const lo = below[i];
  2014. let best = -1;
  2015. let score = -Infinity;
  2016. for (const j of links[i]) {
  2017. if (doneHi[j]) continue;
  2018. const value = overlap(lo, align(lo, above[j]));
  2019. if (value > score) {
  2020. score = value;
  2021. best = j;
  2022. }
  2023. }
  2024. if (best >= 0) {
  2025. doneHi[best] = 1;
  2026. quad(lo, align(lo, above[best]));
  2027. } else {
  2028. const centre = (lo.from + lo.to) / 2;
  2029. quad(lo, { from: centre, to: centre });
  2030. }
  2031. }
  2032. for (let j = 0; j < above.length; j++) {
  2033. if (doneHi[j]) continue;
  2034. const centre = (above[j].from + above[j].to) / 2;
  2035. quad({ from: centre, to: centre }, above[j]);
  2036. }
  2037. };
  2038. for (let tone = 0; tone < 5; tone++) {
  2039. if (!present[tone]) continue;
  2040. for (let q = 1; q < levels.length; q++) strip(tone, levels[q - 1], levels[q]);
  2041. }
  2042. void sheet;
  2043. }
  2044. function t3EmitLathe(run, cam, f) {
  2045. const geo = t3Geo(run.F, cam);
  2046. const k = cam.k;
  2047. const step = T3_TAU / run.fine;
  2048. const sheets = ["", "", "", "", ""];
  2049. const lv = run.levels;
  2050. const levelAt = (s, r, nr, na) => ({ s, r, nr, na, arcs: t3Arcs(nr, na, geo.view, geo.light) });
  2051. const same = (a, b) => {
  2052. if (a.arcs.length !== b.arcs.length) return false;
  2053. for (let i = 0; i < a.arcs.length; i++) if (a.arcs[i].tone !== b.arcs[i].tone || Boolean(a.arcs[i].full) !== Boolean(b.arcs[i].full)) return false;
  2054. return true;
  2055. };
  2056. const reach = (a, b) => Math.hypot((b.s - a.s) * Math.hypot(geo.SA[0], geo.SA[1]), (b.r - a.r) * k) + Math.abs(b.r - a.r) * k;
  2057. const levels = [];
  2058. const wrap = (x, ref) => x + T3_TAU * Math.round((ref - x) / T3_TAU);
  2059. const close = (a, mid, b) => {
  2060. const r = Math.max(a.r, b.r) * k;
  2061. for (let i = 0; i < mid.arcs.length; i++) {
  2062. const m = mid.arcs[i];
  2063. if (m.full) continue;
  2064. for (const key of ["from", "to"]) {
  2065. const x = m[key];
  2066. const guess = (wrap(a.arcs[i][key], x) + wrap(b.arcs[i][key], x)) / 2;
  2067. if (Math.abs(guess - x) * r > 0.25) return false;
  2068. }
  2069. }
  2070. return true;
  2071. };
  2072. const refine = (a, b, depth) => {
  2073. if (depth >= 8 || reach(a, b) < 0.1) {
  2074. levels.push(b);
  2075. return;
  2076. }
  2077. const m = t3LatheMid(a, b);
  2078. const mid = levelAt(m.s, m.r, m.nr, m.na);
  2079. if (same(a, b) && same(a, mid) && close(a, mid, b)) {
  2080. levels.push(b);
  2081. return;
  2082. }
  2083. refine(a, mid, depth + 1);
  2084. refine(mid, b, depth + 1);
  2085. };
  2086. let previous = levelAt(lv[0], lv[1], lv[2], lv[3]);
  2087. levels.push(previous);
  2088. for (let i = 4; i < lv.length; i += 4) {
  2089. const next = levelAt(lv[i], lv[i + 1], lv[i + 2], lv[i + 3]);
  2090. refine(previous, next, 0);
  2091. previous = next;
  2092. }
  2093. t3LatheSheets(levels, geo, step, sheets);
  2094. for (let t = 0; t < 5; t++) f.d[run.role[`s${t}`]] = sheets[t];
  2095. const pts = t3LatheOutline(run, geo, cam);
  2096. const outline = t3PathOf(pts, true);
  2097. f.d[run.role.fill] = outline;
  2098. f.d[run.role.edge] = outline;
  2099. t3BoxOf(pts, f.box);
  2100. t3HullOut(f, pts);
  2101. let crease = "";
  2102. const view = geo.view;
  2103. const ends = [[0, lv[0], lv[1], -1, 4], [1, lv[lv.length - 4], lv[lv.length - 3], 1, lv.length - 8]];
  2104. for (const [end, s, r, sign, near] of ends) {
  2105. const role = run.role[`k${end}`];
  2106. if (role === undefined) continue;
  2107. const face = sign * geo.aV;
  2108. if (!(face > 1e-9) || r <= 1e-9) {
  2109. f.d[role] = "";
  2110. continue;
  2111. }
  2112. const n = run.capCount;
  2113. const buf = t3Scratch("c", 2 * n);
  2114. const table = t3Table(n);
  2115. for (let j = 0; j < n; j++) {
  2116. const c = table[2 * j];
  2117. const q = table[2 * j + 1];
  2118. buf[2 * j] = geo.O[0] + s * geo.SA[0] + r * (c * geo.SU[0] + q * geo.SV[0]);
  2119. buf[2 * j + 1] = geo.O[1] + s * geo.SA[1] + r * (c * geo.SU[1] + q * geo.SV[1]);
  2120. }
  2121. f.d[role] = t3Path(buf, n, true);
  2122. f.q[role] = t3Level(sign * geo.aL, T3_LB);
  2123. const minor = 2 * r * k * Math.abs(face);
  2124. f.w[role] = minor < 0.4 ? Math.round(minor * 100) / 100 : -1;
  2125. if (run.role.crease === undefined) continue;
  2126. const nr = lv[near + 2];
  2127. const na = lv[near + 3];
  2128. let lo;
  2129. let hi;
  2130. if (view.flat < 1e-9) {
  2131. if (!(na * view.a > 1e-9)) continue;
  2132. lo = 0;
  2133. hi = T3_TAU;
  2134. } else {
  2135. const cc = -(na * view.a) / (nr * view.flat);
  2136. if (cc >= 1) continue;
  2137. if (cc <= -1) {
  2138. lo = view.phi;
  2139. hi = view.phi + T3_TAU;
  2140. } else {
  2141. const d = Math.acos(cc);
  2142. lo = view.phi - d;
  2143. hi = view.phi + d;
  2144. }
  2145. }
  2146. const count = Math.min(400, Math.max(4, Math.ceil(((hi - lo) * r * k) / 1.5)));
  2147. const arc = t3Scratch("c", 2 * count + 2);
  2148. for (let j = 0; j <= count; j++) t3At(geo, s, r, lo + ((hi - lo) * j) / count, arc, 2 * j);
  2149. crease += t3Path(arc, count + 1, false);
  2150. }
  2151. if (run.role.crease !== undefined) f.d[run.role.crease] = crease;
  2152. if (run.role.inner !== undefined) {
  2153. let inner = "";
  2154. for (const seam of run.seams) inner += t3SeamArc(geo, seam.s, seam.r, seam.slope, k);
  2155. f.d[run.role.inner] = inner;
  2156. }
  2157. if (run.ribs) {
  2158. const lines = t3State.detail < 0.01 ? t3None : t3RibLines(geo, run.F, cam, run.ribs, 0, 0);
  2159. f.levels = t3Faded(f, run, "r", lines, lines.d.length);
  2160. }
  2161. }
  2162. const T3_SHINE = (() => {
  2163. const l = Math.hypot(-0.55, -0.835);
  2164. return [-0.55 / l, -0.835 / l];
  2165. })();
  2166. function t3RouteOf(flat) {
  2167. const n = flat.length / 3;
  2168. const along = new Float64Array(n);
  2169. for (let i = 1; i < n; i++) along[i] = along[i - 1] + Math.hypot(flat[3 * i] - flat[3 * i - 3], flat[3 * i + 1] - flat[3 * i - 2], flat[3 * i + 2] - flat[3 * i - 1]);
  2170. return { flat, n, along, total: along[n - 1] };
  2171. }
  2172. function t3PointAlong(route, at) {
  2173. const { flat, n, along } = route;
  2174. if (at <= 0) return [flat[0], flat[1], flat[2]];
  2175. if (at >= along[n - 1]) return [flat[3 * n - 3], flat[3 * n - 2], flat[3 * n - 1]];
  2176. let lo = 0;
  2177. let hi = n - 1;
  2178. while (hi - lo > 1) {
  2179. const mid = (lo + hi) >> 1;
  2180. if (along[mid] <= at) lo = mid;
  2181. else hi = mid;
  2182. }
  2183. const span = along[hi] - along[lo] || 1;
  2184. const t = (at - along[lo]) / span;
  2185. return [flat[3 * lo] + (flat[3 * hi] - flat[3 * lo]) * t, flat[3 * lo + 1] + (flat[3 * hi + 1] - flat[3 * lo + 1]) * t, flat[3 * lo + 2] + (flat[3 * hi + 2] - flat[3 * lo + 2]) * t];
  2186. }
  2187. function t3Cut(route, from, to) {
  2188. const { flat, n, along } = route;
  2189. const out = [];
  2190. for (let i = 1; i < n; i++) {
  2191. const start = along[i - 1];
  2192. const end = along[i];
  2193. if (end >= from && start <= to) {
  2194. const length = end - start || 1;
  2195. const t0 = Math.max(0, (from - start) / length);
  2196. const t1 = Math.min(1, (to - start) / length);
  2197. const at = (t) => [flat[3 * i - 3] + (flat[3 * i] - flat[3 * i - 3]) * t, flat[3 * i - 2] + (flat[3 * i + 1] - flat[3 * i - 2]) * t, flat[3 * i - 1] + (flat[3 * i + 2] - flat[3 * i - 1]) * t];
  2198. if (!out.length) out.push(at(t0));
  2199. out.push(at(t1));
  2200. }
  2201. }
  2202. return out;
  2203. }
  2204. function t3TangentAlong(route, at) {
  2205. const a = t3PointAlong(route, Math.max(0, at - 0.6));
  2206. const b = t3PointAlong(route, Math.min(route.total, at + 0.6));
  2207. return t3Unit([b[0] - a[0], b[1] - a[1], b[2] - a[2]]);
  2208. }
  2209. const t3RouteCache = new WeakMap();
  2210. function t3PrepareTube(run, part, data) {
  2211. const spec = part.spec;
  2212. const source = data.routes[spec.route];
  2213. let route = t3RouteCache.get(source);
  2214. if (!route) {
  2215. route = t3RouteOf(source.points);
  2216. t3RouteCache.set(source, route);
  2217. }
  2218. const total = route.total;
  2219. const r = source.r;
  2220. const step = Math.max(0.05, Math.min(source.spacing, total / 4) * 0.5);
  2221. const lead = 0.5;
  2222. run.r = r;
  2223. run.wide = Boolean(source.wide);
  2224. run.hue = source.hue ?? null;
  2225. const partOf = (start, end) => {
  2226. const points = t3Cut(route, Math.max(0, start), Math.min(total, end));
  2227. let walked = Math.max(0, start);
  2228. const count = points.length;
  2229. const P3 = new Float64Array(3 * count);
  2230. const D3 = new Float64Array(3 * count);
  2231. for (let i = 0; i < count; i++) {
  2232. if (i > 0) walked += Math.hypot(points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1], points[i][2] - points[i - 1][2]);
  2233. const a = t3PointAlong(route, Math.max(0, Math.min(total, walked - step)));
  2234. const b = t3PointAlong(route, Math.max(0, Math.min(total, walked + step)));
  2235. for (let c = 0; c < 3; c++) {
  2236. P3[3 * i + c] = points[i][c];
  2237. D3[3 * i + c] = b[c] - a[c];
  2238. }
  2239. }
  2240. return { count, P3, D3 };
  2241. };
  2242. const openStart = spec.open0 && spec.from > 0;
  2243. const openEnd = spec.open1 && spec.to < total;
  2244. run.body = partOf(openStart ? spec.from - lead : spec.from, openEnd ? spec.to + lead : spec.to);
  2245. run.stripe = openStart || openEnd ? partOf(openStart ? spec.from - 2 * lead : spec.from, openEnd ? spec.to + 2 * lead : spec.to) : run.body;
  2246. const ends = [!spec.open0 && (spec.from <= 1e-6 || spec.gap0), !spec.open1 && (spec.to >= total - 1e-6 || spec.gap1)];
  2247. run.capped = [ends[0] && (spec.gap0 || spec.caps[0]), ends[1] && (spec.gap1 || spec.caps[1])];
  2248. const P3 = run.body.P3;
  2249. const last = run.body.count - 1;
  2250. const vec = (i, j) => t3Unit([P3[3 * i] - P3[3 * j], P3[3 * i + 1] - P3[3 * j + 1], P3[3 * i + 2] - P3[3 * j + 2]]);
  2251. run.tips = [vec(1, 0), vec(last, last - 1)];
  2252. run.rings = null;
  2253. if (source.rings) {
  2254. const { pitch = 3, twist = 0, cross = false, fade = [0.1, 0.55], phase = 0, steps = 16 } = source.rings;
  2255. const lo = openStart ? spec.from - 2 * lead : spec.from;
  2256. const hi = openEnd ? spec.to + 2 * lead : spec.to;
  2257. const margin = twist ? 0 : Math.min(pitch * 0.35, (hi - lo) / 2);
  2258. const from = Math.max(lo, !openStart ? lo + margin : lo);
  2259. const to = Math.min(hi, !openEnd ? hi - margin : hi);
  2260. const segments = [];
  2261. if (to > from) {
  2262. const hands = twist ? (cross ? [1, -1] : [1]) : [0];
  2263. const reach = Math.abs(twist) * r;
  2264. const first = Math.ceil((from - reach - phase) / pitch);
  2265. const lastIndex = Math.floor((to + reach - phase) / pitch);
  2266. const surface = (t, theta) => {
  2267. const at = Math.max(0, Math.min(total, t));
  2268. return { c: t3PointAlong(route, at), T: t3TangentAlong(route, at), theta };
  2269. };
  2270. for (let index = first; index <= lastIndex; index++) {
  2271. const station = phase + index * pitch;
  2272. for (const hand of hands) {
  2273. const samples = [];
  2274. for (let k = 0; k <= steps; k++) {
  2275. const theta = (k / steps) * Math.PI;
  2276. const t = station + hand * twist * r * (k / steps - 0.5);
  2277. samples.push({ t, theta });
  2278. }
  2279. for (let k = 0; k < steps; k++) {
  2280. let a = samples[k];
  2281. let b = samples[k + 1];
  2282. if ((a.t < from && b.t < from) || (a.t > to && b.t > to)) continue;
  2283. const clipTo = (x, y, edge) => ({ t: edge, theta: x.theta + ((y.theta - x.theta) * (edge - x.t)) / (y.t - x.t || 1e-9) });
  2284. if (a.t < from) a = clipTo(a, b, from);
  2285. if (b.t < from) b = clipTo(b, a, from);
  2286. if (a.t > to) a = clipTo(a, b, to);
  2287. if (b.t > to) b = clipTo(b, a, to);
  2288. segments.push([surface(a.t, a.theta), surface(b.t, b.theta)]);
  2289. }
  2290. }
  2291. }
  2292. }
  2293. run.rings = { segments, fade, tone: source.rings.tone ?? "lo" };
  2294. }
  2295. }
  2296. function t3Sides(part, cam, r) {
  2297. const m = cam.m;
  2298. const k = cam.k;
  2299. const n = part.count;
  2300. const out = { n, flat: new Float64Array(2 * n), left: new Float64Array(2 * n), right: new Float64Array(2 * n), shineA: new Float64Array(2 * n), shineB: new Float64Array(2 * n), shadeA: new Float64Array(2 * n), shadeB: new Float64Array(2 * n), frames: [] };
  2301. const half = r * k;
  2302. for (let i = 0; i < n; i++) {
  2303. const x = part.P3[3 * i];
  2304. const y = part.P3[3 * i + 1];
  2305. const z = part.P3[3 * i + 2];
  2306. const px = cam.ox + m[0] * x + m[1] * y + m[2] * z;
  2307. const py = cam.oy + m[3] * x + m[4] * y + m[5] * z;
  2308. const dx = m[0] * part.D3[3 * i] + m[1] * part.D3[3 * i + 1] + m[2] * part.D3[3 * i + 2];
  2309. const dy = m[3] * part.D3[3 * i] + m[4] * part.D3[3 * i + 1] + m[5] * part.D3[3 * i + 2];
  2310. const l = Math.hypot(dx, dy) || 1;
  2311. const nx = -dy / l;
  2312. const ny = dx / l;
  2313. out.flat[2 * i] = px;
  2314. out.flat[2 * i + 1] = py;
  2315. out.frames.push({ p: [px, py], nx, ny, half });
  2316. out.left[2 * i] = px + nx * half;
  2317. out.left[2 * i + 1] = py + ny * half;
  2318. out.right[2 * i] = px - nx * half;
  2319. out.right[2 * i + 1] = py - ny * half;
  2320. const toward = nx * T3_SHINE[0] + ny * T3_SHINE[1];
  2321. const shineAt = half * 0.44 * toward;
  2322. const shineHalf = half * 0.24;
  2323. out.shineA[2 * i] = px + nx * (shineAt + shineHalf);
  2324. out.shineA[2 * i + 1] = py + ny * (shineAt + shineHalf);
  2325. out.shineB[2 * i] = px + nx * (shineAt - shineHalf);
  2326. out.shineB[2 * i + 1] = py + ny * (shineAt - shineHalf);
  2327. const shadeAt = -half * 0.62 * toward;
  2328. const shadeHalf = half * 0.2;
  2329. out.shadeA[2 * i] = px + nx * (shadeAt + shadeHalf);
  2330. out.shadeA[2 * i + 1] = py + ny * (shadeAt + shadeHalf);
  2331. out.shadeB[2 * i] = px + nx * (shadeAt - shadeHalf);
  2332. out.shadeB[2 * i + 1] = py + ny * (shadeAt - shadeHalf);
  2333. }
  2334. return out;
  2335. }
  2336. const t3Pts = (buf, n) => {
  2337. const out = new Array(n);
  2338. for (let i = 0; i < n; i++) out[i] = [buf[2 * i], buf[2 * i + 1]];
  2339. return out;
  2340. };
  2341. function t3TubeCap(cam, centre, tangent, radius, inward) {
  2342. const V = cam.V;
  2343. const m = cam.m;
  2344. let n1 = [tangent[1] * V[2] - tangent[2] * V[1], tangent[2] * V[0] - tangent[0] * V[2], tangent[0] * V[1] - tangent[1] * V[0]];
  2345. if (Math.hypot(n1[0], n1[1], n1[2]) < 1e-6) {
  2346. const helper = Math.abs(tangent[2]) > 0.9 ? [1, 0, 0] : [0, 0, 1];
  2347. n1 = [helper[1] * tangent[2] - helper[2] * tangent[1], helper[2] * tangent[0] - helper[0] * tangent[2], helper[0] * tangent[1] - helper[1] * tangent[0]];
  2348. }
  2349. n1 = t3Unit(n1);
  2350. const n2 = t3Unit([tangent[1] * n1[2] - tangent[2] * n1[1], tangent[2] * n1[0] - tangent[0] * n1[2], tangent[0] * n1[1] - tangent[1] * n1[0]]);
  2351. const steps = 28;
  2352. const proj = (p) => [cam.ox + m[0] * p[0] + m[1] * p[1] + m[2] * p[2], cam.oy + m[3] * p[0] + m[4] * p[1] + m[5] * p[2]];
  2353. const ring = new Array(steps);
  2354. for (let index = 0; index < steps; index++) {
  2355. const angle = (index / steps) * T3_TAU;
  2356. const cs = radius * Math.cos(angle);
  2357. const sn = radius * Math.sin(angle);
  2358. ring[index] = proj([centre[0] + n1[0] * cs + n2[0] * sn, centre[1] + n1[1] * cs + n2[1] * sn, centre[2] + n1[2] * cs + n2[2] * sn]);
  2359. }
  2360. const C = proj(centre);
  2361. const probe = proj([centre[0] + n2[0], centre[1] + n2[1], centre[2] + n2[2]]);
  2362. const along = (probe[0] - C[0]) * inward[0] + (probe[1] - C[1]) * inward[1];
  2363. const from = along > 0 ? steps / 2 : 0;
  2364. const half = (start) => Array.from({ length: steps / 2 + 1 }, (_, index) => ring[(start + index) % steps]);
  2365. return { ring, arc: half(from), inner: half((from + steps / 2) % steps) };
  2366. }
  2367. function t3StripeEnd(half, centre, nx, ny, from, to) {
  2368. const offset = (p) => (p[0] - centre[0]) * nx + (p[1] - centre[1]) * ny;
  2369. const values = half.map(offset);
  2370. const lo = Math.min(from, to);
  2371. const hi = Math.max(from, to);
  2372. const points = [];
  2373. const cross = (k, level) => {
  2374. const t = (level - values[k]) / (values[k + 1] - values[k] || 1e-9);
  2375. return [half[k][0] + (half[k + 1][0] - half[k][0]) * t, half[k][1] + (half[k + 1][1] - half[k][1]) * t];
  2376. };
  2377. for (let k = 0; k < half.length; k++) {
  2378. if (values[k] >= lo && values[k] <= hi) points.push(half[k]);
  2379. if (k < half.length - 1) for (const level of [lo, hi]) if ((values[k] - level) * (values[k + 1] - level) < 0) points.push(cross(k, level));
  2380. }
  2381. return points
  2382. .map((p) => [p, offset(p)])
  2383. .sort((x, y) => (from > to ? y[1] - x[1] : x[1] - y[1]))
  2384. .map(([p]) => p);
  2385. }
  2386. function t3EmitTube(run, cam, f) {
  2387. const r = run.r;
  2388. const sides = t3Sides(run.body, cam, r);
  2389. const bands = run.stripe === run.body ? sides : t3Sides(run.stripe, cam, r);
  2390. const n = sides.n;
  2391. const left = t3Pts(sides.left, n);
  2392. const right = t3Pts(sides.right, n);
  2393. const loop = left.concat(right.slice().reverse());
  2394. let area = 0;
  2395. for (let i = 0; i < loop.length; i++) {
  2396. const a = loop[i];
  2397. const b = loop[(i + 1) % loop.length];
  2398. area += a[0] * b[1] - b[0] * a[1];
  2399. }
  2400. const sign = Math.sign(area);
  2401. let body = t3PathOf(loop, true);
  2402. let edges = t3PathOf(left, false) + t3PathOf(right, false);
  2403. const tips = [null, null];
  2404. const last = n - 1;
  2405. const quads = [];
  2406. for (let i = 0; i < last; i++) quads.push([left[i], left[i + 1], right[i + 1], right[i]]);
  2407. for (const side of [0, 1]) {
  2408. if (!run.capped[side]) continue;
  2409. const at = side ? last : 0;
  2410. const other = side ? last - 1 : 1;
  2411. const tangent = run.tips[side];
  2412. const outward = side ? tangent : [-tangent[0], -tangent[1], -tangent[2]];
  2413. const inward = [sides.flat[2 * other] - sides.flat[2 * at], sides.flat[2 * other + 1] - sides.flat[2 * at + 1]];
  2414. const centre = [run.body.P3[3 * at], run.body.P3[3 * at + 1], run.body.P3[3 * at + 2]];
  2415. const { ring, arc, inner } = t3TubeCap(cam, centre, tangent, r, inward);
  2416. let ringArea = 0;
  2417. for (let i = 0; i < ring.length; i++) {
  2418. const a = ring[i];
  2419. const b = ring[(i + 1) % ring.length];
  2420. ringArea += a[0] * b[1] - b[0] * a[1];
  2421. }
  2422. body += t3PathOf(Math.sign(ringArea) === sign ? ring : ring.slice().reverse(), true);
  2423. edges += t3PathOf(arc, false);
  2424. const V = cam.V;
  2425. const open = outward[0] * V[0] + outward[1] * V[1] + outward[2] * V[2] > 0;
  2426. if (open) edges += t3PathOf(inner, false);
  2427. tips[side] = { half: open ? inner : arc, frame: sides.frames[at] };
  2428. quads.push(ring);
  2429. }
  2430. f.d[run.role.body] = body;
  2431. f.d[run.role.edges] = edges;
  2432. if (run.wide) {
  2433. const toward = (frame) => frame.nx * T3_SHINE[0] + frame.ny * T3_SHINE[1];
  2434. const shineOffsets = (frame) => [frame.half * 0.44 * toward(frame) + frame.half * 0.24, frame.half * 0.44 * toward(frame) - frame.half * 0.24];
  2435. const shadeOffsets = (frame) => [-frame.half * 0.62 * toward(frame) + frame.half * 0.2, -frame.half * 0.62 * toward(frame) - frame.half * 0.2];
  2436. const bn = bands.n;
  2437. const band = (A, B, offsets) => {
  2438. const head = tips[1] ? t3StripeEnd(tips[1].half, tips[1].frame.p, tips[1].frame.nx, tips[1].frame.ny, offsets(tips[1].frame)[0], offsets(tips[1].frame)[1]) : [];
  2439. const tail = tips[0] ? t3StripeEnd(tips[0].half, tips[0].frame.p, tips[0].frame.nx, tips[0].frame.ny, offsets(tips[0].frame)[1], offsets(tips[0].frame)[0]) : [];
  2440. return t3PathOf([...t3Pts(A, bn), ...head, ...t3Pts(B, bn).reverse(), ...tail], true);
  2441. };
  2442. f.d[run.role.shine] = band(bands.shineA, bands.shineB, shineOffsets);
  2443. f.d[run.role.shade] = band(bands.shadeA, bands.shadeB, shadeOffsets);
  2444. }
  2445. if (run.rings) {
  2446. const lines = t3Lines;
  2447. lines.d.length = 0;
  2448. lines.alpha.length = 0;
  2449. lines.key.length = 0;
  2450. lines.key.length = 0;
  2451. const V = cam.V;
  2452. const m = cam.m;
  2453. const seg = new Float64Array(4);
  2454. const surface = (sample, out, index) => {
  2455. const T = sample.T;
  2456. let n1 = [T[1] * V[2] - T[2] * V[1], T[2] * V[0] - T[0] * V[2], T[0] * V[1] - T[1] * V[0]];
  2457. const l1 = Math.hypot(n1[0], n1[1], n1[2]);
  2458. if (l1 < 1e-6) return null;
  2459. n1 = [n1[0] / l1, n1[1] / l1, n1[2] / l1];
  2460. let n2 = t3Unit([T[1] * n1[2] - T[2] * n1[1], T[2] * n1[0] - T[0] * n1[2], T[0] * n1[1] - T[1] * n1[0]]);
  2461. if (n2[0] * V[0] + n2[1] * V[1] + n2[2] * V[2] < 0) n2 = [-n2[0], -n2[1], -n2[2]];
  2462. const cs = Math.cos(sample.theta);
  2463. const sn = Math.sin(sample.theta);
  2464. const normal = [n1[0] * cs + n2[0] * sn, n1[1] * cs + n2[1] * sn, n1[2] * cs + n2[2] * sn];
  2465. const p = [sample.c[0] + normal[0] * r, sample.c[1] + normal[1] * r, sample.c[2] + normal[2] * r];
  2466. out[index] = cam.ox + m[0] * p[0] + m[1] * p[1] + m[2] * p[2];
  2467. out[index + 1] = cam.oy + m[3] * p[0] + m[4] * p[1] + m[5] * p[2];
  2468. return normal[0] * V[0] + normal[1] * V[1] + normal[2] * V[2];
  2469. };
  2470. const fade = run.rings.fade;
  2471. let index = -1;
  2472. for (const [a, b] of run.rings.segments) {
  2473. index++;
  2474. const fa = surface(a, seg, 0);
  2475. const fb = surface(b, seg, 2);
  2476. if (fa === null || fb === null) continue;
  2477. const alpha = fade ? t3Step(fade[0], fade[1], (fa + fb) / 2) : 1;
  2478. if (alpha * T3_LEVELS < 0.5) continue;
  2479. lines.d.push(t3Path(seg, 2, false));
  2480. lines.alpha.push(alpha);
  2481. lines.key.push(index);
  2482. }
  2483. f.levels = t3Faded(f, run, "r", lines, lines.d.length);
  2484. }
  2485. const all = left.concat(right);
  2486. t3BoxOf(all, f.box);
  2487. for (const q of quads) for (const p of q) {
  2488. if (p[0] < f.box[0]) f.box[0] = p[0];
  2489. if (p[1] < f.box[1]) f.box[1] = p[1];
  2490. if (p[0] > f.box[2]) f.box[2] = p[0];
  2491. if (p[1] > f.box[3]) f.box[3] = p[1];
  2492. }
  2493. const list = f.quadList && f.quadList.length === quads.length ? f.quadList : (f.quadList = quads.map(() => [new Float64Array(0), 0]));
  2494. for (let qi = 0; qi < quads.length; qi++) {
  2495. const q = quads[qi];
  2496. let entry = list[qi];
  2497. if (entry[0].length < 2 * q.length) entry[0] = new Float64Array(2 * q.length);
  2498. const buf = entry[0];
  2499. for (let i = 0; i < q.length; i++) {
  2500. buf[2 * i] = q[i][0];
  2501. buf[2 * i + 1] = q[i][1];
  2502. }
  2503. entry[1] = q.length;
  2504. }
  2505. f.quadN = quads.length;
  2506. f.quads = f.quadList;
  2507. f.hullN = 0;
  2508. }
  2509. function t3Emit(run, cam, out) {
  2510. const f = out ?? t3Frame(run);
  2511. if (t3Arena.on) {
  2512. t3Arena.f = f;
  2513. f.arenaN = 0;
  2514. }
  2515. if (run.kind === "prism") t3EmitPrism(run, cam, f);
  2516. else if (run.kind === "round") t3EmitRound(run, cam, f);
  2517. else if (run.kind === "ball") t3EmitBall(run, cam, f);
  2518. else if (run.kind === "lathe") t3EmitLathe(run, cam, f);
  2519. else if (run.kind === "tube") {
  2520. t3EmitTube(run, cam, f);
  2521. return f;
  2522. } else if (run.kind === "fixed") {
  2523. t3EmitFixed(run, cam, f);
  2524. return f;
  2525. } else if (run.kind === "item") {
  2526. f.box[0] = run.itemBox[0];
  2527. f.box[1] = run.itemBox[1];
  2528. f.box[2] = run.itemBox[2];
  2529. f.box[3] = run.itemBox[3];
  2530. const count = run.itemHull.length / 2;
  2531. const hull = t3Grow(f, "hull", 2 * Math.max(1, count), Float64Array);
  2532. for (let i = 0; i < 2 * count; i++) hull[i] = run.itemHull[i];
  2533. f.hullN = count;
  2534. return f;
  2535. }
  2536. t3EmitPlanes(run, cam, f);
  2537. t3EmitDots(run, cam, f);
  2538. return f;
  2539. }
  2540. function t3Overlap(a, b, pad) {
  2541. return a[0] < b[2] - pad && b[0] < a[2] - pad && a[1] < b[3] - pad && b[1] < a[3] - pad;
  2542. }
  2543. function t3Apart(A, an, B, bn, pad) {
  2544. for (let pass = 0; pass < 2; pass++) {
  2545. const P = pass ? B : A;
  2546. const pn = pass ? bn : an;
  2547. for (let i = 0; i < pn; i++) {
  2548. const j = (i + 1) % pn;
  2549. const nx = P[2 * j + 1] - P[2 * i + 1];
  2550. const ny = P[2 * i] - P[2 * j];
  2551. const l = Math.hypot(nx, ny);
  2552. if (l < 1e-9) continue;
  2553. let a0 = Infinity;
  2554. let a1 = -Infinity;
  2555. for (let q = 0; q < an; q++) {
  2556. const v = (A[2 * q] * nx + A[2 * q + 1] * ny) / l;
  2557. if (v < a0) a0 = v;
  2558. if (v > a1) a1 = v;
  2559. }
  2560. let b0 = Infinity;
  2561. let b1 = -Infinity;
  2562. for (let q = 0; q < bn; q++) {
  2563. const v = (B[2 * q] * nx + B[2 * q + 1] * ny) / l;
  2564. if (v < b0) b0 = v;
  2565. if (v > b1) b1 = v;
  2566. }
  2567. if (a1 < b0 + pad || b1 < a0 + pad) return true;
  2568. }
  2569. }
  2570. return false;
  2571. }
  2572. function t3Disjoint(fa, fb, pad) {
  2573. const qa = fa.quadN ? fa.quads : null;
  2574. const qb = fb.quadN ? fb.quads : null;
  2575. if (!qa && !qb) return t3Apart(fa.hull, fa.hullN, fb.hull, fb.hullN, pad);
  2576. const listA = qa ? fa.quadList : [[fa.hull, fa.hullN]];
  2577. const listB = qb ? fb.quadList : [[fb.hull, fb.hullN]];
  2578. for (const [A, an] of listA) for (const [B, bn] of listB) if (!t3Apart(A, an, B, bn, pad)) return false;
  2579. return true;
  2580. }
  2581. function t3Support(cloud, R, t, dir, world) {
  2582. let best = -Infinity;
  2583. let at = 0;
  2584. const n = cloud.length / 3;
  2585. const dx = R[0] * dir[0] + R[3] * dir[1] + R[6] * dir[2];
  2586. const dy = R[1] * dir[0] + R[4] * dir[1] + R[7] * dir[2];
  2587. const dz = R[2] * dir[0] + R[5] * dir[1] + R[8] * dir[2];
  2588. for (let i = 0; i < n; i++) {
  2589. const v = cloud[3 * i] * dx + cloud[3 * i + 1] * dy + cloud[3 * i + 2] * dz;
  2590. if (v > best) {
  2591. best = v;
  2592. at = i;
  2593. }
  2594. }
  2595. const x = cloud[3 * at];
  2596. const y = cloud[3 * at + 1];
  2597. const z = cloud[3 * at + 2];
  2598. world[0] = R[0] * x + R[1] * y + R[2] * z + t[0];
  2599. world[1] = R[3] * x + R[4] * y + R[5] * z + t[1];
  2600. world[2] = R[6] * x + R[7] * y + R[8] * z + t[2];
  2601. return best + dir[0] * t[0] + dir[1] * t[1] + dir[2] * t[2];
  2602. }
  2603. function t3Gjk(cloudA, camA, cloudB, camB, warm, rounds = 8, hints = null) {
  2604. let w = warm && (warm[0] || warm[1] || warm[2]) ? [warm[0], warm[1], warm[2]] : null;
  2605. const a = [0, 0, 0];
  2606. const b = [0, 0, 0];
  2607. if (!w) {
  2608. t3Support(cloudA, camA.R, camA.t, [1, 0, 0], a);
  2609. t3Support(cloudB, camB.R, camB.t, [-1, 0, 0], b);
  2610. w = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
  2611. }
  2612. let margin = -Infinity;
  2613. let best = w;
  2614. const step = (limit) => {
  2615. for (let it = 0; it < limit; it++) {
  2616. const l = Math.hypot(w[0], w[1], w[2]);
  2617. if (l < 1e-12) break;
  2618. const n = [w[0] / l, w[1] / l, w[2] / l];
  2619. const hiA = t3Support(cloudA, camA.R, camA.t, n, a);
  2620. const loB = -t3Support(cloudB, camB.R, camB.t, [-n[0], -n[1], -n[2]], b);
  2621. const value = loB - hiA;
  2622. if (value > margin) {
  2623. margin = value;
  2624. best = n;
  2625. }
  2626. const s = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
  2627. const ds = [w[0] - s[0], w[1] - s[1], w[2] - s[2]];
  2628. const dd = ds[0] * ds[0] + ds[1] * ds[1] + ds[2] * ds[2];
  2629. if (dd < 1e-14) break;
  2630. const tt = Math.max(0, Math.min(1, (w[0] * ds[0] + w[1] * ds[1] + w[2] * ds[2]) / dd));
  2631. w = [w[0] - ds[0] * tt, w[1] - ds[1] * tt, w[2] - ds[2] * tt];
  2632. }
  2633. };
  2634. step(rounds);
  2635. if (margin < 0) step(24);
  2636. if (margin < 0.05 && hints) {
  2637. if (hints.centroids) {
  2638. const [ca, cb] = hints.centroids;
  2639. const wa = [camA.R[0] * ca[0] + camA.R[1] * ca[1] + camA.R[2] * ca[2] + camA.t[0], camA.R[3] * ca[0] + camA.R[4] * ca[1] + camA.R[5] * ca[2] + camA.t[1], camA.R[6] * ca[0] + camA.R[7] * ca[1] + camA.R[8] * ca[2] + camA.t[2]];
  2640. const wb = [camB.R[0] * cb[0] + camB.R[1] * cb[1] + camB.R[2] * cb[2] + camB.t[0], camB.R[3] * cb[0] + camB.R[4] * cb[1] + camB.R[5] * cb[2] + camB.t[1], camB.R[6] * cb[0] + camB.R[7] * cb[1] + camB.R[8] * cb[2] + camB.t[2]];
  2641. const n = t3Unit([wb[0] - wa[0], wb[1] - wa[1], wb[2] - wa[2]]);
  2642. const hiA = t3Support(cloudA, camA.R, camA.t, n, a);
  2643. const loB = -t3Support(cloudB, camB.R, camB.t, [-n[0], -n[1], -n[2]], b);
  2644. if (loB - hiA > margin) {
  2645. margin = loB - hiA;
  2646. best = n;
  2647. }
  2648. }
  2649. for (const [axis, cam] of hints) {
  2650. const R = cam.R;
  2651. const w0 = [R[0] * axis[0] + R[1] * axis[1] + R[2] * axis[2], R[3] * axis[0] + R[4] * axis[1] + R[5] * axis[2], R[6] * axis[0] + R[7] * axis[1] + R[8] * axis[2]];
  2652. for (const sign of [1, -1]) {
  2653. const n = [w0[0] * sign, w0[1] * sign, w0[2] * sign];
  2654. const hiA = t3Support(cloudA, camA.R, camA.t, n, a);
  2655. const loB = -t3Support(cloudB, camB.R, camB.t, [-n[0], -n[1], -n[2]], b);
  2656. if (loB - hiA > margin) {
  2657. margin = loB - hiA;
  2658. best = n;
  2659. }
  2660. }
  2661. }
  2662. }
  2663. const l = Math.hypot(best[0], best[1], best[2]) || 1;
  2664. return { n: [best[0] / l, best[1] / l, best[2] / l], margin };
  2665. }
  2666. function t3Order(layer, frames, cams, previous, stats, scene) {
  2667. const parts = layer.parts;
  2668. const count = parts.length;
  2669. const local = layer.local;
  2670. const rank = layer._rank ?? (layer._rank = new Int32Array(count));
  2671. if (previous) for (let at = 0; at < count; at++) rank[local.get(previous[at])] = at;
  2672. else for (let at = 0; at < count; at++) rank[local.get(layer.rest[at])] = at;
  2673. let groupEdges = 0;
  2674. if (layer.groupPairs) for (const gp of layer.groupPairs) groupEdges += gp.a.length * gp.b.length;
  2675. const maxEdges = layer.planar.length / 5 + (layer.framed ? layer.framed.length / 6 : 0) + groupEdges + layer.dynamic.length / 2 + (layer.free ? layer.free.length * count : 0) + 1;
  2676. const head = layer._head ?? (layer._head = new Int32Array(count));
  2677. const next = layer._next && layer._next.length >= maxEdges ? layer._next : (layer._next = new Int32Array(maxEdges));
  2678. const to = layer._to && layer._to.length >= maxEdges ? layer._to : (layer._to = new Int32Array(maxEdges));
  2679. const live = layer._live && layer._live.length >= maxEdges ? layer._live : (layer._live = new Uint8Array(maxEdges));
  2680. const indeg = layer._indeg ?? (layer._indeg = new Int32Array(count));
  2681. head.fill(-1);
  2682. indeg.fill(0);
  2683. let edges = 0;
  2684. const addEdge = (back, front) => {
  2685. to[edges] = front;
  2686. next[edges] = head[back];
  2687. live[edges] = 1;
  2688. head[back] = edges;
  2689. indeg[front]++;
  2690. edges++;
  2691. };
  2692. const runs = scene ? scene.runs : null;
  2693. const groupOf = (global) => (runs ? runs[global].group : -1);
  2694. const planar = layer.planar;
  2695. for (let p = 0; p < planar.length; p += 5) {
  2696. const i = planar[p];
  2697. const j = planar[p + 1];
  2698. const fi = frames[i];
  2699. const fj = frames[j];
  2700. if (!t3Overlap(fi.box, fj.box, -0.05)) continue;
  2701. const g = groupOf(i);
  2702. const V = g >= 0 ? cams[g].V : cams.world.V;
  2703. const s = planar[p + 2] * V[0] + planar[p + 3] * V[1] + planar[p + 4] * V[2];
  2704. if (s < 1e-7 && s > -1e-7) continue;
  2705. const li = local.get(i);
  2706. const lj = local.get(j);
  2707. if (s > 0) addEdge(li, lj);
  2708. else addEdge(lj, li);
  2709. }
  2710. const framed = layer.framed;
  2711. if (framed)
  2712. for (let p = 0; p < framed.length; p += 6) {
  2713. const i = framed[p];
  2714. const j = framed[p + 1];
  2715. if (!t3Overlap(frames[i].box, frames[j].box, -0.05)) continue;
  2716. const g = framed[p + 2];
  2717. const V = g >= 0 ? cams[g].V : cams.world.V;
  2718. const s = framed[p + 3] * V[0] + framed[p + 4] * V[1] + framed[p + 5] * V[2];
  2719. if (s < 1e-7 && s > -1e-7) continue;
  2720. const li = local.get(i);
  2721. const lj = local.get(j);
  2722. if (s > 0) addEdge(li, lj);
  2723. else addEdge(lj, li);
  2724. }
  2725. if (layer.groupPairs)
  2726. for (const gp of layer.groupPairs) {
  2727. const union = (list, box) => {
  2728. box[0] = Infinity;
  2729. box[1] = Infinity;
  2730. box[2] = -Infinity;
  2731. box[3] = -Infinity;
  2732. for (let q = 0; q < list.length; q++) {
  2733. const b = frames[list[q]].box;
  2734. if (b[0] < box[0]) box[0] = b[0];
  2735. if (b[1] < box[1]) box[1] = b[1];
  2736. if (b[2] > box[2]) box[2] = b[2];
  2737. if (b[3] > box[3]) box[3] = b[3];
  2738. }
  2739. };
  2740. union(gp.a, gp.boxA);
  2741. union(gp.b, gp.boxB);
  2742. if (!t3Overlap(gp.boxA, gp.boxB, -0.05)) continue;
  2743. const V = gp.frame >= 0 ? cams[gp.frame].V : cams.world.V;
  2744. const s = gp.n[0] * V[0] + gp.n[1] * V[1] + gp.n[2] * V[2];
  2745. if (s < 1e-7 && s > -1e-7) continue;
  2746. for (let x = 0; x < gp.a.length; x++) {
  2747. const i = gp.a[x];
  2748. const bi = frames[i].box;
  2749. if (!t3Overlap(bi, gp.boxB, -0.05)) continue;
  2750. for (let y = 0; y < gp.b.length; y++) {
  2751. const j = gp.b[y];
  2752. if (!t3Overlap(bi, frames[j].box, -0.05)) continue;
  2753. if (s > 0) addEdge(local.get(i), local.get(j));
  2754. else addEdge(local.get(j), local.get(i));
  2755. }
  2756. }
  2757. }
  2758. const dynamic = layer.dynamic;
  2759. let unseparated = 0;
  2760. let solved = 0;
  2761. const rel = layer.rel ?? (layer.rel = new Map());
  2762. const cross = (i, j) => {
  2763. const ri = runs[i];
  2764. const rj = runs[j];
  2765. const ci = ri.group >= 0 ? cams[ri.group] : cams.world;
  2766. const cj = rj.group >= 0 ? cams[rj.group] : cams.world;
  2767. const A = ci.R;
  2768. const B = cj.R;
  2769. const dx = cj.t[0] - ci.t[0];
  2770. const dy = cj.t[1] - ci.t[1];
  2771. const dz = cj.t[2] - ci.t[2];
  2772. const key = i * 65536 + j;
  2773. let memo = rel.get(key);
  2774. if (!memo) {
  2775. memo = { pose: new Float64Array(12), n: [0, 0, 0], margin: -Infinity, fresh: false, vi: -1, vj: -1 };
  2776. rel.set(key, memo);
  2777. }
  2778. const pose = memo.pose;
  2779. const vi = ri.version ?? 0;
  2780. const vj = rj.version ?? 0;
  2781. let same = memo.fresh && memo.vi === vi && memo.vj === vj;
  2782. memo.vi = vi;
  2783. memo.vj = vj;
  2784. let at = 0;
  2785. for (let c = 0; c < 3; c++)
  2786. for (let r = 0; r < 3; r++) {
  2787. const v = A[c] * B[r] + A[3 + c] * B[3 + r] + A[6 + c] * B[6 + r];
  2788. if (same && Math.abs(pose[at] - v) > 1e-12) same = false;
  2789. pose[at++] = v;
  2790. }
  2791. for (let c = 0; c < 3; c++) {
  2792. const v = A[c] * dx + A[3 + c] * dy + A[6 + c] * dz;
  2793. if (same && Math.abs(pose[at] - v) > 1e-9) same = false;
  2794. pose[at++] = v;
  2795. }
  2796. let nx;
  2797. let ny;
  2798. let nz;
  2799. if (same) {
  2800. const n = memo.n;
  2801. nx = A[0] * n[0] + A[1] * n[1] + A[2] * n[2];
  2802. ny = A[3] * n[0] + A[4] * n[1] + A[5] * n[2];
  2803. nz = A[6] * n[0] + A[7] * n[1] + A[8] * n[2];
  2804. } else {
  2805. const n = memo.n;
  2806. const warm = memo.fresh ? [A[0] * n[0] + A[1] * n[1] + A[2] * n[2], A[3] * n[0] + A[4] * n[1] + A[5] * n[2], A[6] * n[0] + A[7] * n[1] + A[8] * n[2]] : null;
  2807. const hints = [...ri.axes.map((axis) => [axis, ci]), ...rj.axes.map((axis) => [axis, cj]), [[0, 0, 1], cams.world]];
  2808. hints.centroids = [ri.centroid, rj.centroid];
  2809. const hit = t3Gjk(ri.cloud, ci, rj.cloud, cj, warm, 8, hints);
  2810. solved++;
  2811. nx = hit.n[0];
  2812. ny = hit.n[1];
  2813. nz = hit.n[2];
  2814. n[0] = A[0] * nx + A[3] * ny + A[6] * nz;
  2815. n[1] = A[1] * nx + A[4] * ny + A[7] * nz;
  2816. n[2] = A[2] * nx + A[5] * ny + A[8] * nz;
  2817. memo.margin = hit.margin;
  2818. memo.fresh = true;
  2819. }
  2820. if (memo.margin < -0.08) unseparated++;
  2821. const V = cams.world.V;
  2822. return nx * V[0] + ny * V[1] + nz * V[2];
  2823. };
  2824. for (let p = 0; p < dynamic.length; p += 2) {
  2825. const i = dynamic[p];
  2826. const j = dynamic[p + 1];
  2827. if (!t3Overlap(frames[i].box, frames[j].box, -0.05)) continue;
  2828. const s = cross(i, j);
  2829. if (s < 1e-7 && s > -1e-7) continue;
  2830. const li = local.get(i);
  2831. const lj = local.get(j);
  2832. if (s > 0) addEdge(li, lj);
  2833. else addEdge(lj, li);
  2834. }
  2835. const loose = layer.free;
  2836. if (loose && loose.length) {
  2837. const isLoose = layer.looseAt;
  2838. for (let a = 0; a < loose.length; a++) {
  2839. const i = loose[a];
  2840. const gi = runs[i].group;
  2841. const bi = frames[i].box;
  2842. for (let b = 0; b < count; b++) {
  2843. const j = parts[b];
  2844. if (j === i || runs[j].group === gi) continue;
  2845. if (isLoose[b] && j < i) continue;
  2846. if (!t3Overlap(bi, frames[j].box, -0.05)) continue;
  2847. const s = cross(i, j);
  2848. if (s < 1e-7 && s > -1e-7) continue;
  2849. const li = local.get(i);
  2850. if (s > 0) addEdge(li, b);
  2851. else addEdge(b, li);
  2852. }
  2853. }
  2854. }
  2855. const heap = layer._heap ?? (layer._heap = new Int32Array(count));
  2856. const done = layer._done ?? (layer._done = new Uint8Array(count));
  2857. done.fill(0);
  2858. let size = 0;
  2859. const less = (a, b) => rank[a] < rank[b];
  2860. const push = (v) => {
  2861. let i = size++;
  2862. heap[i] = v;
  2863. while (i > 0) {
  2864. const p = (i - 1) >> 1;
  2865. if (!less(heap[i], heap[p])) break;
  2866. const tmp = heap[i];
  2867. heap[i] = heap[p];
  2868. heap[p] = tmp;
  2869. i = p;
  2870. }
  2871. };
  2872. const pop = () => {
  2873. const top = heap[0];
  2874. heap[0] = heap[--size];
  2875. let i = 0;
  2876. for (;;) {
  2877. const l = 2 * i + 1;
  2878. const r = l + 1;
  2879. let s = i;
  2880. if (l < size && less(heap[l], heap[s])) s = l;
  2881. if (r < size && less(heap[r], heap[s])) s = r;
  2882. if (s === i) break;
  2883. const tmp = heap[i];
  2884. heap[i] = heap[s];
  2885. heap[s] = tmp;
  2886. i = s;
  2887. }
  2888. return top;
  2889. };
  2890. for (let v = 0; v < count; v++) if (indeg[v] === 0) push(v);
  2891. const out = new Int32Array(count);
  2892. let placed = 0;
  2893. let forced = 0;
  2894. let refined = 0;
  2895. let tested = false;
  2896. const mark = layer._mark && layer._mark.length >= count ? layer._mark : (layer._mark = new Uint8Array(count));
  2897. const via = layer._via && layer._via.length >= count ? layer._via : (layer._via = new Int32Array(count));
  2898. const iter = layer._iter && layer._iter.length >= count ? layer._iter : (layer._iter = new Int32Array(count));
  2899. const stack = layer._stack && layer._stack.length >= count ? layer._stack : (layer._stack = new Int32Array(count));
  2900. const checked = layer._checked && layer._checked.length >= maxEdges ? layer._checked : (layer._checked = new Uint8Array(maxEdges));
  2901. checked.fill(0, 0, edges);
  2902. const breakCycle = () => {
  2903. mark.fill(0, 0, count);
  2904. for (let root = 0; root < count; root++) {
  2905. if (done[root] || mark[root]) continue;
  2906. let top = 0;
  2907. stack[top++] = root;
  2908. mark[root] = 1;
  2909. iter[root] = head[root];
  2910. while (top) {
  2911. const v = stack[top - 1];
  2912. let e = iter[v];
  2913. while (e >= 0 && (!live[e] || done[to[e]] || mark[to[e]] === 2)) e = next[e];
  2914. if (e < 0) {
  2915. mark[v] = 2;
  2916. top--;
  2917. continue;
  2918. }
  2919. iter[v] = next[e];
  2920. const w = to[e];
  2921. if (mark[w] === 1) {
  2922. let dropped = false;
  2923. let x = v;
  2924. let edge = e;
  2925. for (;;) {
  2926. if (!checked[edge]) {
  2927. checked[edge] = 1;
  2928. const a = x;
  2929. const b = to[edge];
  2930. if (t3Disjoint(frames[parts[a]], frames[parts[b]], 0.1)) {
  2931. live[edge] = 0;
  2932. indeg[b]--;
  2933. refined++;
  2934. dropped = true;
  2935. if (indeg[b] === 0) push(b);
  2936. }
  2937. }
  2938. if (x === w) break;
  2939. edge = via[x];
  2940. let from = -1;
  2941. for (let s = 0; s < top; s++) if (stack[s] === x) from = s > 0 ? stack[s - 1] : -1;
  2942. if (from < 0) break;
  2943. x = from;
  2944. }
  2945. return dropped ? 1 : 0;
  2946. }
  2947. via[w] = e;
  2948. mark[w] = 1;
  2949. iter[w] = head[w];
  2950. stack[top++] = w;
  2951. }
  2952. }
  2953. return -1;
  2954. };
  2955. while (placed < count) {
  2956. if (size === 0) {
  2957. let broken = 0;
  2958. for (let tries = 0; tries < 64 && size === 0; tries++) {
  2959. const result = breakCycle();
  2960. if (result <= 0) break;
  2961. broken++;
  2962. }
  2963. if (size) continue;
  2964. void broken;
  2965. void tested;
  2966. let pick = -1;
  2967. for (let v = 0; v < count; v++) if (!done[v] && (pick < 0 || indeg[v] < indeg[pick] || (indeg[v] === indeg[pick] && rank[v] < rank[pick]))) pick = v;
  2968. forced++;
  2969. indeg[pick] = 0;
  2970. push(pick);
  2971. }
  2972. const v = pop();
  2973. if (done[v]) continue;
  2974. done[v] = 1;
  2975. out[placed++] = parts[v];
  2976. for (let e = head[v]; e >= 0; e = next[e]) {
  2977. if (!live[e]) continue;
  2978. const w = to[e];
  2979. if (done[w]) continue;
  2980. if (--indeg[w] === 0) push(w);
  2981. }
  2982. }
  2983. if (stats) {
  2984. stats.edges = (stats.edges ?? 0) + edges;
  2985. stats.forced = (stats.forced ?? 0) + forced;
  2986. stats.refined = (stats.refined ?? 0) + refined;
  2987. stats.unseparated = (stats.unseparated ?? 0) + unseparated;
  2988. stats.solved = (stats.solved ?? 0) + solved;
  2989. }
  2990. return out;
  2991. }
  2992. function t3Keep(values) {
  2993. const n = values.length;
  2994. const tails = [];
  2995. const tailAt = [];
  2996. const back = new Int32Array(n).fill(-1);
  2997. for (let i = 0; i < n; i++) {
  2998. let lo = 0;
  2999. let hi = tails.length;
  3000. while (lo < hi) {
  3001. const mid = (lo + hi) >> 1;
  3002. if (tails[mid] < values[i]) lo = mid + 1;
  3003. else hi = mid;
  3004. }
  3005. tails[lo] = values[i];
  3006. tailAt[lo] = i;
  3007. back[i] = lo > 0 ? tailAt[lo - 1] : -1;
  3008. }
  3009. const keep = new Uint8Array(n);
  3010. let k = tails.length ? tailAt[tails.length - 1] : -1;
  3011. while (k >= 0) {
  3012. keep[k] = 1;
  3013. k = back[k];
  3014. }
  3015. return keep;
  3016. }
  3017. function t3Cams(scene, values) {
  3018. const poses = t3Poses(scene.groups, values);
  3019. const cams = poses.map((pose) => t3Camera(scene.P, pose));
  3020. cams.world = t3Camera(scene.P, null);
  3021. cams.poses = poses;
  3022. return cams;
  3023. }
  3024. function t3Mount(stage, data, { onHold = null, onFrame = null, follow = null, painter = "svg", numeric = painter === "canvas", canvasLayers = null, shift = false } = {}) {
  3025. const canvasSet = painter === "canvas" ? new Set(canvasLayers ?? data.layers.map((layer) => layer.name)) : new Set();
  3026. const dom = canvasSet.size < data.layers.length;
  3027. const domLayer = data.layers.map((layer) => !canvasSet.has(layer.name));
  3028. const layerEls = new Map([...stage.querySelectorAll("svg[data-live]")].map((svg) => [svg.dataset.live, svg]));
  3029. const first = layerEls.values().next().value;
  3030. const viewWidth = first && first.viewBox && first.viewBox.baseVal ? first.viewBox.baseVal.width : 0;
  3031. const unitOf = () => {
  3032. const width = first ? first.getBoundingClientRect().width : 0;
  3033. return viewWidth && width ? Math.round((width / viewWidth) * 100) / 100 : 1;
  3034. };
  3035. let unit = unitOf();
  3036. let scene = t3Prepare(data, { unit });
  3037. const runs = () => scene.runs;
  3038. const count = data.parts.length;
  3039. const nodes = new Array(count);
  3040. const bound = new Array(count);
  3041. const cache = new Array(count);
  3042. const containers = new Map();
  3043. for (const [name, svg] of layerEls) containers.set(name, svg.querySelector(".iso-parts") ?? svg);
  3044. for (const run of scene.runs) {
  3045. const layer = data.layers[run.layer];
  3046. const container = containers.get(layer.name);
  3047. const node = container ? container.querySelector(`[data-p="${run.index}"]`) : null;
  3048. nodes[run.index] = node;
  3049. const map = {};
  3050. if (node) {
  3051. map.move = node;
  3052. node.querySelectorAll("[data-r]").forEach((el) => (map[el.getAttribute("data-r")] = el));
  3053. }
  3054. bound[run.index] = run.roles.map((role) => map[role.name] ?? null);
  3055. cache[run.index] = run.roles.map(() => ({ d: null, q: null, b: null, f: null, w: null, t: null, o: null, cx: null, cy: null }));
  3056. }
  3057. const frames = scene.runs.map((run) => t3Frame(run));
  3058. const values = Object.fromEntries(data.groups.map((g) => [g.name, data.values ? data.values[g.name] ?? 0 : 0]));
  3059. let lastPoses = null;
  3060. let cams = null;
  3061. const orders = scene.layers.map((layer) => Int32Array.from(layer.rest));
  3062. const changes = [];
  3063. const stats = { ms: 0, writes: 0, moved: 0, forced: 0, refined: 0, unseparated: 0, emitted: 0 };
  3064. let writes = 0;
  3065. const write = (index) => {
  3066. const run = scene.runs[index];
  3067. const f = frames[index];
  3068. const els = bound[index];
  3069. const memo = cache[index];
  3070. for (let r = 0; r < run.roles.length; r++) {
  3071. const el = els[r];
  3072. if (!el) continue;
  3073. const role = run.roles[r];
  3074. const c = memo[r];
  3075. const type = role.type;
  3076. if (type === "path" || type === "face" || type === "slot") {
  3077. const d = f.d[r];
  3078. if (c.d !== d) {
  3079. el.setAttribute("d", d);
  3080. c.d = d;
  3081. writes++;
  3082. }
  3083. if (type === "face") {
  3084. const q = f.q[r];
  3085. if (c.q !== q) {
  3086. const band = Math.min(3, Math.floor(q / T3_Q));
  3087. const mix = (q - T3_Q * band) / T3_Q;
  3088. if (c.b !== band) {
  3089. el.setAttribute("data-b", String(band));
  3090. c.b = band;
  3091. writes++;
  3092. }
  3093. if (c.f !== mix) {
  3094. if (mix) el.style.setProperty("--f", String(mix));
  3095. else el.style.removeProperty("--f");
  3096. c.f = mix;
  3097. writes++;
  3098. }
  3099. c.q = q;
  3100. }
  3101. const w = f.w[r];
  3102. if (c.w !== w) {
  3103. if (w < 0) el.style.removeProperty("stroke-width");
  3104. else el.style.strokeWidth = String(w);
  3105. c.w = w;
  3106. writes++;
  3107. }
  3108. } else if (type === "slot") {
  3109. const o = f.o[r];
  3110. if (c.o !== o) {
  3111. el.setAttribute("opacity", String(Math.round(o * 1000) / 1000));
  3112. c.o = o;
  3113. writes++;
  3114. }
  3115. }
  3116. } else if (type === "xform" || type === "self" || type === "plane") {
  3117. const t = f.t[r];
  3118. if (c.t !== t) {
  3119. if (t) el.setAttribute("transform", t);
  3120. else el.removeAttribute("transform");
  3121. c.t = t;
  3122. writes++;
  3123. }
  3124. if (type === "plane") {
  3125. const o = f.o[r];
  3126. if (c.o !== o) {
  3127. el.setAttribute("opacity", String(o));
  3128. c.o = o;
  3129. writes++;
  3130. }
  3131. }
  3132. } else if (type === "dot") {
  3133. const x = Math.round(f.cx[r] * 100) / 100;
  3134. const y = Math.round(f.cy[r] * 100) / 100;
  3135. const o = f.o[r];
  3136. if (c.cx !== x) {
  3137. el.setAttribute("cx", String(x));
  3138. c.cx = x;
  3139. writes++;
  3140. }
  3141. if (c.cy !== y) {
  3142. el.setAttribute("cy", String(y));
  3143. c.cy = y;
  3144. writes++;
  3145. }
  3146. if (c.o !== o) {
  3147. el.setAttribute("fill-opacity", String(o));
  3148. c.o = o;
  3149. writes++;
  3150. }
  3151. }
  3152. }
  3153. };
  3154. const samePose = (a, b) => {
  3155. if (!a || !b) return false;
  3156. for (let i = 0; i < 9; i++) if (a.R[i] !== b.R[i]) return false;
  3157. return a.t[0] === b.t[0] && a.t[1] === b.t[1] && a.t[2] === b.t[2];
  3158. };
  3159. let lastUnit = unit;
  3160. let moved = 0;
  3161. let snapshotNext = false;
  3162. const emittedList = [];
  3163. const shiftOn = Boolean(shift);
  3164. const emitAt = shiftOn ? new Array(count) : null;
  3165. const shiftable = (run) => run.kind === "prism" || run.kind === "round" || run.kind === "ball" || run.kind === "lathe";
  3166. const sameView = (base, cam) => {
  3167. const m = cam.m;
  3168. const b = base.m;
  3169. for (let i = 0; i < 6; i++) if (m[i] !== b[i]) return false;
  3170. return true;
  3171. };
  3172. const keepEmit = (run, cam, f) => {
  3173. let base = emitAt[run.index];
  3174. if (!base) base = emitAt[run.index] = { m: new Float64Array(6), ox: 0, oy: 0, box: new Float64Array(4), hull: new Float64Array(0), hullN: 0 };
  3175. base.m.set(cam.m);
  3176. base.ox = cam.ox;
  3177. base.oy = cam.oy;
  3178. base.box.set(f.box);
  3179. if (base.hull.length < 2 * f.hullN) base.hull = new Float64Array(2 * f.hullN);
  3180. for (let i = 0; i < 2 * f.hullN; i++) base.hull[i] = f.hull[i];
  3181. base.hullN = f.hullN;
  3182. };
  3183. const shiftFrame = (f, base, dx, dy) => {
  3184. f.box[0] = base.box[0] + dx;
  3185. f.box[1] = base.box[1] + dy;
  3186. f.box[2] = base.box[2] + dx;
  3187. f.box[3] = base.box[3] + dy;
  3188. const hull = t3Grow(f, "hull", 2 * base.hullN, Float64Array);
  3189. for (let i = 0; i < base.hullN; i++) {
  3190. hull[2 * i] = base.hull[2 * i] + dx;
  3191. hull[2 * i + 1] = base.hull[2 * i + 1] + dy;
  3192. }
  3193. f.hullN = base.hullN;
  3194. f.sx = dx;
  3195. f.sy = dy;
  3196. };
  3197. const writeShift = (index, dx, dy) => {
  3198. const node = nodes[index];
  3199. if (!node) return;
  3200. const text = dx || dy ? `translate(${Math.round(dx * 100) / 100} ${Math.round(dy * 100) / 100})` : "";
  3201. if (node.__shift === text) return;
  3202. if (text) node.setAttribute("transform", text);
  3203. else node.removeAttribute("transform");
  3204. node.__shift = text;
  3205. writes++;
  3206. };
  3207. const render = () => {
  3208. const t0 = performance.now();
  3209. writes = 0;
  3210. moved = 0;
  3211. stats.orderMs = 0;
  3212. t3Arena.on = false;
  3213. const snapshotting = snapshotNext;
  3214. snapshotNext = false;
  3215. cams = t3Cams(scene, values);
  3216. t3State.detail = detail;
  3217. const poses = cams.poses;
  3218. const fresh = lastUnit !== unit || !lastPoses;
  3219. let emitted = 0;
  3220. emittedList.length = 0;
  3221. let shifted = 0;
  3222. for (const run of scene.runs) {
  3223. const g = run.group;
  3224. const changed = fresh || (g >= 0 ? !samePose(poses[g], lastPoses[g]) : false);
  3225. if (!changed) continue;
  3226. const domRun = snapshotting || domLayer[run.layer];
  3227. const cam = g >= 0 ? cams[g] : cams.world;
  3228. const f = frames[run.index];
  3229. const base = shiftOn && !fresh && !snapshotting ? emitAt[run.index] : null;
  3230. if (base && sameView(base, cam)) {
  3231. const dx = cam.ox - base.ox;
  3232. const dy = cam.oy - base.oy;
  3233. shiftFrame(f, base, dx, dy);
  3234. if (domRun) writeShift(run.index, dx, dy);
  3235. emittedList.push(run.index);
  3236. shifted++;
  3237. continue;
  3238. }
  3239. t3Arena.on = Boolean(numeric) && !domRun;
  3240. t3Emit(run, cam, f);
  3241. if (f.sx || f.sy) {
  3242. f.sx = 0;
  3243. f.sy = 0;
  3244. }
  3245. if (shiftOn && shiftable(run)) keepEmit(run, cam, f);
  3246. if (domRun) {
  3247. write(run.index);
  3248. if (shiftOn && shiftable(run)) writeShift(run.index, 0, 0);
  3249. }
  3250. emittedList.push(run.index);
  3251. emitted++;
  3252. }
  3253. stats.shifted = shifted;
  3254. lastPoses = poses;
  3255. lastUnit = unit;
  3256. t3Arena.on = false;
  3257. t3Arena.f = null;
  3258. const t1 = performance.now();
  3259. stats.emitMs = t1 - t0;
  3260. const orderStats = { forced: 0, refined: 0, unseparated: 0, edges: 0 };
  3261. scene.layers.forEach((layer, index) => {
  3262. const previous = orders[index];
  3263. const tOrder = performance.now();
  3264. const order = t3Order(layer, frames, cams, previous, orderStats, scene);
  3265. stats.orderMs += performance.now() - tOrder;
  3266. let same = true;
  3267. for (let j = 0; j < order.length; j++)
  3268. if (order[j] !== previous[j]) {
  3269. same = false;
  3270. break;
  3271. }
  3272. if (snapshotting && !domLayer[index]) {
  3273. const container = containers.get(layer.name);
  3274. if (container) for (const global of order) if (nodes[global]) container.appendChild(nodes[global]);
  3275. orders[index] = order;
  3276. return;
  3277. }
  3278. if (same) return;
  3279. if (!domLayer[index]) {
  3280. orders[index] = order;
  3281. return;
  3282. }
  3283. const container = containers.get(layer.name);
  3284. const position = new Map();
  3285. previous.forEach((global, at) => position.set(global, at));
  3286. const keep = t3Keep(Array.from(order, (global) => position.get(global)));
  3287. let after = null;
  3288. const shifted = [];
  3289. for (let j = order.length - 1; j >= 0; j--) {
  3290. const node = nodes[order[j]];
  3291. if (!keep[j] && node && container) {
  3292. container.insertBefore(node, after);
  3293. moved++;
  3294. shifted.push(scene.runs[order[j]].name);
  3295. }
  3296. if (node) after = node;
  3297. }
  3298. orders[index] = order;
  3299. if (shifted.length) changes.push({ layer: layer.name, moved: shifted });
  3300. });
  3301. stats.ms = performance.now() - t0;
  3302. stats.writes = writes;
  3303. stats.moved = moved;
  3304. stats.forced = orderStats.forced;
  3305. stats.refined = orderStats.refined;
  3306. stats.unseparated = orderStats.unseparated;
  3307. stats.emitted = emitted;
  3308. t3State.detail = 1;
  3309. if (onFrame) onFrame(controller);
  3310. return { ...stats };
  3311. };
  3312. let detail = 1;
  3313. const set = (next, options) => {
  3314. if (options && options.detail !== undefined) {
  3315. const value = Math.max(0, Math.min(1, options.detail));
  3316. if (value !== detail) {
  3317. detail = value;
  3318. lastPoses = null;
  3319. }
  3320. }
  3321. if (typeof next === "number") {
  3322. const g = data.groups.find((group) => group.kind === "turn");
  3323. if (g) values[g.name] = next;
  3324. } else if (next) for (const [name, value] of Object.entries(next)) values[name] = value;
  3325. if (follow) Object.assign(values, follow({ ...values }));
  3326. return render();
  3327. };
  3328. const itemRuns = new Map();
  3329. let unwrap = new Map();
  3330. const angleAt = (clientX, clientY, z = 0, groupName) => {
  3331. const svg = first;
  3332. const box = svg.getBoundingClientRect();
  3333. const vb = svg.viewBox.baseVal;
  3334. const x = vb.x + ((clientX - box.left) / box.width) * vb.width;
  3335. const y = vb.y + ((clientY - box.top) / box.height) * vb.height;
  3336. const c = t3Camera(scene.P, null);
  3337. const p = (x - c.ox) / c.k;
  3338. const q = (y - c.oy + z * c.ce * c.k) / (c.se * c.k);
  3339. const wx = p * c.sa + q * c.ca;
  3340. const wy = -p * c.ca + q * c.sa;
  3341. const group = data.groups.find((g) => g.name === groupName) ?? data.groups.find((g) => g.kind === "turn");
  3342. const pivot = group ? group.origin : [0, 0, 0];
  3343. const raw = (Math.atan2(wy - pivot[1], wx - pivot[0]) * 180) / Math.PI;
  3344. const key = group ? group.name : "";
  3345. const last = unwrap.get(key);
  3346. let angle = raw;
  3347. if (last !== undefined) angle = last + ((((raw - last) % 360) + 540) % 360) - 180;
  3348. unwrap.set(key, angle);
  3349. return angle;
  3350. };
  3351. const observer = typeof ResizeObserver === "function" && first
  3352. ? new ResizeObserver(() => {
  3353. if (!dom || !first.isConnected) return;
  3354. const next = unitOf();
  3355. if (Math.abs(next - unit) < 0.05) return;
  3356. unit = next;
  3357. scene = t3Prepare(data, { unit });
  3358. render();
  3359. })
  3360. : null;
  3361. if (observer) observer.observe(first);
  3362. if (follow) Object.assign(values, follow({ ...values }));
  3363. const controller = {
  3364. set,
  3365. render,
  3366. painter,
  3367. emitted: () => emittedList,
  3368. snapshot: () => {
  3369. snapshotNext = true;
  3370. lastPoses = null;
  3371. render();
  3372. lastPoses = null;
  3373. render();
  3374. return [...containers.values()];
  3375. },
  3376. numeric: Boolean(numeric) && canvasSet.size > 0,
  3377. canvasLayers: [...canvasSet],
  3378. setUnit: (next) => {
  3379. if (Math.abs(next - unit) < 1e-6) return null;
  3380. unit = next;
  3381. scene = t3Prepare(data, { unit });
  3382. return render();
  3383. },
  3384. angleAt,
  3385. get values() {
  3386. return { ...values };
  3387. },
  3388. cover: (names, options) => t3Cover(controller, names, options),
  3389. order: (name) => {
  3390. const index = name === undefined ? 0 : scene.layers.findIndex((layer) => layer.name === name);
  3391. return index < 0 ? [] : Array.from(orders[index], (global) => scene.runs[global].name);
  3392. },
  3393. orderIndex: (name) => {
  3394. const index = name === undefined ? 0 : scene.layers.findIndex((layer) => layer.name === name);
  3395. return index < 0 ? null : orders[index];
  3396. },
  3397. events: () => changes.splice(0, changes.length),
  3398. stats: () => ({ ...stats }),
  3399. frames: () => frames,
  3400. cams: () => cams,
  3401. scene: () => scene,
  3402. pose: (name) => t3PoseOf(scene, cams, name),
  3403. detach: (name) => {
  3404. const index = scene.groups.findIndex((g) => g.name === name);
  3405. const pose = t3PoseOf(scene, cams, name);
  3406. const o = scene.groups[index].origin;
  3407. return { world: true, R: pose.R, t: [pose.t[0] - o[0], pose.t[1] - o[1], pose.t[2] - o[2]] };
  3408. },
  3409. anchor: (name, point, direction) => t3Anchor(scene, cams, name, point, direction),
  3410. item: (name, { cloud, box, hull }) => {
  3411. const run = itemRuns.get(name) ?? scene.runs.find((r) => r.name === name);
  3412. if (!run) return null;
  3413. itemRuns.set(name, run);
  3414. run.cloud = cloud instanceof Float64Array ? cloud : Float64Array.from(cloud);
  3415. run.version = (run.version ?? 0) + 1;
  3416. run.itemBox.set(box);
  3417. run.itemHull = hull instanceof Float64Array ? hull : Float64Array.from(hull);
  3418. const n = run.cloud.length / 3;
  3419. run.centroid = [0, 0, 0];
  3420. for (let i = 0; i < n; i++) for (let c = 0; c < 3; c++) run.centroid[c] += run.cloud[3 * i + c] / Math.max(1, n);
  3421. t3Emit(run, null, frames[run.index]);
  3422. return nodes[run.index];
  3423. },
  3424. node: (name) => {
  3425. const run = scene.runs.find((r) => r.name === name);
  3426. return run ? nodes[run.index] : null;
  3427. },
  3428. destroy: () => {
  3429. if (observer) observer.disconnect();
  3430. if (typeof window !== "undefined" && window.__isoTurn && window.__isoTurn.controller === controller) delete window.__isoTurn;
  3431. },
  3432. };
  3433. const hold = () => {
  3434. if (onHold) onHold();
  3435. };
  3436. if (typeof window !== "undefined") {
  3437. window.__isoTurn = {
  3438. controller,
  3439. set(next) {
  3440. hold();
  3441. return set(next);
  3442. },
  3443. get() {
  3444. hold();
  3445. return { ...values };
  3446. },
  3447. order(name) {
  3448. hold();
  3449. return controller.order(name);
  3450. },
  3451. events() {
  3452. hold();
  3453. return controller.events();
  3454. },
  3455. stats() {
  3456. hold();
  3457. return controller.stats();
  3458. },
  3459. layers() {
  3460. hold();
  3461. return scene.layers.map((layer) => layer.name);
  3462. },
  3463. };
  3464. }
  3465. render();
  3466. return controller;
  3467. }
  3468. function t3Enclose(points, edges) {
  3469. const hull = t3Hull(points);
  3470. const n = hull.length;
  3471. if (n < 3) return [];
  3472. let area = 0;
  3473. for (let i = 0; i < n; i++) area += hull[i][0] * hull[(i + 1) % n][1] - hull[(i + 1) % n][0] * hull[i][1];
  3474. const sign = area >= 0 ? 1 : -1;
  3475. let lines = [];
  3476. for (let i = 0; i < n; i++) {
  3477. const p = hull[i];
  3478. const q = hull[(i + 1) % n];
  3479. const dx = q[0] - p[0];
  3480. const dy = q[1] - p[1];
  3481. const l = Math.hypot(dx, dy);
  3482. if (l < 1e-9) continue;
  3483. const nx = (sign * dy) / l;
  3484. const ny = (-sign * dx) / l;
  3485. lines.push([nx, ny, -(nx * p[0] + ny * p[1])]);
  3486. }
  3487. const meet = (A, B) => {
  3488. const det = A[0] * B[1] - A[1] * B[0];
  3489. if (Math.abs(det) < 1e-12) return null;
  3490. return [(-A[2] * B[1] + B[2] * A[1]) / det, (-A[0] * B[2] + B[0] * A[2]) / det];
  3491. };
  3492. while (lines.length > edges) {
  3493. let best = -1;
  3494. let cost = Infinity;
  3495. const m = lines.length;
  3496. for (let i = 0; i < m; i++) {
  3497. const prev = lines[(i - 1 + m) % m];
  3498. const self = lines[i];
  3499. const next = lines[(i + 1) % m];
  3500. const turn = prev[0] * next[1] - prev[1] * next[0];
  3501. if (sign * turn <= 1e-9) continue;
  3502. const apex = meet(prev, next);
  3503. const a = meet(prev, self);
  3504. const b = meet(self, next);
  3505. if (!apex || !a || !b) continue;
  3506. const added = Math.abs((a[0] - apex[0]) * (b[1] - apex[1]) - (a[1] - apex[1]) * (b[0] - apex[0])) / 2;
  3507. if (added < cost) {
  3508. cost = added;
  3509. best = i;
  3510. }
  3511. }
  3512. if (best < 0) break;
  3513. lines.splice(best, 1);
  3514. }
  3515. return lines;
  3516. }
  3517. function t3Cover(controller, names, { polygons = 6, edges = 10, pad = 0.3, layers = null } = {}) {
  3518. const uCoverEdge = new Float32Array(polygons * edges * 3);
  3519. const uCoverCount = new Float32Array(polygons);
  3520. const scene = controller.scene();
  3521. const frames = controller.frames();
  3522. const sets = Array.isArray(names) ? (names.length && Array.isArray(names[0]) ? names : [names]) : [[names]];
  3523. const candidates = [];
  3524. const taken = new Set();
  3525. for (const list of sets) {
  3526. const targets = scene.runs.filter((run) => list.includes(run.name));
  3527. if (!targets.length) continue;
  3528. const box = [Infinity, Infinity, -Infinity, -Infinity];
  3529. for (const run of targets) {
  3530. const b = frames[run.index].box;
  3531. box[0] = Math.min(box[0], b[0]);
  3532. box[1] = Math.min(box[1], b[1]);
  3533. box[2] = Math.max(box[2], b[2]);
  3534. box[3] = Math.max(box[3], b[3]);
  3535. }
  3536. const home = targets[0].layer;
  3537. scene.layers.forEach((layer, index) => {
  3538. const order = controller.orderIndex(layer.name);
  3539. if (!order) return;
  3540. let from = 0;
  3541. if (index === home) {
  3542. for (let at = 0; at < order.length; at++) if (targets.some((run) => run.index === order[at])) from = at + 1;
  3543. } else if (!(layers && layers.includes(layer.name)) || index < home) return;
  3544. for (let at = from; at < order.length; at++) {
  3545. const run = scene.runs[order[at]];
  3546. if (list.includes(run.name) || taken.has(run.index)) continue;
  3547. const f = frames[run.index];
  3548. const b = f.box;
  3549. if (!(b[0] < box[2] + pad && box[0] < b[2] + pad && b[1] < box[3] + pad && box[1] < b[3] + pad)) continue;
  3550. if (!targets.some((target) => !t3Disjoint(frames[target.index], f, -pad))) continue;
  3551. taken.add(run.index);
  3552. const share = (Math.min(b[2], box[2]) - Math.max(b[0], box[0])) * (Math.min(b[3], box[3]) - Math.max(b[1], box[1]));
  3553. candidates.push({ run, f, share });
  3554. }
  3555. });
  3556. }
  3557. candidates.sort((a, b) => b.share - a.share);
  3558. const parts = [];
  3559. let slot = 0;
  3560. for (const { run, f } of candidates) {
  3561. if (slot >= polygons) break;
  3562. const points = [];
  3563. if (f.quadN) for (const [buf, count] of f.quadList) for (let i = 0; i < count; i++) points.push([buf[2 * i], buf[2 * i + 1]]);
  3564. else for (let i = 0; i < f.hullN; i++) points.push([f.hull[2 * i], f.hull[2 * i + 1]]);
  3565. const lines = t3Enclose(points, edges);
  3566. if (!lines.length) continue;
  3567. lines.forEach((line, e) => {
  3568. const at = (slot * edges + e) * 3;
  3569. uCoverEdge[at] = line[0];
  3570. uCoverEdge[at + 1] = line[1];
  3571. uCoverEdge[at + 2] = line[2] - pad;
  3572. });
  3573. uCoverCount[slot] = lines.length;
  3574. parts.push(run.name);
  3575. slot++;
  3576. }
  3577. return { uCoverEdge, uCoverCount, dropped: Math.max(0, candidates.length - slot), parts };
  3578. }
  3579. function t3PoseOf(scene, cams, name) {
  3580. const index = scene.groups.findIndex((g) => g.name === name);
  3581. const cam = index >= 0 && cams ? cams[index] : null;
  3582. return { R: cam ? Array.from(cam.R) : Array.from(T3_EYE), t: cam ? [cam.t[0], cam.t[1], cam.t[2]] : [0, 0, 0] };
  3583. }
  3584. function t3Anchor(scene, cams, name, point, direction) {
  3585. const index = name === null || name === undefined ? -1 : scene.groups.findIndex((g) => g.name === name);
  3586. const cam = index >= 0 ? cams[index] : cams.world;
  3587. const o = index >= 0 ? scene.groups[index].origin : [0, 0, 0];
  3588. const R = cam.R;
  3589. const q = [point[0] - o[0], point[1] - o[1], point[2] - o[2]];
  3590. const world = [R[0] * q[0] + R[1] * q[1] + R[2] * q[2] + cam.t[0], R[3] * q[0] + R[4] * q[1] + R[5] * q[2] + cam.t[1], R[6] * q[0] + R[7] * q[1] + R[8] * q[2] + cam.t[2]];
  3591. const w = cams.world;
  3592. const screen = [w.ox + w.m[0] * world[0] + w.m[1] * world[1] + w.m[2] * world[2], w.oy + w.m[3] * world[0] + w.m[4] * world[1] + w.m[5] * world[2]];
  3593. const out = { world, screen };
  3594. if (direction) out.direction = [R[0] * direction[0] + R[1] * direction[1] + R[2] * direction[2], R[3] * direction[0] + R[4] * direction[1] + R[5] * direction[2], R[6] * direction[0] + R[7] * direction[1] + R[8] * direction[2]];
  3595. return out;
  3596. }
  3597. function t3FloorOf(scene, name, R = T3_EYE) {
  3598. const index = scene.groups.findIndex((g) => g.name === name);
  3599. let low = Infinity;
  3600. for (const run of scene.runs) {
  3601. if (run.group !== index) continue;
  3602. const c = run.cloud;
  3603. for (let i = 0; i < c.length; i += 3) {
  3604. const z = R[6] * c[i] + R[7] * c[i + 1] + R[8] * c[i + 2];
  3605. if (z < low) low = z;
  3606. }
  3607. }
  3608. return low;
  3609. }
  3610. function t3Compose(A, B) {
  3611. return Array.from(t3Mul(A, B));
  3612. }
  3613. function t3PoseUniforms(controller, group, prefix = "uGroup") {
  3614. const scene = controller.scene();
  3615. const index = scene.groups.findIndex((g) => g.name === group);
  3616. const cams = controller.cams();
  3617. const cam = index >= 0 && cams ? cams[index] : null;
  3618. const R = cam ? cam.R : T3_EYE;
  3619. const t = cam ? cam.t : [0, 0, 0];
  3620. const o = index >= 0 ? scene.groups[index].origin : [0, 0, 0];
  3621. const T = [t[0] - (R[0] * o[0] + R[1] * o[1] + R[2] * o[2]), t[1] - (R[3] * o[0] + R[4] * o[1] + R[5] * o[2]), t[2] - (R[6] * o[0] + R[7] * o[1] + R[8] * o[2])];
  3622. return { [`${prefix}X`]: [R[0], R[3], R[6]], [`${prefix}Y`]: [R[1], R[4], R[7]], [`${prefix}Z`]: [R[2], R[5], R[8]], [`${prefix}T`]: T };
  3623. }
  3624. const T3_MAT_KEYS = ["paper", "face", "top", "shade-0", "shade-1", "shade-2", "shade-3", "lit-top", "lit-shade", "hi", "mid", "lo", "faint", "dot", "lit"];
  3625. const T3_MAT_TUBE = ["body", "shine", "shade", "edge"];
  3626. const T3_MATERIALS = {
  3627. gold: {
  3628. light: ["#d3bb88", "#e4d2a8", "#f1e5c6", "#a1844f", "#bc9f69", "#d3bb88", "#e4d2a8", "#f8efd8", "#dfcb9c", "#4b3920", "#86693f", "#a98c5b", "#c1a676", "#4a381f", "#2a1d0c", "#cdb07a", "#f3e8cc", "#8e7044", "#4b3920"],
  3629. dark: ["#3f3521", "#4b3f28", "#5a4c31", "#2b2416", "#352c1b", "#3f3521", "#4b3f28", "#6a5a3b", "#4f4329", "#e6d2a3", "#8a7550", "#5e4e33", "#463a26", "#e6d2a3", "#fff3d6", "#4a3e27", "#8c7853", "#251f13", "#e6d2a3"],
  3630. },
  3631. chrome: {
  3632. light: ["#8e959c", "#c3c8cd", "#f7f8f9", "#a2a9b0", "#6f767d", "#454b52", "#cacfd4", "#ffffff", "#bcc2c8", "#202428", "#585e65", "#878d94", "#a9afb5", "#2a2e33", "#000000", "#8b9299", "#fbfcfd", "#3c4248", "#202428"],
  3633. dark: ["#2a2e32", "#4a5056", "#6e757c", "#2e3236", "#24272b", "#1a1d20", "#4a5056", "#848b92", "#3a3f44", "#dfe3e7", "#7c838a", "#4d5359", "#363b40", "#e4e7ea", "#ffffff", "#34393e", "#9aa1a8", "#16191b", "#dfe3e7"],
  3634. },
  3635. steel: {
  3636. light: ["#b8bdc1", "#cdd1d4", "#e5e8ea", "#8f959b", "#a4aaaf", "#b8bdc1", "#cdd1d4", "#f1f3f4", "#c6cacd", "#2b2f33", "#6b7177", "#959ba1", "#aeb3b8", "#33373b", "#000000", "#b3b8bd", "#eef0f2", "#7d8389", "#2b2f33"],
  3637. dark: ["#2c3034", "#34393d", "#3e4348", "#1f2225", "#25292c", "#2c3034", "#34393d", "#4a5056", "#33383c", "#d0d4d8", "#727980", "#4a5056", "#33383d", "#d8dce0", "#ffffff", "#30353a", "#5c6369", "#1a1d20", "#d0d4d8"],
  3638. },
  3639. gunmetal: {
  3640. light: ["#444a51", "#50575e", "#5f666e", "#2f3439", "#393f45", "#444a51", "#50575e", "#6d757d", "#4b5258", "#0f1113", "#1d2125", "#272b30", "#30353a", "#b0b5ba", "#000000", "#3d4349", "#6e757c", "#24282c", "#0f1113"],
  3641. dark: ["#1d2125", "#22272b", "#2a2f34", "#15181b", "#191c20", "#1d2125", "#22272b", "#323840", "#20252a", "#a9b0b7", "#5c636a", "#3a4046", "#2a2f34", "#b8bec4", "#ffffff", "#1f2327", "#3a4046", "#111316", "#a9b0b7"],
  3642. },
  3643. rubber: {
  3644. light: ["#2a2b2e", "#34363a", "#46484d", "#1b1c1e", "#222326", "#2a2b2e", "#34363a", "#55575c", "#2f3134", "#070708", "#111214", "#18191b", "#1f2023", "#6a6c70", "#000000", "#27282b", "#5b5d62", "#121314", "#050506"],
  3645. dark: ["#121213", "#161618", "#1c1c1f", "#0c0c0d", "#0f0f10", "#121213", "#161618", "#232327", "#141416", "#8c8e92", "#4a4c50", "#2c2d30", "#1f2023", "#9a9ca0", "#ffffff", "#131315", "#2b2c30", "#0a0a0b", "#8c8e92"],
  3646. },
  3647. brass: {
  3648. light: ["#bd9646", "#d2ad5b", "#e6c87e", "#8a6a2c", "#a47f38", "#bd9646", "#d2ad5b", "#f0d796", "#c8a252", "#3f2e0e", "#765a24", "#9a7a3c", "#b08c46", "#3a2a0c", "#1f1606", "#b8913f", "#efd795", "#7d5f26", "#3f2e0e"],
  3649. dark: ["#3d3017", "#49391c", "#574523", "#2a210f", "#332813", "#3d3017", "#49391c", "#66522b", "#45371b", "#e9cf8a", "#8e7438", "#5e4c25", "#44371c", "#e9cf8a", "#fff0c8", "#433419", "#8a6f36", "#21190b", "#e9cf8a"],
  3650. },
  3651. copper: {
  3652. light: ["#b3633e", "#c9784f", "#df9670", "#7c4128", "#9a5132", "#b3633e", "#c9784f", "#eaa985", "#be6d46", "#3a1a0c", "#6e3820", "#925037", "#a65d3f", "#3a1a0c", "#1c0b04", "#ad5f3b", "#f0b896", "#6e3720", "#3a1a0c"],
  3653. dark: ["#3d1f13", "#492617", "#582e1c", "#2a160d", "#331a10", "#3d1f13", "#492617", "#673722", "#432215", "#eaa985", "#8f5236", "#5f3624", "#45271a", "#eaa985", "#ffe0cc", "#42221a", "#8a4c31", "#1f0f08", "#eaa985"],
  3654. },
  3655. };
  3656. function t3MaterialCss() {
  3657. const rules = [];
  3658. const block = (values) => T3_MAT_KEYS.map((key, i) => `--anatomy-${key}:${values[i]}`).concat(T3_MAT_TUBE.map((key, i) => `--mat-${key}:${values[T3_MAT_KEYS.length + i]}`)).join(";");
  3659. for (const [name, { light, dark }] of Object.entries(T3_MATERIALS)) {
  3660. rules.push(`[data-mat="${name}"]{${block(dark)}}`);
  3661. rules.push(`.iso[data-theme="light"] [data-mat="${name}"]{${block(light)}}`);
  3662. rules.push(`.iso[data-theme="dark"] [data-mat="${name}"]{${block(dark)}}`);
  3663. }
  3664. rules.push("[data-mat] .tb-body{fill:var(--mat-body)}");
  3665. rules.push("[data-mat] .tb-shine{fill:var(--mat-shine)}");
  3666. rules.push("[data-mat] .tb-shade{fill:var(--mat-shade)}");
  3667. rules.push("[data-mat] .tb-edge{stroke:var(--mat-edge)}");
  3668. return rules.join("\n");
  3669. }
  3670. function t3Css() {
  3671. const rules = [];
  3672. const ramp = "--tn-0:var(--anatomy-shade-0);--tn-1:var(--anatomy-shade-1);--tn-2:var(--anatomy-shade-2);--tn-3:var(--anatomy-shade-3);--tn-4:var(--anatomy-top)";
  3673. rules.push(`.iso-live{${ramp}}`);
  3674. rules.push(`.iso-live [data-mat]{${ramp}}`);
  3675. rules.push(".iso-live [data-lit]{--tn-0:var(--anatomy-lit-shade);--tn-1:var(--anatomy-lit-shade);--tn-2:var(--anatomy-lit-shade);--tn-3:var(--anatomy-lit-shade);--tn-4:var(--anatomy-lit-top)}");
  3676. const colour = "color-mix(in srgb,var(--ta) calc(100% - var(--f,0) * 100%),var(--tb))";
  3677. rules.push(`.iso-tn{stroke-width:.4;stroke-linejoin:round;--ta:var(--tn-0);--tb:var(--tn-1);fill:${colour};stroke:${colour}}`);
  3678. for (let i = 1; i < 4; i++) rules.push(`.iso-tn[data-b="${i}"]{--ta:var(--tn-${i});--tb:var(--tn-${i + 1})}`);
  3679. rules.push(t3MaterialCss());
  3680. for (const hue of ["red", "green", "blue"]) rules.push(`.tb[data-hue="${hue}"]{--tb-ink:var(--anatomy-${hue})}`);
  3681. rules.push(".tb[data-hue] .tb-body{fill:color-mix(in srgb,var(--tb-ink) 54%,var(--anatomy-shade-2))}");
  3682. rules.push(".tb[data-hue] .tb-shine{fill:color-mix(in srgb,var(--tb-ink) 16%,var(--anatomy-top))}");
  3683. rules.push(".tb[data-hue] .tb-shade{fill:color-mix(in srgb,var(--tb-ink) 30%,var(--anatomy-hi))}");
  3684. rules.push(".tb[data-hue] .tb-edge{stroke:color-mix(in srgb,var(--tb-ink) 38%,var(--anatomy-hi))}");
  3685. rules.push(".tb[data-hue][data-mat] .tb-body{fill:color-mix(in srgb,var(--tb-ink) 62%,var(--mat-body))}");
  3686. rules.push(".tb[data-hue][data-mat] .tb-shine{fill:color-mix(in srgb,var(--tb-ink) 22%,var(--mat-shine))}");
  3687. rules.push(".tb[data-hue][data-mat] .tb-shade{fill:color-mix(in srgb,var(--tb-ink) 46%,var(--mat-shade))}");
  3688. rules.push(".tb[data-hue][data-mat] .tb-edge{stroke:color-mix(in srgb,var(--tb-ink) 30%,var(--mat-edge))}");
  3689. rules.push(".iso-turn{position:relative}");
  3690. rules.push(".iso-turn>.iso-layer{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}");
  3691. return rules.join("\n");
  3692. }
  3693. export const TURN = { materials: Object.keys(T3_MATERIALS), materialCss: t3MaterialCss, rotation: (axis, degrees) => Array.from(t3Rot(axis, degrees)), quat: (q) => Array.from(t3Quat(q)), compose: t3Compose, floorOf: t3FloorOf, anchor: t3Anchor, camera: t3Camera, poses: t3PosesMap, prepare: t3Prepare, emit: t3Emit, order: t3Order, mount: t3Mount, cover: t3Cover, poseUniforms: t3PoseUniforms, css: t3Css, frame: t3Frame, cams: t3Cams, gjk: t3Gjk, hintsOf: (ri, ci, rj, cj, world) => Object.assign([...ri.axes.map((axis) => [axis, ci]), ...rj.axes.map((axis) => [axis, cj]), [[0, 0, 1], world]], { centroids: [ri.centroid, rj.centroid] }), disjoint: t3Disjoint, levels: T3_LEVELS, q: T3_Q, exact: (on) => { t3State.exact = Boolean(on); } };
  3694. export const TURN_CSS = t3Css();