topotopo 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/NOTICE +30 -0
  2. package/README.md +35 -14
  3. package/dist/cli.js +28 -10
  4. package/dist/core/analysis.d.ts +5 -1
  5. package/dist/core/analysis.js +8 -3
  6. package/dist/core/bake.d.ts +2 -5
  7. package/dist/core/bake.js +12 -25
  8. package/dist/core/bevel.js +165 -97
  9. package/dist/core/geometry.js +1 -1
  10. package/dist/core/imageops.d.ts +6 -0
  11. package/dist/core/imageops.js +51 -0
  12. package/dist/core/materials.d.ts +4 -0
  13. package/dist/core/materials.js +11 -0
  14. package/dist/core/packed.js +11 -0
  15. package/dist/core/particles.d.ts +1 -1
  16. package/dist/core/particles.js +1 -1
  17. package/dist/core/rbd.js +13 -1
  18. package/dist/core/scatter.d.ts +1 -1
  19. package/dist/core/scatter.js +1 -1
  20. package/dist/core/scene.d.ts +20 -0
  21. package/dist/core/scene.js +71 -0
  22. package/dist/core/snippet-lib.d.ts +1 -1
  23. package/dist/core/snippet-lib.js +1 -1
  24. package/dist/core/solidify.d.ts +38 -0
  25. package/dist/core/solidify.js +356 -0
  26. package/dist/core/tangents.d.ts +52 -0
  27. package/dist/core/tangents.js +214 -0
  28. package/dist/core/texcoord.d.ts +4 -0
  29. package/dist/core/texcoord.js +14 -0
  30. package/dist/core/topology.d.ts +22 -0
  31. package/dist/core/topology.js +70 -7
  32. package/dist/core/traceimage.d.ts +7 -0
  33. package/dist/core/traceimage.js +221 -0
  34. package/dist/core/tritri.d.ts +5 -0
  35. package/dist/core/tritri.js +120 -0
  36. package/dist/core/uv.d.ts +13 -0
  37. package/dist/core/uv.js +3 -3
  38. package/dist/core/uvreport.d.ts +66 -0
  39. package/dist/core/uvreport.js +308 -0
  40. package/dist/core/xatlas.js +32 -2
  41. package/dist/gallery/app/gallery.css +100 -0
  42. package/dist/gallery/app/gallery.js +80 -0
  43. package/dist/gallery/bake.d.ts +34 -0
  44. package/dist/gallery/bake.js +144 -0
  45. package/dist/gallery/cli.d.ts +4 -0
  46. package/dist/gallery/cli.js +157 -0
  47. package/dist/gallery/library.d.ts +124 -0
  48. package/dist/gallery/library.js +366 -0
  49. package/dist/gallery/pages.d.ts +94 -0
  50. package/dist/gallery/pages.js +148 -0
  51. package/dist/gallery/server.d.ts +21 -0
  52. package/dist/gallery/server.js +391 -0
  53. package/dist/host/export-targets.js +1 -1
  54. package/dist/index.d.ts +3 -1
  55. package/dist/index.js +2 -1
  56. package/dist/inspect.d.ts +6 -1
  57. package/dist/inspect.js +13 -1
  58. package/dist/io/common.d.ts +8 -0
  59. package/dist/io/gltf.js +236 -19
  60. package/dist/io/targets.js +1 -1
  61. package/dist/mcp/docs.d.ts +1 -1
  62. package/dist/mcp/docs.js +58 -4
  63. package/dist/mcp/library.d.ts +12 -0
  64. package/dist/mcp/library.js +159 -0
  65. package/dist/mcp/server.js +29 -12
  66. package/dist/mcp/tools.js +16 -10
  67. package/dist/nodes/bake.js +56 -36
  68. package/dist/nodes/bevel.js +4 -3
  69. package/dist/nodes/code.js +1 -1
  70. package/dist/nodes/curves.js +7 -0
  71. package/dist/nodes/generate.js +1 -1
  72. package/dist/nodes/imageops.d.ts +1 -0
  73. package/dist/nodes/imageops.js +206 -0
  74. package/dist/nodes/index.d.ts +3 -0
  75. package/dist/nodes/index.js +3 -0
  76. package/dist/nodes/material.js +3 -0
  77. package/dist/nodes/measure.js +3 -2
  78. package/dist/nodes/rbd.js +1 -1
  79. package/dist/nodes/scene.d.ts +1 -0
  80. package/dist/nodes/scene.js +53 -0
  81. package/dist/nodes/solidify.d.ts +1 -0
  82. package/dist/nodes/solidify.js +52 -0
  83. package/dist/nodes/transform.js +5 -1
  84. package/dist/nodes/util.d.ts +1 -1
  85. package/dist/nodes/wasmcall.js +1 -1
  86. package/dist/render/options.js +1 -1
  87. package/dist/render/pbr.d.ts +28 -0
  88. package/dist/render/pbr.js +378 -0
  89. package/dist/render/preview.d.ts +58 -0
  90. package/dist/render/preview.js +24 -0
  91. package/dist/render/raster.d.ts +12 -2
  92. package/dist/render/raster.js +98 -11
  93. package/dist/render/texview.d.ts +1 -1
  94. package/dist/render/texview.js +7 -2
  95. package/dist/viewer/app/camera.js +1 -1
  96. package/dist/viewer/app/embed.js +80 -0
  97. package/dist/viewer/app/grid.js +1 -1
  98. package/dist/viewer/app/guides.js +1 -1
  99. package/dist/viewer/app/keymap.js +1 -1
  100. package/dist/viewer/app/layers.js +1 -1
  101. package/dist/viewer/app/main.js +1 -1
  102. package/dist/viewer/app/markers.js +1 -1
  103. package/dist/viewer/app/outliner.js +1 -1
  104. package/dist/viewer/app/props.js +1 -1
  105. package/dist/viewer/app/scene.js +6 -2
  106. package/dist/viewer/app/select.js +1 -1
  107. package/dist/viewer/app/selection.js +1 -1
  108. package/dist/viewer/app/status.js +1 -1
  109. package/dist/viewer/app/style.css +1 -1
  110. package/dist/viewer/app/units.js +1 -1
  111. package/dist/viewer/app/vars.js +1 -1
  112. package/dist/viewer/index.html +1 -1
  113. package/dist/viewer/server.d.ts +14 -2
  114. package/dist/viewer/server.js +30 -10
  115. package/dist/workspace.d.ts +13 -0
  116. package/dist/workspace.js +87 -1
  117. package/kernels/pkg/README.md +21 -28
  118. package/kernels/pkg-simd/README.md +21 -28
  119. package/package.json +9 -3
@@ -509,112 +509,180 @@ export function bevelEdges(g, sel, opts) {
509
509
  offE[e] = offsetMode === 'fraction' ? opts.offset * Math.min(minFanLen(he.edgeA[e]), minFanLen(he.edgeB[e])) : opts.offset;
510
510
  const C = new Ctx(g, opts.divisions ?? 0, opts.shape ?? 0);
511
511
  const n = C.n;
512
- const recs = new Map();
513
- // ---- pass A: symbolic corner chains and offset vectors at scale 1
514
- for (const [v, fan] of fans) {
515
- if (!fan)
516
- continue;
517
- const k = fan.hs.length, m = fan.edges.length;
518
- const bev = new Uint8Array(m), d = new Float64Array(m), elen = new Float64Array(m);
519
- const dir = [];
520
- let any = false;
521
- const pv = C.pt(v);
522
- for (let j = 0; j < m; j++) {
523
- bev[j] = bevE[fan.edges[j]];
524
- if (bev[j])
525
- any = true;
526
- d[j] = bev[j] ? offE[fan.edges[j]] : 0;
527
- const w = sub(C.pt(fan.ends[j]), pv);
528
- elen[j] = len(w);
529
- dir.push(unit(w, [1, 0, 0]));
530
- }
531
- if (!any)
532
- continue;
533
- const rec = {
534
- fan, k, bev, d, dir, elen, slideT: new Float64Array(m).fill(NaN), elems: [],
535
- slidePt: new Int32Array(m).fill(-1), chains: [], chainSrc: [],
536
- };
537
- const sum = new Float64Array(m), cnt = new Int32Array(m);
538
- const uu = [];
539
- for (let i = 0; i < k; i++) {
540
- const N = C.faceN(he.heFace[fan.hs[i]]);
541
- const jo = i, ji = inIdx(rec, i);
542
- const uo = dir[jo], ui = dir[ji];
543
- const upo = unit(sub(uo, scale(N, dot(uo, N))), uo), upi = unit(sub(ui, scale(N, dot(ui, N))), ui);
544
- const mo = cross3(N, upo), mi = cross3(upi, N);
545
- if (bev[jo] && bev[ji]) {
546
- const sig = dot(N, cross3(upo, upi));
547
- let x;
548
- if (Math.abs(sig) > 1e-4)
549
- x = scale(add(scale(upi, d[jo]), scale(upo, d[ji])), 1 / sig);
512
+ // Pass A and the crossing constraints at the current offsets: each constraint is [largest scale, its two points].
513
+ const analyse = () => {
514
+ const recs = new Map();
515
+ const cons = [];
516
+ // ---- pass A: symbolic corner chains and offset vectors at scale 1
517
+ for (const [v, fan] of fans) {
518
+ if (!fan)
519
+ continue;
520
+ const k = fan.hs.length, m = fan.edges.length;
521
+ const bev = new Uint8Array(m), d = new Float64Array(m), elen = new Float64Array(m);
522
+ const dir = [];
523
+ let any = false;
524
+ const pv = C.pt(v);
525
+ for (let j = 0; j < m; j++) {
526
+ bev[j] = bevE[fan.edges[j]];
527
+ if (bev[j])
528
+ any = true;
529
+ d[j] = bev[j] ? offE[fan.edges[j]] : 0;
530
+ const w = sub(C.pt(fan.ends[j]), pv);
531
+ elen[j] = len(w);
532
+ dir.push(unit(w, [1, 0, 0]));
533
+ }
534
+ if (!any)
535
+ continue;
536
+ const rec = {
537
+ fan, k, bev, d, dir, elen, slideT: new Float64Array(m).fill(NaN), elems: [],
538
+ slidePt: new Int32Array(m).fill(-1), chains: [], chainSrc: [],
539
+ };
540
+ const sum = new Float64Array(m), cnt = new Int32Array(m);
541
+ const uu = [];
542
+ for (let i = 0; i < k; i++) {
543
+ const N = C.faceN(he.heFace[fan.hs[i]]);
544
+ const jo = i, ji = inIdx(rec, i);
545
+ const uo = dir[jo], ui = dir[ji];
546
+ const upo = unit(sub(uo, scale(N, dot(uo, N))), uo), upi = unit(sub(ui, scale(N, dot(ui, N))), ui);
547
+ const mo = cross3(N, upo), mi = cross3(upi, N);
548
+ if (bev[jo] && bev[ji]) {
549
+ const sig = dot(N, cross3(upo, upi));
550
+ let x;
551
+ if (Math.abs(sig) > 1e-4)
552
+ x = scale(add(scale(upi, d[jo]), scale(upo, d[ji])), 1 / sig);
553
+ else
554
+ x = scale(unit(add(mi, mo), mo), (d[jo] + d[ji]) / 2);
555
+ rec.elems[i] = [{ k: 2, x }];
556
+ }
557
+ else if (bev[jo]) {
558
+ const s = dot(ui, mo);
559
+ sum[ji] += s > 0 ? d[jo] / Math.max(s, 0.2) : d[jo];
560
+ cnt[ji]++;
561
+ rec.elems[i] = [{ k: 1, j: ji }];
562
+ }
563
+ else if (bev[ji]) {
564
+ const s = dot(uo, mi);
565
+ sum[jo] += s > 0 ? d[ji] / Math.max(s, 0.2) : d[ji];
566
+ cnt[jo]++;
567
+ rec.elems[i] = [{ k: 1, j: jo }];
568
+ }
550
569
  else
551
- x = scale(unit(add(mi, mo), mo), (d[jo] + d[ji]) / 2);
552
- rec.elems[i] = [{ k: 2, x }];
570
+ uu.push(i);
553
571
  }
554
- else if (bev[jo]) {
555
- const s = dot(ui, mo);
556
- sum[ji] += s > 0 ? d[jo] / Math.max(s, 0.2) : d[jo];
557
- cnt[ji]++;
558
- rec.elems[i] = [{ k: 1, j: ji }];
572
+ for (let j = 0; j < m; j++)
573
+ if (cnt[j])
574
+ rec.slideT[j] = sum[j] / cnt[j];
575
+ for (const i of uu) {
576
+ const jo = i, ji = inIdx(rec, i);
577
+ const a = Number.isNaN(rec.slideT[ji]) ? { k: 0 } : { k: 1, j: ji };
578
+ const c = Number.isNaN(rec.slideT[jo]) ? { k: 0 } : { k: 1, j: jo };
579
+ rec.elems[i] = a.k === 0 && c.k === 0 ? [a] : [a, c];
559
580
  }
560
- else if (bev[ji]) {
561
- const s = dot(uo, mi);
562
- sum[jo] += s > 0 ? d[ji] / Math.max(s, 0.2) : d[ji];
563
- cnt[jo]++;
564
- rec.elems[i] = [{ k: 1, j: jo }];
581
+ recs.set(v, rec);
582
+ }
583
+ // ---- clamp: largest scale at which nothing crosses
584
+ const vecOf = (rec, el) => (el.k === 0 ? [0, 0, 0] : el.k === 1 ? scale(rec.dir[el.j], rec.slideT[el.j]) : el.x);
585
+ let lambda = Infinity;
586
+ let pair = [-1, -1];
587
+ const limit = (length, coef) => {
588
+ if (coef <= 1e-12)
589
+ return;
590
+ const l = length / coef;
591
+ if (l < lambda)
592
+ lambda = l;
593
+ if (l < 1)
594
+ cons.push([l, pair[0], pair[1]]);
595
+ };
596
+ for (const [v, rec] of recs) {
597
+ const { fan } = rec;
598
+ for (let j = 0; j < fan.edges.length; j++) {
599
+ if (rec.bev[j] || Number.isNaN(rec.slideT[j]))
600
+ continue;
601
+ const w = fan.ends[j], rw = recs.get(w);
602
+ let tw = 0;
603
+ if (rw) {
604
+ const jw = rw.fan.edges.indexOf(fan.edges[j]);
605
+ if (jw >= 0 && !Number.isNaN(rw.slideT[jw]))
606
+ tw = rw.slideT[jw];
607
+ }
608
+ pair = [v, w];
609
+ limit(rec.elen[j], rec.slideT[j] + tw);
565
610
  }
566
- else
567
- uu.push(i);
568
- }
569
- for (let j = 0; j < m; j++)
570
- if (cnt[j])
571
- rec.slideT[j] = sum[j] / cnt[j];
572
- for (const i of uu) {
573
- const jo = i, ji = inIdx(rec, i);
574
- const a = Number.isNaN(rec.slideT[ji]) ? { k: 0 } : { k: 1, j: ji };
575
- const c = Number.isNaN(rec.slideT[jo]) ? { k: 0 } : { k: 1, j: jo };
576
- rec.elems[i] = a.k === 0 && c.k === 0 ? [a] : [a, c];
577
- }
578
- recs.set(v, rec);
579
- }
580
- // ---- clamp: largest scale at which nothing crosses
581
- const vecOf = (rec, el) => (el.k === 0 ? [0, 0, 0] : el.k === 1 ? scale(rec.dir[el.j], rec.slideT[el.j]) : el.x);
582
- let lambda = Infinity;
583
- const limit = (length, coef) => { if (coef > 1e-12)
584
- lambda = Math.min(lambda, length / coef); };
585
- for (const [v, rec] of recs) {
586
- const { fan } = rec;
587
- for (let j = 0; j < fan.edges.length; j++) {
588
- if (rec.bev[j] || Number.isNaN(rec.slideT[j]))
611
+ }
612
+ for (let e = 0; e < ne; e++) {
613
+ if (!bevE[e])
589
614
  continue;
590
- const w = fan.ends[j], rw = recs.get(w);
591
- let tw = 0;
592
- if (rw) {
593
- const jw = rw.fan.edges.indexOf(fan.edges[j]);
594
- if (jw >= 0 && !Number.isNaN(rw.slideT[jw]))
595
- tw = rw.slideT[jw];
615
+ const h = he.edgeHalf[e], t = he.heTwin[h];
616
+ const a = he.heOrigin[h], c = he.dest(h);
617
+ const ra = recs.get(a), rc = recs.get(c);
618
+ const ja = ra.fan.hs.indexOf(h), jc = rc.fan.hs.indexOf(t);
619
+ const u = unit(sub(C.pt(c), C.pt(a)));
620
+ const L = len(sub(C.pt(c), C.pt(a)));
621
+ // side F_L: a's chain in face(h) (last element), c's chain in face(h) = face before jc (first element)
622
+ pair = [a, c];
623
+ const La = ra.elems[ja][ra.elems[ja].length - 1], Lc = rc.elems[faceBefore(rc, jc)][0];
624
+ limit(L, dot(vecOf(ra, La), u) - dot(vecOf(rc, Lc), u));
625
+ const Ra = ra.elems[faceBefore(ra, ja)][0], Rc = rc.elems[jc][rc.elems[jc].length - 1];
626
+ limit(L, dot(vecOf(ra, Ra), u) - dot(vecOf(rc, Rc), u));
627
+ }
628
+ return { recs, cons, lambda };
629
+ };
630
+ // ---- clamp, locally: where bevels would cross, shrink only the offsets of the edges at the points involved (a
631
+ // few rounds), so one short edge does not flatten every bevel of the mesh; an edge that would keep under a tenth of
632
+ // what the best-kept edges keep (a zero-length or tiny edge next to it) stays sharp. Whatever still crosses is
633
+ // clamped by one factor.
634
+ const clamp = opts.clamp ?? true;
635
+ const off0 = Float64Array.from(offE);
636
+ let { recs, cons, lambda } = analyse();
637
+ let nDropped = 0;
638
+ for (let round = 0; clamp && lambda < 1 && round < 8; round++) {
639
+ const sV = new Map();
640
+ const lower = (v, l) => { if (v >= 0)
641
+ sV.set(v, Math.min(sV.get(v) ?? 1, l)); };
642
+ for (const [l, p, q] of cons) {
643
+ lower(p, l * 0.999);
644
+ lower(q, l * 0.999);
645
+ }
646
+ let best = 0;
647
+ for (let e = 0; e < ne; e++) {
648
+ if (!bevE[e])
649
+ continue;
650
+ const f = Math.min(sV.get(he.edgeA[e]) ?? 1, sV.get(he.edgeB[e]) ?? 1);
651
+ if (f < 1)
652
+ offE[e] *= f;
653
+ best = Math.max(best, offE[e] / off0[e]);
654
+ }
655
+ // an edge keeping under a tenth of what the best-kept edges keep would only be a sliver: leave it sharp (a huge
656
+ // offset that every edge must give up evenly is not dropped)
657
+ for (let e = 0; e < ne; e++)
658
+ if (bevE[e] && offE[e] < off0[e] * 0.1 * best) {
659
+ bevE[e] = 0;
660
+ offE[e] = 0;
661
+ nDropped++;
596
662
  }
597
- limit(rec.elen[j], rec.slideT[j] + tw);
598
- }
599
- void v;
663
+ ({ recs, cons, lambda } = analyse());
600
664
  }
601
- for (let e = 0; e < ne; e++) {
602
- if (!bevE[e])
603
- continue;
604
- const h = he.edgeHalf[e], t = he.heTwin[h];
605
- const a = he.heOrigin[h], c = he.dest(h);
606
- const ra = recs.get(a), rc = recs.get(c);
607
- const ja = ra.fan.hs.indexOf(h), jc = rc.fan.hs.indexOf(t);
608
- const u = unit(sub(C.pt(c), C.pt(a)));
609
- const L = len(sub(C.pt(c), C.pt(a)));
610
- // side F_L: a's chain in face(h) (last element), c's chain in face(h) = face before jc (first element)
611
- const La = ra.elems[ja][ra.elems[ja].length - 1], Lc = rc.elems[faceBefore(rc, jc)][0];
612
- limit(L, dot(vecOf(ra, La), u) - dot(vecOf(rc, Lc), u));
613
- const Ra = ra.elems[faceBefore(ra, ja)][0], Rc = rc.elems[jc][rc.elems[jc].length - 1];
614
- limit(L, dot(vecOf(ra, Ra), u) - dot(vecOf(rc, Rc), u));
665
+ let reduced = 0, minLocal = 1;
666
+ for (let e = 0; e < ne; e++)
667
+ if (bevE[e] && offE[e] < off0[e] * 0.9999) {
668
+ reduced++;
669
+ minLocal = Math.min(minLocal, offE[e] / off0[e]);
670
+ }
671
+ if (reduced)
672
+ warnings.push(`offset reduced at ${reduced} edge(s) (to ${(minLocal * 100).toFixed(1)}% at least) so neighbouring bevels do not overlap; the other edges keep the full offset`);
673
+ if (nDropped)
674
+ warnings.push(`${nDropped} edge(s) left sharp: a neighbouring edge is too short to fit the bevel (zero-length edges from duplicate points? fuse first)`);
675
+ if (nDropped) {
676
+ count = 0;
677
+ for (let e = 0; e < ne; e++)
678
+ count += bevE[e];
679
+ }
680
+ if (!count) {
681
+ warnings.push('no edges to bevel: geometry unchanged');
682
+ return { geo: g, warnings, count: 0, scale: 0 };
615
683
  }
616
684
  let sc = 1;
617
- if ((opts.clamp ?? true) && lambda < 1) {
685
+ if (clamp && lambda < 1) {
618
686
  sc = lambda * 0.999;
619
687
  warnings.push(`offset clamped to ${(sc * 100).toFixed(1)}% so neighbouring bevels do not overlap`);
620
688
  }
@@ -389,7 +389,7 @@ export function cloneVolumes(vs) {
389
389
  /**
390
390
  * Every Geometry object the engine made (the constructor and Geometry.blank add them). A brand check that runs no user
391
391
  * code: `instanceof` and Object.getPrototypeOf call a Proxy's getPrototypeOf trap, and a script node may hand back a
392
- * Proxy of a geometry (R-18). WeakSet.prototype.has is bound now, so a later change to WeakSet.prototype in this realm
392
+ * Proxy of a geometry. WeakSet.prototype.has is bound now, so a later change to WeakSet.prototype in this realm
393
393
  * does not reach the check either.
394
394
  */
395
395
  const GEOMETRIES = new WeakSet();
@@ -0,0 +1,6 @@
1
+ import { Image } from './image.ts';
2
+ export declare function cropImage(img: Image, x: number, y: number, w: number, h: number, ow: number, oh: number, nearest: boolean, name: string): Image;
3
+ /** Exact nearest-site padding, sharing the distance transform used by wide bake padding.
4
+ * Ties are deterministic (topmost site, then leftmost). Unreached and valid values are untouched.
5
+ */
6
+ export declare function dilateImage(data: Float32Array, ch: number, w: number, h: number, mask: Float32Array, threshold: number, radius: number, preserveAlpha: boolean): Float32Array;
@@ -0,0 +1,51 @@
1
+ // General image operations. Pixel coordinates start at the top left; values stay in their source encoding.
2
+ import { Image, resizeLayer, samplePixelNearest } from './image.js';
3
+ import { distanceTransform } from './heightfield.js';
4
+ export function cropImage(img, x, y, w, h, ow, oh, nearest, name) {
5
+ const out = new Image(ow, oh, name);
6
+ for (const [layer, data] of img.layers) {
7
+ const ch = img.channels(layer), crop = new Float32Array(w * h * ch);
8
+ for (let j = 0; j < h; j++) {
9
+ const sy = y + j;
10
+ if (sy < 0 || sy >= img.height)
11
+ continue;
12
+ const start = Math.max(0, -x), end = Math.min(w, img.width - x);
13
+ if (end > start)
14
+ crop.set(data.subarray((sy * img.width + x + start) * ch, (sy * img.width + x + end) * ch), (j * w + start) * ch);
15
+ }
16
+ if (w === ow && h === oh)
17
+ out.set(layer, crop);
18
+ else if (!nearest)
19
+ out.set(layer, resizeLayer(crop, ch, w, h, ow, oh, false));
20
+ else {
21
+ const resized = new Float32Array(ow * oh * ch), pixel = new Float32Array(ch);
22
+ for (let j = 0; j < oh; j++)
23
+ for (let i = 0; i < ow; i++) {
24
+ samplePixelNearest(crop, ch, w, h, (i + 0.5) * w / ow, (j + 0.5) * h / oh, pixel, false);
25
+ resized.set(pixel, (j * ow + i) * ch);
26
+ }
27
+ out.set(layer, resized);
28
+ }
29
+ }
30
+ return out;
31
+ }
32
+ /** Exact nearest-site padding, sharing the distance transform used by wide bake padding.
33
+ * Ties are deterministic (topmost site, then leftmost). Unreached and valid values are untouched.
34
+ */
35
+ export function dilateImage(data, ch, w, h, mask, threshold, radius, preserveAlpha) {
36
+ const out = data.slice();
37
+ if (!radius)
38
+ return out;
39
+ const valid = Uint8Array.from(mask, (v) => v > threshold ? 1 : 0);
40
+ if (!valid.some(Boolean) || valid.every(Boolean))
41
+ return out;
42
+ const { d2, nearest } = distanceTransform(valid, w, h);
43
+ for (let i = 0; i < valid.length; i++) {
44
+ if (valid[i] || nearest[i] < 0 || d2[i] > radius * radius)
45
+ continue;
46
+ for (let c = 0; c < ch; c++)
47
+ if (!(ch === 4 && c === 3 && preserveAlpha))
48
+ out[i * ch + c] = data[nearest[i] * ch + c];
49
+ }
50
+ return out;
51
+ }
@@ -5,6 +5,9 @@ export interface Material {
5
5
  roughness: number;
6
6
  emissive: [number, number, number];
7
7
  alpha: number;
8
+ /** Absent = legacy auto (blend only for scalar / vertex opacity). */
9
+ alphaMode?: 'OPAQUE' | 'MASK' | 'BLEND';
10
+ alphaCutoff?: number;
8
11
  doubleSided: boolean;
9
12
  unlit: boolean;
10
13
  /**
@@ -27,6 +30,7 @@ export declare const MATERIALS_DETAIL = "materials";
27
30
  export declare const DEFAULT_MATERIAL: Readonly<Material>;
28
31
  /** Fill missing fields with defaults and coerce types (tolerant of hand-written tables). */
29
32
  export declare function normalizeMaterial(m: any): Material;
33
+ export declare function materialAlphaMode(m: Material, vertexAlpha?: boolean): 'OPAQUE' | 'MASK' | 'BLEND';
30
34
  /** Every texture path used by a table (deduplicated, table order). */
31
35
  export declare function texturePaths(t: MaterialTable): string[];
32
36
  /** The material table stored on the geometry (empty when there is none or it does not parse). */
@@ -22,11 +22,22 @@ export function normalizeMaterial(m) {
22
22
  roughness: num(m?.roughness, d.roughness),
23
23
  emissive: vec3(m?.emissive, d.emissive),
24
24
  alpha: num(m?.alpha, d.alpha),
25
+ ...alphaFields(m),
25
26
  doubleSided: typeof m?.doubleSided === 'boolean' ? m.doubleSided : d.doubleSided,
26
27
  unlit: typeof m?.unlit === 'boolean' ? m.unlit : d.unlit,
27
28
  ...textureField(m?.textures),
28
29
  };
29
30
  }
31
+ /** Keep auto materials byte-compatible with existing graphs and fingerprints. */
32
+ function alphaFields(m) {
33
+ const mode = typeof m?.alphaMode === 'string' ? m.alphaMode.toUpperCase() : '';
34
+ if (mode !== 'OPAQUE' && mode !== 'MASK' && mode !== 'BLEND')
35
+ return {};
36
+ return { alphaMode: mode, ...(mode === 'MASK' ? { alphaCutoff: Math.max(0, Math.min(1, num(m?.alphaCutoff, 0.5))) } : {}) };
37
+ }
38
+ export function materialAlphaMode(m, vertexAlpha = false) {
39
+ return m.alphaMode ?? (m.alpha < 1 || vertexAlpha ? 'BLEND' : 'OPAQUE');
40
+ }
30
41
  /** { textures } with the non-empty string slots, or {} when there is none (keeps texture-free tables unchanged). */
31
42
  function textureField(t) {
32
43
  if (!t || typeof t !== 'object')
@@ -21,6 +21,7 @@ import { mergeMaterialTables, writeMaterials } from './materials.js';
21
21
  import { m4normalMatrix, qFromMat, qMul } from './math.js';
22
22
  import { resolveVertexNormals } from './topology.js';
23
23
  import { splineCounts, splinesToPolylines } from './splines.js';
24
+ import { TANGENT_ATTRIB, transformTangents } from './tangents.js';
24
25
  /**
25
26
  * Default triangle budget of the renderer: above it, an evenly spread subset of the instances is drawn. The software
26
27
  * rasteriser spends about 2 s on per-mesh analysis and 0.5 s per view for 1.5M triangles; 600k keeps a quad view of
@@ -294,6 +295,12 @@ export function expandPacked(g, o = {}) {
294
295
  if (a && a.type === 'float' && a.size === 3)
295
296
  vecAttrs.push({ c, a });
296
297
  }
298
+ const tanAttrs = [];
299
+ for (const c of ['point', 'vertex']) {
300
+ const a = tables[c].get(TANGENT_ATTRIB);
301
+ if (a && a.type === 'float' && a.size === 4)
302
+ tanAttrs.push({ c, a });
303
+ }
297
304
  const orientA = out.points.get('orient');
298
305
  const orient = orientA && orientA.type === 'float' && orientA.size === 4 ? orientA.data : null;
299
306
  const OP = out.P;
@@ -361,6 +368,10 @@ export function expandPacked(g, o = {}) {
361
368
  d[i * 3 + 2] = m[2] * x + m[6] * y + m[10] * z;
362
369
  }
363
370
  }
371
+ for (const { c, a: A } of tanAttrs) {
372
+ const [e0, e1] = range(c, j);
373
+ transformTangents(A.data.subarray(e0 * 4, e1 * 4), e1 - e0, xform3(m));
374
+ }
364
375
  // one-level expansion: instances inside the source compose this instance's transform
365
376
  if (out.primKind)
366
377
  composePackedXforms(out, m, null, offs[j * 3 + 2], offs[j * 3 + 5]);
@@ -153,7 +153,7 @@ export interface EmitParams {
153
153
  * `max_particles` counts every particle from its birth through its death step, including the ones a collision removed
154
154
  * (listed in __pholders). `end` is s1, or the end of the first earlier step at which this call's births reach
155
155
  * `maxBirths`: the caller integrates [s0, end) and continues from there, which gives the same result as one run (runs
156
- * can be cut anywhere) while the births held at once stay bounded (R-17 N3: a high rate with a short life over many
156
+ * can be cut anywhere) while the births held at once stay bounded (a high rate with a short life over many
157
157
  * steps materialised every birth of the run and exhausted the heap).
158
158
  */
159
159
  export declare function emitSteps(state: Geometry | null, em: EmitterData, s0: number, s1: number, ep: EmitParams): {
@@ -645,7 +645,7 @@ function phaseOf(ep, key) {
645
645
  * `max_particles` counts every particle from its birth through its death step, including the ones a collision removed
646
646
  * (listed in __pholders). `end` is s1, or the end of the first earlier step at which this call's births reach
647
647
  * `maxBirths`: the caller integrates [s0, end) and continues from there, which gives the same result as one run (runs
648
- * can be cut anywhere) while the births held at once stay bounded (R-17 N3: a high rate with a short life over many
648
+ * can be cut anywhere) while the births held at once stay bounded (a high rate with a short life over many
649
649
  * steps materialised every birth of the run and exhausted the heap).
650
650
  */
651
651
  export function emitSteps(state, em, s0, s1, ep) {
package/dist/core/rbd.js CHANGED
@@ -26,6 +26,7 @@ import { expandPacked, flattenSource } from './packed.js';
26
26
  import { heightfieldsOf, heightfieldToMesh } from './heightfield.js';
27
27
  import { qFromMat, qMul, qNormalize } from './math.js';
28
28
  import { rand } from './random.js';
29
+ import { TANGENT_ATTRIB } from './tangents.js';
29
30
  export const RBD_SHAPES = ['convex_hull', 'box', 'sphere', 'mesh'];
30
31
  export const RBD_PIECE_MODES = ['auto', 'connectivity', 'name', 'attrib'];
31
32
  // ------------------------------------------------------------------ small math
@@ -564,7 +565,7 @@ export class RbdSim {
564
565
  }
565
566
  // bodies in a stable order: by input position (so permuting the input does not change the result); pieces at the
566
567
  // same position (to 1e-6 m: rbd_stack's "every crate at the same spot") by a hash of what they are, so permuting
567
- // coincident pieces of different shapes changes nothing either (R-17 N7: ties went by input index). Pieces that
568
+ // coincident pieces of different shapes changes nothing either (ties went by input index). Pieces that
568
569
  // tie on that too are interchangeable: same shape, pose and velocities, so the set of results is the same.
569
570
  const order = pieces.map((_, i) => i);
570
571
  const q6 = (x) => Math.round(x * 1e6);
@@ -1147,6 +1148,17 @@ function rotateVectors(t, pieceOf, dR, dQ, point) {
1147
1148
  d[i * 3 + 2] = R[2] * x + R[5] * y + R[8] * z;
1148
1149
  }
1149
1150
  }
1151
+ else if (name === TANGENT_ATTRIB && a.size === 4) {
1152
+ for (let i = 0; i < t.count; i++) {
1153
+ const k = pieceOf(i);
1154
+ if (k < 0)
1155
+ continue;
1156
+ const R = dR.subarray(k * 9, k * 9 + 9), x = d[i * 4], y = d[i * 4 + 1], z = d[i * 4 + 2];
1157
+ d[i * 4] = R[0] * x + R[3] * y + R[6] * z;
1158
+ d[i * 4 + 1] = R[1] * x + R[4] * y + R[7] * z;
1159
+ d[i * 4 + 2] = R[2] * x + R[5] * y + R[8] * z;
1160
+ }
1161
+ }
1150
1162
  else if (point && name === 'orient' && a.size === 4) {
1151
1163
  for (let i = 0; i < t.count; i++) {
1152
1164
  const k = pieceOf(i);
@@ -21,7 +21,7 @@ export type RunKernel = (kernel: string, job: ScatterJob, opts?: {
21
21
  }>;
22
22
  type Maybe<T> = T | Promise<T>;
23
23
  /**
24
- * Loaded-WASM auto policy, calibrated with interleaved medians (BENCH.md session 13).
24
+ * Loaded-WASM auto policy, calibrated with interleaved medians.
25
25
  * `workers` is zero for an unavailable/cold pool or a stage below its pool threshold.
26
26
  * Large elimination lists and projection passes benefit from multiple JS workers
27
27
  * despite faster individual Rust loops. Minimum-distance rejection stays in WASM.
@@ -24,7 +24,7 @@ import { hypot3 } from './math.js';
24
24
  /** f(x) for a value, x.then(f) for a promise (f may return a promise: it is flattened either way). */
25
25
  const then = (x, f) => (x instanceof Promise ? x.then(f) : f(x));
26
26
  /**
27
- * Loaded-WASM auto policy, calibrated with interleaved medians (BENCH.md session 13).
27
+ * Loaded-WASM auto policy, calibrated with interleaved medians.
28
28
  * `workers` is zero for an unavailable/cold pool or a stage below its pool threshold.
29
29
  * Large elimination lists and projection passes benefit from multiple JS workers
30
30
  * despite faster individual Rust loops. Minimum-distance rejection stays in WASM.
@@ -0,0 +1,20 @@
1
+ import type { Geometry } from './geometry.ts';
2
+ import type { Quat, Vec3 } from './math.ts';
3
+ export declare const EMPTY_ATTRIB = "scene_empty";
4
+ export declare const PARENT_ATTRIB = "parent";
5
+ /** Point attributes the empty contract owns (not written as extras). */
6
+ export declare const EMPTY_RESERVED: Set<string>;
7
+ export interface SceneEmpty {
8
+ point: number;
9
+ name: string;
10
+ parent: string;
11
+ P: Vec3;
12
+ orient: Quat;
13
+ scale: Vec3;
14
+ /** other point attributes that differ from their defaults */
15
+ extras: Record<string, number | number[] | string>;
16
+ }
17
+ /** Points marked scene_empty = 1. Throws when a marked point is used by a primitive (it would be drawn). */
18
+ export declare function sceneEmpties(g: Geometry): SceneEmpty[];
19
+ /** A geometry holding one empty (merge it with the rest). */
20
+ export declare function emptyGeometry(name: string, parent: string, P: Vec3, orient: Quat, scale: Vec3): Geometry;
@@ -0,0 +1,71 @@
1
+ import { Geometry as Geo, defaultValueFor } from './geometry.js';
2
+ export const EMPTY_ATTRIB = 'scene_empty';
3
+ export const PARENT_ATTRIB = 'parent';
4
+ /** Point attributes the empty contract owns (not written as extras). */
5
+ export const EMPTY_RESERVED = new Set(['P', 'orient', 'scale', 'name', PARENT_ATTRIB, EMPTY_ATTRIB, 'pscale', 'path']);
6
+ /** Points marked scene_empty = 1. Throws when a marked point is used by a primitive (it would be drawn). */
7
+ export function sceneEmpties(g) {
8
+ const m = g.points.get(EMPTY_ATTRIB);
9
+ if (!m || m.type !== 'int' || m.size !== 1)
10
+ return [];
11
+ const flag = m.data;
12
+ let any = false;
13
+ for (let i = 0; i < g.numPoints; i++)
14
+ if (flag[i]) {
15
+ any = true;
16
+ break;
17
+ }
18
+ if (!any)
19
+ return [];
20
+ const used = new Uint8Array(g.numPoints);
21
+ for (let v = 0; v < g.numVertices; v++)
22
+ used[g.vertexPoint[v]] = 1;
23
+ const str = (n, i) => { const a = g.points.get(n); return a && a.type === 'string' ? String(a.get(i) ?? '') : ''; };
24
+ const vec = (n, i, size, def) => {
25
+ const a = g.points.get(n);
26
+ if (!a || a.type !== 'float' || a.size !== size)
27
+ return def.slice();
28
+ return Array.from(a.data.subarray(i * size, i * size + size));
29
+ };
30
+ const out = [];
31
+ for (let i = 0; i < g.numPoints; i++) {
32
+ if (!flag[i])
33
+ continue;
34
+ if (used[i])
35
+ throw new Error(`scene empty: point ${i} ("${str('name', i)}") is marked ${EMPTY_ATTRIB} but used by a primitive; empties must be isolated points`);
36
+ const extras = {};
37
+ for (const [k, a] of g.points.map) {
38
+ if (EMPTY_RESERVED.has(k) || a.isArray)
39
+ continue;
40
+ const v = a.get(i), d = a.def;
41
+ if (a.type === 'string') {
42
+ if (v !== '' && v !== d)
43
+ extras[k] = v;
44
+ continue;
45
+ }
46
+ const arr = Array.isArray(v) ? v : [v];
47
+ if (!arr.every(Number.isFinite))
48
+ continue;
49
+ const def = Array.isArray(d) ? d : [];
50
+ if (arr.every((x, c) => x === (def[c] ?? 0)))
51
+ continue;
52
+ extras[k] = arr.length === 1 ? arr[0] : arr;
53
+ }
54
+ const q = vec('orient', i, 4, [0, 0, 0, 1]), ql = Math.hypot(q[0], q[1], q[2], q[3]) || 1;
55
+ out.push({
56
+ point: i, name: str('name', i), parent: str(PARENT_ATTRIB, i), P: [g.P[i * 3], g.P[i * 3 + 1], g.P[i * 3 + 2]],
57
+ orient: [q[0] / ql, q[1] / ql, q[2] / ql, q[3] / ql], scale: vec('scale', i, 3, [1, 1, 1]), extras,
58
+ });
59
+ }
60
+ return out;
61
+ }
62
+ /** A geometry holding one empty (merge it with the rest). */
63
+ export function emptyGeometry(name, parent, P, orient, scale) {
64
+ const g = new Geo({ positions: P });
65
+ g.points.add(EMPTY_ATTRIB, 'int', 1).set(0, 1);
66
+ g.points.add('name', 'string', 1).set(0, name);
67
+ g.points.add(PARENT_ATTRIB, 'string', 1).set(0, parent);
68
+ g.points.add('orient', 'float', 4, defaultValueFor('orient', 4, 'float')).set(0, orient);
69
+ g.points.add('scale', 'float', 3, defaultValueFor('scale', 3, 'float')).set(0, scale);
70
+ return g;
71
+ }
@@ -22,7 +22,7 @@ export declare const REALM_CONTROL = "__topotopo";
22
22
  * The host keeps the object and calls setJob/setCur directly, outside the time limit, so they must not run user code:
23
23
  * the job and the API are closure variables, the object is frozen (own data properties only) and a global `const`
24
24
  * can be neither reassigned nor redefined by later code (user code never runs at the realm's top level, and a
25
- * property of the global object of the same name is shadowed by the binding). Before R-18 the host assigned
25
+ * property of the global object of the same name is shadowed by the binding). Previously the host assigned
26
26
  * global properties `__job` and `__cur`, and a script that gave them a looping setter hung the process.
27
27
  */
28
28
  export declare const SCRIPT_REALM_SETUP: string;
@@ -473,7 +473,7 @@ export const REALM_CONTROL = '__topotopo';
473
473
  * The host keeps the object and calls setJob/setCur directly, outside the time limit, so they must not run user code:
474
474
  * the job and the API are closure variables, the object is frozen (own data properties only) and a global `const`
475
475
  * can be neither reassigned nor redefined by later code (user code never runs at the realm's top level, and a
476
- * property of the global object of the same name is shadowed by the binding). Before R-18 the host assigned
476
+ * property of the global object of the same name is shadowed by the binding). Previously the host assigned
477
477
  * global properties `__job` and `__cur`, and a script that gave them a looping setter hung the process.
478
478
  */
479
479
  export const SCRIPT_REALM_SETUP = `const ${REALM_CONTROL} = (() => {