audit.mjs 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  1. import { cameraOf, roundedPlan } from "./iso-kit.mjs";
  2. import { add3, sub3, mul3, dot3, len3, unit3, pathLength, resample, curveRuns, cut as cutAlong, tangentAlong } from "./lathe.mjs";
  3. import { runsOf } from "./tube.mjs";
  4. const BIG = 1e9;
  5. export function body(F, poly, meta = {}) {
  6. return { kind: "body", F, poly: poly.map(([s, r]) => [s, Math.max(0, r)]), ...meta };
  7. }
  8. export function traced(meridian, { radius = null, error = 0.02, depth = 6 } = {}) {
  9. const segments = radius ? null : curveRuns(meridian);
  10. const out = [[meridian[0][0], meridian[0][1]]];
  11. for (let index = 0; index < meridian.length - 1; index++) {
  12. const [s0] = meridian[index];
  13. const [s1, r1] = meridian[index + 1];
  14. const along = Math.abs(s1 - s0) > 1e-9;
  15. const at = along && radius ? radius : along && segments[index] ? segments[index].radius : null;
  16. if (at) {
  17. const split = (a, b, level) => {
  18. const mid = (a + b) / 2;
  19. if (level >= depth || Math.abs(at(mid) - (at(a) + at(b)) / 2) <= error) return;
  20. split(a, mid, level + 1);
  21. out.push([mid, at(mid)]);
  22. split(mid, b, level + 1);
  23. };
  24. split(s0, s1, 0);
  25. }
  26. out.push([s1, r1]);
  27. }
  28. return out;
  29. }
  30. export function lathe(F, meridian, { radius = null, ...meta } = {}) {
  31. return body(F, traced(meridian, { radius }), meta);
  32. }
  33. export function solid(F, profile, { radius = null, ...meta } = {}) {
  34. const first = profile[0];
  35. const last = profile[profile.length - 1];
  36. return body(F, traced([[first[0], 0], ...profile, [last[0], 0]], { radius: radius && ((s) => radius(Math.max(first[0], Math.min(last[0], s)))) }), meta);
  37. }
  38. export function prism(F, polygon, s0, s1, meta = {}) {
  39. return { kind: "prism", F, poly: polygon.map(([x, y]) => [x, y]), s0: Math.min(s0, s1), s1: Math.max(s0, s1), ...meta };
  40. }
  41. const FLOOR = { o: [0, 0, 0], a: [0, 0, 1], u: [1, 0, 0], v: [0, 1, 0] };
  42. export const extruded = (ring, z, height, meta = {}) => prism(FLOOR, ring, z, z + height, meta);
  43. export const slab = (plan, z, height, meta = {}, steps = 8) => extruded(roundedPlan(plan, steps), z, height, meta);
  44. export const cylinder = (cx, cy, r, z, height, meta = {}) => disc({ o: [cx, cy, 0], a: [0, 0, 1], u: [1, 0, 0], v: [0, 1, 0] }, z, z + height, r, meta);
  45. export const disc = (F, s0, s1, r, meta = {}) => body(F, [[s0, 0], [s0, r], [s1, r], [s1, 0]], meta);
  46. export const ring = (F, s0, s1, rIn, rOut, meta = {}) => body(F, [[s0, rIn], [s0, rOut], [s1, rOut], [s1, rIn]], meta);
  47. export function box(min, max, meta = {}) {
  48. const centre = mul3(add3(min, max), 0.5);
  49. return { kind: "box", o: centre, axes: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], half: mul3(sub3(max, min), 0.5), ...meta };
  50. }
  51. export const orientedBox = (centre, axes, half, meta = {}) => ({ kind: "box", o: centre, axes: axes.map(unit3), half, ...meta });
  52. export const ball = (at, r, meta = {}) => ({ kind: "ball", o: at, r, ...meta });
  53. export function tube(points, radius, meta = {}) {
  54. const total = pathLength(points) || 1;
  55. let walked = 0;
  56. const radii = Array.isArray(radius)
  57. ? radius
  58. : points.map((point, index) => {
  59. if (index > 0) walked += len3(sub3(point, points[index - 1]));
  60. return typeof radius === "function" ? radius(walked / total) : radius;
  61. });
  62. return { kind: "tube", points, radii, round: meta.round ?? [false, false], ...meta };
  63. }
  64. export const slide = (F, from, to, r, meta = {}) => ({ ...disc(F, from, to, r, meta), slide: { from, to, r } });
  65. export function moved(shape, offset) {
  66. if (!offset || (!offset[0] && !offset[1] && !offset[2])) return shape;
  67. if (shape.slide) {
  68. const { from, to, r } = shape.slide;
  69. const reach = Math.max(from + 1e-3, to + dot3(offset, shape.F.a));
  70. return { ...shape, poly: [[from, 0], [from, r], [reach, r], [reach, 0]], slide: { from, to: reach, r }, _b: undefined, _f: undefined };
  71. }
  72. const cut = shape.cut ? (Array.isArray(shape.cut) ? shape.cut.map((one) => moved(one, offset)) : moved(shape.cut, offset)) : undefined;
  73. if (shape.kind === "body" || shape.kind === "prism") return { ...shape, cut, F: { ...shape.F, o: add3(shape.F.o, offset) }, _b: undefined, _f: undefined };
  74. if (shape.kind === "tube") return { ...shape, cut, points: shape.points.map((p) => add3(p, offset)), tips: shape.tips && shape.tips.map((tip) => tip && add3(tip, offset)), _b: undefined };
  75. return { ...shape, cut, o: add3(shape.o, offset), _b: undefined };
  76. }
  77. function polyDistance(poly, s, r) {
  78. let best = BIG;
  79. let inside = false;
  80. for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
  81. const [s0, r0] = poly[j];
  82. const [s1, r1] = poly[i];
  83. const ds = s1 - s0;
  84. const dr = r1 - r0;
  85. const span = ds * ds + dr * dr;
  86. const t = span > 0 ? Math.max(0, Math.min(1, ((s - s0) * ds + (r - r0) * dr) / span)) : 0;
  87. const es = s - s0 - ds * t;
  88. const er = r - r0 - dr * t;
  89. const d = es * es + er * er;
  90. if (d < best && (r0 > 1e-9 || r1 > 1e-9)) best = d;
  91. if (r0 > r !== r1 > r && s < s0 + ((r - r0) * ds) / (dr || 1e-12)) inside = !inside;
  92. }
  93. const d = Math.sqrt(best);
  94. return inside ? -d : d;
  95. }
  96. function polygonDistance(poly, x, y) {
  97. let best = BIG;
  98. let inside = false;
  99. for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
  100. const [x0, y0] = poly[j];
  101. const [x1, y1] = poly[i];
  102. const dx = x1 - x0;
  103. const dy = y1 - y0;
  104. const span = dx * dx + dy * dy;
  105. const t = span > 0 ? Math.max(0, Math.min(1, ((x - x0) * dx + (y - y0) * dy) / span)) : 0;
  106. const ex = x - x0 - dx * t;
  107. const ey = y - y0 - dy * t;
  108. const d = ex * ex + ey * ey;
  109. if (d < best) best = d;
  110. if (y0 > y !== y1 > y && x < x0 + ((y - y0) * dx) / (dy || 1e-12)) inside = !inside;
  111. }
  112. const d = Math.sqrt(best);
  113. return inside ? -d : d;
  114. }
  115. function cappedSegment(p, a, b, r) {
  116. const bx = b[0] - a[0];
  117. const by = b[1] - a[1];
  118. const bz = b[2] - a[2];
  119. const px = p[0] - a[0];
  120. const py = p[1] - a[1];
  121. const pz = p[2] - a[2];
  122. const baba = bx * bx + by * by + bz * bz || 1e-12;
  123. const paba = px * bx + py * by + pz * bz;
  124. const x = Math.hypot(px * baba - bx * paba, py * baba - by * paba, pz * baba - bz * paba) - r * baba;
  125. const y = Math.abs(paba - baba * 0.5) - baba * 0.5;
  126. const x2 = x * x;
  127. const y2 = y * y * baba;
  128. const d = Math.max(x, y) < 0 ? -Math.min(x2, y2) : (x > 0 ? x2 : 0) + (y > 0 ? y2 : 0);
  129. return (Math.sign(d) * Math.sqrt(Math.abs(d))) / baba;
  130. }
  131. function segmentPoint(p, a, b) {
  132. const ba = sub3(b, a);
  133. const pa = sub3(p, a);
  134. const t = Math.max(0, Math.min(1, dot3(pa, ba) / (dot3(ba, ba) || 1e-12)));
  135. return { d: len3(sub3(pa, mul3(ba, t))), t };
  136. }
  137. export function sdf(shape, p) {
  138. const d = baseSdf(shape, p);
  139. return shape.cut ? Math.max(d, -cutDistance(shape, p)) : d;
  140. }
  141. function cutDistance(shape, p) {
  142. if (!Array.isArray(shape.cut)) return sdf(shape.cut, p);
  143. let best = BIG;
  144. for (const cut of shape.cut) best = Math.min(best, sdf(cut, p));
  145. return best;
  146. }
  147. function baseSdf(shape, p) {
  148. if (shape.kind === "body") {
  149. const { F } = shape;
  150. const q = sub3(p, F.o);
  151. const s = dot3(q, F.a);
  152. const x = dot3(q, F.u);
  153. const y = dot3(q, F.v);
  154. return polyDistance(shape.poly, s, Math.hypot(x, y));
  155. }
  156. if (shape.kind === "ball") {
  157. let d = len3(sub3(p, shape.o)) - shape.r;
  158. if (shape.flats) for (const [nx, ny, nz, cut] of shape.flats) d = Math.max(d, nx * (p[0] - shape.o[0]) + ny * (p[1] - shape.o[1]) + nz * (p[2] - shape.o[2]) - cut);
  159. return d;
  160. }
  161. if (shape.kind === "prism") {
  162. const { F } = shape;
  163. const q = sub3(p, F.o);
  164. const s = dot3(q, F.a);
  165. const flat = polygonDistance(shape.poly, dot3(q, F.u), dot3(q, F.v));
  166. const along = Math.max(shape.s0 - s, s - shape.s1);
  167. return Math.hypot(Math.max(flat, 0), Math.max(along, 0)) + Math.min(Math.max(flat, along), 0);
  168. }
  169. if (shape.kind === "box") {
  170. const q = sub3(p, shape.o);
  171. const d = shape.axes.map((axis, index) => Math.abs(dot3(q, axis)) - shape.half[index]);
  172. const outside = Math.hypot(Math.max(d[0], 0), Math.max(d[1], 0), Math.max(d[2], 0));
  173. return outside + Math.min(Math.max(d[0], d[1], d[2]), 0);
  174. }
  175. const { points, radii, round } = shape;
  176. let best = BIG;
  177. const last = points.length - 1;
  178. for (let index = 0; index < last; index++) {
  179. const r = (radii[index] + radii[index + 1]) / 2;
  180. const d = cappedSegment(p, points[index], points[index + 1], r);
  181. if (d < best) best = d;
  182. }
  183. if (round[0]) best = Math.min(best, len3(sub3(p, points[0])) - radii[0]);
  184. if (round[1]) best = Math.min(best, len3(sub3(p, points[last])) - radii[last]);
  185. return best;
  186. }
  187. export function boundsOf(shape) {
  188. if (shape._b) return shape._b;
  189. let min;
  190. let max;
  191. if (shape.kind === "body") {
  192. const { F, poly } = shape;
  193. const s0 = Math.min(...poly.map(([s]) => s));
  194. const s1 = Math.max(...poly.map(([s]) => s));
  195. const rm = Math.max(...poly.map(([, r]) => r));
  196. const a = add3(F.o, mul3(F.a, s0));
  197. const b = add3(F.o, mul3(F.a, s1));
  198. const spread = [0, 1, 2].map((i) => rm * Math.sqrt(Math.max(0, 1 - F.a[i] * F.a[i])));
  199. min = [0, 1, 2].map((i) => Math.min(a[i], b[i]) - spread[i]);
  200. max = [0, 1, 2].map((i) => Math.max(a[i], b[i]) + spread[i]);
  201. } else if (shape.kind === "ball") {
  202. min = shape.o.map((v) => v - shape.r);
  203. max = shape.o.map((v) => v + shape.r);
  204. } else if (shape.kind === "prism") {
  205. const { F } = shape;
  206. min = [BIG, BIG, BIG];
  207. max = [-BIG, -BIG, -BIG];
  208. for (const s of [shape.s0, shape.s1])
  209. for (const [x, y] of shape.poly) {
  210. const p = add3(add3(F.o, mul3(F.a, s)), add3(mul3(F.u, x), mul3(F.v, y)));
  211. for (let i = 0; i < 3; i++) (min[i] = Math.min(min[i], p[i])), (max[i] = Math.max(max[i], p[i]));
  212. }
  213. } else if (shape.kind === "box") {
  214. const extent = [0, 1, 2].map((i) => shape.axes.reduce((sum, axis, j) => sum + Math.abs(axis[i]) * shape.half[j], 0));
  215. min = shape.o.map((v, i) => v - extent[i]);
  216. max = shape.o.map((v, i) => v + extent[i]);
  217. } else {
  218. min = [BIG, BIG, BIG];
  219. max = [-BIG, -BIG, -BIG];
  220. shape.points.forEach((p, index) => {
  221. for (let i = 0; i < 3; i++) {
  222. min[i] = Math.min(min[i], p[i] - shape.radii[index]);
  223. max[i] = Math.max(max[i], p[i] + shape.radii[index]);
  224. }
  225. });
  226. }
  227. shape._b = { min, max };
  228. return shape._b;
  229. }
  230. export function cameraBasis(P) {
  231. const { sinA, cosA, sinE, cosE, k } = cameraOf(P);
  232. return { R: [sinA, -cosA, 0], D: [cosA * sinE, sinA * sinE, -cosE], V: [cosA * cosE, sinA * cosE, sinE], k, origin: P.origin };
  233. }
  234. function screenBox(shape, cam, offset) {
  235. const { min, max } = boundsOf(shape);
  236. let x0 = BIG;
  237. let y0 = BIG;
  238. let x1 = -BIG;
  239. let y1 = -BIG;
  240. const visit = (p) => {
  241. const x = cam.origin[0] + dot3(p, cam.R) * cam.k;
  242. const y = cam.origin[1] + dot3(p, cam.D) * cam.k;
  243. x0 = Math.min(x0, x);
  244. y0 = Math.min(y0, y);
  245. x1 = Math.max(x1, x);
  246. y1 = Math.max(y1, y);
  247. };
  248. if (shape.kind === "tube") {
  249. shape.points.forEach((p, index) => {
  250. const r = shape.radii[index];
  251. const q = add3(p, offset);
  252. visit(add3(q, mul3(cam.R, r)));
  253. visit(add3(q, mul3(cam.R, -r)));
  254. visit(add3(q, mul3(cam.D, r)));
  255. visit(add3(q, mul3(cam.D, -r)));
  256. });
  257. } else {
  258. for (const x of [min[0], max[0]]) for (const y of [min[1], max[1]]) for (const z of [min[2], max[2]]) visit(add3([x, y, z], offset));
  259. }
  260. return [x0, y0, x1, y1];
  261. }
  262. function spanOf(c, V, min, max) {
  263. let t0 = -BIG;
  264. let t1 = BIG;
  265. for (let i = 0; i < 3; i++) {
  266. if (Math.abs(V[i]) < 1e-12) {
  267. if (c[i] < min[i] || c[i] > max[i]) return null;
  268. continue;
  269. }
  270. let a = (min[i] - c[i]) / V[i];
  271. let b = (max[i] - c[i]) / V[i];
  272. if (a > b) [a, b] = [b, a];
  273. t0 = Math.max(t0, a);
  274. t1 = Math.min(t1, b);
  275. }
  276. return t0 <= t1 ? [t0, t1] : null;
  277. }
  278. function tubeDistance(shape, p, segments) {
  279. const { points, radii, round } = shape;
  280. const last = points.length - 1;
  281. let best = BIG;
  282. for (const index of segments) {
  283. const d = cappedSegment(p, points[index], points[index + 1], (radii[index] + radii[index + 1]) / 2);
  284. if (d < best) best = d;
  285. for (const [joint, flag] of [[0, round[0]], [last, round[1]]]) {
  286. if (!flag || (joint !== index && joint !== index + 1)) continue;
  287. const q = points[joint];
  288. const e = Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]) - radii[joint];
  289. if (e < best) best = e;
  290. }
  291. }
  292. return best;
  293. }
  294. function bodyDepth(shape, c, V, eps) {
  295. const { F, poly } = shape;
  296. if (!shape._f) {
  297. const s = poly.map(([value]) => value);
  298. shape._f = { aV: dot3(F.a, V), uV: dot3(F.u, V), vV: dot3(F.v, V), s0: Math.min(...s), s1: Math.max(...s), rm: Math.max(...poly.map(([, r]) => r)) };
  299. }
  300. const { aV, uV, vV, s0, s1, rm } = shape._f;
  301. const q = [c[0] - F.o[0], c[1] - F.o[1], c[2] - F.o[2]];
  302. const sc = dot3(q, F.a);
  303. const xc = dot3(q, F.u);
  304. const yc = dot3(q, F.v);
  305. let lo = -BIG;
  306. let hi = BIG;
  307. if (Math.abs(aV) > 1e-9) {
  308. const a = (s0 - sc) / aV;
  309. const b = (s1 - sc) / aV;
  310. lo = Math.min(a, b);
  311. hi = Math.max(a, b);
  312. } else if (sc < s0 || sc > s1) return null;
  313. const qa = uV * uV + vV * vV;
  314. if (qa > 1e-12) {
  315. const qb = 2 * (xc * uV + yc * vV);
  316. const qc = xc * xc + yc * yc - rm * rm;
  317. const disc = qb * qb - 4 * qa * qc;
  318. if (disc < 0) return null;
  319. const root = Math.sqrt(disc);
  320. lo = Math.max(lo, (-qb - root) / (2 * qa));
  321. hi = Math.min(hi, (-qb + root) / (2 * qa));
  322. } else if (xc * xc + yc * yc > rm * rm) return null;
  323. if (lo > hi) return null;
  324. let t = hi + eps;
  325. for (let step = 0; step < 160 && t >= lo - eps; step++) {
  326. let d = polyDistance(poly, sc + t * aV, Math.hypot(xc + t * uV, yc + t * vV));
  327. if (shape.cut) d = Math.max(d, -cutDistance(shape, [c[0] + V[0] * t, c[1] + V[1] * t, c[2] + V[2] * t]));
  328. if (d < eps) return t;
  329. t -= Math.max(d, eps * 0.5);
  330. }
  331. return null;
  332. }
  333. function rayDepth(shape, c, V, eps, segments) {
  334. if (shape.kind === "body") return bodyDepth(shape, c, V, eps);
  335. const span = spanOf(c, V, boundsOf(shape).min, boundsOf(shape).max);
  336. if (!span) return null;
  337. let t = span[1] + eps;
  338. for (let step = 0; step < 160 && t >= span[0] - eps; step++) {
  339. const p = [c[0] + V[0] * t, c[1] + V[1] * t, c[2] + V[2] * t];
  340. const d = segments ? tubeDistance(shape, p, segments) : sdf(shape, p);
  341. if (d < eps) return t;
  342. t -= Math.max(d, eps * 0.5);
  343. }
  344. return null;
  345. }
  346. function flatDistance(x, y, a, b) {
  347. const dx = b[0] - a[0];
  348. const dy = b[1] - a[1];
  349. const span = dx * dx + dy * dy;
  350. const t = span > 0 ? Math.max(0, Math.min(1, ((x - a[0]) * dx + (y - a[1]) * dy) / span)) : 0;
  351. return Math.hypot(x - a[0] - dx * t, y - a[1] - dy * t);
  352. }
  353. export const shareOf = (item, state) => (typeof state === "number" ? state : state.shares[item.ride ?? item.piece] ?? 0);
  354. export const offsetOf = (item, state) => mul3(item.move ?? [0, 0, 0], shareOf(item, state));
  355. export const labelOf = (state) => (typeof state === "number" ? `share ${Math.round(state * 1000) / 1000}` : state.label);
  356. export function springStates(order, { stagger = 0.035, stiffness = 64, damping = 14.2, substeps = 4, fps = 60, settle = 1e-3, stride = 1, reversals = [] } = {}) {
  357. const out = [];
  358. const scripts = [[true], [false], ...reversals.flatMap((at) => [[true, at], [false, at]])];
  359. for (const [on, back] of scripts) {
  360. const springs = Object.fromEntries(order.map((id) => [id, { x: on ? 0 : 1, v: 0, target: on ? 0 : 1, pending: null }]));
  361. const toggle = (value, clock) => {
  362. const goal = value ? 1 : 0;
  363. let index = 0;
  364. for (const id of value ? order : [...order].reverse()) {
  365. if (springs[id].target === goal) springs[id].pending = null;
  366. else springs[id].pending = { value: goal, at: clock + index++ * stagger };
  367. }
  368. };
  369. const name = back === undefined ? (on ? "apart" : "together") : `${on ? "apart" : "together"}, back at ${back.toFixed(2)} s,`;
  370. const dt = 1 / fps;
  371. let clock = 0;
  372. let goal = on ? 1 : 0;
  373. toggle(on, 0);
  374. for (let frame = 0; frame < 100000; frame++) {
  375. if (back !== undefined && clock < back && clock + dt >= back) toggle(!on, back), (goal = on ? 0 : 1);
  376. clock += dt;
  377. for (const spring of Object.values(springs)) {
  378. if (spring.pending && clock >= spring.pending.at) (spring.target = spring.pending.value), (spring.pending = null);
  379. for (let index = 0; index < substeps; index++) {
  380. const h = dt / substeps;
  381. spring.v += ((spring.target - spring.x) * stiffness - spring.v * damping) * h;
  382. spring.x += spring.v * h;
  383. }
  384. }
  385. const settled = (back === undefined || clock >= back) && Object.values(springs).every((spring) => !spring.pending && Math.abs(spring.x - goal) < settle && Math.abs(spring.v) < settle);
  386. if (settled) break;
  387. if ((frame + 1) % stride === 0) out.push({ label: `${name} ${clock.toFixed(3)} s`, shares: Object.fromEntries(Object.entries(springs).map(([id, spring]) => [id, spring.x])) });
  388. }
  389. }
  390. return out;
  391. }
  392. export const uniformStates = (count = 10) => Array.from({ length: count + 1 }, (_, index) => index / count);
  393. export const reversalsOf = (order, stagger = 0.035, margin = 0.008) => order.flatMap((_, index) => [index * stagger - margin, index * stagger + margin]).filter((at) => at > 0);
  394. export function prefixStates(order, { shares = [0.25, 0.5, 0.75, 1] } = {}) {
  395. const out = [];
  396. for (let count = 1; count < order.length; count++)
  397. for (const s of shares)
  398. out.push({ label: `first ${count - 1} out, ${order[count - 1]} at ${s}`, shares: Object.fromEntries(order.map((id, index) => [id, index < count - 1 ? 1 : index === count - 1 ? s : 0])) });
  399. return out;
  400. }
  401. function rasterOf(item, cam, step, offset) {
  402. const shapes = item.shapes.map((shape) => moved(shape, offset));
  403. const flat = (p) => [cam.origin[0] + dot3(p, cam.R) * cam.k, cam.origin[1] + dot3(p, cam.D) * cam.k];
  404. const boxes = shapes.map((shape) => screenBox(shape, cam, [0, 0, 0]));
  405. const guides = shapes.map((shape) => {
  406. if (shape.kind === "tube") {
  407. const points = shape.points.map(flat);
  408. const widths = shape.radii.map((r) => r * cam.k);
  409. const boxes = new Float64Array((points.length - 1) * 4);
  410. for (let i = 0; i < points.length - 1; i++) {
  411. const pad = Math.max(widths[i], widths[i + 1]) + step * 0.5;
  412. boxes[i * 4] = Math.min(points[i][0], points[i + 1][0]) - pad;
  413. boxes[i * 4 + 1] = Math.max(points[i][0], points[i + 1][0]) + pad;
  414. boxes[i * 4 + 2] = Math.min(points[i][1], points[i + 1][1]) - pad;
  415. boxes[i * 4 + 3] = Math.max(points[i][1], points[i + 1][1]) + pad;
  416. }
  417. return { points, widths, boxes };
  418. }
  419. if (shape.kind === "body") {
  420. const s = shape.poly.map(([value]) => value);
  421. return { axis: [flat(add3(shape.F.o, mul3(shape.F.a, Math.min(...s)))), flat(add3(shape.F.o, mul3(shape.F.a, Math.max(...s))))], reach: Math.max(...shape.poly.map(([, r]) => r)) * cam.k };
  422. }
  423. return null;
  424. });
  425. const x0 = Math.floor(Math.min(...boxes.map((b) => b[0])) / step);
  426. const y0 = Math.floor(Math.min(...boxes.map((b) => b[1])) / step);
  427. const x1 = Math.ceil(Math.max(...boxes.map((b) => b[2])) / step);
  428. const y1 = Math.ceil(Math.max(...boxes.map((b) => b[3])) / step);
  429. const w = x1 - x0 + 1;
  430. const h = y1 - y0 + 1;
  431. return { x0, y0, x1, y1, w, h, boxes, shapes, guides, depth: null };
  432. }
  433. function depthAt(raster, cam, step, cx, cy) {
  434. if (!raster.depth) {
  435. raster.depth = new Float32Array(raster.w * raster.h);
  436. raster.done = new Uint8Array(raster.w * raster.h);
  437. }
  438. const cell = (cy - raster.y0) * raster.w + (cx - raster.x0);
  439. if (raster.done[cell]) return raster.depth[cell];
  440. const x = cx * step;
  441. const y = cy * step;
  442. const c = add3(mul3(cam.R, (x - cam.origin[0]) / cam.k), mul3(cam.D, (y - cam.origin[1]) / cam.k));
  443. let best = NaN;
  444. for (let index = 0; index < raster.shapes.length; index++) {
  445. const shape = raster.shapes[index];
  446. const b = raster.boxes[index];
  447. if (x < b[0] || x > b[2] || y < b[1] || y > b[3]) continue;
  448. const guide = raster.guides[index];
  449. let segments = null;
  450. if (shape.kind === "tube") {
  451. segments = [];
  452. const boxes = guide.boxes;
  453. for (let i = 0; i < guide.points.length - 1; i++) {
  454. if (x < boxes[i * 4] || x > boxes[i * 4 + 1] || y < boxes[i * 4 + 2] || y > boxes[i * 4 + 3]) continue;
  455. if (flatDistance(x, y, guide.points[i], guide.points[i + 1]) <= Math.max(guide.widths[i], guide.widths[i + 1]) + step * 0.5) segments.push(i);
  456. }
  457. if (!segments.length) continue;
  458. } else if (shape.kind === "body" && flatDistance(x, y, guide.axis[0], guide.axis[1]) > guide.reach + step) continue;
  459. const t = rayDepth(shape, c, cam.V, 0.02, segments);
  460. if (t !== null && !(t <= best)) best = t;
  461. }
  462. raster.depth[cell] = best;
  463. raster.done[cell] = 1;
  464. return best;
  465. }
  466. function regionOf(flags, gw, gh, value, step) {
  467. const n = gw * gh;
  468. const on = new Uint8Array(n);
  469. let all = 0;
  470. let inner = 0;
  471. for (let cell = 0; cell < n; cell++) if (flags[cell] === value) (on[cell] = 1), all++;
  472. if (!all) return { all, inner, area: 0 };
  473. const grow = new Uint8Array(n);
  474. for (let y = 0; y < gh; y++)
  475. for (let x = 0; x < gw; x++) {
  476. const cell = y * gw + x;
  477. if (on[cell] && x > 0 && x < gw - 1 && y > 0 && y < gh - 1 && on[cell - 1] && on[cell + 1] && on[cell - gw] && on[cell + gw]) inner++;
  478. if (on[cell] || (x > 0 && on[cell - 1]) || (x < gw - 1 && on[cell + 1]) || (y > 0 && on[cell - gw]) || (y < gh - 1 && on[cell + gw])) grow[cell] = 1;
  479. }
  480. const shut = new Uint8Array(n);
  481. for (let y = 0; y < gh; y++)
  482. for (let x = 0; x < gw; x++) {
  483. const cell = y * gw + x;
  484. shut[cell] = on[cell] || (grow[cell] && (x === 0 || grow[cell - 1]) && (x === gw - 1 || grow[cell + 1]) && (y === 0 || grow[cell - gw]) && (y === gh - 1 || grow[cell + gw])) ? 1 : 0;
  485. }
  486. const core = new Uint8Array(n);
  487. for (let y = 1; y < gh - 1; y++)
  488. for (let x = 1; x < gw - 1; x++) {
  489. const cell = y * gw + x;
  490. core[cell] = shut[cell] && shut[cell - 1] && shut[cell + 1] && shut[cell - gw] && shut[cell + gw] ? 1 : 0;
  491. }
  492. const seen = new Uint8Array(n);
  493. const stack = new Int32Array(n);
  494. let largest = 0;
  495. for (let start = 0; start < n; start++) {
  496. if (!core[start] || seen[start]) continue;
  497. let top = 0;
  498. let size = 0;
  499. stack[top++] = start;
  500. seen[start] = 1;
  501. while (top) {
  502. const cell = stack[--top];
  503. size++;
  504. const x = cell % gw;
  505. const y = (cell - x) / gw;
  506. const visit = (next) => {
  507. if (core[next] && !seen[next]) (seen[next] = 1), (stack[top++] = next);
  508. };
  509. if (x > 0) visit(cell - 1);
  510. if (x < gw - 1) visit(cell + 1);
  511. if (y > 0) visit(cell - gw);
  512. if (y < gh - 1) visit(cell + gw);
  513. }
  514. if (size > largest) largest = size;
  515. }
  516. return { all, inner, area: largest * step * step };
  517. }
  518. function measure(ra, rb, dx, dy, dz, cam, step, tolerance, least) {
  519. if (ra.x1 < rb.x0 + dx || rb.x1 + dx < ra.x0 || ra.y1 < rb.y0 + dy || rb.y1 + dy < ra.y0) return null;
  520. const ix0 = Math.max(ra.x0, rb.x0 + dx);
  521. const ix1 = Math.min(ra.x1, rb.x1 + dx);
  522. const iy0 = Math.max(ra.y0, rb.y0 + dy);
  523. const iy1 = Math.min(ra.y1, rb.y1 + dy);
  524. const gw = ix1 - ix0 + 1;
  525. const gh = iy1 - iy0 + 1;
  526. const flags = new Int8Array(gw * gh);
  527. const worst = [0, 0];
  528. const at = [null, null];
  529. let any = false;
  530. for (let y = iy0; y <= iy1; y++) {
  531. for (let x = ix0; x <= ix1; x++) {
  532. const ta = depthAt(ra, cam, step, x, y);
  533. if (Number.isNaN(ta)) continue;
  534. const tb = depthAt(rb, cam, step, x - dx, y - dy) + dz;
  535. if (Number.isNaN(tb)) continue;
  536. const cell = (y - iy0) * gw + (x - ix0);
  537. if (ta > tb + tolerance) {
  538. flags[cell] = 1;
  539. any = true;
  540. if (ta - tb > worst[0]) (worst[0] = ta - tb), (at[0] = [x * step, y * step]);
  541. } else if (tb > ta + tolerance) {
  542. flags[cell] = -1;
  543. any = true;
  544. if (tb - ta > worst[1]) (worst[1] = tb - ta), (at[1] = [x * step, y * step]);
  545. }
  546. }
  547. }
  548. if (!any) return null;
  549. const front = [regionOf(flags, gw, gh, 1, step), regionOf(flags, gw, gh, -1, step)];
  550. if (front[0].area < least && front[1].area < least) return null;
  551. return front.map((region, side) => ({ ...region, depth: worst[side], at: at[side] }));
  552. }
  553. export function overlapsOf(items, P, { step = 0.25, tolerance = 0.3, least = 0.25, states = [0], skip = () => false } = {}) {
  554. const cam = cameraBasis(P);
  555. const live = items.map((item, index) => ({ item, index })).filter(({ item }) => item.shapes && item.shapes.length);
  556. const homes = live.map(() => null);
  557. let uid = 0;
  558. const stamp = (raster) => Object.assign(raster, { uid: uid++ });
  559. const home = (index) => homes[index] ?? (homes[index] = stamp(rasterOf(live[index].item, cam, step, [0, 0, 0])));
  560. const sliding = live.map(({ item }) => item.shapes.some((shape) => shape.slide));
  561. const slid = new Map();
  562. const rasterAt = (index, offset) => {
  563. if (!sliding[index]) return home(index);
  564. const id = `${index}|${offset.map((v) => v.toFixed(2)).join(",")}`;
  565. if (!slid.has(id)) slid.set(id, stamp(rasterOf(live[index].item, cam, step, offset)));
  566. return slid.get(id);
  567. };
  568. const shiftOf = (offset) => ({ gx: Math.round((dot3(offset, cam.R) * cam.k) / step), gy: Math.round((dot3(offset, cam.D) * cam.k) / step), dz: dot3(offset, cam.V) });
  569. const memo = new Map();
  570. const pairs = [];
  571. for (const state of states) {
  572. const offsets = live.map(({ item }) => offsetOf(item, state));
  573. const shifts = live.map((_, index) => (sliding[index] ? { gx: 0, gy: 0, dz: 0 } : shiftOf(offsets[index])));
  574. for (let a = 0; a < live.length; a++) {
  575. const ra = rasterAt(a, offsets[a]);
  576. const sa = shifts[a];
  577. for (let b = a + 1; b < live.length; b++) {
  578. const rb = rasterAt(b, offsets[b]);
  579. const sb = shifts[b];
  580. if (ra.x1 + sa.gx < rb.x0 + sb.gx || rb.x1 + sb.gx < ra.x0 + sa.gx || ra.y1 + sa.gy < rb.y0 + sb.gy || rb.y1 + sb.gy < ra.y0 + sa.gy) continue;
  581. if (skip(live[a].item, live[b].item)) continue;
  582. const dx = sb.gx - sa.gx;
  583. const dy = sb.gy - sa.gy;
  584. const dz = sb.dz - sa.dz;
  585. const id = `${ra.uid}|${rb.uid}|${dx},${dy},${dz.toFixed(3)}`;
  586. let hit = memo.get(id);
  587. if (hit === undefined) {
  588. hit = measure(ra, rb, dx, dy, dz, cam, step, tolerance, least);
  589. memo.set(id, hit);
  590. }
  591. if (!hit) continue;
  592. pairs.push({ state, a: live[a].index, b: live[b].index, front: hit.map((side) => ({ ...side, at: side.at && [side.at[0] + sa.gx * step, side.at[1] + sa.gy * step] })) });
  593. }
  594. }
  595. }
  596. return { pairs, least, states, step, V: cam.V };
  597. }
  598. const liftOf = (item, V) => dot3(item.move ?? [0, 0, 0], V);
  599. export const keyAt = (item, state, V) => item.key + liftOf(item, V) * shareOf(item, state);
  600. export function orderKeys(items, overlaps, { gap = 0.02, rounds = 0 } = {}) {
  601. const { pairs, least, V } = overlaps;
  602. const start = items.map((item) => item.key);
  603. const strongest = new Map();
  604. const cycles = [];
  605. for (const pair of pairs) {
  606. const aFront = pair.front[0].area >= least;
  607. const bFront = pair.front[1].area >= least;
  608. if (aFront && bFront) {
  609. cycles.push(pair);
  610. continue;
  611. }
  612. const [front, back] = aFront ? [pair.a, pair.b] : [pair.b, pair.a];
  613. const weight = pair.front[aFront ? 0 : 1].area;
  614. const need = gap + shareOf(items[back], pair.state) * liftOf(items[back], V) - shareOf(items[front], pair.state) * liftOf(items[front], V);
  615. const id = `${front}|${back}`;
  616. const prior = strongest.get(id);
  617. if (!prior) strongest.set(id, { front, back, weight, pair, need });
  618. else {
  619. prior.weight = Math.max(prior.weight, weight);
  620. if (need > prior.need) (prior.need = need), (prior.pair = pair);
  621. }
  622. }
  623. const rules = [...strongest.values()];
  624. const limit = rounds || Math.min(items.length + 1, 400);
  625. const dropped = [];
  626. let keys = start.slice();
  627. let active = rules.slice();
  628. for (let attempt = 0; attempt < 400; attempt++) {
  629. keys = start.slice();
  630. const by = new Array(items.length).fill(null);
  631. let changed = true;
  632. let round = 0;
  633. let last = -1;
  634. for (; changed && round < limit; round++) {
  635. changed = false;
  636. for (const rule of active) {
  637. if (keys[rule.front] - keys[rule.back] >= rule.need - 1e-9) continue;
  638. keys[rule.front] = keys[rule.back] + rule.need;
  639. by[rule.front] = rule;
  640. last = rule.front;
  641. changed = true;
  642. }
  643. }
  644. if (!changed) break;
  645. const seen = new Map();
  646. let node = last;
  647. let step = 0;
  648. while (node !== -1 && by[node] && !seen.has(node) && step < items.length * 2) {
  649. seen.set(node, step++);
  650. node = by[node].back;
  651. }
  652. const loop = [];
  653. if (node !== -1 && seen.has(node)) {
  654. let walk = node;
  655. do {
  656. loop.push(by[walk]);
  657. walk = by[walk].back;
  658. } while (walk !== node && loop.length <= items.length);
  659. }
  660. const victim = (loop.length ? loop : active.filter((rule) => keys[rule.front] - keys[rule.back] < rule.need - 1e-9)).reduce((low, rule) => (rule.weight < low.weight ? rule : low));
  661. dropped.push(victim);
  662. active = active.filter((rule) => rule !== victim);
  663. }
  664. return { keys, rules: rules.length, cycles, dropped };
  665. }
  666. export function depthOrder(items, P, options = {}) {
  667. const overlaps = options.overlaps ?? overlapsOf(items, P, options);
  668. const { pairs, least, states, V } = overlaps;
  669. const allow = options.allow ?? [];
  670. const dropped = new Set((options.solved?.dropped ?? []).map((rule) => `${rule.front}|${rule.back}`));
  671. const missing = items.filter((item) => !item.shapes || !item.shapes.length).map((item) => item.name);
  672. const ranks = new Map();
  673. for (const state of states) {
  674. const order = items.map((item, index) => ({ index, key: keyAt(item, state, V) })).sort((x, y) => x.key - y.key || x.index - y.index);
  675. const rank = new Int32Array(items.length);
  676. order.forEach(({ index }, position) => (rank[index] = position));
  677. ranks.set(state, rank);
  678. }
  679. const rest = options.rest ?? states.filter((state) => state === 0 || state === 1);
  680. const problems = [];
  681. const passing = [];
  682. for (const pair of pairs) {
  683. const rank = ranks.get(pair.state);
  684. const aFirst = rank[pair.a] < rank[pair.b];
  685. const wrong = pair.front[aFirst ? 0 : 1];
  686. const right = pair.front[aFirst ? 1 : 0];
  687. if (wrong.area < least) continue;
  688. const front = items[aFirst ? pair.a : pair.b];
  689. const back = items[aFirst ? pair.b : pair.a];
  690. const excused = allow.find(([x, y]) => (matches([x], front.name) && matches([y], back.name)) || (matches([y], front.name) && matches([x], back.name)));
  691. const entry = {
  692. state: pair.state,
  693. label: labelOf(pair.state),
  694. front: front.name,
  695. back: back.name,
  696. frontKey: keyAt(front, pair.state, V),
  697. backKey: keyAt(back, pair.state, V),
  698. cells: wrong.all,
  699. area: wrong.area,
  700. against: right.area,
  701. cycle: right.area >= least,
  702. depth: wrong.depth,
  703. at: wrong.at,
  704. };
  705. const front_ = aFirst ? pair.a : pair.b;
  706. const back_ = aFirst ? pair.b : pair.a;
  707. entry.unorderable = !rest.includes(pair.state) && dropped.has(`${front_}|${back_}`);
  708. const replayed = typeof pair.state !== "number";
  709. (!excused && (rest.includes(pair.state) || replayed || (!entry.cycle && !entry.unorderable)) ? problems : passing).push(entry);
  710. }
  711. return { problems, passing, missing };
  712. }
  713. function samplesOf(shape, spacing) {
  714. const dense = resample(shape.points, spacing);
  715. const total = pathLength(shape.points) || 1;
  716. const lengths = [0];
  717. for (let index = 1; index < shape.points.length; index++) lengths.push(lengths[index - 1] + len3(sub3(shape.points[index], shape.points[index - 1])));
  718. const radiusAt = (at) => {
  719. let index = 1;
  720. while (index < lengths.length - 1 && lengths[index] < at) index++;
  721. const span = lengths[index] - lengths[index - 1] || 1;
  722. const t = Math.max(0, Math.min(1, (at - lengths[index - 1]) / span));
  723. return shape.radii[index - 1] + (shape.radii[index] - shape.radii[index - 1]) * t;
  724. };
  725. const step = total / Math.max(1, dense.length - 1);
  726. return dense.map((p, index) => {
  727. const t = unit3(sub3(dense[Math.min(dense.length - 1, index + 1)], dense[Math.max(0, index - 1)]));
  728. return { p, t, along: index * step, edge: Math.min(index * step, total - index * step), r: radiusAt(index * step) };
  729. });
  730. }
  731. const overlaps = (a, b, pad) => a.min.every((v, i) => v - pad <= b.max[i] && b.min[i] - pad <= a.max[i]);
  732. function centreline(shape, p) {
  733. let best = { d: BIG, r: 0 };
  734. for (let index = 0; index < shape.points.length - 1; index++) {
  735. const { d, t } = segmentPoint(p, shape.points[index], shape.points[index + 1]);
  736. if (d < best.d) best = { d, r: shape.radii[index] + (shape.radii[index + 1] - shape.radii[index]) * t };
  737. }
  738. return best;
  739. }
  740. const matches = (list, name) =>
  741. (list ?? []).some((entry) => {
  742. if (typeof entry === "function") return entry(name);
  743. if (entry.endsWith("*")) return name.startsWith(entry.slice(0, -1));
  744. return name === entry || name.startsWith(entry + ".") || name.startsWith(entry + ":") || name.startsWith(entry + "#");
  745. });
  746. const sameOffset = (a, b) => Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]) + Math.abs(a[2] - b[2]) < 1e-6;
  747. const placed = (shape, state) => (state === undefined || !shape.move ? shape : moved(shape, offsetOf(shape, state)));
  748. const offsetAt = (shape, state) => (state === undefined || !shape.move ? [0, 0, 0] : offsetOf(shape, state));
  749. function tipDistance(other, p) {
  750. if (other.kind === "tube") {
  751. const { d, r } = centreline(other, p);
  752. return d - r;
  753. }
  754. return sdf(other, p);
  755. }
  756. function rimOf(tube, index) {
  757. const tip = tube.tips[index];
  758. const axis = tube.tipAxes ? tube.tipAxes[index] : unit3(index ? sub3(tube.points[tube.points.length - 1], tube.points[tube.points.length - 2]) : sub3(tube.points[1], tube.points[0]));
  759. const radius = tube.tipRims ? tube.tipRims[index] : tube.radii[index ? tube.radii.length - 1 : 0];
  760. const helper = Math.abs(axis[2]) > 0.9 ? [1, 0, 0] : [0, 0, 1];
  761. const u = unit3([helper[1] * axis[2] - helper[2] * axis[1], helper[2] * axis[0] - helper[0] * axis[2], helper[0] * axis[1] - helper[1] * axis[0]]);
  762. const v = [axis[1] * u[2] - axis[2] * u[1], axis[2] * u[0] - axis[0] * u[2], axis[0] * u[1] - axis[1] * u[0]];
  763. return Array.from({ length: 12 }, (_, k) => add3(tip, add3(mul3(u, radius * Math.cos((k * Math.PI) / 6)), mul3(v, radius * Math.sin((k * Math.PI) / 6)))));
  764. }
  765. export function mountsOf(tubes, solids, { tolerance = 0.15 } = {}) {
  766. const byName = new Map(tubes.map((tube) => [tube.name, tube]));
  767. const out = new Map();
  768. for (const tube of tubes) {
  769. const found = [null, null];
  770. (tube.tips ?? []).forEach((tip, index) => {
  771. if (!tip) return;
  772. const rim = rimOf(tube, index);
  773. let best = null;
  774. const consider = (other) => {
  775. if (other === tube || (other.owner && other.owner === tube.owner) || other.name === tube.owner || other.anchor === false) return;
  776. const { min, max } = boundsOf(other);
  777. if (!overlaps({ min: tip, max: tip }, { min, max }, 3 + (tube.tipRims ? tube.tipRims[index] : 0))) return;
  778. const ds = rim.map((p) => tipDistance(other, p));
  779. const score = (Math.abs(tipDistance(other, tip)) + ds.reduce((sum, d) => sum + Math.abs(d), 0) / ds.length) / 2;
  780. if (!best || score < best.score) best = { shape: other, score, d: tipDistance(other, tip), high: Math.max(...ds), low: Math.min(...ds) };
  781. };
  782. solids.forEach(consider);
  783. tubes.forEach(consider);
  784. if (best && byName.get(best.shape.owner) && best.shape.kind !== "tube") best.host = byName.get(best.shape.owner);
  785. found[index] = best && { ...best, tip, landed: best.high <= tolerance && best.low >= -tolerance };
  786. });
  787. out.set(tube, found);
  788. }
  789. return out;
  790. }
  791. function ringAround(sample, r) {
  792. const axis = sample.t;
  793. const helper = Math.abs(axis[2]) > 0.9 ? [1, 0, 0] : [0, 0, 1];
  794. const u = unit3([helper[1] * axis[2] - helper[2] * axis[1], helper[2] * axis[0] - helper[0] * axis[2], helper[0] * axis[1] - helper[1] * axis[0]]);
  795. const v = [axis[1] * u[2] - axis[2] * u[1], axis[2] * u[0] - axis[0] * u[2], axis[0] * u[1] - axis[1] * u[0]];
  796. return Array.from({ length: 12 }, (_, k) => add3(sample.p, add3(mul3(u, r * Math.cos((k * Math.PI) / 6)), mul3(v, r * Math.sin((k * Math.PI) / 6)))));
  797. }
  798. export function clearances(tubes, solids, { ratio = 0.5, least = 0.2, spacing = 0.5, touching = -0.05, through = -0.1, state, only, mounts = mountsOf(tubes, solids) } = {}) {
  799. const gapOf = (r) => Math.max(least, ratio * r);
  800. const problems = new Map();
  801. const note = (tube, other, kind, clearance, need, sample) => {
  802. if (only && kind !== only) return;
  803. const id = `${tube.name}|${other.name}`;
  804. const prior = problems.get(id);
  805. if (prior && prior.clearance <= clearance) {
  806. prior.from = Math.min(prior.from, sample.along);
  807. prior.to = Math.max(prior.to, sample.along);
  808. return;
  809. }
  810. problems.set(id, { tube: tube.name, other: other.name, kind, clearance, need, at: sample.p, from: prior ? Math.min(prior.from, sample.along) : sample.along, to: prior ? Math.max(prior.to, sample.along) : sample.along, length: pathLength(tube.points), state: state === undefined ? "" : labelOf(state) });
  811. };
  812. const poseOf = new Map([...tubes, ...solids].map((shape) => [shape, placed(shape, state)]));
  813. const offsets = new Map([...tubes, ...solids].map((shape) => [shape, offsetAt(shape, state)]));
  814. const together = (a, b) => len3(sub3(offsets.get(a), offsets.get(b))) < 0.05;
  815. const runsBy = new Map();
  816. for (const tube of tubes) runsBy.set(tube.owner, [...(runsBy.get(tube.owner) ?? []), tube]);
  817. const tipsOf = (owner) => (runsBy.get(owner) ?? []).flatMap((run) => (mounts.get(run) ?? []).filter(Boolean).map((mount) => ({ run, mount })));
  818. const seatedOn = (shape, owner) => shape && shape.cut && [shape.cut].flat().some((cut) => cut.owner === owner);
  819. const zone = (r) => r + gapOf(r) + 1;
  820. const ownerOf = (other) => other.owner ?? other.name;
  821. const related = (tube, other, sample) => {
  822. if (seatedOn(other, tube.owner)) return true;
  823. const tips = tipsOf(tube.owner);
  824. const near = (entry) => len3(sub3(sample.p, add3(entry.mount.tip, offsets.get(entry.run)))) <= zone(sample.r) + (entry.run.tipRims ? Math.max(...entry.run.tipRims) : 0);
  825. for (const entry of tips) {
  826. if (!near(entry) || !together(tube, entry.mount.shape)) continue;
  827. const mount = entry.mount.shape;
  828. if (mount === other || (entry.mount.host && (entry.mount.host === other || other.owner === entry.mount.host.owner))) return true;
  829. if (tipsOf(ownerOf(other)).some((theirs) => theirs.mount.shape === mount)) return true;
  830. }
  831. for (const entry of tipsOf(ownerOf(other))) {
  832. const mount = entry.mount.shape;
  833. const lands = mount.owner === tube.owner || seatedOn(mount, tube.owner);
  834. if (!lands || !together(entry.run, tube)) continue;
  835. if (len3(sub3(sample.p, add3(entry.mount.tip, offsets.get(entry.run)))) <= zone(sample.r) + (entry.run.tipRims ? Math.max(...entry.run.tipRims) : 0) + sample.r) return true;
  836. }
  837. return false;
  838. };
  839. const nearTip = (tube, sample) => {
  840. const at = (tube.offset ?? 0) + sample.along;
  841. const total = tube.total ?? pathLength(tube.points);
  842. const tips = mounts.get(tube) ?? [null, null];
  843. return (tips[0] && at <= zone(sample.r)) || (tips[1] && total - at <= zone(sample.r));
  844. };
  845. const clearanceTo = (other, sample) => {
  846. if (sample.edge >= sample.r) return sdf(other, sample.p) - sample.r;
  847. return Math.min(...ringAround(sample, sample.r).map((q) => sdf(other, q)));
  848. };
  849. for (const tube of tubes) {
  850. const posed = poseOf.get(tube);
  851. const samples = samplesOf(posed, spacing);
  852. const tb = boundsOf(posed);
  853. for (const shape of solids) {
  854. if (shape.owner && shape.owner === tube.owner) continue;
  855. if (matches(tube.touch, shape.name) || matches(shape.touch, tube.name)) continue;
  856. const other = poseOf.get(shape);
  857. const ob = boundsOf(other);
  858. if (!overlaps(tb, ob, 4)) continue;
  859. for (const sample of samples) {
  860. if (!overlaps({ min: sample.p, max: sample.p }, ob, sample.r + 3)) continue;
  861. const gap = gapOf(sample.r);
  862. const clearance = clearanceTo(other, sample);
  863. if (clearance >= gap) continue;
  864. if (related(tube, shape, sample)) continue;
  865. if (nearTip(tube, sample) && clearance >= through) continue;
  866. note(tube, shape, clearance < 0 ? "through" : "close", clearance, gap, sample);
  867. }
  868. }
  869. }
  870. for (let a = 0; a < tubes.length; a++) {
  871. const ta = poseOf.get(tubes[a]);
  872. const samples = samplesOf(ta, spacing);
  873. for (let b = 0; b < tubes.length; b++) {
  874. if (a === b) continue;
  875. const tb = poseOf.get(tubes[b]);
  876. if (tubes[a].owner && tubes[a].owner === tubes[b].owner && tubes[a].joined) continue;
  877. if (matches(tubes[a].touch, tubes[b].name) || matches(tubes[b].touch, tubes[a].name)) continue;
  878. if (!overlaps(boundsOf(ta), boundsOf(tb), 3)) continue;
  879. const bundled = tubes[a].bundle && tubes[a].bundle === tubes[b].bundle;
  880. for (const sample of samples) {
  881. if (!overlaps({ min: sample.p, max: sample.p }, boundsOf(tb), sample.r + 3)) continue;
  882. const clearance = sample.edge >= sample.r ? sdf(tb, sample.p) - sample.r : Math.min(...ringAround(sample, sample.r).map((q) => sdf(tb, q)));
  883. const r = centreline(tb, sample.p).r;
  884. const gap = bundled ? touching : gapOf(Math.min(sample.r, r));
  885. if (clearance >= gap) continue;
  886. if (related(tubes[a], tubes[b], sample)) continue;
  887. if (nearTip(tubes[a], sample) && clearance >= through) continue;
  888. if (a > b && problems.has(`${tubes[b].name}|${tubes[a].name}`)) continue;
  889. note(tubes[a], tubes[b], clearance < 0 ? "through" : "close", clearance, gap, sample);
  890. }
  891. }
  892. }
  893. const seen = new Set();
  894. return [...problems.values()]
  895. .sort((x, y) => x.clearance - y.clearance)
  896. .filter((c) => {
  897. const id = [c.tube, c.other].sort().join("|");
  898. if (seen.has(id)) return false;
  899. seen.add(id);
  900. return true;
  901. });
  902. }
  903. export function terminals(tubes, solids, { tolerance = 0.15, mounts = mountsOf(tubes, solids, { tolerance }) } = {}) {
  904. const out = [];
  905. for (const tube of tubes) {
  906. (mounts.get(tube) ?? []).forEach((mount, index) => {
  907. if (!tube.tips || !tube.tips[index] || (mount && mount.landed)) return;
  908. out.push({ tube: tube.name, end: index ? "end" : "start", at: tube.tips[index], d: mount ? mount.d : Infinity, high: mount ? mount.high : Infinity, low: mount ? mount.low : -Infinity, nearest: mount ? mount.shape.name : "nothing" });
  909. });
  910. }
  911. return out;
  912. }
  913. export function looseEnds(tubes, solids, { state = 1, tolerance = 0.15 } = {}) {
  914. const out = [];
  915. for (const tube of tubes) {
  916. const offset = offsetAt(tube, state);
  917. (tube.tips ?? []).forEach((tip, index) => {
  918. if (!tip) return;
  919. const hit = solids.some((shape) => {
  920. if ((shape.owner && shape.owner === tube.owner) || shape.name === tube.owner) return false;
  921. if (!sameOffset(offsetAt(shape, state), offset)) return false;
  922. const { min, max } = boundsOf(shape);
  923. return overlaps({ min: tip, max: tip }, { min, max }, 1) && sdf(shape, tip) <= tolerance;
  924. });
  925. if (!hit) out.push({ tube: tube.name, end: index ? "end" : "start", at: add3(tip, offset), state: labelOf(state), free: Boolean(tube.free && tube.free[index]) });
  926. });
  927. }
  928. return out;
  929. }
  930. function surfaceOf(shape, spacing = 0.6) {
  931. const points = [];
  932. if (shape.kind === "body") {
  933. const { F, poly } = shape;
  934. const u = F.u ?? unit3(Math.abs(F.a[2]) > 0.9 ? [1, 0, 0] : [-F.a[1], F.a[0], 0]);
  935. const v = F.v ?? [F.a[1] * u[2] - F.a[2] * u[1], F.a[2] * u[0] - F.a[0] * u[2], F.a[0] * u[1] - F.a[1] * u[0]];
  936. for (let i = 0; i < poly.length - 1; i++) {
  937. const [s0, r0] = poly[i];
  938. const [s1, r1] = poly[i + 1];
  939. const steps = Math.max(1, Math.ceil(Math.hypot(s1 - s0, r1 - r0) / spacing));
  940. for (let j = 0; j <= steps; j++) {
  941. const s = s0 + ((s1 - s0) * j) / steps;
  942. const r = r0 + ((r1 - r0) * j) / steps;
  943. const around = Math.max(1, Math.min(160, Math.ceil((2 * Math.PI * r) / spacing)));
  944. for (let k = 0; k < around; k++) {
  945. const t = (k / around) * 2 * Math.PI;
  946. points.push(add3(add3(F.o, mul3(F.a, s)), add3(mul3(u, r * Math.cos(t)), mul3(v, r * Math.sin(t)))));
  947. }
  948. }
  949. }
  950. } else if (shape.kind === "box") {
  951. for (let axis = 0; axis < 3; axis++)
  952. for (const sign of [-1, 1]) {
  953. const o1 = (axis + 1) % 3;
  954. const o2 = (axis + 2) % 3;
  955. const n1 = Math.max(1, Math.ceil((2 * shape.half[o1]) / spacing));
  956. const n2 = Math.max(1, Math.ceil((2 * shape.half[o2]) / spacing));
  957. for (let i = 0; i <= n1; i++)
  958. for (let j = 0; j <= n2; j++) {
  959. const c = [0, 0, 0];
  960. c[axis] = sign * shape.half[axis];
  961. c[o1] = -shape.half[o1] + (2 * shape.half[o1] * i) / n1;
  962. c[o2] = -shape.half[o2] + (2 * shape.half[o2] * j) / n2;
  963. points.push(add3(shape.o, add3(add3(mul3(shape.axes[0], c[0]), mul3(shape.axes[1], c[1])), mul3(shape.axes[2], c[2]))));
  964. }
  965. }
  966. } else if (shape.kind === "prism") {
  967. const { F, poly, s0, s1 } = shape;
  968. const at = (s, x, y) => add3(add3(F.o, mul3(F.a, s)), add3(mul3(F.u, x), mul3(F.v, y)));
  969. const rows = Math.max(1, Math.ceil((s1 - s0) / spacing));
  970. for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
  971. const [x0, y0] = poly[j];
  972. const [x1, y1] = poly[i];
  973. const steps = Math.max(1, Math.ceil(Math.hypot(x1 - x0, y1 - y0) / spacing));
  974. for (let k = 0; k < steps; k++)
  975. for (let row = 0; row <= rows; row++) points.push(at(s0 + ((s1 - s0) * row) / rows, x0 + ((x1 - x0) * k) / steps, y0 + ((y1 - y0) * k) / steps));
  976. }
  977. const xs = poly.map(([x]) => x);
  978. const ys = poly.map(([, y]) => y);
  979. for (let x = Math.min(...xs); x <= Math.max(...xs); x += spacing)
  980. for (let y = Math.min(...ys); y <= Math.max(...ys); y += spacing) if (polygonDistance(poly, x, y) < 0) points.push(at(s0, x, y), at(s1, x, y));
  981. } else if (shape.kind === "ball") {
  982. const count = Math.max(24, Math.min(600, Math.ceil((4 * Math.PI * shape.r * shape.r) / (spacing * spacing))));
  983. for (let i = 0; i < count; i++) {
  984. const z = 1 - (2 * (i + 0.5)) / count;
  985. const ring = Math.sqrt(1 - z * z);
  986. const t = i * 2.399963;
  987. points.push(add3(shape.o, mul3([ring * Math.cos(t), ring * Math.sin(t), z], shape.r)));
  988. }
  989. if (shape.flats) {
  990. const kept = points.filter((p) => shape.flats.every(([nx, ny, nz, cut]) => nx * (p[0] - shape.o[0]) + ny * (p[1] - shape.o[1]) + nz * (p[2] - shape.o[2]) <= cut + 1e-9));
  991. points.length = 0;
  992. points.push(...kept);
  993. for (const [nx, ny, nz, cut] of shape.flats) {
  994. const n = [nx, ny, nz];
  995. const helper = Math.abs(nz) > 0.9 ? [1, 0, 0] : [0, 0, 1];
  996. const u = unit3([helper[1] * nz - helper[2] * ny, helper[2] * nx - helper[0] * nz, helper[0] * ny - helper[1] * nx]);
  997. const v = [ny * u[2] - nz * u[1], nz * u[0] - nx * u[2], nx * u[1] - ny * u[0]];
  998. const rho = Math.sqrt(Math.max(0, shape.r * shape.r - cut * cut));
  999. const centre = add3(shape.o, mul3(n, cut));
  1000. for (let x = -rho; x <= rho; x += spacing)
  1001. for (let y = -rho; y <= rho; y += spacing) {
  1002. if (x * x + y * y > rho * rho) continue;
  1003. const p = add3(centre, add3(mul3(u, x), mul3(v, y)));
  1004. if (shape.flats.every(([mx, my, mz, other]) => mx * (p[0] - shape.o[0]) + my * (p[1] - shape.o[1]) + mz * (p[2] - shape.o[2]) <= other + 1e-6)) points.push(p);
  1005. }
  1006. }
  1007. }
  1008. } else {
  1009. for (const { p, r } of samplesOf(shape, spacing)) for (let k = 0; k < 8; k++) points.push(add3(p, mul3([Math.cos((k * Math.PI) / 4), Math.sin((k * Math.PI) / 4), 0], r)));
  1010. }
  1011. return shape.cut ? points.filter((p) => cutDistance(shape, p) >= -1e-3) : points;
  1012. }
  1013. const seatedOn = (shape, host) => Boolean(shape.seated && shape.cut && [shape.cut].flat().some((cut) => cut === host || (cut.name && cut.name === host.name)));
  1014. export const grounded = (shape) => Boolean(shape.ground) || (shape.name ?? "").startsWith("stand.");
  1015. export function supports(solids, tubes, { ground = grounded, touch = 0.15, sunk = 0.5 } = {}) {
  1016. const nodes = [...solids, ...tubes.filter((tube) => !tube.limp)];
  1017. const surfaces = nodes.map((shape) => surfaceOf(shape));
  1018. const links = nodes.map(() => []);
  1019. const deep = [];
  1020. for (let a = 0; a < nodes.length; a++) {
  1021. const ba = boundsOf(nodes[a]);
  1022. for (let b = a + 1; b < nodes.length; b++) {
  1023. const bb = boundsOf(nodes[b]);
  1024. if (!overlaps(ba, bb, touch + 0.05)) continue;
  1025. const same = (nodes[a].owner && (nodes[a].owner === nodes[b].owner || nodes[a].owner === nodes[b].name)) || (nodes[b].owner && nodes[b].owner === nodes[a].name);
  1026. let gap = BIG;
  1027. for (const p of surfaces[a]) gap = Math.min(gap, sdf(nodes[b], p));
  1028. for (const p of surfaces[b]) gap = Math.min(gap, sdf(nodes[a], p));
  1029. if (gap <= touch) links[a].push(b), links[b].push(a);
  1030. const solidPair = nodes[a].kind !== "tube" && nodes[b].kind !== "tube";
  1031. if (solidPair && !same && gap < -sunk && !seatedOn(nodes[a], nodes[b]) && !seatedOn(nodes[b], nodes[a])) deep.push({ a: nodes[a].name, b: nodes[b].name, depth: -gap });
  1032. }
  1033. }
  1034. const held = new Uint8Array(nodes.length);
  1035. const queue = [];
  1036. nodes.forEach((shape, index) => ground(shape) && ((held[index] = 1), queue.push(index)));
  1037. while (queue.length) {
  1038. const index = queue.pop();
  1039. for (const next of links[index]) if (!held[next]) (held[next] = 1), queue.push(next);
  1040. }
  1041. const loose = nodes.filter((_, index) => !held[index] && nodes[index].kind !== "tube").map((shape) => shape.name);
  1042. const hanging = nodes.filter((_, index) => !held[index] && nodes[index].kind === "tube").map((shape) => shape.name);
  1043. return { loose, hanging, sunk: deep.sort((x, y) => y.depth - x.depth) };
  1044. }
  1045. export function folds(routes, P, { fold = 140, turn = 110, pinch = 2, items = null } = {}) {
  1046. const cam = cameraBasis(P);
  1047. const entries = items ? entriesOf(items, cam) : null;
  1048. const shown = (name, p) => !entries || frontAt(entries, cam, cam.origin[0] + dot3(p, cam.R) * cam.k, cam.origin[1] + dot3(p, cam.D) * cam.k) === name;
  1049. const flat = (p) => [dot3(p, cam.R) * cam.k, dot3(p, cam.D) * cam.k];
  1050. const angle = (a, b) => (Math.acos(Math.max(-1, Math.min(1, (a[0] * b[0] + a[1] * b[1]) / (Math.hypot(a[0], a[1]) * Math.hypot(b[0], b[1]) || 1)))) * 180) / Math.PI;
  1051. const out = [];
  1052. for (const { name, points, r } of routes) {
  1053. const step = Math.max(0.25, r * 0.5);
  1054. const dense = resample(points, step);
  1055. const screen = dense.map(flat);
  1056. const reach = Math.max(2, Math.round((4 * r) / step));
  1057. const width = r * cam.k;
  1058. let worst = null;
  1059. for (const span of [1.5, 3, 6]) {
  1060. const near = Math.max(1, Math.round((span * r) / step));
  1061. for (let i = near; i < dense.length - near; i++) {
  1062. const p0 = screen[i - near];
  1063. const p1 = screen[i];
  1064. const p2 = screen[i + near];
  1065. const a = [p1[0] - p0[0], p1[1] - p0[1]];
  1066. const b = [p2[0] - p1[0], p2[1] - p1[1]];
  1067. const c = [p2[0] - p0[0], p2[1] - p0[1]];
  1068. const la = Math.hypot(a[0], a[1]);
  1069. const lb = Math.hypot(b[0], b[1]);
  1070. if (la < width * 0.3 || lb < width * 0.3) continue;
  1071. const bend = angle(a, b);
  1072. const area = Math.abs(a[0] * b[1] - a[1] * b[0]) / 2;
  1073. const radius = area > 1e-9 ? (la * lb * Math.hypot(c[0], c[1])) / (4 * area) : Infinity;
  1074. if (bend > 90 && radius < pinch * width && (!worst || radius < worst.radius) && shown(name, dense[i])) worst = { name, kind: "pinch", flatTurn: bend, radius, width, at: dense[i], index: i };
  1075. }
  1076. }
  1077. if (worst) {
  1078. let toStart = 0;
  1079. for (let i = 1; i <= worst.index; i++) toStart += Math.hypot(screen[i][0] - screen[i - 1][0], screen[i][1] - screen[i - 1][1]);
  1080. let toEnd = 0;
  1081. for (let i = worst.index + 1; i < screen.length; i++) toEnd += Math.hypot(screen[i][0] - screen[i - 1][0], screen[i][1] - screen[i - 1][1]);
  1082. if (Math.min(toStart, toEnd) > 3 * width) out.push(worst);
  1083. }
  1084. for (let i = reach; i < dense.length - reach; i++) {
  1085. const a = [screen[i][0] - screen[i - reach][0], screen[i][1] - screen[i - reach][1]];
  1086. const b = [screen[i + reach][0] - screen[i][0], screen[i + reach][1] - screen[i][1]];
  1087. if (Math.hypot(a[0], a[1]) < 1e-6 || Math.hypot(b[0], b[1]) < 1e-6) continue;
  1088. const flatTurn = angle(a, b);
  1089. const A3 = sub3(dense[i], dense[i - reach]);
  1090. const B3 = sub3(dense[i + reach], dense[i]);
  1091. const realTurn = (Math.acos(Math.max(-1, Math.min(1, dot3(A3, B3) / (len3(A3) * len3(B3) || 1)))) * 180) / Math.PI;
  1092. if (flatTurn > fold && realTurn < turn && shown(name, dense[i])) {
  1093. out.push({ name, kind: "fold", flatTurn, realTurn, at: dense[i] });
  1094. i += 2 * reach;
  1095. }
  1096. }
  1097. }
  1098. return out;
  1099. }
  1100. export function linksOf(tubes, mounts) {
  1101. const links = new Map();
  1102. const link = (a, b) => {
  1103. if (!a || !b || a === b) return;
  1104. if (!links.has(a)) links.set(a, new Set());
  1105. if (!links.has(b)) links.set(b, new Set());
  1106. links.get(a).add(b);
  1107. links.get(b).add(a);
  1108. };
  1109. const ownerOf = (shape) => shape.owner ?? shape.name;
  1110. const seats = new Map();
  1111. for (const tube of tubes)
  1112. for (const mount of mounts.get(tube) ?? []) {
  1113. if (!mount) continue;
  1114. const host = ownerOf(mount.shape);
  1115. link(tube.owner, host);
  1116. if (!seats.has(host)) seats.set(host, []);
  1117. seats.get(host).push(tube.owner);
  1118. if (mount.shape.cut) for (const cut of [mount.shape.cut].flat()) link(tube.owner, ownerOf(cut));
  1119. }
  1120. for (const owners of seats.values()) for (const a of owners) for (const b of owners) link(a, b);
  1121. return links;
  1122. }
  1123. const entriesOf = (items, cam) => items.flatMap((item) => (item.shapes ?? []).map((shape) => ({ shape, box: screenBox(shape, cam, [0, 0, 0]).map((v, i) => v + (i < 2 ? -1 : 1)), owner: item.route ?? shape.owner ?? item.name, bundle: shape.bundle ?? null, item: item.name })));
  1124. function frontEntry(entries, cam, x, y) {
  1125. const c = add3(mul3(cam.R, (x - cam.origin[0]) / cam.k), mul3(cam.D, (y - cam.origin[1]) / cam.k));
  1126. let best = -BIG;
  1127. let who = null;
  1128. for (const entry of entries) {
  1129. const { shape, box } = entry;
  1130. if (x < box[0] || x > box[2] || y < box[1] || y > box[3]) continue;
  1131. const t = rayDepth(shape, c, cam.V, 0.02, null);
  1132. if (t !== null && t > best) (best = t), (who = entry);
  1133. }
  1134. return who;
  1135. }
  1136. function frontAt(entries, cam, x, y) {
  1137. const entry = frontEntry(entries, cam, x, y);
  1138. return entry ? entry.owner : null;
  1139. }
  1140. const belongs = (entry, name, bundle) => Boolean(entry) && (entry.owner === name || entry.item === name || (bundle && entry.bundle === bundle));
  1141. export function slenderOf(solids, { ratio = 4, least = 0.3 } = {}) {
  1142. const out = [];
  1143. const axisLine = (centre, axis, half, r, shape) => {
  1144. out.push({ name: shape.owner ?? shape.name, solid: shape.name, owners: new Set([shape.name, shape.owner].filter(Boolean)), points: [add3(centre, mul3(axis, -half)), add3(centre, mul3(axis, half))], r, move: shape.move, ride: shape.ride, piece: shape.piece, rod: true });
  1145. };
  1146. for (const shape of solids) {
  1147. if (!shape || shape.kind === "tube" || shape.kind === "ball" || shape.fitting) continue;
  1148. if (shape.kind === "body") {
  1149. const s = shape.poly.map(([value]) => value);
  1150. const s0 = Math.min(...s);
  1151. const s1 = Math.max(...s);
  1152. const r = Math.max(...shape.poly.map(([, value]) => value));
  1153. if (r >= least && s1 - s0 >= ratio * r) axisLine(add3(shape.F.o, mul3(shape.F.a, (s0 + s1) / 2)), shape.F.a, (s1 - s0) / 2, r, shape);
  1154. continue;
  1155. }
  1156. let axes;
  1157. let half;
  1158. let centre;
  1159. if (shape.kind === "prism") {
  1160. const xs = shape.poly.map(([x]) => x);
  1161. const ys = shape.poly.map(([, y]) => y);
  1162. const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];
  1163. axes = [shape.F.u, shape.F.v, shape.F.a];
  1164. half = [(x1 - x0) / 2, (y1 - y0) / 2, (shape.s1 - shape.s0) / 2];
  1165. centre = add3(shape.F.o, add3(add3(mul3(shape.F.u, (x0 + x1) / 2), mul3(shape.F.v, (y0 + y1) / 2)), mul3(shape.F.a, (shape.s0 + shape.s1) / 2)));
  1166. } else if (shape.kind === "box") {
  1167. axes = shape.axes;
  1168. half = shape.half;
  1169. centre = shape.o;
  1170. } else continue;
  1171. const order = [0, 1, 2].sort((a, b) => half[b] - half[a]);
  1172. const r = half[order[1]];
  1173. if (r >= least && half[order[0]] >= ratio * r) axisLine(centre, axes[order[0]], half[order[0]], r, shape);
  1174. }
  1175. return out;
  1176. }
  1177. export function crowding(routes, P, { gap = 1, bend = 30, links = new Map(), items = null, allow = [], state, clear = 2, rods = [] } = {}) {
  1178. const cam = cameraBasis(P);
  1179. const shift = (thing) => (state === undefined ? [0, 0, 0] : offsetOf(thing, state));
  1180. const entries = items ? entriesOf(items.map((item) => ({ ...item, shapes: (item.shapes ?? []).map((shape) => moved(shape, shift(item))) })), cam) : null;
  1181. const bundles = new Map(routes.map((route) => [route.name, route.bundle]));
  1182. const shown = (owner, x, y, rod) => {
  1183. if (!entries) return true;
  1184. const entry = frontEntry(entries, cam, x, y);
  1185. if (rod) return Boolean(entry) && (entry.shape.name === rod.solid || (!entry.shape.name && entry.item === rod.solid));
  1186. return belongs(entry, owner, bundles.get(owner));
  1187. };
  1188. const flat = (p) => [cam.origin[0] + dot3(p, cam.R) * cam.k, cam.origin[1] + dot3(p, cam.D) * cam.k];
  1189. const lines = [...routes, ...rods].map((route) => {
  1190. const step = Math.max(0.25, route.r * 0.5);
  1191. const offset = shift(route);
  1192. const dense = resample(route.points.map((p) => add3(p, offset)), step);
  1193. return { ...route, step, dense, screen: dense.map(flat), width: route.r * cam.k };
  1194. });
  1195. const marksOf = (line) => {
  1196. const out = [];
  1197. const reach = Math.max(2, Math.round((2 * line.r) / line.step));
  1198. const last = line.dense.length - 1;
  1199. for (let i = 0; i <= last; i++) {
  1200. if (i <= reach || i >= last - reach) {
  1201. out.push({ i, where: i <= reach ? "start" : "end" });
  1202. continue;
  1203. }
  1204. const A = sub3(line.dense[i], line.dense[i - reach]);
  1205. const B = sub3(line.dense[i + reach], line.dense[i]);
  1206. const turn = (Math.acos(Math.max(-1, Math.min(1, dot3(A, B) / (len3(A) * len3(B) || 1)))) * 180) / Math.PI;
  1207. if (turn > bend) out.push({ i, where: "bend" });
  1208. }
  1209. return out;
  1210. };
  1211. const found = new Map();
  1212. for (const a of lines) {
  1213. if (a.rod) continue;
  1214. const marks = marksOf(a);
  1215. for (const b of lines) {
  1216. if (a === b || (a.bundle && a.bundle === b.bundle) || links.get(a.name)?.has(b.name)) continue;
  1217. if (b.rod && [...b.owners].some((name) => name === a.name || links.get(a.name)?.has(name))) continue;
  1218. if (allow.some(([x, y]) => [b.name, b.solid].filter(Boolean).some((name) => (matches([x], a.name) && matches([y], name)) || (matches([y], a.name) && matches([x], name))))) continue;
  1219. for (const { i, where } of marks) {
  1220. const [x, y] = a.screen[i];
  1221. let best = { d: BIG, j: -1 };
  1222. for (let j = 0; j < b.screen.length; j++) {
  1223. const d = Math.hypot(b.screen[j][0] - x, b.screen[j][1] - y);
  1224. if (d < best.d) best = { d, j };
  1225. }
  1226. const touch = best.d - a.width - b.width;
  1227. if (touch >= gap) continue;
  1228. if (where !== "bend" && touch <= -2 * Math.min(a.width, b.width)) {
  1229. const tip = a.screen[where === "start" ? 0 : a.screen.length - 1];
  1230. let clearTip = BIG;
  1231. for (const q of b.screen) clearTip = Math.min(clearTip, Math.hypot(q[0] - tip[0], q[1] - tip[1]));
  1232. const reachB = Math.max(2, Math.round((2 * b.r) / b.step));
  1233. const j0 = Math.max(0, best.j - reachB);
  1234. const j1 = Math.min(b.dense.length - 1, best.j + reachB);
  1235. const straight = j1 - j0 >= 2 && dot3(unit3(sub3(b.dense[best.j], b.dense[j0])), unit3(sub3(b.dense[j1], b.dense[best.j]))) > Math.cos((bend * Math.PI) / 180);
  1236. if (straight && clearTip > b.width + a.width + 1) continue;
  1237. }
  1238. const [bx, by] = b.screen[best.j];
  1239. const u = [(bx - x) / (best.d || 1), (by - y) / (best.d || 1)];
  1240. const inA = Math.max(0.2, a.width - 0.35);
  1241. const inB = Math.max(0.2, b.width - 0.35);
  1242. if (!shown(a.name, x + u[0] * inA, y + u[1] * inA)) continue;
  1243. if (b.rod) {
  1244. if (!shown(b.name, bx - u[0] * inB, by - u[1] * inB, b) && !shown(b.name, bx + u[0] * inB, by + u[1] * inB, b)) continue;
  1245. } else if (!shown(b.name, bx - u[0] * inB, by - u[1] * inB)) continue;
  1246. const depth = Math.abs(dot3(sub3(a.dense[i], b.dense[best.j]), cam.V));
  1247. const need = 2 * (a.r + b.r);
  1248. const id = [a.name, b.name].sort().join("|");
  1249. const prior = found.get(id);
  1250. if (!prior || Math.abs(touch) < Math.abs(prior.gap)) found.set(id, { a: a.name, b: b.rod ? `${b.solid} (rod)` : b.name, where, gap: touch, depth, need, screen: [x, y], at: a.dense[i], state: state === undefined ? "" : labelOf(state) });
  1251. }
  1252. }
  1253. }
  1254. if (entries)
  1255. for (const fitting of entries.filter((entry) => entry.shape.fitting && entry.shape.kind === "body")) {
  1256. const { shape } = fitting;
  1257. const reach = Math.max(...shape.poly.map(([, r]) => r));
  1258. const [x, y] = flat(shape.F.o);
  1259. for (const b of lines) {
  1260. if (b.rod) continue;
  1261. if ((fitting.bundle && b.bundle === fitting.bundle) || b.name === fitting.owner || links.get(fitting.owner)?.has(b.name)) continue;
  1262. if (allow.some(([p, q]) => (matches([p], fitting.item) && matches([q], b.name)) || (matches([q], fitting.item) && matches([p], b.name)))) continue;
  1263. let best = { d: BIG, j: -1 };
  1264. for (let j = 0; j < b.screen.length; j++) {
  1265. const d = Math.hypot(b.screen[j][0] - x, b.screen[j][1] - y);
  1266. if (d < best.d) best = { d, j };
  1267. }
  1268. const touch = best.d - reach * cam.k - b.width;
  1269. if (touch >= clear) continue;
  1270. const front = frontEntry(entries, cam, x, y);
  1271. if (!(front === fitting || belongs(front, fitting.owner, fitting.bundle))) continue;
  1272. const id = [fitting.item, b.name].sort().join("|");
  1273. const prior = found.get(id);
  1274. if (!prior || Math.abs(touch) < Math.abs(prior.gap)) found.set(id, { a: fitting.item, b: b.name, where: "fitting", gap: touch, depth: Math.abs(dot3(sub3(shape.F.o, b.dense[best.j]), cam.V)), need: 0, screen: [x, y], at: shape.F.o, state: state === undefined ? "" : labelOf(state) });
  1275. }
  1276. }
  1277. return [...found.values()].sort((x, y) => Math.abs(x.gap) - Math.abs(y.gap));
  1278. }
  1279. const multiply = (m, n) => [m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1], m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3], m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5]];
  1280. function matrixOf(text) {
  1281. let m = [1, 0, 0, 1, 0, 0];
  1282. if (!text) return m;
  1283. for (const [, kind, args] of text.matchAll(/(matrix|translate|scale|rotate)\s*\(([^)]*)\)/g)) {
  1284. const v = (args.match(/-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi) ?? []).map(Number);
  1285. let n = [1, 0, 0, 1, 0, 0];
  1286. if (kind === "matrix" && v.length === 6) n = v;
  1287. else if (kind === "translate") n = [1, 0, 0, 1, v[0] ?? 0, v[1] ?? 0];
  1288. else if (kind === "scale") n = [v[0] ?? 1, 0, 0, v[1] ?? v[0] ?? 1, 0, 0];
  1289. else if (kind === "rotate") {
  1290. const a = ((v[0] ?? 0) * Math.PI) / 180;
  1291. const [cx, cy] = [v[1] ?? 0, v[2] ?? 0];
  1292. n = multiply(multiply([1, 0, 0, 1, cx, cy], [Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]), [1, 0, 0, 1, -cx, -cy]);
  1293. }
  1294. m = multiply(m, n);
  1295. }
  1296. return m;
  1297. }
  1298. const NUMBER = /-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi;
  1299. function pointsOfShape(tag, attrs) {
  1300. const get = (name) => {
  1301. const hit = attrs.match(new RegExp(`(?:^|\\s)${name}="([^"]*)"`));
  1302. return hit ? hit[1] : null;
  1303. };
  1304. const num = (name) => Number(get(name) ?? 0);
  1305. if (tag === "path") {
  1306. const d = get("d") ?? "";
  1307. const out = [];
  1308. let x = 0;
  1309. let y = 0;
  1310. for (const [, command, args] of d.matchAll(/([MmLlHhVvCcSsQqTtAaZz])([^MmLlHhVvCcSsQqTtAaZz]*)/g)) {
  1311. const v = (args.match(NUMBER) ?? []).map(Number);
  1312. const rel = command === command.toLowerCase();
  1313. const C = command.toUpperCase();
  1314. const pair = (i) => [v[i] + (rel ? x : 0), v[i + 1] + (rel ? y : 0)];
  1315. const take = (p) => {
  1316. out.push(p);
  1317. return p;
  1318. };
  1319. if (C === "H") for (const value of v) [x] = take([value + (rel ? x : 0), y]);
  1320. else if (C === "V") for (const value of v) [, y] = take([x, value + (rel ? y : 0)]);
  1321. else if (C === "A") for (let i = 0; i + 6 < v.length; i += 7) [x, y] = take([v[i + 5] + (rel ? x : 0), v[i + 6] + (rel ? y : 0)]);
  1322. else if (C !== "Z") {
  1323. const width = C === "C" ? 6 : C === "S" || C === "Q" ? 4 : 2;
  1324. for (let i = 0; i + 1 < v.length; i += width) {
  1325. for (let j = 0; j < width; j += 2) out.push(pair(i + j));
  1326. [x, y] = pair(i + width - 2);
  1327. }
  1328. }
  1329. }
  1330. return out;
  1331. }
  1332. if (tag === "circle" || tag === "ellipse") {
  1333. const r = Number(get("r") ?? get("rx") ?? 0);
  1334. const ry = Number(get("r") ?? get("ry") ?? 0);
  1335. return [[num("cx") - r, num("cy") - ry], [num("cx") + r, num("cy") + ry]];
  1336. }
  1337. if (tag === "line") return [[num("x1"), num("y1")], [num("x2"), num("y2")]];
  1338. if (tag === "rect") return [[num("x"), num("y")], [num("x") + num("width"), num("y") + num("height")]];
  1339. if (tag === "polyline" || tag === "polygon") {
  1340. const v = (get("points") ?? "").match(NUMBER)?.map(Number) ?? [];
  1341. const out = [];
  1342. for (let i = 0; i + 1 < v.length; i += 2) out.push([v[i], v[i + 1]]);
  1343. return out;
  1344. }
  1345. return [];
  1346. }
  1347. const boxOfPoints = (points, m) => {
  1348. let box = null;
  1349. for (const [x, y] of points) {
  1350. const px = m[0] * x + m[2] * y + m[4];
  1351. const py = m[1] * x + m[3] * y + m[5];
  1352. box = box ? [Math.min(box[0], px), Math.min(box[1], py), Math.max(box[2], px), Math.max(box[3], py)] : [px, py, px, py];
  1353. }
  1354. return box;
  1355. };
  1356. const unionBox = (a, b) => (!a ? b : !b ? a : [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[2], b[2]), Math.max(a[3], b[3])]);
  1357. const meetBox = (a, b) => (!a || !b ? a ?? null : [Math.max(a[0], b[0]), Math.max(a[1], b[1]), Math.min(a[2], b[2]), Math.min(a[3], b[3])]);
  1358. const areaOf = (box) => (box ? Math.max(0, box[2] - box[0]) * Math.max(0, box[3] - box[1]) : 0);
  1359. export function markupBox(svg) {
  1360. const tags = [...svg.matchAll(/<(\/?)([a-zA-Z]+)([^>]*?)(\/?)>/g)];
  1361. const clips = new Map();
  1362. let clipId = null;
  1363. for (const [, close, tag, attrs, self] of tags) {
  1364. if (tag === "clipPath" && !close) {
  1365. clipId = self ? null : (attrs.match(/id="([^"]*)"/) ?? [])[1] ?? null;
  1366. continue;
  1367. }
  1368. if (clipId) {
  1369. if (tag === "clipPath" && close) {
  1370. clipId = null;
  1371. continue;
  1372. }
  1373. clips.set(clipId, unionBox(clips.get(clipId), boxOfPoints(pointsOfShape(tag, attrs), matrixOf((attrs.match(/transform="([^"]*)"/) ?? [])[1]))));
  1374. }
  1375. }
  1376. const stack = [{ m: [1, 0, 0, 1, 0, 0], clip: null, skip: false }];
  1377. let box = null;
  1378. for (const [, close, tag, attrs, self] of tags) {
  1379. const top = stack[stack.length - 1];
  1380. if (close) {
  1381. if (stack.length > 1) stack.pop();
  1382. continue;
  1383. }
  1384. const m = multiply(top.m, matrixOf((attrs.match(/transform="([^"]*)"/) ?? [])[1]));
  1385. const ref = (attrs.match(/clip-path="url\(#([^)]*)\)"/) ?? [])[1];
  1386. const own = ref && clips.get(ref) ? boxOfPoints([[clips.get(ref)[0], clips.get(ref)[1]], [clips.get(ref)[2], clips.get(ref)[3]]], m) : null;
  1387. const frame = { m, clip: own ? meetBox(top.clip ?? own, own) : top.clip, skip: top.skip || ["defs", "clipPath", "mask", "linearGradient", "radialGradient", "pattern", "text", "title"].includes(tag) || /class="[^"]*iso-halo/.test(attrs) };
  1388. if (!frame.skip) {
  1389. const shape = boxOfPoints(pointsOfShape(tag, attrs), m);
  1390. if (shape) box = unionBox(box, frame.clip ? meetBox(shape, frame.clip) : shape);
  1391. }
  1392. if (!self) stack.push(frame);
  1393. }
  1394. return box;
  1395. }
  1396. export function footprintOf(shape, cam) {
  1397. const flat = (p) => [cam.origin[0] + dot3(p, cam.R) * cam.k, cam.origin[1] + dot3(p, cam.D) * cam.k];
  1398. if (shape.kind === "body") {
  1399. const { F } = shape;
  1400. const points = [];
  1401. for (const [s, r] of shape.poly) {
  1402. if (r <= 0) {
  1403. points.push(flat(add3(F.o, mul3(F.a, s))));
  1404. continue;
  1405. }
  1406. for (let i = 0; i < 16; i++) {
  1407. const a = (i / 16) * Math.PI * 2;
  1408. points.push(flat(add3(add3(F.o, mul3(F.a, s)), add3(mul3(F.u, r * Math.cos(a)), mul3(F.v, r * Math.sin(a))))));
  1409. }
  1410. }
  1411. return boxOfPoints(points, [1, 0, 0, 1, 0, 0]);
  1412. }
  1413. if (shape.kind === "prism") {
  1414. const { F } = shape;
  1415. const points = [];
  1416. for (const s of [shape.s0, shape.s1]) for (const [x, y] of shape.poly) points.push(flat(add3(add3(F.o, mul3(F.a, s)), add3(mul3(F.u, x), mul3(F.v, y)))));
  1417. return boxOfPoints(points, [1, 0, 0, 1, 0, 0]);
  1418. }
  1419. const [x0, y0, x1, y1] = screenBox(shape, cam, [0, 0, 0]);
  1420. return [x0, y0, x1, y1];
  1421. }
  1422. export function coverage(items, P, { least = 0.6, pad = 1, allow = [] } = {}) {
  1423. const cam = cameraBasis(P);
  1424. const out = [];
  1425. for (const item of items) {
  1426. if (typeof item.svg !== "string" || !item.shapes || !item.shapes.length || matches(allow, item.name)) continue;
  1427. const drawn = markupBox(item.svg);
  1428. if (!drawn) continue;
  1429. const grow = (box) => [box[0] - pad, box[1] - pad, box[2] + pad, box[3] + pad];
  1430. const shapes = item.shapes.map((shape) => footprintOf(shape, cam)).reduce(unionBox, null);
  1431. const share = areaOf(meetBox(grow(drawn), grow(shapes))) / (areaOf(grow(drawn)) || 1);
  1432. if (share < least) out.push({ name: item.name, share, drawn, shapes });
  1433. }
  1434. return out.sort((a, b) => a.share - b.share);
  1435. }
  1436. export function selfOverlaps(items, P, { entries: given = null, fold = 0.25, least = 0.5 } = {}) {
  1437. const cam = cameraBasis(P);
  1438. const entries = given ?? entriesOf(items, cam);
  1439. const flat = (p) => [cam.origin[0] + dot3(p, cam.R) * cam.k, cam.origin[1] + dot3(p, cam.D) * cam.k];
  1440. const out = [];
  1441. for (const item of items) {
  1442. if (!item.route || !item.shapes || !item.shapes.length || item.shapes[0].kind !== "tube") continue;
  1443. const shape = item.shapes[0];
  1444. const r = shape.radii.reduce((sum, value) => sum + value, 0) / shape.radii.length;
  1445. const dense = resample(shape.points, Math.max(0.1, r * 0.2));
  1446. const screen = dense.map(flat);
  1447. const n = screen.length;
  1448. if (n < 4) continue;
  1449. const width = r * cam.k;
  1450. const span = 3;
  1451. const normals = screen.map((_, i) => {
  1452. const a = screen[Math.max(0, i - span)];
  1453. const b = screen[Math.min(n - 1, i + span)];
  1454. const length = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
  1455. return [-(b[1] - a[1]) / length, (b[0] - a[0]) / length];
  1456. });
  1457. let worst = null;
  1458. for (const side of [1, -1]) {
  1459. const edge = screen.map((p, i) => [p[0] + side * normals[i][0] * width, p[1] + side * normals[i][1] * width]);
  1460. for (let i = span; i < n - span - 1; i++) {
  1461. const along = [screen[i + 1][0] - screen[i][0], screen[i + 1][1] - screen[i][1]];
  1462. const step = [edge[i + 1][0] - edge[i][0], edge[i + 1][1] - edge[i][1]];
  1463. const length = Math.hypot(along[0], along[1]);
  1464. if (length < 1e-6) continue;
  1465. const forward = (step[0] * along[0] + step[1] * along[1]) / length;
  1466. if (forward > -fold * length) continue;
  1467. const x = (screen[i][0] + screen[i + 1][0]) / 2;
  1468. const y = (screen[i][1] + screen[i + 1][1]) / 2;
  1469. const front = frontEntry(entries, cam, x, y);
  1470. if (front && front.owner !== item.route && front.item !== item.name) continue;
  1471. const radius = Math.abs(forward / length - 1) > 1e-6 ? width / Math.abs(1 - forward / length) : Infinity;
  1472. if (width - radius < least) continue;
  1473. if (!worst || radius < worst.radius) worst = { name: item.name, route: item.route, radius, width, at: dense[i], screen: [x, y] };
  1474. }
  1475. }
  1476. if (worst) out.push(worst);
  1477. }
  1478. return out;
  1479. }
  1480. export function solidClearances(solids, { state, sunk = 0.5, spacing = 0.6, cell = 4 } = {}) {
  1481. const list = solids.filter((shape) => shape.kind !== "tube").map((shape) => (shape.slide && state !== undefined && shape.move ? { ...moved(shape, offsetOf(shape, state)), move: undefined } : shape));
  1482. if (!solidClearances.cache) solidClearances.cache = new WeakMap();
  1483. const cache = solidClearances.cache;
  1484. const gridOf = (shape) => {
  1485. let grid = cache.get(shape);
  1486. if (grid) return grid;
  1487. grid = new Map();
  1488. for (const p of surfaceOf(shape, spacing)) {
  1489. const key = p.map((v) => Math.floor(v / cell)).join(",");
  1490. if (!grid.has(key)) grid.set(key, []);
  1491. grid.get(key).push(p);
  1492. }
  1493. cache.set(shape, grid);
  1494. return grid;
  1495. };
  1496. const pointsIn = (shape, box) => {
  1497. const grid = gridOf(shape);
  1498. const lo = box.min.map((v) => Math.floor(v / cell));
  1499. const hi = box.max.map((v) => Math.floor(v / cell));
  1500. const out = [];
  1501. if ((hi[0] - lo[0] + 1) * (hi[1] - lo[1] + 1) * (hi[2] - lo[2] + 1) > grid.size) {
  1502. for (const points of grid.values()) for (const p of points) if (p.every((v, i) => v >= box.min[i] && v <= box.max[i])) out.push(p);
  1503. return out;
  1504. }
  1505. for (let x = lo[0]; x <= hi[0]; x++)
  1506. for (let y = lo[1]; y <= hi[1]; y++)
  1507. for (let z = lo[2]; z <= hi[2]; z++) {
  1508. const points = grid.get(`${x},${y},${z}`);
  1509. if (points) for (const p of points) if (p.every((v, i) => v >= box.min[i] && v <= box.max[i])) out.push(p);
  1510. }
  1511. return out;
  1512. };
  1513. const offsets = list.map((shape) => offsetAt(shape, state));
  1514. const bounds = list.map((shape) => boundsOf(shape));
  1515. const found = [];
  1516. for (let a = 0; a < list.length; a++)
  1517. for (let b = a + 1; b < list.length; b++) {
  1518. const rel = sub3(offsets[a], offsets[b]);
  1519. if (Math.abs(rel[0]) + Math.abs(rel[1]) + Math.abs(rel[2]) < 1e-6) continue;
  1520. const box = { min: [0, 1, 2].map((i) => Math.max(bounds[a].min[i] + rel[i], bounds[b].min[i])), max: [0, 1, 2].map((i) => Math.min(bounds[a].max[i] + rel[i], bounds[b].max[i])) };
  1521. if (box.min.some((v, i) => v > box.max[i] - sunk)) continue;
  1522. if (seatedOn(list[a], list[b]) || seatedOn(list[b], list[a])) continue;
  1523. let worst = -sunk;
  1524. let at = null;
  1525. const local = { min: sub3(box.min, rel), max: sub3(box.max, rel) };
  1526. for (const p of pointsIn(list[a], local)) {
  1527. const d = sdf(list[b], add3(p, rel));
  1528. if (d < worst) (worst = d), (at = add3(p, offsets[a]));
  1529. }
  1530. for (const p of pointsIn(list[b], box)) {
  1531. const d = sdf(list[a], sub3(p, rel));
  1532. if (d < worst) (worst = d), (at = add3(p, offsets[b]));
  1533. }
  1534. if (at) found.push({ tube: list[a].name, other: list[b].name, kind: "through", solid: true, clearance: worst, need: -sunk, at, from: 0, to: 0, length: 0, state: state === undefined ? "" : labelOf(state) });
  1535. }
  1536. return found.sort((x, y) => x.clearance - y.clearance);
  1537. }
  1538. export function wobble(solids, { samples = 20 } = {}) {
  1539. const out = [];
  1540. for (const shape of solids) {
  1541. const profile = shape.curve;
  1542. if (!profile) continue;
  1543. const segments = curveRuns(profile);
  1544. let run = [];
  1545. const flush = () => {
  1546. if (run.length) {
  1547. const values = [];
  1548. for (const index of run) {
  1549. const [s0] = profile[index];
  1550. const [s1] = profile[index + 1];
  1551. for (let j = values.length ? 1 : 0; j <= samples; j++) {
  1552. const s = s0 + ((s1 - s0) * j) / samples;
  1553. values.push([s, segments[index].slope(s)]);
  1554. }
  1555. }
  1556. const scale = Math.max(1, ...values.map(([, g]) => Math.abs(g))) * 1e-6;
  1557. const turns = [];
  1558. let last = 0;
  1559. for (let i = 1; i < values.length; i++) {
  1560. const d = values[i][1] - values[i - 1][1];
  1561. if (Math.abs(d) <= scale) continue;
  1562. const sign = Math.sign(d);
  1563. if (last && sign !== last) turns.push(Math.round(values[i - 1][0] * 100) / 100);
  1564. last = sign;
  1565. }
  1566. if (turns.length) out.push({ name: shape.name, at: turns, from: profile[run[0]][0], to: profile[run[run.length - 1] + 1][0] });
  1567. }
  1568. run = [];
  1569. };
  1570. segments.forEach((segment, index) => (segment ? run.push(index) : flush()));
  1571. flush();
  1572. }
  1573. return out;
  1574. }
  1575. export function seats(solids) {
  1576. const out = [];
  1577. for (const shape of solids) {
  1578. if (!shape.seated || !shape.cut) continue;
  1579. for (const host of [shape.cut].flat()) {
  1580. const mine = mul3(shape.move ?? [0, 0, 0], 1);
  1581. const theirs = mul3(host.move ?? [0, 0, 0], 1);
  1582. if ((shape.ride ?? shape.piece) === (host.ride ?? host.piece) && sameOffset(mine, theirs)) continue;
  1583. out.push({ name: shape.name, host: host.name, piece: shape.ride ?? shape.piece, hostPiece: host.ride ?? host.piece });
  1584. }
  1585. }
  1586. return out;
  1587. }
  1588. export function report({ clearance = [], depth = { problems: [], missing: [] }, terminals: ends, folds: bends, supports: held, loose, apart, flight, crowding: crowded, self, wobble: wobbly, seats: seated, cover: covered } = {}, { limit = 4000 } = {}) {
  1589. const lines = [];
  1590. const f = (v) => (Math.round(v * 100) / 100).toFixed(2);
  1591. const p3 = (p) => `[${p.map((v) => v.toFixed(1)).join(", ")}]`;
  1592. const clash = (c) => (c.solid ? ` solid ${c.state ? c.state + " " : ""}${c.tube} × ${c.other} sunk ${f(-c.clearance)} deep at ${p3(c.at)}` : ` ${c.kind.padEnd(7)} ${c.state ? c.state + " " : ""}${c.tube} × ${c.other} clearance ${f(c.clearance)} < ${f(c.need)} along ${f(c.from)}–${f(c.to)} of ${f(c.length)} at ${p3(c.at)}`);
  1593. lines.push(`clearance: ${clearance.length} problem${clearance.length === 1 ? "" : "s"}`);
  1594. for (const c of clearance.slice(0, limit)) lines.push(clash(c));
  1595. if (apart) {
  1596. lines.push(`clearance apart: ${apart.length} problem${apart.length === 1 ? "" : "s"}`);
  1597. for (const c of apart.slice(0, limit)) lines.push(clash(c));
  1598. }
  1599. if (ends) {
  1600. lines.push(`terminals: ${ends.length} end${ends.length === 1 ? "" : "s"} not on a mount`);
  1601. for (const e of ends.slice(0, limit)) lines.push(` ${e.tube} ${e.end} ${Number.isFinite(e.d) ? f(e.d) : "∞"} from ${e.nearest} (rim ${Number.isFinite(e.high) ? `${f(e.low)}…${f(e.high)}` : "-"}) at ${p3(e.at)}`);
  1602. }
  1603. if (loose) {
  1604. const hanging = loose.filter((e) => !e.free);
  1605. lines.push(`loose ends: ${hanging.length}`);
  1606. for (const e of hanging.slice(0, limit)) lines.push(` ${e.state} ${e.tube} ${e.end} touches nothing that moves with it at ${p3(e.at)}`);
  1607. }
  1608. if (bends) {
  1609. lines.push(`screen folds: ${bends.length}`);
  1610. for (const b of bends.slice(0, limit))
  1611. lines.push(b.kind === "pinch" ? ` ${b.name} turns ${b.flatTurn.toFixed(0)}° on screen round a ${f(b.radius)} px bend, under ${f(b.width * 2)} px for a ${f(b.width)} px tube at ${p3(b.at)}` : ` ${b.name} turns ${b.flatTurn.toFixed(0)}° on screen for ${b.realTurn.toFixed(0)}° in 3D at ${p3(b.at)}`);
  1612. }
  1613. if (held) {
  1614. const hanging = held.hanging ?? [];
  1615. lines.push(`support: ${held.loose.length} unsupported solid${held.loose.length === 1 ? "" : "s"} · ${hanging.length} hanging tube${hanging.length === 1 ? "" : "s"} · ${held.sunk.length} sunk pair${held.sunk.length === 1 ? "" : "s"}`);
  1616. for (const name of held.loose.slice(0, limit)) lines.push(` loose ${name}`);
  1617. for (const name of hanging.slice(0, limit)) lines.push(` hanging ${name}`);
  1618. for (const d of held.sunk.slice(0, limit)) lines.push(` sunk ${d.a} × ${d.b} ${f(d.depth)} deep`);
  1619. }
  1620. lines.push(`depth order: ${depth.problems.length} problem${depth.problems.length === 1 ? "" : "s"}`);
  1621. for (const d of depth.problems.slice(0, limit))
  1622. lines.push(` ${d.cycle ? "cycle " : "order "} ${d.label} ${d.front} (k ${f(d.frontKey)}) is in front of ${d.back} (k ${f(d.backKey)}) but drawn first ${f(d.area)} px²${d.against ? ` (${f(d.against)} px² the other way)` : ""}, up to ${f(d.depth)} nearer, at ${d.at.map((v) => v.toFixed(1)).join(",")}`);
  1623. if (flight) {
  1624. lines.push(`through in mid-flight: ${flight.length} pair${flight.length === 1 ? "" : "s"}`);
  1625. for (const c of flight.slice(0, limit)) lines.push(clash(c));
  1626. }
  1627. if (self) {
  1628. lines.push(`self-overlap: ${self.length} chunk${self.length === 1 ? "" : "s"} whose outline crosses itself on screen`);
  1629. for (const c of self.slice(0, limit)) lines.push(` ${c.name} its outline folds back on screen: the line turns on a ${f(c.radius)} px radius, under its ${f(c.width)} px half-width at ${p3(c.at)}, screen ${c.screen.map((v) => v.toFixed(1)).join(",")}`);
  1630. }
  1631. if (wobbly) {
  1632. lines.push(`wobble: ${wobbly.length} smoothed profile${wobbly.length === 1 ? "" : "s"} whose slope turns between its ends`);
  1633. for (const w of wobbly.slice(0, limit)) lines.push(` ${w.name} dr/ds turns at s = ${w.at.join(", ")} on the run ${f(w.from)}–${f(w.to)}; give it an analytic profile and smooth.slope`);
  1634. }
  1635. if (seated) {
  1636. lines.push(`saddles off their host apart: ${seated.length}`);
  1637. for (const d of seated.slice(0, limit)) lines.push(` ${d.name} (${d.piece}) is cut to ${d.host} (${d.hostPiece}); apart, its cut base is on show`);
  1638. }
  1639. if (covered) {
  1640. lines.push(`stand-in shapes: ${covered.length} item${covered.length === 1 ? "" : "s"} whose recorded shape covers too little of what it draws`);
  1641. for (const c of covered.slice(0, limit)) lines.push(` ${c.name} its shapes cover ${Math.round(c.share * 100)}% of its drawing (drawn ${c.drawn.map((v) => v.toFixed(0)).join(",")}, recorded ${c.shapes.map((v) => v.toFixed(0)).join(",")}); record the true shape of what you draw`);
  1642. }
  1643. if (crowded) {
  1644. lines.push(`crowding: ${crowded.length} pair${crowded.length === 1 ? "" : "s"} where a bend or end touches another line on screen`);
  1645. for (const c of crowded.slice(0, limit)) lines.push(` ${c.state ? c.state + " " : ""}${c.a} ${c.where} × ${c.b} outlines ${c.gap < 0 ? `overlap ${f(-c.gap)}` : `${f(c.gap)} apart`} px, ${f(c.depth)} apart in depth at screen ${c.screen.map((v) => v.toFixed(1)).join(",")}`);
  1646. }
  1647. if (depth.passing && depth.passing.length) {
  1648. const pairs = (list) => new Set(list.map((d) => [d.front, d.back].sort().join("|"))).size;
  1649. lines.push(`in passing (uniform explode states only, not failing): ${pairs(depth.passing.filter((d) => d.cycle))} interlocked pairs, ${pairs(depth.passing.filter((d) => !d.cycle))} pairs no linear key can order`);
  1650. for (const d of depth.passing.slice(0, limit)) lines.push(` ${d.cycle ? "cycle " : "unorderable"} ${d.label} ${d.front} / ${d.back} ${f(d.area)} px²`);
  1651. }
  1652. if (depth.missing.length) lines.push(`items with no shape: ${depth.missing.length} ${depth.missing.slice(0, 20).join(", ")}`);
  1653. if (loose && loose.some((e) => e.free)) {
  1654. const free = loose.filter((e) => e.free);
  1655. lines.push(`free ends apart (marked free, not failing): ${free.length}`);
  1656. for (const e of free.slice(0, limit)) lines.push(` ${e.tube} ${e.end} at ${p3(e.at)}`);
  1657. }
  1658. return lines.join("\n");
  1659. }
  1660. export const failures = ({ clearance = [], depth = { problems: [], missing: [] }, terminals: ends = [], folds: bends = [], supports: held = { loose: [], sunk: [] }, loose = [], apart = [], flight = [], crowding: crowded = [], self = [], wobble: wobbly = [], seats: seated = [], cover: covered = [] }) =>
  1661. covered.length + clearance.length + apart.length + flight.length + crowded.length + ends.length + loose.filter((e) => !e.free).length + bends.length + held.loose.length + (held.hanging ?? []).length + held.sunk.length + depth.problems.length + depth.missing.length + self.length + wobbly.length + seated.length;
  1662. export const sameRun = (a, b) => Boolean(a.route) && a.route === b.route && Math.abs(a.chunk - b.chunk) <= 1;
  1663. export function recorder(P, { order = [], spring = {}, ground = grounded } = {}) {
  1664. const V = cameraBasis(P).V;
  1665. const counts = new Map();
  1666. const R = { P, V, order, spring, ground, items: [], solids: [], tubes: [], routes: [], settled: null };
  1667. R.nameFor = (base) => {
  1668. const count = (counts.get(base) ?? 0) + 1;
  1669. counts.set(base, count);
  1670. return count === 1 ? base : `${base}#${count}`;
  1671. };
  1672. R.solid = (shape) => {
  1673. R.solids.push(shape);
  1674. return shape;
  1675. };
  1676. R.put = ({ at = null, bias = 0, key, name, piece = "", move = [0, 0, 0], ride, shapes = [], ...rest } = {}) => {
  1677. const item = { ...rest, piece, ride: ride ?? piece, key: key ?? (at ? dot3(at, V) : 0) + bias, move, shapes, name: name ?? R.nameFor(`${piece || "item"}.item`) };
  1678. for (const shape of shapes) (shape.move = item.move), (shape.ride = item.ride), (shape.piece = piece);
  1679. R.items.push(item);
  1680. return item;
  1681. };
  1682. R.route = (name, points, radius, { owner = name, touch, bundle, limp = false, gaps = [], closed = false, ends = [true, true], rims, free = [false, false], piece = "", move = [0, 0, 0], ride = piece } = {}) => {
  1683. const total = pathLength(points);
  1684. const radiusOf = typeof radius === "function" ? radius : () => radius;
  1685. const runs = runsOf(total, gaps);
  1686. const recorded = runs.map(([from, to], index) => ({
  1687. ...tube(cutAlong(points, from, to), (t) => radiusOf((from + (to - from) * t) / total), { name, owner, touch, bundle, limp, joined: true }),
  1688. tips: closed ? [null, null] : [index === 0 && ends[0] ? points[0] : null, index === runs.length - 1 && ends[1] ? points[points.length - 1] : null],
  1689. tipAxes: [tangentAlong(points, 0), tangentAlong(points, total)],
  1690. tipRims: rims ?? [radiusOf(0), radiusOf(1)],
  1691. free: [index === 0 && free[0], index === runs.length - 1 && free[1]],
  1692. offset: from,
  1693. total,
  1694. move,
  1695. ride,
  1696. piece,
  1697. }));
  1698. R.tubes.push(...recorded);
  1699. R.routes.push({ name, points, r: radiusOf(0.5), bundle, move, ride, piece });
  1700. return recorded;
  1701. };
  1702. return R;
  1703. }
  1704. export function explodeStates(order = [], spring = {}, { uniform = 10, stride = 4 } = {}) {
  1705. if (!order.length) return { depth: [0], frames: [], apart: false };
  1706. const reversals = reversalsOf(order, spring.stagger ?? 0.035);
  1707. const prefix = prefixStates(order);
  1708. return {
  1709. depth: [...uniformStates(uniform), ...springStates(order, { ...spring, stride, reversals }), ...prefix],
  1710. frames: [...springStates(order, { ...spring, reversals }), ...prefix],
  1711. apart: true,
  1712. };
  1713. }
  1714. export function settle(R, P = R.P, { states = explodeStates(R.order, R.spring).depth, skip = sameRun, ...options } = {}) {
  1715. const items = R.items.slice();
  1716. const overlaps = overlapsOf(items, P, { states, skip, ...options });
  1717. const solved = orderKeys(items, overlaps);
  1718. items.forEach((item, index) => (item.key = solved.keys[index]));
  1719. R.settled = { items, overlaps, solved, states };
  1720. return R.settled;
  1721. }
  1722. const worstOf = (lists) => [...lists.flat().reduce((all, c) => (all.has(`${c.tube}|${c.other}`) && all.get(`${c.tube}|${c.other}`).clearance <= c.clearance ? all : all.set(`${c.tube}|${c.other}`, c)), new Map()).values()].sort((x, y) => x.clearance - y.clearance);
  1723. export function audit(R, P = R.P, { allow = [], crowd = [], cover = [], ground = R.ground, frames = explodeStates(R.order, R.spring).frames, apart = R.order.length > 0 } = {}) {
  1724. const { items, overlaps, solved } = R.settled ?? settle(R, P);
  1725. const mounts = mountsOf(R.tubes, R.solids);
  1726. const links = linksOf(R.tubes, mounts);
  1727. return {
  1728. clearance: clearances(R.tubes, R.solids, { mounts }),
  1729. apart: apart ? [...clearances(R.tubes, R.solids, { state: 1, mounts, only: "through" }), ...solidClearances(R.solids, { state: 1 })] : [],
  1730. flight: worstOf(frames.map((state) => [...clearances(R.tubes, R.solids, { state, mounts, only: "through" }), ...solidClearances(R.solids, { state })])),
  1731. crowding: (apart ? [0, 1] : [0]).flatMap((state) => crowding(R.routes, P, { links, items, allow: crowd, state, rods: slenderOf(R.solids) })),
  1732. cover: coverage(items, P, { allow: cover }),
  1733. terminals: terminals(R.tubes, R.solids, { mounts }),
  1734. loose: looseEnds(R.tubes, R.solids, { state: 1 }),
  1735. folds: folds(R.routes, P, { items }),
  1736. self: selfOverlaps(items, P),
  1737. wobble: wobble(R.solids),
  1738. seats: seats(R.solids),
  1739. supports: supports(R.solids, R.tubes, { ground }),
  1740. depth: depthOrder(items, P, { overlaps, solved, allow }),
  1741. };
  1742. }
  1743. export function auditOrExit(R, P = R.P, { flag = "--audit", argv = process.argv, ...options } = {}) {
  1744. if (!argv.includes(flag)) return null;
  1745. const started = Date.now();
  1746. const result = audit(R, P, options);
  1747. const { overlaps, solved, states } = R.settled;
  1748. console.log(report(result));
  1749. console.log(`audit · ${R.tubes.length} tubes · ${R.solids.length} solids · ${R.items.length} items · ${states.length} depth states · ${overlaps.pairs.length} overlaps · ${solved.rules} order rules · ${((Date.now() - started) / 1000).toFixed(1)} s`);
  1750. const count = failures(result);
  1751. console.log(count ? `audit failed: ${count} problem${count === 1 ? "" : "s"}` : "audit passed");
  1752. if (count) process.exitCode = 1;
  1753. return result;
  1754. }