@ac-kit/math-geometry 0.4.0 → 0.5.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 (46) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +37 -6
  3. package/dist/_polyline-simplify.d.ts +11 -0
  4. package/dist/_polyline-simplify.d.ts.map +1 -0
  5. package/dist/_polyline-simplify.js +92 -0
  6. package/dist/_polyline-simplify.js.map +1 -0
  7. package/dist/_triangle3-cross.d.ts.map +1 -1
  8. package/dist/_triangle3-cross.js +16 -7
  9. package/dist/_triangle3-cross.js.map +1 -1
  10. package/dist/convex-hull2.d.ts +26 -0
  11. package/dist/convex-hull2.d.ts.map +1 -0
  12. package/dist/convex-hull2.js +88 -0
  13. package/dist/convex-hull2.js.map +1 -0
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +2 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/mesh/_index-kernels-u16.d.ts +21 -28
  19. package/dist/mesh/_index-kernels-u16.d.ts.map +1 -1
  20. package/dist/mesh/_index-kernels-u16.js +892 -363
  21. package/dist/mesh/_index-kernels-u16.js.map +1 -1
  22. package/dist/mesh/_index-kernels-u32.d.ts +21 -28
  23. package/dist/mesh/_index-kernels-u32.d.ts.map +1 -1
  24. package/dist/mesh/_index-kernels-u32.js +892 -363
  25. package/dist/mesh/_index-kernels-u32.js.map +1 -1
  26. package/dist/mesh/mesh3-kernels.d.ts +73 -29
  27. package/dist/mesh/mesh3-kernels.d.ts.map +1 -1
  28. package/dist/mesh/mesh3-kernels.js +92 -34
  29. package/dist/mesh/mesh3-kernels.js.map +1 -1
  30. package/dist/polygon2.d.ts +22 -0
  31. package/dist/polygon2.d.ts.map +1 -1
  32. package/dist/polygon2.js +69 -0
  33. package/dist/polygon2.js.map +1 -1
  34. package/dist/polyline2.d.ts +20 -0
  35. package/dist/polyline2.d.ts.map +1 -1
  36. package/dist/polyline2.js +25 -0
  37. package/dist/polyline2.js.map +1 -1
  38. package/dist/polyline3.d.ts +17 -0
  39. package/dist/polyline3.d.ts.map +1 -1
  40. package/dist/polyline3.js +22 -0
  41. package/dist/polyline3.js.map +1 -1
  42. package/dist/predicates2.d.ts +51 -0
  43. package/dist/predicates2.d.ts.map +1 -0
  44. package/dist/predicates2.js +172 -0
  45. package/dist/predicates2.js.map +1 -0
  46. package/package.json +8 -8
@@ -1,5 +1,5 @@
1
1
  // Generated from scripts/templates/index-kernels.liquid by scripts/generate-index-kernels.ts. Do not edit.
2
- import { binaryExponent, PreciseSum, scaleByPowerOfTwoInPlace, } from "@ac-kit/core";
2
+ import { binaryExponent, binaryExponentAt, PreciseSum, scaleByPowerOfTwoInPlace, } from "@ac-kit/core";
3
3
  import { vec2Create, vec3Create, } from "@ac-kit/math-linear";
4
4
  import { DotExactAccumulator, twoProductInRangeInPlace, twoSumInPlace, } from "@ac-kit/math-scalar";
5
5
  import { triangle3Cross_, writeScaledComponents_, } from "../_triangle3-cross.js";
@@ -13,25 +13,12 @@ const CORNERS_ = new Float64Array(9);
13
13
  const BARYCENTRIC_ = vec2Create();
14
14
  const NORMAL_ = vec3Create();
15
15
  const AREA_ = new PreciseSum();
16
- const SIX_VOLUMES_ = new PreciseSum();
17
- /** Three times the total weight, then the sums of its products with x, y and z. */
18
- const CENTROID_SUMS_ = [
19
- new PreciseSum(),
20
- new PreciseSum(),
21
- new PreciseSum(),
22
- new PreciseSum(),
23
- ];
24
16
  /**
25
- * The frame of the area, volume and centroid kernels, per axis: the anchor
26
- * (0–2), the exponent e of the axis's scale 2^−e (3–5), the factor a difference
27
- * along the axis is multiplied by (6–8: 2^−e, or 2^(1−e) where the halves are
28
- * subtracted), 1 when some extent is so wide that a difference of two
29
- * coordinates may overflow (9), and a second factor where the first alone would
30
- * leave the doubles (10–12, otherwise 1).
17
+ * The frame of the volume: the anchor (0–2), per axis the exponent e with 2^e
18
+ * above its extent (3–5), and 1 when some extent is so wide that a difference
19
+ * of two coordinates may overflow (6).
31
20
  */
32
- const FRAME_ = new Float64Array(13);
33
- /** A corner relative to the anchor, scaled: x, y, z, then their low parts. */
34
- const VERTEX_ = new Float64Array(6);
21
+ const FRAME_ = new Float64Array(7);
35
22
  /**
36
23
  * One face's doubled area as `[m, k]`, the area being m · 2^k: k is 0 when m is
37
24
  * the area itself, otherwise m is between 1 and 4 (0 for a degenerate face,
@@ -42,16 +29,10 @@ const FACE_AREA_ = new Float64Array(2);
42
29
  const FACE_CROSS_ = new Float64Array(4);
43
30
  /** A double computed and scaled in place, never boxed by a call. */
44
31
  const VALUE_ = new Float64Array(1);
45
- /** A face's scaled edges `b − a` and `c − a`. */
46
- const EDGES_ = new Float64Array(6);
47
- /** The exponents bounding a face's `a − o`, `b − a` and `c − a`. */
48
- const BOUNDS_ = new Float64Array(3);
49
32
  /** Two numbers TwoSum replaces by their sum and its error. */
50
33
  const PAIR_ = new Float64Array(2);
51
34
  /** The volume filter's operands, TwoSum and TwoProduct pairs in place. */
52
35
  const FILTER_ = new Float64Array(36);
53
- const CROSS_ = new Float64Array(12);
54
- const TERMS_ = new Float64Array(48);
55
36
  /**
56
37
  * The accuracy a vertex's sum must be certified to: each component's bound
57
38
  * within 2^−50 of the largest component, so that the unit normal stays within
@@ -63,7 +44,10 @@ const VERTEX_ACCURACY_ = 2 ** -50;
63
44
  * term below 2^−1070), far above it.
64
45
  */
65
46
  const SCALED_TERM_BOUND_ = 2 ** -1000;
66
- /** The least exponent of a term a `DotExactAccumulator` holds. */
47
+ /**
48
+ * The least exponent of a term the exact vertex sums add, inside a
49
+ * `DotExactAccumulator`'s span (from 2^−3350).
50
+ */
67
51
  const EXACT_TERM_MIN_EXPONENT_ = -2166;
68
52
  /** The exact sums of a vertex's components. */
69
53
  const EXACT_SUMS_ = [
@@ -389,15 +373,11 @@ export function mesh3FaceNormalsU16(out, positions, indices) {
389
373
  /** An exponent below every one a face can have: "no difference". */
390
374
  const NONE_ = -4096;
391
375
  /**
392
- * Fills `FRAME_` for the triangles of `indices`. The anchor is the least x, y
393
- * and z of the vertices they use: a corner of their bounding box, the same in
394
- * every face order, and a vertex no triangle uses is never read. Each axis has
395
- * its own e, 2^e above the box's extent along it (0 for a flat or non-finite
396
- * one), at least −1021 so that 2^−e is a double: a corner relative to the
397
- * anchor, scaled by its axis's 2^−e, lies in [0, 1) on every axis however thin
398
- * the box is along the others. When an extent reaches 2^1023, so that a
399
- * difference of two coordinates may overflow, every difference subtracts
400
- * halves, which is exact for normal coordinates.
376
+ * Fills `FRAME_` for the triangles of `indices`: the anchor o, the least x, y
377
+ * and z of the vertices they use (a corner of their bounding box, the same in
378
+ * every face order, and a vertex no triangle uses is never read), then per axis
379
+ * e, 2^e above the box's extent along it (0 for a flat or non-finite one), then
380
+ * 1 where an extent reaches 2^1023.
401
381
  */
402
382
  function frameU16_(positions, indices) {
403
383
  let minX = Number.POSITIVE_INFINITY;
@@ -429,104 +409,116 @@ function frameU16_(positions, indices) {
429
409
  frame[3] = halfX;
430
410
  frame[4] = halfY;
431
411
  frame[5] = halfZ;
432
- frame[9] =
412
+ frame[6] =
433
413
  halfX >= 2 ** 1022 || halfY >= 2 ** 1022 || halfZ >= 2 ** 1022 ? 1 : 0;
434
414
  for (let axis = 3; axis < 6; axis++) {
435
415
  // The half extent becomes e: 2^e is above the extent.
436
416
  const half = frame[axis];
437
417
  frame[axis] =
438
418
  half > 0 && half < Number.POSITIVE_INFINITY
439
- ? Math.max(binaryExponent(half) + 2, -1021)
419
+ ? Math.max(binaryExponentAt(frame, axis) + 2, -1021)
440
420
  : 0;
441
421
  }
442
- scaleFrameU16_(0);
443
422
  }
423
+ /** The exact sum of six times the volume, from {@link exactSixVolume_}. */
424
+ const SIX_VOLUME_ = new DotExactAccumulator();
444
425
  /**
445
- * Sets the factors of `FRAME_` to 2^−(e + extra) per axis, 2^(1 − e − extra)
446
- * where halves are subtracted. `extra` is 0 or the volume's common rescaling,
447
- * never so far below −e that the factor leaves the doubles: from −1020 to 0.
426
+ * A face's corners a (0–2), b (3–5) and c (6–8), then the frame's anchor o
427
+ * (9–11), as they are; then a, b and c again as significands in ±[1, 2) (0 for
428
+ * a zero coordinate) with the exponents they are scaled by.
448
429
  */
449
- function scaleFrameU16_(extra) {
450
- const shift = FRAME_[9] === 1 ? 1 : 0;
451
- for (let axis = 0; axis < 3; axis++) {
452
- // Beyond 2^1023 the factor is two: only an axis whose differences are
453
- // all below 1 gets there, and those stay finite after the first.
454
- const exponent = shift - FRAME_[3 + axis] - extra;
455
- FRAME_[6 + axis] = 2 ** Math.min(exponent, 1023);
456
- FRAME_[10 + axis] = 2 ** Math.max(exponent - 1023, 0);
457
- }
458
- }
430
+ const VOLUME_FACTORS_ = new Float64Array(12);
431
+ const VOLUME_SIGNIFICANDS_ = new Float64Array(9);
432
+ const VOLUME_EXPONENTS_ = new Int32Array(9);
433
+ /** One product of three coordinates as two products of two doubles. */
434
+ const TRIPLE_LEFT_ = new Float64Array(2);
435
+ const TRIPLE_RIGHT_ = new Float64Array(2);
459
436
  /**
460
- * Writes the edges `b − a` (0–2) and `c − a` (3–5) of a face into `EDGES_`,
461
- * scaled by the frame's factors: exact where the differences are (Sterbenz) and
462
- * the results are not subnormal. When the frame is wide, `p − q` may overflow,
463
- * so the halves are subtracted, which is exact for every normal `p` and `q`. No
464
- * double crosses the call, so it allocates nothing, inlined or not.
437
+ * The 24 products of three coordinates whose sum is det[a − o, b − o, c − o] =
438
+ * det[a, b, c] − o · (a × b + b × c + c × a), four entries each: the slots in
439
+ * `VOLUME_FACTORS_` of the two factors taken as significands and of the third,
440
+ * then the sign.
465
441
  */
466
- function scaledEdgesU16_(positions, a, b, c, isWide) {
467
- const frame = FRAME_;
468
- const edges = EDGES_;
469
- for (let axis = 0; axis < 3; axis++) {
470
- const factor = frame[6 + axis];
471
- const second = frame[10 + axis];
472
- const p = positions[a + axis];
473
- const q = positions[b + axis];
474
- const r = positions[c + axis];
475
- edges[axis] = (isWide ? q * 0.5 - p * 0.5 : q - p) * factor * second;
476
- edges[axis + 3] = (isWide ? r * 0.5 - p * 0.5 : r - p) * factor * second;
442
+ const VOLUME_TERMS_ = volumeTerms_();
443
+ function volumeTerms_() {
444
+ const terms = [];
445
+ for (let i = 0; i < 3; i++) {
446
+ const j = (i + 1) % 3;
447
+ const k = (i + 2) % 3;
448
+ terms.push(i, 3 + j, 6 + k, 1, i, 3 + k, 6 + j, -1);
477
449
  }
450
+ for (let k = 0; k < 3; k++) {
451
+ const i = (k + 1) % 3;
452
+ const j = (k + 2) % 3;
453
+ const o = 9 + k;
454
+ // −o_k ((a × b)_k + (b × c)_k + (c × a)_k), (u × v)_k = u_i v_j − u_j v_i.
455
+ terms.push(i, 3 + j, o, -1, j, 3 + i, o, 1);
456
+ terms.push(3 + i, 6 + j, o, -1, 3 + j, 6 + i, o, 1);
457
+ terms.push(6 + i, j, o, -1, 6 + j, i, o, 1);
458
+ }
459
+ return Int8Array.from(terms);
478
460
  }
479
461
  /**
480
- * Writes into `BOUNDS_` the exponents, as {@link binaryExponent} reads them, of
481
- * the largest component of `a − o`, `b − a` and `c − a` scaled into the frame
482
- * (`NONE_` for a zero or non-finite vector): each is below 2^(exponent + 1).
462
+ * Replaces `values[slot]`, finite and nonzero, by its significand in ±[1, 2),
463
+ * exactly (subnormals included), and writes its exponent plus `shift` to
464
+ * `exponents[slot]`; 0 and a non-finite value stay, with `shift`. No double
465
+ * crosses a call.
483
466
  */
484
- function faceBoundsU16_(positions, a, b, c, isWide) {
485
- const frame = FRAME_;
486
- const bounds = BOUNDS_;
487
- const shift = isWide ? 1 : 0;
488
- bounds[0] = NONE_;
489
- bounds[1] = NONE_;
490
- bounds[2] = NONE_;
491
- for (let axis = 0; axis < 3; axis++) {
492
- const p = positions[a + axis];
493
- const anchored = isWide ? p * 0.5 - frame[axis] * 0.5 : p - frame[axis];
494
- const ab = isWide
495
- ? positions[b + axis] * 0.5 - p * 0.5
496
- : positions[b + axis] - p;
497
- const ac = isWide
498
- ? positions[c + axis] * 0.5 - p * 0.5
499
- : positions[c + axis] - p;
500
- const offset = shift - frame[3 + axis];
501
- if (anchored !== 0 && anchored - anchored === 0) {
502
- bounds[0] = Math.max(bounds[0], binaryExponent(anchored) + offset);
503
- }
504
- if (ab !== 0 && ab - ab === 0) {
505
- bounds[1] = Math.max(bounds[1], binaryExponent(ab) + offset);
506
- }
507
- if (ac !== 0 && ac - ac === 0) {
508
- bounds[2] = Math.max(bounds[2], binaryExponent(ac) + offset);
509
- }
467
+ function splitAt_(values, exponents, slot, shift) {
468
+ const value = values[slot];
469
+ if (value === 0 || value - value !== 0) {
470
+ exponents[slot] = shift;
471
+ return;
510
472
  }
473
+ const exponent = binaryExponentAt(values, slot);
474
+ scaleByPowerOfTwoInPlace(values, slot, 0 - exponent);
475
+ exponents[slot] = exponent + shift;
511
476
  }
512
477
  /**
513
- * Writes the corner at `vertex` relative to the anchor, scaled by the frame's
514
- * factors, into `VERTEX_` as high parts (0–2) and the low parts TwoSum recovers
515
- * (3–5): their sum is the scaled difference exactly, wherever it is not
516
- * subnormal.
478
+ * Adds six times the signed volume of the face at `a`, `b` and `c` against the
479
+ * anchor o in `VOLUME_FACTORS_[9–11]` to `SIX_VOLUME_`, exactly, for any finite
480
+ * corners: det[a − o, b − o, c − o], the same for each rotation of the face,
481
+ * expanded into the 24 products of three coordinates of {@link VOLUME_TERMS_},
482
+ * so that no difference is ever rounded. Each is the product of two
483
+ * significands, exact by TwoProduct, times the third coordinate, scaled by the
484
+ * two exponents: two products of two doubles the long accumulator holds at any
485
+ * magnitude, so no term is lost to overflow or to the subnormals. Non-finite
486
+ * corners leave the accumulator's plain sum.
517
487
  */
518
- function anchoredCornerU16_(positions, vertex, isWide) {
519
- const pair = PAIR_;
488
+ function exactSixVolumeU16_(positions, a, b, c) {
489
+ const factors = VOLUME_FACTORS_;
490
+ const significands = VOLUME_SIGNIFICANDS_;
491
+ const exponents = VOLUME_EXPONENTS_;
520
492
  for (let axis = 0; axis < 3; axis++) {
521
- const factor = FRAME_[6 + axis];
522
- const second = FRAME_[10 + axis];
523
- pair[0] = isWide
524
- ? positions[vertex + axis] * 0.5
525
- : positions[vertex + axis];
526
- pair[1] = isWide ? -(FRAME_[axis] * 0.5) : -FRAME_[axis];
527
- twoSumInPlace(pair, 0);
528
- VERTEX_[axis] = pair[0] * factor * second;
529
- VERTEX_[axis + 3] = pair[1] * factor * second;
493
+ factors[axis] = positions[a + axis];
494
+ factors[3 + axis] = positions[b + axis];
495
+ factors[6 + axis] = positions[c + axis];
496
+ }
497
+ for (let slot = 0; slot < 9; slot++) {
498
+ significands[slot] = factors[slot];
499
+ splitAt_(significands, exponents, slot, 0);
500
+ }
501
+ const terms = VOLUME_TERMS_;
502
+ const product = PAIR_;
503
+ const left = TRIPLE_LEFT_;
504
+ const right = TRIPLE_RIGHT_;
505
+ for (let term = 0; term < terms.length; term += 4) {
506
+ const first = terms[term];
507
+ const second = terms[term + 1];
508
+ const third = factors[terms[term + 2]];
509
+ if (significands[first] === 0 ||
510
+ significands[second] === 0 ||
511
+ third === 0) {
512
+ continue;
513
+ }
514
+ product[0] = significands[first];
515
+ product[1] = significands[second];
516
+ twoProductInRangeInPlace(product, 0);
517
+ left[0] = terms[term + 3] * third;
518
+ left[1] = left[0];
519
+ right[0] = product[0];
520
+ right[1] = product[1];
521
+ SIX_VOLUME_.addProducts(left, right, exponents[first] + exponents[second]);
530
522
  }
531
523
  }
532
524
  /**
@@ -597,29 +589,31 @@ export function mesh3SurfaceAreaU16(positions, indices) {
597
589
  }
598
590
  /** The unit roundoff, 2^−53. */
599
591
  const UNIT_ROUNDOFF_ = 2 ** -53;
592
+ /** Veltkamp's splitter, 2^27 + 1, for exact Dekker products in range. */
593
+ const SPLITTER_ = 134217729;
600
594
  /**
601
595
  * The adaptive filter of {@link mesh3Volume}: six times the volume, over the
602
- * same terms as the exact sum (`a − o` exactly as TwoSum's pair, the edges as
603
- * rounded), in doubled precision. Each cross component is the difference of two
604
- * TwoProducts with their errors; each term's high products are TwoProducts too
605
- * and summed by TwoSum, and every remaining part goes into one plain sum. What
606
- * that drops is bounded rigorously: per face, below 12u² Σ |a − o|ₖ (|p|
607
- *
608
- * - |q|)ₖ over the products p, q of each cross component (u = 2^−53, the
609
- * neglected low-by-low products and the roundings of the low parts), plus the
610
- * plain sum's rounding, γ_N Σ |parts| for its N parts (Higham, "Accuracy and
611
- * Stability of Numerical Algorithms", §4.2), plus an absolute 2^−1066 per
612
- * face for products in the subnormal range. When the rounded total r is
613
- * normal and its distance to the double sum, plus that bound, stays short of
614
- * the midpoint on that side (half its unit in the last place, a quarter below
615
- * a power of two), the exact value rounds to r: written to `VALUE_[0]`, and
616
- * `true`. Otherwise `false`, and the exact sum decides. The frame must be set
617
- * and no extent may reach 2^300, so no product overflows.
596
+ * same value as the exact sum, Σ (a − o) · ((b − a) × (c − a)) with `a − o` and
597
+ * the edges exactly as TwoSum's pairs, in doubled precision. Each edge
598
+ * component is split once and reused across both cross-product terms; every
599
+ * product and sum runs in scalar registers with no typed-array traffic or
600
+ * range-scaling checks (the caller guarantees extents below 2^300 and anchor
601
+ * below 2^1000, so no intermediate reaches 2^903). What that drops is bounded
602
+ * rigorously: per face, below (128u + 9γ_N)·u·Σ |a − o|ₖ (|p| + |q|)ₖ over the
603
+ * products p, q of each cross component (u = 2^−53: the neglected low-by-low
604
+ * products, the products of two edge errors, each below u² of the product of
605
+ * the edges, and the roundings of the low parts, the edges' first-order terms,
606
+ * each below 2.01u (|p| + |q|), included), plus the plain sum's rounding, γ_N Σ
607
+ * |parts| for its N parts (Higham, "Accuracy and Stability of Numerical
608
+ * Algorithms", §4.2), plus an absolute 2^−1065 per face and per cross product
609
+ * component, the latter times the frame's bound 2^e on `a − o`, for products in
610
+ * the subnormal range. Then {@link certifySixVolume_} rounds the sixth of the
611
+ * total and proves it.
618
612
  */
619
613
  function certifiedSixVolumeU16_(positions, indices) {
620
- // Every TwoSum and TwoProduct runs in place on this buffer: no double
621
- // crosses a call, so nothing is boxed whether or not the engine inlines them.
622
- const filter = FILTER_;
614
+ const negOX = -FRAME_[0];
615
+ const negOY = -FRAME_[1];
616
+ const negOZ = -FRAME_[2];
623
617
  let high = 0;
624
618
  let low = 0;
625
619
  let lowMagnitude = 0;
@@ -628,89 +622,226 @@ function certifiedSixVolumeU16_(positions, indices) {
628
622
  const a = indices[corner] * 3;
629
623
  const b = indices[corner + 1] * 3;
630
624
  const c = indices[corner + 2] * 3;
631
- // a − o as TwoSum's pairs, at 0–5.
632
- for (let axis = 0; axis < 3; axis++) {
633
- filter[2 * axis] = positions[a + axis];
634
- filter[2 * axis + 1] = -FRAME_[axis];
635
- twoSumInPlace(filter, 2 * axis);
636
- }
637
- const abX = positions[b] - positions[a];
638
- const abY = positions[b + 1] - positions[a + 1];
639
- const abZ = positions[b + 2] - positions[a + 2];
640
- const acX = positions[c] - positions[a];
641
- const acY = positions[c + 1] - positions[a + 1];
642
- const acZ = positions[c + 2] - positions[a + 2];
643
- // Cross component k is p − q, p at 6 + 4k and q at 8 + 4k, each with its
644
- // TwoProduct error after it.
645
- filter[6] = abY;
646
- filter[7] = acZ;
647
- filter[8] = abZ;
648
- filter[9] = acY;
649
- filter[10] = abZ;
650
- filter[11] = acX;
651
- filter[12] = abX;
652
- filter[13] = acZ;
653
- filter[14] = abX;
654
- filter[15] = acY;
655
- filter[16] = abY;
656
- filter[17] = acX;
657
- // One call site for all nine TwoProducts, so the engine inlines it once:
658
- // the six of the cross components first, then the three of the terms
659
- // (a − o)ₖ · crossₖ at 24–29, with each cross component's low part at
660
- // 30 + k and the component itself at 33 + k.
661
- let end = 18;
662
- for (let phase = 0; phase < 2; phase++) {
663
- for (let at = phase === 0 ? 6 : 24; at < end; at += 2) {
664
- twoProductInRangeInPlace(filter, at);
665
- }
666
- if (phase === 1) {
667
- break;
668
- }
669
- for (let axis = 0; axis < 3; axis++) {
670
- const first = filter[6 + 4 * axis];
671
- const second = filter[8 + 4 * axis];
672
- filter[18] = first;
673
- filter[19] = -second;
674
- twoSumInPlace(filter, 18);
675
- const anchored = filter[2 * axis];
676
- filter[30 + axis] =
677
- filter[19] + filter[7 + 4 * axis] - filter[9 + 4 * axis];
678
- filter[33 + axis] = filter[18];
679
- filter[24 + 2 * axis] = anchored;
680
- filter[25 + 2 * axis] = filter[18];
681
- magnitude += Math.abs(anchored) * (Math.abs(first) + Math.abs(second));
682
- }
683
- end = 30;
684
- }
685
- for (let axis = 0; axis < 3; axis++) {
686
- filter[22] = high;
687
- filter[23] = filter[24 + 2 * axis];
688
- twoSumInPlace(filter, 22);
689
- high = filter[22];
690
- const carry = filter[23];
691
- const error = filter[25 + 2 * axis];
692
- const mixed = filter[2 * axis] * filter[30 + axis];
693
- const mixedLow = filter[2 * axis + 1] * filter[33 + axis];
694
- low += carry + error + mixed + mixedLow;
695
- lowMagnitude +=
696
- Math.abs(carry) +
697
- Math.abs(error) +
698
- Math.abs(mixed) +
699
- Math.abs(mixedLow);
700
- }
625
+ const paX = positions[a];
626
+ const paY = positions[a + 1];
627
+ const paZ = positions[a + 2];
628
+ const pbX = positions[b];
629
+ const pbY = positions[b + 1];
630
+ const pbZ = positions[b + 2];
631
+ const pcX = positions[c];
632
+ const pcY = positions[c + 1];
633
+ const pcZ = positions[c + 2];
634
+ // The edges and their exact errors (TwoSum).
635
+ const abX = pbX - paX;
636
+ let t = abX - pbX;
637
+ const abXErr = pbX - (abX - t) + (-paX - t);
638
+ const abY = pbY - paY;
639
+ t = abY - pbY;
640
+ const abYErr = pbY - (abY - t) + (-paY - t);
641
+ const abZ = pbZ - paZ;
642
+ t = abZ - pbZ;
643
+ const abZErr = pbZ - (abZ - t) + (-paZ - t);
644
+ const acX = pcX - paX;
645
+ t = acX - pcX;
646
+ const acXErr = pcX - (acX - t) + (-paX - t);
647
+ const acY = pcY - paY;
648
+ t = acY - pcY;
649
+ const acYErr = pcY - (acY - t) + (-paY - t);
650
+ const acZ = pcZ - paZ;
651
+ t = acZ - pcZ;
652
+ const acZErr = pcZ - (acZ - t) + (-paZ - t);
653
+ // Split each edge component once (reused in two cross products).
654
+ let s = SPLITTER_ * abX;
655
+ const abXHi = s - (s - abX);
656
+ const abXLo = abX - abXHi;
657
+ s = SPLITTER_ * abY;
658
+ const abYHi = s - (s - abY);
659
+ const abYLo = abY - abYHi;
660
+ s = SPLITTER_ * abZ;
661
+ const abZHi = s - (s - abZ);
662
+ const abZLo = abZ - abZHi;
663
+ s = SPLITTER_ * acX;
664
+ const acXHi = s - (s - acX);
665
+ const acXLo = acX - acXHi;
666
+ s = SPLITTER_ * acY;
667
+ const acYHi = s - (s - acY);
668
+ const acYLo = acY - acYHi;
669
+ s = SPLITTER_ * acZ;
670
+ const acZHi = s - (s - acZ);
671
+ const acZLo = acZ - acZHi;
672
+ // Cross X = abY * acZ - abZ * acY, then X term of dot product.
673
+ const pX = abY * acZ;
674
+ const pXErr = abYLo * acZLo - (pX - abYHi * acZHi - abYLo * acZHi - abYHi * acZLo);
675
+ const qX = abZ * acY;
676
+ const qXErr = abZLo * acYLo - (qX - abZHi * acYHi - abZLo * acYHi - abZHi * acYLo);
677
+ const cX = pX - qX;
678
+ let r = cX + qX;
679
+ const cXLo = pX -
680
+ r +
681
+ (-qX - (cX - r)) +
682
+ pXErr -
683
+ qXErr +
684
+ (abY * acZErr + abYErr * acZ - (abZ * acYErr + abZErr * acY));
685
+ const ax = paX + negOX;
686
+ r = ax - negOX;
687
+ const axLo = paX - r + (negOX - (ax - r));
688
+ let faceMag = Math.abs(ax) * (Math.abs(pX) + Math.abs(qX));
689
+ s = SPLITTER_ * ax;
690
+ const axHi = s - (s - ax);
691
+ const axSp = ax - axHi;
692
+ s = SPLITTER_ * cX;
693
+ const cXHi = s - (s - cX);
694
+ const cXSp = cX - cXHi;
695
+ const tX = ax * cX;
696
+ let faceLow = axSp * cXSp -
697
+ (tX - axHi * cXHi - axSp * cXHi - axHi * cXSp) +
698
+ ax * cXLo +
699
+ axLo * cX;
700
+ // Cross Y = abZ * acX - abX * acZ, then Y term of dot product.
701
+ const pY = abZ * acX;
702
+ const pYErr = abZLo * acXLo - (pY - abZHi * acXHi - abZLo * acXHi - abZHi * acXLo);
703
+ const qY = abX * acZ;
704
+ const qYErr = abXLo * acZLo - (qY - abXHi * acZHi - abXLo * acZHi - abXHi * acZLo);
705
+ const cY = pY - qY;
706
+ r = cY + qY;
707
+ const cYLo = pY -
708
+ r +
709
+ (-qY - (cY - r)) +
710
+ pYErr -
711
+ qYErr +
712
+ (abZ * acXErr + abZErr * acX - (abX * acZErr + abXErr * acZ));
713
+ const ay = paY + negOY;
714
+ r = ay - negOY;
715
+ const ayLo = paY - r + (negOY - (ay - r));
716
+ faceMag += Math.abs(ay) * (Math.abs(pY) + Math.abs(qY));
717
+ s = SPLITTER_ * ay;
718
+ const ayHi = s - (s - ay);
719
+ const aySp = ay - ayHi;
720
+ s = SPLITTER_ * cY;
721
+ const cYHi = s - (s - cY);
722
+ const cYSp = cY - cYHi;
723
+ const tY = ay * cY;
724
+ faceLow +=
725
+ aySp * cYSp -
726
+ (tY - ayHi * cYHi - aySp * cYHi - ayHi * cYSp) +
727
+ ay * cYLo +
728
+ ayLo * cY;
729
+ // Cross Z = abX * acY - abY * acX, then Z term of dot product.
730
+ const pZ = abX * acY;
731
+ const pZErr = abXLo * acYLo - (pZ - abXHi * acYHi - abXLo * acYHi - abXHi * acYLo);
732
+ const qZ = abY * acX;
733
+ const qZErr = abYLo * acXLo - (qZ - abYHi * acXHi - abYLo * acXHi - abYHi * acXLo);
734
+ const cZ = pZ - qZ;
735
+ r = cZ + qZ;
736
+ const cZLo = pZ -
737
+ r +
738
+ (-qZ - (cZ - r)) +
739
+ pZErr -
740
+ qZErr +
741
+ (abX * acYErr + abXErr * acY - (abY * acXErr + abYErr * acX));
742
+ const az = paZ + negOZ;
743
+ r = az - negOZ;
744
+ const azLo = paZ - r + (negOZ - (az - r));
745
+ magnitude += faceMag + Math.abs(az) * (Math.abs(pZ) + Math.abs(qZ));
746
+ s = SPLITTER_ * az;
747
+ const azHi = s - (s - az);
748
+ const azSp = az - azHi;
749
+ s = SPLITTER_ * cZ;
750
+ const cZHi = s - (s - cZ);
751
+ const cZSp = cZ - cZHi;
752
+ const tZ = az * cZ;
753
+ faceLow +=
754
+ azSp * cZSp -
755
+ (tZ - azHi * cZHi - azSp * cZHi - azHi * cZSp) +
756
+ az * cZLo +
757
+ azLo * cZ;
758
+ // Sum the face's three high terms first, then add once to `high` so the
759
+ // loop-carried dependency chain is one TwoSum per face instead of three.
760
+ const s01 = tX + tY;
761
+ r = s01 - tY;
762
+ const e01 = tX - r + (tY - (s01 - r));
763
+ const fHi = s01 + tZ;
764
+ r = fHi - tZ;
765
+ const e02 = s01 - r + (tZ - (fHi - r));
766
+ const nextHigh = high + fHi;
767
+ r = nextHigh - fHi;
768
+ const carry = high - r + (fHi - (nextHigh - r));
769
+ high = nextHigh;
770
+ low += carry + (faceLow + e01 + e02);
771
+ lowMagnitude += Math.abs(carry);
701
772
  }
773
+ const filter = FILTER_;
702
774
  filter[22] = high;
703
775
  filter[23] = low;
704
776
  filter[0] = magnitude;
705
777
  filter[1] = lowMagnitude;
706
778
  return certifySixVolumeU16_(indices.length);
707
779
  }
780
+ /*
781
+ * Faithful rounding (`rounding: "faithful"`): what a first stage at about the
782
+ * plain sum's cost can prove. The contract is a result within one unit in the
783
+ * last place of the default one, R: r and R equal or adjacent doubles, counted
784
+ * through the subnormals. A first stage may return r only where a rigorous
785
+ * bound proves it; anywhere else the default computation runs.
786
+ *
787
+ * Notation (Higham, "Accuracy and Stability of Numerical Algorithms", 2nd ed.,
788
+ * §2.2 and §3.1): u = 2^−53, η = 2^−1075, γ_k = k·u / (1 − k·u). Rounding to
789
+ * nearest gives fl(a ∘ b) = (a ∘ b)(1 + δ) + ε with |δ| ≤ u and |ε| ≤ η, ε = 0
790
+ * for a sum or difference (an underflowing sum is exact). So |fl(z) − z| ≤
791
+ * u·|fl(z)| for a sum or a difference at any magnitude, but for a product or a
792
+ * quotient only |fl(z) − z| ≤ u·|fl(z)| + η: fl(3·2^−1074 · 0.5) = 2^−1073
793
+ * is η from 1.5·2^−1074, far beyond u of it. Away from the subnormals, k
794
+ * factors 1 + δ in a chain compose to 1 + θ_k with |θ_k| ≤ γ_k (Lemma 3.1);
795
+ * each product or quotient that may underflow adds its η, carried through
796
+ * the rest of the chain. The compensated sum (Neumaier's, the same values as
797
+ * Ogita, Rump and Oishi's Sum2, "Accurate Sum and Dot Product", SIAM J. Sci.
798
+ * Comput. 26, 2005, Proposition 4.5) of n terms x_i, with res = fl(sum +
799
+ * compensation), keeps |res − Σ x_i| ≤ u·|Σ x_i| + γ²_{n−1}·Σ |x_i|,
800
+ * underflow included, since each error-free sum stays exact there.
801
+ *
802
+ * Volume: no uniform error bound on a plain pass proves one ulp. R = RN(T /
803
+ * 6), T = Σ_f T_f and T_f = Σ_k (a − o)_k (p_k − q_k), p_k and q_k the exact
804
+ * products of the exact edges. A plain evaluation rounds a − o, the edges,
805
+ * both products, their difference, the product by a − o and two sums:
806
+ * |T̂_f − T_f| ≤ γ_8·M_f (plus η per product below the normal range) with M_f
807
+ * = Σ_k |a − o|_k (|p_k| + |q_k|), and the sum adds γ²_{n−1}·Σ |T̂_f|. r6,
808
+ * the rounded total, is faithful to T only when |T − r6| stays below the gap
809
+ * from r6 to its neighbour toward T, at most 2^(e − 52) ≤ 2u·|r6| for 2^e ≤
810
+ * |r6|. But M = Σ M_f ≥ |T|, so the bound, about 8u·M, exceeds every such gap
811
+ * for every nonzero volume: a test against it can never pass. The bound is
812
+ * not merely pessimistic; already the rounding of one product and of its
813
+ * product by a − o reach u·|T| each on a face whose term dominates, and a
814
+ * plain compensated sum is 2 ulps off on a near-cancelling tetrahedron of the
815
+ * tests. A running error bound (Wilkinson) is no better, since it sums u
816
+ * times every computed intermediate, at least 2u·|T|.
817
+ *
818
+ * That rules out certifying a plain pass by an error bound that holds for
819
+ * every input, not every cheap certification. Where no operation of the plain
820
+ * pass rounds (coordinates on a coarse dyadic grid, as a voxel or small-integer
821
+ * box mesh has them, whose products and sums all fit in 53 bits), T̂ = T, and
822
+ * a check of that grid would prove R at about plain cost. It covers only such
823
+ * meshes: a tessellated, generated or scanned surface has full-precision
824
+ * coordinates, whose products round, and the doubled-precision filter already
825
+ * certifies a grid mesh unless its volume cancels by some 2^44. So no such
826
+ * check is added. In general the roundings of the products must be removed, by
827
+ * TwoProduct (Dekker's, no fused multiply-add in JavaScript): a
828
+ * doubled-precision first stage, which is what the default filter already is.
829
+ * And the division by 6 rounds again: a faithful r6 can give fl(r6 / 6) two
830
+ * ulps from R, so even that stage has to enclose T / 6 and check it against
831
+ * the midpoints, as the default filter does. `"faithful"` volume therefore
832
+ * runs the default computation; a looser
833
+ * contract with a proven k (k ulps of M / 6, not of the volume, since T may
834
+ * cancel) or a doubled stage are the alternatives.
835
+ *
836
+ * Centroid: see {@link faithfulCentroid_}, which can be proven at plain cost,
837
+ * but only where the result is large beside the mesh's extent.
838
+ */
708
839
  /**
709
840
  * The end of {@link certifiedSixVolume_}, from the sums it leaves in `FILTER_`
710
841
  * (the high and low parts at 22 and 23, the magnitudes of the products and of
711
- * the low parts at 0 and 1), for `cornerCount` corners: kept apart so that
712
- * `binaryExponent` is inlined here whatever budget the accumulation spent (a
713
- * double passed to a call the engine does not inline is boxed).
842
+ * the low parts at 0 and 1), for `cornerCount` corners: kept apart, its doubles
843
+ * read from there (a double passed to a call the engine does not inline is
844
+ * boxed).
714
845
  */
715
846
  function certifySixVolumeU16_(cornerCount) {
716
847
  const filter = FILTER_;
@@ -719,175 +850,594 @@ function certifySixVolumeU16_(cornerCount) {
719
850
  twoSumInPlace(filter, 22);
720
851
  const total = filter[22];
721
852
  const difference = filter[23];
722
- // N parts: four per axis of each face, summed into one plain sum.
723
- const parts = (cornerCount / 3) * 12 + 2;
853
+ // Each face adds 2 terms into `low` (`carry` and `faceLow + e01 + e02`);
854
+ // the face-local low terms, the edges' first-order ones included, have sum
855
+ // of magnitudes at most 8.3u · faceMag, so their internal rounding is below
856
+ // 128u² · magnitude and their contribution to `low`'s rounding is below
857
+ // 9 · gamma · u · magnitude.
858
+ const parts = (cornerCount / 3) * 2 + 2;
724
859
  const gamma = (parts * UNIT_ROUNDOFF_) / (1 - parts * UNIT_ROUNDOFF_);
725
860
  if (!(gamma < 0.01)) {
726
861
  return false;
727
862
  }
728
- const bound = 12 * UNIT_ROUNDOFF_ * UNIT_ROUNDOFF_ * magnitude * (1 + 2 * gamma) +
863
+ // Below 2^−969 a product's TwoProduct error is no longer exact and a product
864
+ // may underflow: at most 2^−1065 for each of a face's three terms and for
865
+ // each component of its cross product, which a − o then multiplies, below
866
+ // 2^e along its axis.
867
+ const reach = 3 + 2 ** FRAME_[3] + 2 ** FRAME_[4] + 2 ** FRAME_[5];
868
+ const bound = (128 * UNIT_ROUNDOFF_ + 9 * gamma) *
869
+ UNIT_ROUNDOFF_ *
870
+ magnitude *
871
+ (1 + 2 * gamma) +
729
872
  gamma * lowMagnitude * (1 + 2 * gamma) +
730
- (cornerCount / 3) * 2 ** -1066;
873
+ (cornerCount / 3) * 2 ** -1065 * reach;
731
874
  const size = Math.abs(total);
732
- if (!(size >= 2 ** -960 && size < Number.POSITIVE_INFINITY)) {
875
+ if (!(size >= 2 ** -960 && size < 2 ** 1000)) {
733
876
  return false;
734
877
  }
735
- // The exact value lies within `bound` of total + difference; it rounds to
736
- // `total` while that stays short of the midpoint on difference's side: half
737
- // a unit in the last place, a quarter below a power of two.
738
- const exponent = binaryExponent(total);
739
- const isTowardZero = difference !== 0 && difference < 0 !== total < 0;
740
- const isPowerOfTwo = size === 2 ** exponent;
741
- const half = 2 ** (exponent - (isTowardZero && isPowerOfTwo ? 54 : 53));
742
- if (!(Math.abs(difference) + bound < half)) {
878
+ // The volume is T / 6, T within `bound` of total + difference. Its
879
+ // candidate q = fl(total / 6): 6q = pair[0] + pair[1] exactly (TwoProduct),
880
+ // and total − pair[0] is exact (Sterbenz), so `offset` is (T − 6q) / 6 up to
881
+ // the bound's sixth and a few roundings of u times some units of q's last
882
+ // place, far below 2^−40 of it. T / 6 rounds to q while it stays short of
883
+ // the nearer midpoint: half a unit in the last place, a quarter at a power
884
+ // of two (on either side, conservatively).
885
+ const quotient = total / 6;
886
+ const pair = PAIR_;
887
+ pair[0] = quotient;
888
+ pair[1] = 6;
889
+ twoProductInRangeInPlace(pair, 0);
890
+ const offset = (total - pair[0] - pair[1] + difference) / 6;
891
+ filter[24] = quotient;
892
+ const exponent = binaryExponentAt(filter, 24);
893
+ const isPowerOfTwo = Math.abs(quotient) === 2 ** exponent;
894
+ const half = 2 ** (exponent - (isPowerOfTwo ? 54 : 53));
895
+ if (!(Math.abs(offset) + (bound / 6) * (1 + 2 ** -40) + half * 2 ** -40 < half)) {
743
896
  return false;
744
897
  }
745
- VALUE_[0] = total;
898
+ VALUE_[0] = quotient;
746
899
  return true;
747
900
  }
748
901
  /**
749
- * The `Uint16Array` twin of the signed volume: six times it is `Σ (a − o) · ((b
750
- * − a) × (c − a))` over the faces, o being the frame's anchor (any point gives
751
- * the same volume for a closed mesh). The sum is a determinant per face, so
752
- * each axis may take its own power-of-two scale: the frame brings every axis's
753
- * extent below 1, then a first pass over the faces bounds their terms and one
754
- * common power of two brings the largest near 2^1000, so that no product
755
- * overflows and small faces keep their digits, however thin, wide or far from
756
- * the origin the mesh is. Each face's term is then written as exact products:
757
- * `a − o` as TwoSum's pair, the cross product as an expansion (each component
758
- * two products and their rounding errors, Ogita, Rump & Oishi's TwoProduct),
759
- * and the whole summed exactly (`PreciseSum`). With the face-local edge
760
- * differences exact, which they are wherever a face is small beside its
761
- * distance from the origin (Sterbenz), the result is six times the volume
762
- * rounded once, then divided by 6: the same number in every face order and at
763
- * every offset, and a vertex no triangle uses is never read. A term below about
764
- * 2^−1900 of the largest may lose digits to the subnormal range; so may a
765
- * volume that small beside the largest term. O(triangles), no allocation.
902
+ * The `Uint16Array` twin of the signed volume: six times it is T = `Σ det[a −
903
+ * o, b − o, c − o]` over the faces, o being the frame's anchor (any point gives
904
+ * the same volume for a closed mesh), every coordinate exact. An ordinary mesh
905
+ * is certified by the doubled-precision filter, which proves the rounded T / 6;
906
+ * anywhere else every face's term is summed exactly in a long accumulator
907
+ * ({@link exactSixVolume_}), whatever the magnitudes, and T / 6 is rounded once
908
+ * from it ({@link roundQuotient_}): the same number in every face order and for
909
+ * every rotation of a face's corners, and a vertex no triangle uses is never
910
+ * read. Written to `out[0]`: a double returned from a call the engine does not
911
+ * inline is boxed. O(triangles), no allocation.
766
912
  */
767
- export function mesh3VolumeU16(positions, indices) {
768
- const sum = SIX_VOLUMES_;
769
- const vertex = VERTEX_;
770
- const cross = CROSS_;
771
- const terms = TERMS_;
913
+ export function mesh3VolumeU16(out, positions, indices) {
772
914
  const frame = FRAME_;
773
- sum.reset();
774
915
  frameU16_(positions, indices);
775
- const isWide = frame[9] === 1;
776
- // The filter: an ordinary mesh (no extent from 2^300 up) is summed in
777
- // doubled precision with a rigorous error bound, and the exact sums below
778
- // run only when that bound cannot certify the rounded result.
916
+ const isWide = frame[6] === 1;
917
+ // The filter: an ordinary mesh (no extent from 2^300 up, anchor below
918
+ // 2^1000) is summed in doubled precision with a rigorous error bound, and
919
+ // the exact sums below run only when that bound cannot certify the rounded
920
+ // result.
779
921
  if (!isWide &&
780
922
  frame[3] <= 300 &&
781
923
  frame[4] <= 300 &&
782
924
  frame[5] <= 300 &&
925
+ Math.abs(frame[0]) < 2 ** 1000 &&
926
+ Math.abs(frame[1]) < 2 ** 1000 &&
927
+ Math.abs(frame[2]) < 2 ** 1000 &&
783
928
  certifiedSixVolumeU16_(positions, indices)) {
784
- // `+ 0`: an empty sum is −0, as `Math.sumPrecise`'s.
785
- return VALUE_[0] / 6 + 0;
929
+ out[0] = VALUE_[0];
930
+ return;
786
931
  }
787
- const bounds = BOUNDS_;
788
- let termMax = NONE_;
789
- let crossMax = NONE_;
790
- let differenceMax = NONE_;
932
+ const sum = SIX_VOLUME_;
933
+ sum.reset();
934
+ VOLUME_FACTORS_[9] = frame[0];
935
+ VOLUME_FACTORS_[10] = frame[1];
936
+ VOLUME_FACTORS_[11] = frame[2];
791
937
  for (let corner = 0; corner < indices.length; corner += 3) {
792
- faceBoundsU16_(positions, indices[corner] * 3, indices[corner + 1] * 3, indices[corner + 2] * 3, isWide);
793
- const anchored = bounds[0];
794
- const ab = bounds[1];
795
- const ac = bounds[2];
796
- differenceMax = Math.max(differenceMax, anchored, ab, ac);
797
- if (ab > NONE_ && ac > NONE_) {
798
- crossMax = Math.max(crossMax, ab + ac);
799
- if (anchored > NONE_) {
800
- termMax = Math.max(termMax, anchored + ab + ac);
801
- }
938
+ exactSixVolumeU16_(positions, indices[corner] * 3, indices[corner + 1] * 3, indices[corner + 2] * 3);
939
+ }
940
+ const reads = QUOTIENT_READS_;
941
+ readPieces_(sum, reads, 4);
942
+ if (reads[4] - reads[4] !== 0) {
943
+ // A non-finite corner: the plain sum's sixth.
944
+ out[0] = reads[4] / 6;
945
+ return;
946
+ }
947
+ // The divisor 6 as 3 · 2^1 (`roundQuotient_` divides by 3 times it).
948
+ reads[0] = 1;
949
+ reads[1] = 1;
950
+ reads[2] = 0;
951
+ reads[3] = 0;
952
+ // An exact zero is +0; a nonzero volume that rounds to zero keeps its sign.
953
+ roundQuotientU16_(out, 0, positions, indices, VOLUME_AXIS_);
954
+ }
955
+ /**
956
+ * The sums {@link faithfulCentroid_} leaves for {@link certifyCentroid_}: the
957
+ * weights' compensated sum (0, 1), the weighted offsets' per axis (2–4, their
958
+ * compensations 5–7), the first corner o′ (8–10), the sum of the faces' cross
959
+ * product magnitudes P (11), the least (12–14) and greatest (15–17) coordinates
960
+ * per axis, and the result (18–20).
961
+ */
962
+ const CENTROID_FILTER_ = new Float64Array(21);
963
+ /**
964
+ * The faithful first stage of {@link mesh3Centroid}, at about a plain sum's
965
+ * cost: in one pass, each face's weight w = ‖ĉ‖ from its plain cross product ĉ,
966
+ * its corners' offsets from the first corner o′ summed into ŝ, and w and w·ŝ
967
+ * summed with Neumaier's compensation, while the bounding box and Σ P, P = Σ_k
968
+ * (|p̂_k| + |q̂_k|) over the six rounded products of ĉ, are kept for the bound.
969
+ * Then {@link certifyCentroid_} proves the result or returns `false`, and the
970
+ * default computation runs.
971
+ *
972
+ * The bound (notation and the compensated sum's error: the block above the
973
+ * volume kernel). R, the default result per axis, is RN(Q), Q = Σ ω_f c_f / Σ
974
+ * ω_f the exact mean of the faces' centroids c_f under the default weights ω_f,
975
+ * rounded once ({@link roundQuotient_}). Let x be the axis's extent, n the face
976
+ * count, and recall that |fl(z) − z| ≤ u·|fl(z)| holds for a sum or a
977
+ * difference (exact in the subnormals) but a product or a quotient may lose up
978
+ * to η more there: fl(1.5 · 2^−1074) = 2^−1073, an error of 2^−1075.
979
+ *
980
+ * 1. The weights. Each edge rounds once, each product once more and may underflow,
981
+ * each difference once: |ĉ_k − X_k| ≤ 4.002u (|p̂_k| + |q̂_k|) + 2.01η
982
+ * against the exact cross product X of the exact corners. The squares, their
983
+ * sum and the root put w within 2.53u·w + 2^−535 of ‖ĉ‖, the 2^−535 only
984
+ * where the squares' sum is below 2^−970 and ĉ ≠ 0. So |w − ‖X‖| ≤ 2.53u·w +
985
+ * 4.02u·P + 2^−535 + 6.03η. The default weight is `triangle3Cross_`'s
986
+ * product, each component within 2^−49 of the largest of X, then squared,
987
+ * summed and rooted, and taken as m · 2^k exactly: |ω_f − ‖X‖| ≤ 30.3u·‖X‖.
988
+ * Together |ω_f − w_f| ≤ ε_f, Σ ε_f ≤ 33u·Σ w + 4.03u·Σ P / (1 − γ_n) +
989
+ * 2^−534 per such tiny face + n·2^−1072 =: E_w.
990
+ * 2. Changing the weights moves the mean by Σ (ω_f − w_f)(c_f − q_w) / Σ ω_f, and
991
+ * every c_f and q_w lies in the box: |Q − q_w| ≤ x·E_w / (Σ w − E_w), q_w
992
+ * the exact mean under the weights w.
993
+ * 3. The pass, under the weights w: ŝ = fl(fl(â + b̂) + ĉ) of the three offsets â
994
+ * = fl(a − o′) from the first corner o′, each below x, is within 8.01u·x of
995
+ * the exact 3·(c_f − o′); w·ŝ rounds once more (3.0001u·w·x + η); the
996
+ * compensated sums add (u + γ²_{n−1})·Σ |w·ŝ| for the offsets and (u +
997
+ * γ²_{n−1})·Σ w for the weights; 3·Σw and the quotient round once each, and
998
+ * may each lose η. With |q_w − o′| ≤ x, the quotient q̂ is within x·(7.7u +
999
+ * 2.1γ²_n + 2^−1074 / Σ w) + n·2^−1074 / Σ w + η of q_w − o′.
1000
+ *
1001
+ * So |Q − o′ − q̂| ≤ B = x·(E_w / (Σ w − E_w) + 7.7u + 2.1γ²_n + 2^−1074 / Σ w) +
1002
+ * n·2^−1074 / Σ w + 2^−1071. The bound is evaluated in doubles, rounded upward
1003
+ * by a factor 1 + 2^−38, with 3u·|q̂| and 2^−1073 for the roundings of q̂ ± B
1004
+ * (sums: within u of their result, exact in the subnormals). So o′ + fl(q̂ − B)
1005
+ * ≤ Q ≤ o′ + fl(q̂ + B), and as RN is monotone and fl(o′ + v) = RN(o′ + v), R
1006
+ * lies between fl(o′ + fl(q̂ − B)) and fl(o′ + fl(q̂ + B)); the result r =
1007
+ * fl(o′ + q̂) is returned when both are r or its neighbour, the neighbour's gap
1008
+ * read from r's exponent, 2^−1074 through the subnormals and half a gap toward
1009
+ * zero at a normal power of two.
1010
+ *
1011
+ * Every term is a multiple of x·u, so the proof needs |r| about 2^7 times x or
1012
+ * more: a mesh far from the origin beside its size. Nearer, a plain pass cannot
1013
+ * prove one ulp (its offsets alone round by about u·x, against a gap of about
1014
+ * u·|r|), and the default computation runs after it.
1015
+ */
1016
+ function faithfulCentroidU16_(out, positions, indices) {
1017
+ if (indices.length === 0) {
1018
+ return false;
1019
+ }
1020
+ const first = indices[0] * 3;
1021
+ const anchorX = positions[first];
1022
+ const anchorY = positions[first + 1];
1023
+ const anchorZ = positions[first + 2];
1024
+ let minX = anchorX;
1025
+ let minY = anchorY;
1026
+ let minZ = anchorZ;
1027
+ let maxX = anchorX;
1028
+ let maxY = anchorY;
1029
+ let maxZ = anchorZ;
1030
+ let weightSum = 0;
1031
+ let weightCompensation = 0;
1032
+ let sumX = 0;
1033
+ let sumY = 0;
1034
+ let sumZ = 0;
1035
+ let compensationX = 0;
1036
+ let compensationY = 0;
1037
+ let compensationZ = 0;
1038
+ let crossMagnitude = 0;
1039
+ let tinyCount = 0;
1040
+ for (let corner = 0; corner < indices.length; corner += 3) {
1041
+ const a = indices[corner] * 3;
1042
+ const b = indices[corner + 1] * 3;
1043
+ const c = indices[corner + 2] * 3;
1044
+ const aX = positions[a];
1045
+ const aY = positions[a + 1];
1046
+ const aZ = positions[a + 2];
1047
+ const bX = positions[b];
1048
+ const bY = positions[b + 1];
1049
+ const bZ = positions[b + 2];
1050
+ const cX = positions[c];
1051
+ const cY = positions[c + 1];
1052
+ const cZ = positions[c + 2];
1053
+ minX = Math.min(minX, aX, bX, cX);
1054
+ minY = Math.min(minY, aY, bY, cY);
1055
+ minZ = Math.min(minZ, aZ, bZ, cZ);
1056
+ maxX = Math.max(maxX, aX, bX, cX);
1057
+ maxY = Math.max(maxY, aY, bY, cY);
1058
+ maxZ = Math.max(maxZ, aZ, bZ, cZ);
1059
+ const abX = bX - aX;
1060
+ const abY = bY - aY;
1061
+ const abZ = bZ - aZ;
1062
+ const acX = cX - aX;
1063
+ const acY = cY - aY;
1064
+ const acZ = cZ - aZ;
1065
+ const pX = abY * acZ;
1066
+ const qX = abZ * acY;
1067
+ const pY = abZ * acX;
1068
+ const qY = abX * acZ;
1069
+ const pZ = abX * acY;
1070
+ const qZ = abY * acX;
1071
+ const crossX = pX - qX;
1072
+ const crossY = pY - qY;
1073
+ const crossZ = pZ - qZ;
1074
+ const areaSquared = crossX * crossX + crossY * crossY + crossZ * crossZ;
1075
+ if (areaSquared < 2 ** -970 &&
1076
+ (crossX !== 0 || crossY !== 0 || crossZ !== 0)) {
1077
+ tinyCount++;
1078
+ }
1079
+ const weight = Math.sqrt(areaSquared);
1080
+ const weightedX = weight * (aX - anchorX + (bX - anchorX) + (cX - anchorX));
1081
+ const weightedY = weight * (aY - anchorY + (bY - anchorY) + (cY - anchorY));
1082
+ const weightedZ = weight * (aZ - anchorZ + (bZ - anchorZ) + (cZ - anchorZ));
1083
+ // Neumaier: each branch is the exact error of the rounded sum.
1084
+ let next = weightSum + weight;
1085
+ weightCompensation +=
1086
+ weightSum >= weight
1087
+ ? weightSum - next + weight
1088
+ : weight - next + weightSum;
1089
+ weightSum = next;
1090
+ next = sumX + weightedX;
1091
+ compensationX +=
1092
+ Math.abs(sumX) >= Math.abs(weightedX)
1093
+ ? sumX - next + weightedX
1094
+ : weightedX - next + sumX;
1095
+ sumX = next;
1096
+ next = sumY + weightedY;
1097
+ compensationY +=
1098
+ Math.abs(sumY) >= Math.abs(weightedY)
1099
+ ? sumY - next + weightedY
1100
+ : weightedY - next + sumY;
1101
+ sumY = next;
1102
+ next = sumZ + weightedZ;
1103
+ compensationZ +=
1104
+ Math.abs(sumZ) >= Math.abs(weightedZ)
1105
+ ? sumZ - next + weightedZ
1106
+ : weightedZ - next + sumZ;
1107
+ sumZ = next;
1108
+ crossMagnitude +=
1109
+ Math.abs(pX) +
1110
+ Math.abs(qX) +
1111
+ Math.abs(pY) +
1112
+ Math.abs(qY) +
1113
+ Math.abs(pZ) +
1114
+ Math.abs(qZ);
1115
+ }
1116
+ const filter = CENTROID_FILTER_;
1117
+ filter[0] = weightSum;
1118
+ filter[1] = weightCompensation;
1119
+ filter[2] = sumX;
1120
+ filter[3] = sumY;
1121
+ filter[4] = sumZ;
1122
+ filter[5] = compensationX;
1123
+ filter[6] = compensationY;
1124
+ filter[7] = compensationZ;
1125
+ filter[8] = anchorX;
1126
+ filter[9] = anchorY;
1127
+ filter[10] = anchorZ;
1128
+ filter[11] = crossMagnitude;
1129
+ filter[12] = minX;
1130
+ filter[13] = minY;
1131
+ filter[14] = minZ;
1132
+ filter[15] = maxX;
1133
+ filter[16] = maxY;
1134
+ filter[17] = maxZ;
1135
+ return certifyCentroidU16_(out, indices.length / 3, tinyCount);
1136
+ }
1137
+ /**
1138
+ * The end of {@link faithfulCentroid_}, from the sums it leaves in
1139
+ * `CENTROID_FILTER_`, for `faceCount` faces of which `tinyCount` have a nonzero
1140
+ * cross product whose squares sum below 2^−970: writes `out` and returns `true`
1141
+ * where the bound proves each component within one ulp of the default one,
1142
+ * `false` otherwise. Kept apart, as {@link certifySixVolume_} is, so that no
1143
+ * double crosses a call.
1144
+ */
1145
+ function certifyCentroidU16_(out, faceCount, tinyCount) {
1146
+ const filter = CENTROID_FILTER_;
1147
+ const gamma = (faceCount * UNIT_ROUNDOFF_) / (1 - faceCount * UNIT_ROUNDOFF_);
1148
+ const gammaSquared = gamma * gamma;
1149
+ const weight = filter[0] + filter[1];
1150
+ const thrice = 3 * weight;
1151
+ // Σ w lies within (u + γ²)·Σ w of `weight`; E_w bounds Σ |ω_f − w_f|.
1152
+ const weightError = (33 *
1153
+ UNIT_ROUNDOFF_ *
1154
+ weight *
1155
+ (1 + 2 * UNIT_ROUNDOFF_ + 2 * gammaSquared) +
1156
+ (4.03 * UNIT_ROUNDOFF_ * filter[11]) / (1 - gamma) +
1157
+ tinyCount * 2 ** -534 +
1158
+ faceCount * 2 ** -1072) *
1159
+ (1 + 2 ** -40);
1160
+ const margin = (weight * (1 - 2 * UNIT_ROUNDOFF_ - 2 * gammaSquared) - weightError) *
1161
+ (1 - 2 ** -40);
1162
+ if (!(gamma < 2 ** -20 && weight - weight === 0 && margin > 0)) {
1163
+ return false;
1164
+ }
1165
+ const relative = (weightError / margin) * (1 + 2 ** -40) +
1166
+ 7.7 * UNIT_ROUNDOFF_ +
1167
+ 2.1 * gammaSquared +
1168
+ 2 ** -1074 / margin;
1169
+ const absolute = (faceCount * 2 ** -1074) / margin + 2 ** -1071;
1170
+ for (let axis = 0; axis < 3; axis++) {
1171
+ const extent = filter[15 + axis] - filter[12 + axis];
1172
+ if (!(extent < 2 ** 1000)) {
1173
+ return false;
1174
+ }
1175
+ const anchor = filter[8 + axis];
1176
+ const value = (filter[2 + axis] + filter[5 + axis]) / thrice;
1177
+ const size = Math.abs(value);
1178
+ const bound = (extent * relative + 3 * UNIT_ROUNDOFF_ * size + absolute) *
1179
+ (1 + 2 ** -38) +
1180
+ 2 ** -1073;
1181
+ const rounded = anchor + value;
1182
+ const below = anchor + (value - bound);
1183
+ const above = anchor + (value + bound);
1184
+ // The gaps from `rounded` to its neighbours: 2^(e − 52) away from zero
1185
+ // (2^−1074 through the subnormals), half that toward zero at a normal
1186
+ // power of two.
1187
+ const magnitude = Math.abs(rounded);
1188
+ filter[18 + axis] = rounded;
1189
+ let away = 2 ** -1074;
1190
+ let toward = away;
1191
+ if (magnitude !== 0) {
1192
+ const exponent = binaryExponentAt(filter, 18 + axis);
1193
+ away = 2 ** (Math.max(exponent, -1022) - 52);
1194
+ toward =
1195
+ exponent > -1022 && magnitude === 2 ** exponent ? away / 2 : away;
1196
+ }
1197
+ // Exact differences: neighbours are within a factor of two (Sterbenz).
1198
+ if (!(rounded - below <= (rounded > 0 ? toward : away) &&
1199
+ above - rounded <= (rounded < 0 ? toward : away))) {
1200
+ return false;
802
1201
  }
803
1202
  }
804
- // A scaled difference is below 2^(d + 1), a cross product component below
805
- // 2^(x + 3), a term below 2^(t + 6): the common exponent keeps the three
806
- // below 2^1021, 2^1020 and 2^1002, where TwoProduct is exact.
807
- // Integers kept small integers (`| 0`), so that no exponent is boxed on its
808
- // way into a call.
809
- const extra = termMax > NONE_
810
- ? Math.min(Math.max(Math.ceil((termMax - 996) / 3), Math.ceil((crossMax - 1017) / 2), differenceMax - 1020, -1020), 0) | 0
811
- : 0;
812
- scaleFrameU16_(extra);
1203
+ out[0] = filter[18];
1204
+ out[1] = filter[19];
1205
+ out[2] = filter[20];
1206
+ return true;
1207
+ }
1208
+ /**
1209
+ * The default centroid's exact sums: Σ ω, then Σ ω (a + b + c) per axis, ω each
1210
+ * face's doubled area m · 2^k (`faceArea_`), at any magnitude.
1211
+ */
1212
+ const CENTROID_SUMS_ = [
1213
+ new DotExactAccumulator(),
1214
+ new DotExactAccumulator(),
1215
+ new DotExactAccumulator(),
1216
+ new DotExactAccumulator(),
1217
+ ];
1218
+ /** Σ ω (a + b + c − 3μ) along one axis, for a midpoint μ the rounding tests. */
1219
+ const CENTROID_RESIDUAL_ = new DotExactAccumulator();
1220
+ /**
1221
+ * A face's m, six times, and its corners along one axis then −μ's high part
1222
+ * thrice.
1223
+ */
1224
+ const CENTROID_LEFT_ = new Float64Array(6);
1225
+ const CENTROID_RIGHT_ = new Float64Array(6);
1226
+ const CENTROID_LEFT_THREE_ = CENTROID_LEFT_.subarray(0, 3);
1227
+ const CENTROID_RIGHT_THREE_ = CENTROID_RIGHT_.subarray(0, 3);
1228
+ const CENTROID_SINGLE_ = new Float64Array(1);
1229
+ const CENTROID_FACTOR_ = new Float64Array(1);
1230
+ /**
1231
+ * A divisor's and a numerator's sums, each as two pieces of 53 bits
1232
+ * (significand then exponent): the divisor over 3 (the centroid's weights, or 2
1233
+ * for the volume) at 0–3, the numerator (an axis's sum, or six times the
1234
+ * volume) at 4–7; then two scratch slots.
1235
+ */
1236
+ const QUOTIENT_READS_ = new Float64Array(10);
1237
+ /** The `axis` {@link roundQuotient_} takes for the volume. */
1238
+ const VOLUME_AXIS_ = 3;
1239
+ /**
1240
+ * Writes `sum` to `reads` at `at` as two pieces of 53 bits, significand then
1241
+ * exponent each, whose sum is within 2^−106 of it: the sum rounded, then what
1242
+ * is left of it rounded. Leaves `sum` less its first piece.
1243
+ */
1244
+ function readPieces_(sum, reads, at) {
1245
+ sum.writeScaled(reads, at);
1246
+ const single = CENTROID_SINGLE_;
1247
+ single[0] = -reads[at];
1248
+ if (single[0] !== 0 && single[0] - single[0] === 0) {
1249
+ sum.addProducts(single, ONE_, reads[at + 1] | 0);
1250
+ }
1251
+ sum.writeScaled(reads, at + 2);
1252
+ }
1253
+ /**
1254
+ * The sign of `Σ ω (a + b + c) − 3μ · Σ ω` along `axis`, μ = σ (units + 1/2) ·
1255
+ * 2^g the midpoint the rounding of the centroid tests: exact, from a second
1256
+ * pass over the faces. Runs only where the doubled-precision quotient lies
1257
+ * within 2^−41 of a unit of that midpoint.
1258
+ */
1259
+ function centroidResidualSignU16_(positions, indices, axis, sign, gridExponent) {
1260
+ const residual = CENTROID_RESIDUAL_;
1261
+ const left = CENTROID_LEFT_;
1262
+ const right = CENTROID_RIGHT_;
1263
+ const single = CENTROID_SINGLE_;
1264
+ const area = FACE_AREA_;
1265
+ const factor = CENTROID_FACTOR_;
1266
+ const reads = QUOTIENT_READS_;
1267
+ residual.reset();
1268
+ // The units of the candidate, in `reads[8]`: a double crossing a call is
1269
+ // boxed.
1270
+ const high = -sign * reads[8] * 2 ** gridExponent;
1271
+ factor[0] = -3 * sign;
813
1272
  for (let corner = 0; corner < indices.length; corner += 3) {
814
1273
  const a = indices[corner] * 3;
815
- scaledEdgesU16_(positions, a, indices[corner + 1] * 3, indices[corner + 2] * 3, isWide);
816
- anchoredCornerU16_(positions, a, isWide);
817
- // Component k of the cross product is cross[4k] + cross[4k + 1] +
818
- // cross[4k + 2] + cross[4k + 3], exactly: edges 0–2 are b − a, 3–5 c − a.
819
- crossTermsU16_(cross, 0, 1, 5, 2, 4);
820
- crossTermsU16_(cross, 4, 2, 3, 0, 5);
821
- crossTermsU16_(cross, 8, 0, 4, 1, 3);
822
- for (let term = 0; term < 12; term++) {
823
- productTermsU16_(terms, 4 * term, vertex, term >> 2, cross, term);
824
- productTermsU16_(terms, 4 * term + 2, vertex, (term >> 2) + 3, cross, term);
1274
+ const b = indices[corner + 1] * 3;
1275
+ const c = indices[corner + 2] * 3;
1276
+ faceAreaU16_(positions, a, b, c);
1277
+ if (area[0] === 0) {
1278
+ continue;
1279
+ }
1280
+ const exponent = area[1] | 0;
1281
+ for (let slot = 0; slot < 6; slot++) {
1282
+ left[slot] = area[0];
825
1283
  }
826
- sum.addRange(terms, 0, 48);
1284
+ right[0] = positions[a + axis];
1285
+ right[1] = positions[b + axis];
1286
+ right[2] = positions[c + axis];
1287
+ right[3] = high;
1288
+ right[4] = high;
1289
+ right[5] = high;
1290
+ residual.addProducts(left, right, exponent);
1291
+ single[0] = area[0];
1292
+ residual.addProducts(single, factor, (exponent + gridExponent - 1) | 0);
827
1293
  }
828
- const value = VALUE_;
829
- sum.writeValue(value, 0);
830
- value[0] = value[0] / 6;
831
- scaleByPowerOfTwoInPlace(value, 0, (frame[3] + frame[4] + frame[5] + 3 * extra) | 0);
832
- // `+ 0`: an empty sum is −0, as `Math.sumPrecise`'s.
833
- return value[0] + 0;
1294
+ residual.writeScaled(reads, 8);
1295
+ return reads[8] > 0 ? 1 : reads[8] < 0 ? -1 : 0;
834
1296
  }
835
1297
  /**
836
- * Writes `x[i] · y[j]` into `out` at `at` as two numbers that sum to it exactly
837
- * (TwoProduct, for products from 2^−969 to below 2^1023; within 5 · 2^−1074
838
- * below). No double crosses the call.
1298
+ * The sign of `T − 6μ`, T six times the volume and μ = σ (units + 1/2) · 2^g
1299
+ * the midpoint the rounding of the volume tests: exact, from `SIX_VOLUME_`,
1300
+ * which {@link readPieces_} left less its first piece. Runs only where the
1301
+ * doubled-precision quotient lies within 2^−41 of a unit of that midpoint.
839
1302
  */
840
- function productTermsU16_(out, at, x, i, y, j) {
841
- out[at] = x[i];
842
- out[at + 1] = y[j];
843
- twoProductInRangeInPlace(out, at);
1303
+ function volumeResidualSign_(sign, gridExponent) {
1304
+ const sum = SIX_VOLUME_;
1305
+ const single = CENTROID_SINGLE_;
1306
+ const factor = CENTROID_FACTOR_;
1307
+ const reads = QUOTIENT_READS_;
1308
+ single[0] = reads[4];
1309
+ sum.addProducts(single, ONE_, reads[5] | 0);
1310
+ // The units of the candidate, in `reads[8]`: a double crossing a call is
1311
+ // boxed.
1312
+ single[0] = reads[8];
1313
+ factor[0] = -6 * sign;
1314
+ sum.addProducts(single, factor, gridExponent);
1315
+ single[0] = -3 * sign;
1316
+ sum.addProducts(single, ONE_, gridExponent);
1317
+ sum.writeScaled(reads, 8);
1318
+ return reads[8] > 0 ? 1 : reads[8] < 0 ? -1 : 0;
844
1319
  }
845
1320
  /**
846
- * Writes `e[i] · e[j] − e[k] · e[l]`, `e` being `EDGES_`, into `out` at `at` as
847
- * four numbers that sum to it exactly: both products and their rounding errors,
848
- * negated for the second.
1321
+ * Writes to `out[at]` the binary64 nearest a quotient, ties to even, from the
1322
+ * two-piece reads of its numerator and of a third of its divisor in
1323
+ * `QUOTIENT_READS_`: the centroid along `axis` (0–2), or the volume
1324
+ * ({@link VOLUME_AXIS_}). Their quotient in doubled precision (Dekker's
1325
+ * division, within 2^−99 of the exact one), rounded at the result's last bit,
1326
+ * 2^−1074 through the subnormals, `±Infinity` beyond `Number.MAX_VALUE`; where
1327
+ * it lies within 2^−41 of a unit of a midpoint, the exact residual decides.
1328
+ * `NaN` for a zero divisor or a non-finite numerator.
849
1329
  */
850
- function crossTermsU16_(out, at, i, j, k, l) {
851
- const edges = EDGES_;
852
- out[at] = edges[i];
853
- out[at + 1] = edges[j];
854
- twoProductInRangeInPlace(out, at);
855
- out[at + 2] = edges[k];
856
- out[at + 3] = edges[l];
857
- twoProductInRangeInPlace(out, at + 2);
858
- out[at + 2] = -out[at + 2];
859
- out[at + 3] = -out[at + 3];
1330
+ function roundQuotientU16_(out, at, positions, indices, axis) {
1331
+ const reads = QUOTIENT_READS_;
1332
+ const weight = reads[0];
1333
+ const numerator = reads[4];
1334
+ if (!(weight > 0 && weight - weight === 0 && numerator - numerator === 0)) {
1335
+ out[at] = Number.NaN;
1336
+ return;
1337
+ }
1338
+ if (numerator === 0) {
1339
+ out[at] = 0;
1340
+ return;
1341
+ }
1342
+ // The second pieces against the first: exact but in the subnormals, where
1343
+ // they are below 2^−1022 of it.
1344
+ reads[8] = reads[2];
1345
+ if (reads[8] !== 0) {
1346
+ scaleByPowerOfTwoInPlace(reads, 8, (reads[3] - reads[1]) | 0);
1347
+ }
1348
+ reads[9] = reads[6];
1349
+ if (reads[9] !== 0) {
1350
+ scaleByPowerOfTwoInPlace(reads, 9, (reads[7] - reads[5]) | 0);
1351
+ }
1352
+ const sign = numerator < 0 ? -1 : 1;
1353
+ const high = sign * numerator;
1354
+ const low = sign * reads[9];
1355
+ // 3 Σ ω as divisorHigh + divisorLow, then the quotient as quotientHigh +
1356
+ // quotientLow, times 2^exponent.
1357
+ const pair = PAIR_;
1358
+ pair[0] = 3;
1359
+ pair[1] = weight;
1360
+ twoProductInRangeInPlace(pair, 0);
1361
+ const divisorHigh = pair[0];
1362
+ const divisorLow = pair[1] + 3 * reads[8];
1363
+ const quotientHigh = high / divisorHigh;
1364
+ pair[0] = quotientHigh;
1365
+ pair[1] = divisorHigh;
1366
+ twoProductInRangeInPlace(pair, 0);
1367
+ const remainder = high - pair[0] - pair[1] + low - quotientHigh * divisorLow;
1368
+ const quotientLow = remainder / divisorHigh;
1369
+ const exponent = (reads[5] - reads[1]) | 0;
1370
+ // quotientHigh is within 2^−51 of the quotient, in (1/6, 2/3): its binade,
1371
+ // moved where the low part takes the quotient across a power of two.
1372
+ let binade = quotientHigh >= 0.5 ? -1 : quotientHigh >= 0.25 ? -2 : -3;
1373
+ if (quotientHigh - 2 ** binade + quotientLow < 0) {
1374
+ binade--;
1375
+ }
1376
+ else if (quotientHigh - 2 ** (binade + 1) + quotientLow >= 0) {
1377
+ binade++;
1378
+ }
1379
+ const leading = binade + exponent;
1380
+ if (leading > 1023) {
1381
+ out[at] = sign * Number.POSITIVE_INFINITY;
1382
+ return;
1383
+ }
1384
+ if (leading < -1077) {
1385
+ // Below a quarter of the least subnormal, within 2^−99: far from half
1386
+ // of it, the midpoint to 2^−1074. Nearer, the general rounding below and,
1387
+ // close to that midpoint, the exact residual decide.
1388
+ out[at] = sign < 0 ? -0 : 0;
1389
+ return;
1390
+ }
1391
+ const gridExponent = Math.max(leading - 52, -1074);
1392
+ const shift = exponent - gridExponent;
1393
+ // The quotient in units of the last place: an integer, or one and a half,
1394
+ // from the high part (exact), then the low part's whole units and fraction.
1395
+ const scaledHigh = quotientHigh * 2 ** shift;
1396
+ const highUnits = Math.floor(scaledHigh);
1397
+ const scaledLow = scaledHigh - highUnits + quotientLow * 2 ** shift;
1398
+ const lowUnits = Math.floor(scaledLow);
1399
+ let units = highUnits + lowUnits;
1400
+ const fraction = scaledLow - lowUnits;
1401
+ const slack = scaledHigh * 2 ** -96 + 2 ** -50;
1402
+ if (fraction > 0.5 + slack) {
1403
+ units++;
1404
+ }
1405
+ else if (!(fraction < 0.5 - slack)) {
1406
+ reads[8] = units;
1407
+ // The residual's sign is the quotient's against the midpoint; the
1408
+ // magnitude's is that times the sign.
1409
+ const side = sign *
1410
+ (axis === VOLUME_AXIS_
1411
+ ? volumeResidualSign_(sign, gridExponent)
1412
+ : centroidResidualSignU16_(positions, indices, axis, sign, gridExponent));
1413
+ if (side > 0 || (side === 0 && units % 2 === 1)) {
1414
+ units++;
1415
+ }
1416
+ }
1417
+ out[at] = sign * units * 2 ** gridExponent;
860
1418
  }
861
1419
  /**
862
- * The `Uint16Array` twin of the surface centroid: `o + Σ A · (a + b + c − 3o) /
863
- * 3` over `Σ A`, o being the frame's anchor and A each face's doubled area
864
- * (`faceArea_`), scaled by one power of two that brings the largest near 1, so
865
- * no weight overflows and only one below 2^−1070 of the largest is lost. Every
866
- * corner minus o is TwoSum's exact pair scaled into the frame per axis, every
867
- * product split exactly (TwoProduct) and every sum exact (`PreciseSum`), so the
868
- * result is the same in every face order, nothing overflows at any size or
869
- * distance from the origin, and a vertex no triangle uses is never read. A zero
870
- * total area divides zero by zero: `NaN`. O(triangles), no allocation.
1420
+ * The `Uint16Array` twin of the surface centroid: `Σ ω (a + b + c) / (3 Σ ω)`,
1421
+ * ω each face's doubled area (`faceArea_`, as m · 2^k), both sums exact in long
1422
+ * accumulators at any magnitude, their quotient rounded once
1423
+ * ({@link roundQuotient_}): the same number in every face order, correctly
1424
+ * rounded for those weights at any size or distance from the origin, and a
1425
+ * vertex no triangle uses is never read. A zero total area divides zero by
1426
+ * zero: `NaN`. With `faithful`, the first stage {@link faithfulCentroid_} runs
1427
+ * first and the rest only where it cannot prove its result. O(triangles), no
1428
+ * allocation.
871
1429
  */
872
- export function mesh3CentroidU16(out, positions, indices) {
873
- const weights = CENTROID_SUMS_[0];
874
- const terms = TERMS_;
875
- const vertex = VERTEX_;
1430
+ export function mesh3CentroidU16(out, positions, indices, faithful = false) {
1431
+ if (faithful && faithfulCentroidU16_(out, positions, indices)) {
1432
+ return;
1433
+ }
876
1434
  const area = FACE_AREA_;
877
- const value = VALUE_;
878
- const frame = FRAME_;
1435
+ const left = CENTROID_LEFT_THREE_;
1436
+ const right = CENTROID_RIGHT_THREE_;
1437
+ const single = CENTROID_SINGLE_;
879
1438
  for (let sum = 0; sum < CENTROID_SUMS_.length; sum++) {
880
1439
  CENTROID_SUMS_[sum].reset();
881
1440
  }
882
- frameU16_(positions, indices);
883
- const isWide = frame[9] === 1;
884
- let weightExponent = NONE_;
885
- for (let corner = 0; corner < indices.length; corner += 3) {
886
- faceAreaU16_(positions, indices[corner] * 3, indices[corner + 1] * 3, indices[corner + 2] * 3);
887
- if (area[0] > 0) {
888
- weightExponent = Math.max(weightExponent, area[1] + binaryExponent(area[0]));
889
- }
890
- }
891
1441
  for (let corner = 0; corner < indices.length; corner += 3) {
892
1442
  const a = indices[corner] * 3;
893
1443
  const b = indices[corner + 1] * 3;
@@ -896,44 +1446,23 @@ export function mesh3CentroidU16(out, positions, indices) {
896
1446
  if (area[0] === 0) {
897
1447
  continue;
898
1448
  }
899
- value[0] = area[0];
900
- if (area[0] > 0) {
901
- // The largest weight is in [1, 2); a power within the normal range is
902
- // one multiplication.
903
- const power = area[1] - weightExponent;
904
- if (power >= -1022) {
905
- value[0] = area[0] * 2 ** power;
906
- }
907
- else {
908
- scaleByPowerOfTwoInPlace(value, 0, power);
909
- }
910
- }
911
- // Three times the weight, as w + 2w exactly: the sums then divide once.
912
- terms[0] = value[0];
913
- terms[1] = 2 * value[0];
914
- weights.addRange(terms, 0, 2);
915
- for (let index = 0; index < 3; index++) {
916
- anchoredCornerU16_(positions, index === 0 ? a : index === 1 ? b : c, isWide);
917
- for (let axis = 0; axis < 3; axis++) {
918
- productTermsU16_(terms, 4 * index + 12 * axis, value, 0, vertex, axis);
919
- productTermsU16_(terms, 4 * index + 12 * axis + 2, value, 0, vertex, axis + 3);
920
- }
921
- }
1449
+ const exponent = area[1] | 0;
1450
+ single[0] = area[0];
1451
+ CENTROID_SUMS_[0].addProducts(single, ONE_, exponent);
1452
+ left[0] = area[0];
1453
+ left[1] = area[0];
1454
+ left[2] = area[0];
922
1455
  for (let axis = 0; axis < 3; axis++) {
923
- CENTROID_SUMS_[axis + 1].addRange(terms, 12 * axis, 12 * axis + 12);
1456
+ right[0] = positions[a + axis];
1457
+ right[1] = positions[b + axis];
1458
+ right[2] = positions[c + axis];
1459
+ CENTROID_SUMS_[axis + 1].addProducts(left, right, exponent);
924
1460
  }
925
1461
  }
926
- weights.writeValue(value, 0);
927
- const thrice = value[0];
1462
+ readPieces_(CENTROID_SUMS_[0], QUOTIENT_READS_, 0);
928
1463
  for (let axis = 0; axis < 3; axis++) {
929
- CENTROID_SUMS_[axis + 1].writeValue(value, 0);
930
- value[0] = value[0] / thrice;
931
- // Halves where the frame is wide: the anchor plus a scaled offset may
932
- // pass Number.MAX_VALUE on the way to a centroid that does not.
933
- scaleByPowerOfTwoInPlace(value, 0, frame[3 + axis] - (isWide ? 1 : 0));
934
- out[axis] = isWide
935
- ? 2 * (frame[axis] * 0.5 + value[0])
936
- : frame[axis] + value[0];
1464
+ readPieces_(CENTROID_SUMS_[axis + 1], QUOTIENT_READS_, 4);
1465
+ roundQuotientU16_(out, axis, positions, indices, axis);
937
1466
  }
938
1467
  }
939
1468
  /**