turn.mjs 137 KB

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