-
Notifications
You must be signed in to change notification settings - Fork 208
/
Polynomials.ts
1930 lines (1830 loc) · 73.3 KB
/
Polynomials.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Numerics
*/
import { Geometry } from "../Geometry";
import { Angle } from "../geometry3d/Angle";
import { AngleSweep } from "../geometry3d/AngleSweep";
import { GrowableFloat64Array, OptionalGrowableFloat64Array } from "../geometry3d/GrowableFloat64Array";
import { LongitudeLatitudeNumber } from "../geometry3d/LongitudeLatitudeAltitude";
import { Point2d, Vector2d } from "../geometry3d/Point2dVector2d";
import { Point3d, Vector3d, XYZ } from "../geometry3d/Point3dVector3d";
import { Range1d, Range3d } from "../geometry3d/Range";
import { Ray3d } from "../geometry3d/Ray3d";
import { XAndY } from "../geometry3d/XYZProps";
import { Point4d } from "../geometry4d/Point4d";
// cspell:word Cardano
// cspell:word CCminusSS
/* eslint-disable @typescript-eslint/naming-convention */
/**
* degree 2 (quadratic) polynomial in for y = c0 + c1*x + c2*x^2
* @internal
*/
export class Degree2PowerPolynomial {
/** The three coefficients for the quartic */
public coffs: number[];
constructor(c0: number = 0, c1: number = 0, c2: number = 0) {
this.coffs = [c0, c1, c2];
}
/**
* * Return 2 duplicate roots in double root case.
* * The solutions are always in algebraic order.
* @returns 0, 1, or 2 solutions of the usual quadratic (a*x*x + b * x + c = 0)
*/
public static solveQuadratic(a: number, b: number, c: number): number[] | undefined {
const b1 = Geometry.conditionalDivideFraction(b, a);
const c1 = Geometry.conditionalDivideFraction(c, a);
if (b1 !== undefined && c1 !== undefined) {
// now solving xx + b1*x + c1 = 0 -- i.e. implied "a" coefficient is 1 . .
const q = b1 * b1 - 4 * c1;
if (q > 0) {
const e = Math.sqrt(q);
// e is positive, so this sorts algebraically
return [0.5 * (-b1 - e), 0.5 * (-b1 + e)];
}
if (q < 0)
return undefined;
const root = -0.5 * b1;
return [root, root];
}
// "divide by a" failed. solve bx + c = 0
const x = Geometry.conditionalDivideFraction(-c, b);
if (x !== undefined)
return [x];
return undefined;
}
/** Add `a` to the constant term. */
public addConstant(a: number) {
this.coffs[0] += a;
}
/** Add `s * (a + b*x)^2` to the quadratic coefficients */
public addSquaredLinearTerm(a: number, b: number, s: number = 1): void {
this.coffs[0] += s * (a * a);
this.coffs[1] += s * (2.0 * a * b);
this.coffs[2] += s * (b * b);
}
/** Return the real roots of this polynomial */
public realRoots(): number[] | undefined {
const ss = Degree2PowerPolynomial.solveQuadratic(this.coffs[2], this.coffs[1], this.coffs[0]);
if (ss && ss.length > 1) {
if (ss[0] > ss[1]) {
const temp = ss[0];
ss[0] = ss[1];
ss[1] = temp;
}
}
return ss;
}
/** Evaluate the quadratic at x. */
public evaluate(x: number): number {
return this.coffs[0] + x * (this.coffs[1] + x * this.coffs[2]);
}
/**
* Evaluate the bezier function at a parameter value. (i.e. sum the basis functions times coefficients)
* @param u parameter for evaluation
*/
public evaluateDerivative(x: number): number {
return this.coffs[1] + 2 * x * this.coffs[2];
}
/** Factor the polynomial in to the form `y0 + c * (x-x0)^2)`, i.e. complete the square. */
public tryGetVertexFactorization(): { x0: number, y0: number, c: number } | undefined {
const x = Geometry.conditionalDivideFraction(-this.coffs[1], 2.0 * this.coffs[2]);
if (x !== undefined) {
const y = this.evaluate(x);
return { c: this.coffs[2], x0: x, y0: y };
}
return undefined;
}
/** Construct a quadratic from input form `c2 * (x-root0) * (x-root1)` */
public static fromRootsAndC2(root0: number, root1: number, c2: number = 1): Degree2PowerPolynomial {
return new Degree2PowerPolynomial(
c2 * root0 * root1,
- c2 * (root0 + root1),
c2);
}
}
/**
* degree 3 (cubic) polynomial in for y = c0 + c1*x + c2*x^2 + c3*x^3
* @internal
*/
export class Degree3PowerPolynomial {
/** polynomial coefficients, index corresponds to power */
public coffs: number[];
constructor(c0: number = 0, c1: number = 0, c2: number = 0, c3: number = 1) {
this.coffs = [c0, c1, c2, c3];
}
/** Add `a` to the constant term. */
public addConstant(a: number) {
this.coffs[0] += a;
}
/** Add `s * (a + b*x)^2` to the cubic */
public addSquaredLinearTerm(a: number, b: number, s: number = 1): void {
this.coffs[0] += s * (a * a);
this.coffs[1] += s * (2.0 * a * b);
this.coffs[2] += s * (b * b);
}
/**
* Evaluate the polynomial at x
* @param u parameter for evaluation
*/
public evaluate(x: number): number {
return this.coffs[0] + x * (this.coffs[1] + x * (this.coffs[2] + x * this.coffs[3]));
}
/**
* Evaluate the polynomial derivative
* @param u parameter for evaluation
*/
public evaluateDerivative(x: number): number {
return this.coffs[1] + x * (2.0 * this.coffs[2] + x * 3.0 * this.coffs[3]);
}
/** Construct a cubic from the form `c3 * (x-root0) * (x - root1) * (x- root2)` */
public static fromRootsAndC3(root0: number, root1: number, root2: number, c3: number = 1.0): Degree3PowerPolynomial {
return new Degree3PowerPolynomial(
-c3 * root0 * root1 * root2,
c3 * (root0 * root1 + root1 * root2 + root0 * root2),
- c3 * (root0 + root1 + root2),
c3);
}
}
/**
* degree 4 (quartic) polynomial in for y = c0 + c1*x + c2*x^2 + c4*x^4
* @internal
*/
export class Degree4PowerPolynomial {
/** polynomial coefficients, index corresponds to power */
public coffs: number[];
constructor(c0: number = 0, c1: number = 0, c2: number = 0, c3: number = 0, c4: number = 0) {
this.coffs = [c0, c1, c2, c3, c4];
}
/** Add `a` to the constant term. */
public addConstant(a: number) {
this.coffs[0] += a;
}
/**
* Evaluate the polynomial
* @param x x coordinate for evaluation
*/
public evaluate(x: number): number {
return this.coffs[0] + x * (this.coffs[1] + x * (this.coffs[2] + x * (this.coffs[3] + x * this.coffs[4])));
}
/**
* Evaluate the derivative
* @param x x coordinate for evaluation
*/
public evaluateDerivative(x: number): number {
return (this.coffs[1] + x * (2.0 * this.coffs[2] + x * (3.0 * this.coffs[3] + x * 4.0 * this.coffs[4])));
}
/** Construct a quartic from the form `c3 * (x-root0) * (x - root1) * (x- root2) * (x-root3)` */
public static fromRootsAndC4(root0: number, root1: number, root2: number, root3: number, c4: number = 1): Degree4PowerPolynomial {
return new Degree4PowerPolynomial(
c4 * (root0 * root1 * root2 * root3),
-c4 * (root0 * root1 * root2 + root0 * root1 * root3 + root0 * root2 * root3 + root1 * root2 * root3),
c4 * (root0 * root1 + root0 * root2 + root0 * root3 + root1 * root2 + root1 * root3 + root2 * root3),
-c4 * (root0 + root1 + root2 + root3),
c4);
}
}
/**
* polynomial services for an implicit torus with
* * z axis is "through the donut hole"
* * `majorRadius` is the radius of the circle "around the z axis"
* * `minorRadius` is the radius of circles around the major circle
* * for simple xyz the implicit form is
* * `(x^2+y^2+z^2+(R^2-r^2))^2 = 4 R^2(x^2+y^2)`
* * In weighted form
* * `(x^2+y^2+z^2+(R^2-r^2)w^2)^2 = 4 R^2 w^2 (x^2+y^2)`
* @internal
*/
export class TorusImplicit {
/** major (xy plane) radius */
public majorRadius: number;
/** hoop (perpendicular to major circle) radius */
public minorRadius: number;
constructor(majorRadius: number, minorRadius: number) {
this.majorRadius = majorRadius;
this.minorRadius = minorRadius;
}
/** Return sum of (absolute) major and minor radii, which is (half) the box size in x and y directions */
public boxSize() {
return (Math.abs(this.majorRadius) + Math.abs(this.minorRadius));
}
/** Return scale factor appropriate to control the magnitude of the implicit function. */
public implicitFunctionScale(): number {
const a = this.boxSize();
if (a === 0.0)
return 1.0;
return 1.0 / (a * a * a * a);
}
/**
* At space point (x,y,z) evaluate the implicit form of the torus (See `ImplicitTorus`)
*/
public evaluateImplicitFunctionXYZ(x: number, y: number, z: number): number {
const rho2 = x * x + y * y;
const z2 = z * z;
const R2 = this.majorRadius * this.majorRadius;
const r2 = this.minorRadius * this.minorRadius;
const f = rho2 + z2 + (R2 - r2);
const g = 4.0 * R2 * rho2;
return (f * f - g) * this.implicitFunctionScale();
}
/** Evaluate the implicit function at a point. */
public evaluateImplicitFunctionPoint(xyz: Point3d): number {
return this.evaluateImplicitFunctionXYZ(xyz.x, xyz.y, xyz.z);
}
/** Evaluate the implicit function at homogeneous coordinates */
public evaluateImplicitFunctionXYZW(x: number, y: number, z: number, w: number) {
const rho2 = x * x + y * y;
const z2 = z * z;
const w2 = w * w;
const R2 = this.majorRadius * this.majorRadius;
const r2 = this.minorRadius * this.minorRadius;
const f = rho2 + z2 + w2 * (R2 - r2);
const g = w2 * 4.0 * R2 * rho2;
return (f * f - g) * this.implicitFunctionScale();
}
/** Evaluate the surface point at angles (in radians) on the major and minor circles. */
public evaluateThetaPhi(thetaRadians: number, phiRadians: number): Point3d {
const c = Math.cos(thetaRadians);
const s = Math.sin(thetaRadians);
// theta=0 point
const x0 = this.majorRadius + this.minorRadius * Math.cos(phiRadians);
const z0 = this.minorRadius * Math.sin(phiRadians);
return Point3d.create(c * x0, s * x0, z0);
}
/** Evaluate partial derivatives at angles (int radians) on major and minor circles. */
public evaluateDerivativesThetaPhi(thetaRadians: number, phiRadians: number, dxdTheta: Vector3d, dxdPhi: Vector3d) {
const cTheta = Math.cos(thetaRadians);
const sTheta = Math.sin(thetaRadians);
const bx = this.minorRadius * Math.cos(phiRadians);
const bz = this.minorRadius * Math.sin(phiRadians);
const x0 = this.majorRadius + bx;
Vector3d.create(-x0 * sTheta, x0 * cTheta, 0.0, dxdTheta);
Vector3d.create(-cTheta * bz, -sTheta * bz, bx, dxdPhi);
}
/** Evaluate space point at major and minor angles (in radians) and distance from major hoop. */
public evaluateThetaPhiDistance(thetaRadians: number, phiRadians: number, distance: number): Point3d {
const c = Math.cos(thetaRadians);
const s = Math.sin(thetaRadians);
// theta=0 point
const x0 = this.majorRadius + distance * Math.cos(phiRadians);
const z0 = distance * Math.sin(phiRadians);
return Point3d.create(c * x0, s * x0, z0);
}
/** Given an xyz coordinate in the local system of the toroid, compute the torus parametrization
* * theta = angular coordinate in xy plane
* * phi = angular coordinate in minor circle.
* * distance = distance from major circle
* * rho = distance from origin to xy part of the input.
* @param xyz space point in local coordinates.
* @return object with properties theta, phi, distance, rho
*/
public xyzToThetaPhiDistance(xyz: Point3d): { theta: number, phi: number, distance: number, rho: number, safePhi: boolean } {
const rho = xyz.magnitudeXY();
const majorRadiusFactor = Geometry.conditionalDivideFraction(this.majorRadius, rho);
let safeMajor;
let majorCirclePoint;
if (majorRadiusFactor) {
safeMajor = true;
majorCirclePoint = Point3d.create(majorRadiusFactor * xyz.x, majorRadiusFactor * xyz.y, 0.0);
} else {
safeMajor = false;
majorCirclePoint = Point3d.create(xyz.x, xyz.y, 0.0);
}
const theta = safeMajor ? Math.atan2(xyz.y, xyz.x) : 0.0;
const vectorFromMajorCircle = Vector3d.createStartEnd(majorCirclePoint, xyz);
const distance = vectorFromMajorCircle.magnitude();
const dRho = rho - this.majorRadius;
let safePhi;
let phi;
if (xyz.z === 0.0 && dRho === 0.0) {
phi = 0.0;
safePhi = false;
} else {
phi = Math.atan2(xyz.z, dRho);
safePhi = true;
}
return { theta, phi, distance, rho, safePhi: safeMajor && safePhi };
}
/*
public minorCircle(theta: Angle): Arc3d {
const c = Math.cos(theta.radians);
const s = Math.sin(theta.radians);
return Arc3d.create(
Point3d.create(c * this.majorRadius, s * this.majorRadius, 0.0),
Vector3d.create(c * this.minorRadius, s * this.minorRadius, 0.0),
Vector3d.create(0.0, 0.0, this.minorRadius),
AngleSweep.create360()) as Arc3d;
}
public majorCircle(phi: Angle): Arc3d {
const c = Math.cos(phi.radians);
const s = Math.sin(phi.radians);
const a = this.majorRadius + c * this.minorRadius;
return Arc3d.create(
Point3d.create(0.0, 0.0, this.minorRadius * s),
Vector3d.create(a, 0.0, 0.0),
Vector3d.create(0.0, a, 0.0),
AngleSweep.create360()) as Arc3d;
}
*/
}
/**
* evaluation methods for an implicit sphere
* * xyz function `x*x + y*y + z*z - r*r = 0`.
* * xyzw function `x*x + y*y + z*z - r*r*w*w = 0`.
* @internal
*/
export class SphereImplicit {
/** Radius of sphere. */
public radius: number;
constructor(r: number) { this.radius = r; }
/** Evaluate the implicit function at coordinates x,y,z */
public evaluateImplicitFunction(x: number, y: number, z: number): number {
return x * x + y * y + z * z - this.radius * this.radius;
}
/** Evaluate the implicit function at homogeneous coordinates x,y,z,w */
public evaluateImplicitFunctionXYZW(wx: number, wy: number, wz: number, w: number): number {
return (wx * wx + wy * wy + wz * wz) - this.radius * this.radius * w * w;
}
/** Given an xyz coordinate in the local system of the toroid, compute the sphere parametrization
* * theta = angular coordinate in xy plane
* * phi = rotation from xy plane towards z axis.
* @param xyz space point in local coordinates.
* @return object with properties thetaRadians, phi, r
*/
public xyzToThetaPhiR(xyz: Point3d): { thetaRadians: number, phiRadians: number, r: number, valid: boolean } {
const rhoSquared = xyz.x * xyz.x + xyz.y * xyz.y;
const rho = Math.sqrt(rhoSquared);
const r = Math.sqrt(rhoSquared + xyz.z * xyz.z);
let theta;
let phi;
let valid;
if (r === 0.0) {
theta = phi = 0.0;
valid = false;
} else {
phi = Math.atan2(xyz.z, rho); // At least one of these is nonzero
if (rhoSquared !== 0.0) {
theta = Math.atan2(xyz.y, xyz.x);
valid = true;
} else {
theta = 0.0;
valid = false;
}
}
return { thetaRadians: (theta), phiRadians: (phi), r, valid };
}
/** Return the range of a uv-aligned patch of the sphere. */
public static patchRangeStartEndRadians(center: Point3d, radius: number, theta0Radians: number, theta1Radians: number, phi0Radians: number, phi1Radians: number, result?: Range3d): Range3d {
const thetaSweep = AngleSweep.createStartEndRadians(theta0Radians, theta1Radians);
const phiSweep = AngleSweep.createStartEndRadians(phi0Radians, phi1Radians);
const range = Range3d.createNull(result);
const xyz = Point3d.create();
if (thetaSweep.isFullCircle && phiSweep.isFullLatitudeSweep) {
// full sphere, no trimming -- build directly
range.extendPoint(center);
range.expandInPlace(Math.abs(radius));
} else {
const sphere = new SphereImplicit(radius);
// construct range for ORIGIN CENTERED sphere ...
const pi = Math.PI;
const piOver2 = 0.5 * Math.PI;
let phi, theta;
// 6 candidate interior extreme points on equator and 0, 90 degree meridians
for (const thetaPhi of [
[0.0, 0.0],
[pi, 0.0],
[piOver2, 0.0],
[-piOver2, 0.0],
[theta0Radians, piOver2],
[theta0Radians, -piOver2]]) {
theta = thetaPhi[0];
phi = thetaPhi[1];
if (thetaSweep.isRadiansInSweep(theta) && phiSweep.isRadiansInSweep(phi))
range.extendPoint(sphere.evaluateThetaPhi(theta, phi, xyz));
}
// 4 boundary curves, each with 3 components ...
// BUT: phi should not extend beyond poles. Hence z extremes on constant theta curve will never be different from z of constant phi curve or of poles as tested above.
const axisRange = Range1d.createNull();
const cosPhi0 = Math.cos(phi0Radians);
const cosPhi1 = Math.cos(phi1Radians);
const sinPhi0 = Math.sin(phi0Radians);
const sinPhi1 = Math.sin(phi1Radians);
const trigForm = new SineCosinePolynomial(0, 0, 0);
// constant phi curves at phi0 and phi1
for (const cosPhi of [cosPhi0, cosPhi1]) {
trigForm.set(0, cosPhi * radius, 0);
trigForm.rangeInSweep(thetaSweep, axisRange);
range.extendXOnly(axisRange.low); range.extendXOnly(axisRange.high);
trigForm.set(0, 0, cosPhi * radius);
trigForm.rangeInSweep(thetaSweep, axisRange);
range.extendYOnly(axisRange.low); range.extendYOnly(axisRange.high);
}
range.extendZOnly(sinPhi0 * radius);
range.extendZOnly(sinPhi1 * radius);
// constant theta curves as theta0 and theta1:
for (const thetaRadians of [theta0Radians, theta1Radians]) {
const cosThetaR = Math.cos(thetaRadians) * radius;
const sinThetaR = Math.sin(thetaRadians) * radius;
trigForm.set(0, cosThetaR, 0);
trigForm.rangeInSweep(phiSweep, axisRange);
range.extendXOnly(axisRange.low); range.extendXOnly(axisRange.high);
trigForm.set(0, sinThetaR, 0);
trigForm.rangeInSweep(phiSweep, axisRange);
range.extendYOnly(axisRange.low); range.extendYOnly(axisRange.high);
}
range.cloneTranslated(center, range);
}
return range;
}
/** Compute intersections with a ray.
* * Return the number of intersections
* * Fill any combinations of arrays of
* * rayFractions = fractions along the ray
* * xyz = xyz intersection coordinates points in space
* * thetaPhiRadians = sphere longitude and latitude in radians.
* * For each optional array, caller must of course initialize an array (usually empty)
*/
public static intersectSphereRay(center: Point3d, radius: number, ray: Ray3d, rayFractions: number[] | undefined, xyz: Point3d[] | undefined, thetaPhiRadians: LongitudeLatitudeNumber[] | undefined): number {
const vx = ray.origin.x - center.x;
const vy = ray.origin.y - center.y;
const vz = ray.origin.z - center.z;
const ux = ray.direction.x;
const uy = ray.direction.y;
const uz = ray.direction.z;
const a0 = Geometry.hypotenuseSquaredXYZ(vx, vy, vz) - radius * radius;
const a1 = 2.0 * Geometry.dotProductXYZXYZ(ux, uy, uz, vx, vy, vz);
const a2 = Geometry.hypotenuseSquaredXYZ(ux, uy, uz);
const parameters = Degree2PowerPolynomial.solveQuadratic(a2, a1, a0);
if (rayFractions !== undefined)
rayFractions.length = 0;
if (xyz !== undefined)
xyz.length = 0;
if (thetaPhiRadians !== undefined)
thetaPhiRadians.length = 0;
if (parameters === undefined) {
return 0;
}
const sphere = new SphereImplicit(radius);
if (rayFractions !== undefined)
for (const f of parameters) rayFractions.push(f);
if (xyz !== undefined || thetaPhiRadians !== undefined) {
for (const f of parameters) {
const point = ray.fractionToPoint(f);
if (xyz !== undefined)
xyz.push(point);
if (thetaPhiRadians !== undefined) {
const data = sphere.xyzToThetaPhiR(point);
thetaPhiRadians.push(LongitudeLatitudeNumber.createRadians(data.thetaRadians, data.phiRadians));
}
}
}
return parameters.length;
}
// public intersectRay(ray: Ray3d, maxHit: number): {rayFractions: number, points: Point3d} {
// const q = new Degree2PowerPolynomial();
// // Ray is (origin.x + s * direction.x, etc)
// // squared distance from origin is (origin.x + s*direction.x)^2 + etc
// // sphere radius in local system is 1.
// q.addSquaredLinearTerm(ray.origin.x, ray.direction.x);
// q.addSquaredLinearTerm(ray.origin.y, ray.direction.y);
// q.addSquaredLinearTerm(ray.origin.z, ray.direction.z);
// q.addConstant(-this.radius * this.radius);
// let ss = [];
// let n = q.realRoots(ss);
// if (n > maxHit)
// n = maxHit;
// let rayFractions;
// let points;
// for (let i = 0; i < n; i++) {
// rayFractions[i] = ss[i];
// points[i] = Point3d. // What is the equivalent of FromSumOf in TS?
// }
/** Compute the point on a sphere at angular coordinates.
* @param thetaRadians latitude angle
* @param phiRadians longitude angle
*/
public evaluateThetaPhi(thetaRadians: number, phiRadians: number, result?: Point3d): Point3d {
const rc = this.radius * Math.cos(thetaRadians);
const rs = this.radius * Math.sin(thetaRadians);
const cosPhi = Math.cos(phiRadians);
const sinPhi = Math.sin(phiRadians);
return Point3d.create(rc * cosPhi, rs * cosPhi, this.radius * sinPhi, result);
}
/**
* * convert radians to xyz on unit sphere
* * Note that there is no radius used -- implicitly radius is 1
* * Evaluation is always to a preallocated xyz.
*/
public static radiansToUnitSphereXYZ(thetaRadians: number, phiRadians: number, xyz: XYZ) {
const cosTheta = Math.cos(thetaRadians);
const sinTheta = Math.sin(thetaRadians);
const cosPhi = Math.cos(phiRadians);
const sinPhi = Math.sin(phiRadians);
xyz.x = cosTheta * cosPhi;
xyz.y = sinTheta * cosPhi;
xyz.z = sinPhi;
}
/** Compute the derivatives with respect to spherical angles.
* @param thetaRadians latitude angle
* @param phiRadians longitude angle
*/
public evaluateDerivativesThetaPhi(thetaRadians: number, phiRadians: number, dxdTheta: Vector3d, dxdPhi: Vector3d) {
const rc = this.radius * Math.cos(thetaRadians);
const rs = this.radius * Math.sin(thetaRadians);
const cosPhi = Math.cos(phiRadians);
const sinPhi = Math.sin(phiRadians);
Vector3d.create(-rs * cosPhi, rc * cosPhi, 0.0, dxdTheta);
Vector3d.create(-rc * sinPhi, -rs * sinPhi, this.radius * cosPhi, dxdPhi);
}
/*
public meridianCircle(theta: number): Arc3d {
const rc = this.radius * Math.cos(theta);
const rs = this.radius * Math.sin(theta);
return Arc3d.create(
Point3d.create(0.0, 0.0, 0.0),
Vector3d.create(rc, rs, 0),
Vector3d.create(0, 0, this.radius),
AngleSweep.create360()) as Arc3d;
}
public parallelCircle(phi: number): Arc3d {
const cr = this.radius * Math.cos(phi);
const sr = this.radius * Math.sin(phi);
return Arc3d.create(
Point3d.create(0, 0, sr),
Vector3d.create(cr, 0, 0),
Vector3d.create(0, cr, 0),
AngleSweep.create360()) as Arc3d;
}
*/
}
/** AnalyticRoots has static methods for solving quadratic, cubic, and quartic equations.
* @internal
*
*/
export class AnalyticRoots {
private static readonly _EQN_EPS = 1.0e-9;
private static readonly _safeDivideFactor = 1.0e-14;
/** Absolute zero test with a tolerance that has worked well for the analytic root use case . . . */
private static isZero(x: number): boolean {
return Math.abs(x) < this._EQN_EPS;
}
/** Without actually doing a division, test if (x/y) is small.
* @param x numerator
* @param y denominator
* @param absTol absolute tolerance
* @param relTol relative tolerance
*/
private static isSmallRatio(x: number, y: number, absTol: number = 1.0e-9, relTol: number = 8.0e-16) {
return Math.abs(x) <= absTol || Math.abs(x) < relTol * Math.abs(y);
}
/** Return the (real, signed) principal cube root of x */
public static cbrt(x: number): number {
return ((x) > 0.0
? Math.pow((x), 1.0 / 3.0)
: ((x) < 0.0
? -Math.pow(-(x), 1.0 / 3.0)
: 0.0));
}
/**
* Try to divide `numerator/denominator` and place the result (or defaultValue) in `values[offset]`
* @param values array of values. `values[offset]` will be replaced.
* @param numerator numerator for division.
* @param denominator denominator for division.
* @param defaultValue value to save if denominator is too small to divide.
* @param offset index of value to replace.
*/
private static safeDivide(values: Float64Array, numerator: number, denominator: number, defaultValue: number = 0.0, offset: number): boolean {
if (Math.abs(denominator) > (this._safeDivideFactor * Math.abs(numerator))) {
values[offset] = numerator / denominator;
return true;
}
values[offset] = defaultValue;
return false;
}
// Used in NewtonMethod for testing if a root has been adjusted past its bounding region
private static checkRootProximity(roots: GrowableFloat64Array, i: number): boolean {
if (i === 0) { // Case 1: Beginning Root (check root following it)
return roots.atUncheckedIndex(i) < roots.atUncheckedIndex(i + 1);
} else if (i > 0 && i + 1 < roots.length) { // Case 2: Middle Root (check roots before and after)
return (roots.atUncheckedIndex(i) > roots.atUncheckedIndex(i - 1)) && (roots.atUncheckedIndex(i) < roots.atUncheckedIndex(i + 1));
} else { // Case 3: End root (check preceding root)
return (roots.atUncheckedIndex(i) > roots.atUncheckedIndex(i - 1));
}
}
private static newtonMethodAdjustment(coffs: Float64Array | number[], root: number, degree: number): number | undefined {
let p = coffs[degree];
let q = 0.0;
for (let i = degree - 1; i >= 0; i--) {
q = p + root * q;
p = coffs[i] + root * p;
}
if (Math.abs(q) >= 1.0e-14 * (1.0 + Math.abs(root))) {
return p / q;
}
return undefined;
}
private static improveRoots(coffs: Float64Array | number[], degree: number, roots: GrowableFloat64Array, restrictOrderChanges: boolean) {
const relTol = 1.0e-10;
// Loop through each root
for (let i = 0; i < roots.length; i++) {
let dx = this.newtonMethodAdjustment(coffs, roots.atUncheckedIndex(i), degree);
if (dx === undefined || dx === 0.0) continue; // skip if newton step had divide by zero.
const originalValue = roots.atUncheckedIndex(i);
let counter = 0;
let convergenceCounter = 0;
// Loop through applying changes to found root until dx is diminished or counter is hit
while (dx !== undefined && dx !== 0.0 && (counter < 12)) {
// consider it converged if two successive iterations satisfy the (not too demanding) tolerance.
if (Math.abs(dx) < relTol * (1.0 + Math.abs(roots.atUncheckedIndex(i)))) {
if (++convergenceCounter > 1)
break;
} else {
convergenceCounter = 0;
}
const rootDX = roots.atUncheckedIndex(i) - dx;
roots.reassign(i, rootDX);
// If root is thrown past one of its neighboring roots, unstable condition is assumed.. revert
// to originally found root
if (restrictOrderChanges && !this.checkRootProximity(roots, i)) {
roots.reassign(i, originalValue);
break;
}
dx = this.newtonMethodAdjustment(coffs, roots.atUncheckedIndex(i), degree);
counter++;
}
}
}
/**
* Append (if defined) value to results.
* @param value optional value to append
* @param results growing array
*/
private static appendSolution(value: number | undefined, results: GrowableFloat64Array) {
if (value !== undefined) {
results.push(value);
}
}
/**
* Append 2 solutions -- note that both are required args, no option of omitting as in single solution case
* @param value1
* @param value2
* @param results
*/
private static append2Solutions(valueA: number, valueB: number, results: GrowableFloat64Array) {
results.push(valueA);
results.push(valueB);
}
/**
* If `co/c1` is a safe division, append it to the values array.
* @param c0 numerator
* @param c1 denominator
* @param values array to expand
*/
public static appendLinearRoot(c0: number, c1: number, values: GrowableFloat64Array) {
AnalyticRoots.appendSolution(Geometry.conditionalDivideFraction(-c0, c1), values);
}
/**
* * Compute the mean of all the entries in `data`
* * Return the data value that is farthest away
*/
public static mostDistantFromMean(data: GrowableFloat64Array | undefined): number {
if (!data || data.length === 0) return 0;
let a = 0.0; // to become the sum and finally the average.
for (let i = 0; i < data.length; i++) a += data.atUncheckedIndex(i);
a /= data.length;
let dMax = 0.0;
let result = data.atUncheckedIndex(0);
for (let i = 0; i < data.length; i++) {
const d = Math.abs(data.atUncheckedIndex(i) - a);
if (d > dMax) {
dMax = d;
result = data.atUncheckedIndex(i);
}
}
return result;
}
/**
* Append 0, 1, or 2 solutions of a quadratic to the values array.
* @param c array of coefficients for quadratic `c[0] + c[1] * x + c[2] * x*x`
* @param values array to be expanded.
*/
public static appendQuadraticRoots(c: Float64Array | number[], values: GrowableFloat64Array) {
// Normal form: x^2 + 2px + q = 0
const divFactor = Geometry.conditionalDivideFraction(1.0, c[2]);
if (!divFactor) {
this.appendLinearRoot(c[0], c[1], values);
return;
}
const p = 0.5 * c[1] * divFactor;
const q = c[0] * divFactor;
const D = p * p - q;
if (this.isZero(D)) {
this.appendSolution(-p, values);
return;
} else if (D < 0) {
return;
} else if (D > 0) {
const sqrt_D = Math.sqrt(D);
this.append2Solutions(sqrt_D - p, - sqrt_D - p, values);
return;
}
return;
}
/** Add `a` to the constant term. */
private static addConstant(value: number, data: GrowableFloat64Array) {
for (let i = 0; i < data.length; i++) data.reassign(i, data.atUncheckedIndex(i) + value);
}
private static signedCubeRoot(y: number): number {
if (y >= 0.0)
return Math.pow(y, 1.0 / 3.0);
return -Math.pow(-y, 1.0 / 3.0);
}
/**
* RWD Nickalls Cubic solution
* The Mathematical Gazette (1993) (vol 77) pp 354-359
* * ASSUME a is nonzero.
*/
// Solve full cubic ASSUMING a3 is nonzero.
private static appendFullCubicSolutions(a: number, b: number, c: number, d: number, result: GrowableFloat64Array) {
const q = b * b - 3.0 * a * c;
const aa = a * a;
const delta2 = q / (9.0 * aa);
const xN = - b / (3.0 * a);
const yN = d + xN * (c + xN * (b + xN * a));
const yN2 = yN * yN;
const h2 = 4.0 * a * a * delta2 * delta2 * delta2;
const discriminant = yN2 - h2;
if (discriminant > 0) {
// 1 real root
const r = Math.sqrt(discriminant);
const f = 0.5 / a;
result.push(xN + this.signedCubeRoot(f * (-yN + r)) + this.signedCubeRoot(f * (-yN - r)));
} else if (discriminant < 0) {
// 3 real roots
let h = Math.sqrt(h2);
// I don't see comment in Nickalls about sign of h -- but this sign change is needed ...
if (a < 0)
h = -h;
// sign of h?
const thetaRadians = Math.acos(-yN / h) / 3.0;
const g = 2.0 * Math.sqrt(delta2);
const shift = 2.0 * Math.PI / 3.0;
result.push(xN + g * Math.cos(thetaRadians));
result.push(xN + g * Math.cos(thetaRadians + shift));
result.push(xN + g * Math.cos(thetaRadians - shift));
} else {
// NOTE: The double-root case is not toleranced.
// double root + single root
const delta = this.signedCubeRoot(0.5 * yN / a);
const minMaxRoot = xN + delta;
result.push(xN - 2 * delta);
result.push(minMaxRoot);
result.push(minMaxRoot);
}
}
/* return roots of a cubic c0 + c1 *x + c2 * x^2 + c2 * x3.
* In the usual case where c0 is non-zero, there are either 1 or 3 roots.
* But if c0 is zero the (0, 1, or 2) roots of the lower order equation
*/
/*
private static _appendCubicRootsUnsorted(c: Float64Array | number[], results: GrowableFloat64Array) {
let sq_A: number;
let p: number;
let q: number;
// normal form: x^3 + Ax^2 + Bx + C = 0
const scaleFactor = Geometry.conditionalDivideFraction(1.0, c[3]);
if (!scaleFactor) {
this.appendQuadraticRoots(c, results);
return;
}
// It is a real cubic. There MUST be at least one real solution . . .
const A: number = c[2] * scaleFactor;
const B: number = c[1] * scaleFactor;
const C: number = c[0] * scaleFactor;
// substitute x = y - A/3 to eliminate quadric term:
// f = y^3 +3py + 2q = 0
// f' = 3y^2 + p
// local min/max at Y = +-sqrt (-p)
// f(+Y) = -p sqrt(-p) + 3p sqrt (-p) + 2q = 2 p sqrt (-p) + 2q
sq_A = A * A;
p = (3.0 * B - sq_A) / 9.0;
q = 1.0 / 2 * (2.0 / 27 * A * sq_A - 1.0 / 3 * A * B + C);
// Use Cardano formula
const cb_p: number = p * p * p;
const D: number = q * q + cb_p;
const origin = A / (-3.0);
if (D >= 0.0 && this.isZero(D)) {
if (this.isZero(q)) {
// One triple solution
results.push(origin);
results.push(origin);
results.push(origin);
return;
} else {
// One single and one double solution
const u = this.cbrt(-q);
if (u < 0) {
results.push(origin + 2 * u);
results.push(origin - u);
results.push(origin - u);
return;
} else {
results.push(origin - u);
results.push(origin - u);
results.push(origin + 2 * u);
return;
}
}
} else if (D <= 0) { // three real solutions
const phi = 1.0 / 3 * Math.acos(-q / Math.sqrt(-cb_p));
const t = 2 * Math.sqrt(-p);
results.push(origin + t * Math.cos(phi));
results.push(origin - t * Math.cos(phi + Math.PI / 3));
results.push(origin - t * Math.cos(phi - Math.PI / 3));
this.improveRoots(c, 3, results, false);
return;
} else { // One real solution
const sqrt_D = Math.sqrt(D);
const u = this.cbrt(sqrt_D - q);
const v = -(this.cbrt(sqrt_D + q));
results.push(origin + u + v);
this.improveRoots(c, 3, results, false);
return;
}
}
*/
/** Compute roots of cubic 'c[0] + c[1] * x + c[2] * x^2 + c[3] * x^3 */
public static appendCubicRoots(c: Float64Array | number[], results: GrowableFloat64Array) {
if (Geometry.conditionalDivideCoordinate(1.0, c[3]) !== undefined) {
this.appendFullCubicSolutions(c[3], c[2], c[1], c[0], results);
// EDL April 5, 2020 replace classic GraphicsGems solver by RWDNickalls.
// Don't know if improveRoots is needed.
// Breaks in AnalyticRoots.test.ts checkQuartic suggest it indeed converts many e-16 errors to zero.
// e-13 cases are unaffected
this.improveRoots(c, 3, results, false);
} else {
this.appendQuadraticRoots(c, results);
}
// this.appendCubicRootsUnsorted(c, results);
results.sort();
}
/** Compute roots of quartic 'c[0] + c[1] * x + c[2] * x^2 + c[3] * x^3 + c[4] * x^4 */
public static appendQuarticRoots(c: Float64Array | number[], results: GrowableFloat64Array) {
const coffs = new Float64Array(4); // at various times .. coefficients of quadratic an cubic intermediates.
let u: number;
let v: number;
// normal form: x^4 + Ax^3 + Bx^2 + Cx + D = 0
const coffScale = new Float64Array(1);
if (!this.safeDivide(coffScale, 1.0, c[4], 0.0, 0)) {
this.appendCubicRoots(c, results);
return;
}
const A: number = c[3] * coffScale[0];
const B: number = c[2] * coffScale[0];
const C: number = c[1] * coffScale[0];
const D: number = c[0] * coffScale[0];
const origin = -0.25 * A;
/* substitute x = y - A/4 to eliminate cubic term:
x^4 + px^2 + qx + r = 0 */
const sq_A: number = A * A;
const p: number = -3.0 / 8 * sq_A + B;
const q: number = 0.125 * sq_A * A - 0.5 * A * B + C;
const r: number = -3.0 / 256 * sq_A * sq_A + 1.0 / 16 * sq_A * B - 1.0 / 4 * A * C + D;
const tempStack = new GrowableFloat64Array();
if (this.isZero(r)) {
// no absolute term: y(y^3 + py + q) = 0
coffs[0] = q;
coffs[1] = p;
coffs[2] = 0;
coffs[3] = 1;
this.appendCubicRoots(coffs, results);
results.push(0); // APPLY ORIGIN ....
this.addConstant(origin, results);
return;
} else {
// Solve the resolvent cubic
coffs[0] = 1.0 / 2 * r * p - 1.0 / 8 * q * q;
coffs[1] = - r;
coffs[2] = - 1.0 / 2 * p;
coffs[3] = 1;
this.appendCubicRoots(coffs, tempStack);
const z = this.mostDistantFromMean(tempStack);
// ... to build two quadric equations
u = z * z - r;
v = 2 * z - p;
if (this.isSmallRatio(u, r)) {
u = 0;
} else if (u > 0) {
u = Math.sqrt(u);
} else {
return;
}
if (this.isSmallRatio(v, p)) {
v = 0;
} else if (v > 0) {
v = Math.sqrt(v);
} else {
for (let i = 0; i < tempStack.length; i++) {
results.push(tempStack.atUncheckedIndex(i));
}
return;
}
coffs[0] = z - u;
coffs[1] = ((q < 0) ? (-v) : (v));