/
AccuDraw.ts
3416 lines (2870 loc) · 120 KB
/
AccuDraw.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 AccuDraw
*/
import { BentleyStatus } from "@itwin/core-bentley";
import {
Arc3d, AxisOrder, CurveCurve, CurvePrimitive, Geometry, IModelJson as GeomJson, LineSegment3d, LineString3d, Matrix3d, Plane3dByOriginAndUnitNormal, Point2d, Point3d,
PointString3d, Ray3d, Transform, Vector3d,
} from "@itwin/core-geometry";
import { ColorByName, ColorDef, GeometryStreamProps, LinePixels } from "@itwin/core-common";
import { TentativeOrAccuSnap } from "./AccuSnap";
import { ACSDisplayOptions, AuxCoordSystemState } from "./AuxCoordSys";
import { HitDetail, SnapDetail, SnapHeat, SnapMode } from "./HitDetail";
import { IModelApp } from "./IModelApp";
import { GraphicBuilder, GraphicType } from "./render/GraphicBuilder";
import { StandardViewId } from "./StandardView";
import { BeButton, BeButtonEvent, CoordinateLockOverrides, InputCollector, InputSource } from "./tools/Tool";
import { ViewTool } from "./tools/ViewTool";
import { DecorateContext } from "./ViewContext";
import { linePlaneIntersect } from "./LinePlaneIntersect";
import { ScreenViewport, Viewport } from "./Viewport";
import { ViewState } from "./ViewState";
import { QuantityType } from "./quantity-formatting/QuantityFormatter";
import { ParseError, Parser, QuantityParseResult } from "@itwin/core-quantity";
// cspell:ignore dont primitivetools
/** @internal */
export enum AccuDrawFlags {
None = 0,
SetModePolar = 1,
SetModeRect = 1 << 1,
SetOrigin = (1 << 2),
FixedOrigin = (1 << 3),
SetRMatrix = (1 << 4),
SetXAxis = (1 << 5),
SetNormal = (1 << 6),
SetDistance = (1 << 7),
LockDistance = (1 << 8),
Lock_X = (1 << 9),
Lock_Y = (1 << 10),
Lock_Z = (1 << 11),
Disable = (1 << 12),
OrientDefault = (1 << 14),
SetFocus = (1 << 15),
OrientACS = (1 << 17),
SetXAxis2 = (1 << 18),
LockAngle = (1 << 19),
AlwaysSetOrigin = SetOrigin | (1 << 21),
RedrawCompass = (1 << 22),
UpdateRotation = (1 << 23),
SmartRotation = (1 << 24),
}
/** AccuDraw coordinate input mode
* @public
*/
export enum CompassMode {
/** Coordinate input using distance and angle */
Polar = 0,
/** Coordinate input using x, y, and z deltas */
Rectangular = 1,
}
/** AccuDraw compass base rotation
* @public
*/
export enum RotationMode {
/** Aligned with standard view top or ACS top when [[ToolAdmin.acsContextLock]] is enabled */
Top = 1,
/** Aligned with standard view front or ACS front when [[ToolAdmin.acsContextLock]] is enabled */
Front = 2,
/** Aligned with standard view right or ACS right when [[ToolAdmin.acsContextLock]] is enabled */
Side = 3,
/** Aligned with view */
View = 4,
/** Aligned with view ACS */
ACS = 5,
/** Not aligned with a standard rotation or ACS */
Context = 6,
}
/** @internal */
export enum LockedStates {
NONE_LOCKED = 0,
X_BM = (1),
Y_BM = (1 << 1),
VEC_BM = (1 << 2),
DIST_BM = (1 << 3),
XY_BM = (X_BM | Y_BM),
ANGLE_BM = (XY_BM | VEC_BM),
}
/** AccuDraw enabled states
* @public
*/
export enum CurrentState {
/** Compass disabled/unwanted for this session */
NotEnabled = 0,
/** Compass deactivated but CAN be activated by user */
Deactivated = 1,
/** Compass not displayed awaiting automatic activation (default tool state) */
Inactive = 2,
/** Compass displayed and adjusting points */
Active = 3,
}
/** @internal */
export enum ContextMode {
Locked = 0,
XAxis = 1,
YAxis = 2,
ZAxis = 3,
XAxis2 = 4,
None = 15,
}
/** AccuDraw coordinate input fields
* @public
*/
export enum ItemField {
/** Distance for polar mode */
DIST_Item = 0,
/** Angle for polar mode */
ANGLE_Item = 1,
/** X delta for rectangular mode */
X_Item = 2,
/** Y delta for rectangular mode */
Y_Item = 3,
/** Z delta (3d only) */
Z_Item = 4,
}
/** @internal */
export enum KeyinStatus {
Dynamic = 0,
Partial = 1,
DontUpdate = 2,
}
const enum Constants { // eslint-disable-line no-restricted-syntax
MAX_SAVED_VALUES = 20,
SMALL_ANGLE = 1.0e-12,
SMALL_DELTA = 0.00001,
}
/** @internal */
export class AccudrawData {
public flags = 0; // AccuDrawFlags
public readonly origin = new Point3d(); // used if ACCUDRAW_SetOrigin
public readonly delta = new Point3d(); // if ACCUDRAW_Lock_X, etc.
public readonly rMatrix = new Matrix3d(); // if ACCUDRAW_SetRMatrix/ACCUDRAW_Set3dMatrix
public readonly vector = new Vector3d(); // if ACCUDRAW_SetXAxis, etc.
public distance = 0; // if ACCUDRAW_SetDistance
public angle = 0; // if ACCUDRAW_SetAngle
public zero() {
this.flags = this.distance = this.angle = 0;
this.origin.setZero();
this.delta.setZero();
this.vector.setZero();
this.rMatrix.setIdentity();
}
}
/** @internal */
export class Flags {
public redrawCompass = false;
public dialogNeedsUpdate = false;
public rotationNeedsUpdate = true;
public lockedRotation = false;
public indexLocked = false;
public haveValidOrigin = false;
public fixedOrg = false;
public auxRotationPlane = RotationMode.Top;
public contextRotMode = 0;
public baseRotation = RotationMode.View;
public baseMode = 0;
public pointIsOnPlane = false; // whether rawPointOnPlane is on compass plane
public softAngleLock = false;
public bearingFixToPlane2D = false;
public inDataPoint = false;
public ignoreDataButton = false;
public animateRotation = false;
}
/** @internal */
export class RoundOff {
public active = false;
public units = new Set<number>();
}
/** @internal */
export class SavedState {
public state = CurrentState.NotEnabled;
public mode = CompassMode.Polar;
public rotationMode = RotationMode.View;
public readonly axes = new ThreeAxes();
public readonly origin = new Point3d();
public auxRotationPlane = 0;
public contextRotMode = 0;
public fixedOrg = false;
public ignoreDataButton = true; // By default the data point that terminates a view tool or input collector should be ignored...
public ignoreFlags: AccuDrawFlags = 0;
}
/** @internal */
class SavedCoords {
public nSaveValues = 0;
public readonly savedValues: number[] = [];
public readonly savedValIsAngle: boolean[] = [];
}
/** @internal */
export class ThreeAxes {
public readonly x = Vector3d.unitX();
public readonly y = Vector3d.unitY();
public readonly z = Vector3d.unitZ();
public setFrom(other: ThreeAxes) {
this.x.setFrom(other.x);
this.y.setFrom(other.y);
this.z.setFrom(other.z);
}
public fromMatrix3d(rMatrix: Matrix3d): void {
rMatrix.getRow(0, this.x);
rMatrix.getRow(1, this.y);
rMatrix.getRow(2, this.z);
}
public static createFromMatrix3d(rMatrix: Matrix3d, result?: ThreeAxes): ThreeAxes {
result = result ? result : new ThreeAxes();
result.fromMatrix3d(rMatrix);
return result;
}
public toMatrix3d(out?: Matrix3d) { return Matrix3d.createRows(this.x, this.y, this.z, out); }
public clone(): ThreeAxes {
const out = new ThreeAxes();
out.setFrom(this);
return out;
}
public equals(other: ThreeAxes): boolean { return this.x.isExactEqual(other.x) && this.y.isExactEqual(other.y) && this.z.isExactEqual(other.z); }
}
/** Accudraw is an aide for entering coordinate data.
* This class is public to allow applications to provide a user interface for AccuDraw, either by implementing their own, or
* using the one supplied by the itwin appui package.
* @note When writing an [[InteractiveTool]] it is not correct to call methods on AccuDraw directly, tools should instead
* provide hints to AccuDraw using [[AccuDrawHintBuilder]].
* @public
*/
export class AccuDraw {
public currentState = CurrentState.NotEnabled; // Compass state
public compassMode = CompassMode.Rectangular; // Compass mode
public rotationMode = RotationMode.View; // Compass rotation
/** @internal */
public currentView?: ScreenViewport; // will be nullptr if view not yet defined
/** @internal */
public readonly published = new AccudrawData(); // Staging area for hints
/** @internal */
public readonly origin = new Point3d(); // origin point...not on compass plane when z != 0.0
/** @internal */
public readonly axes = new ThreeAxes(); // X, Y and Z vectors (3d rotation matrix)
/** @internal */
public readonly delta = Vector3d.unitZ(); // dialog items (x, y & z)
private _distance = 0; // current distance
private _angle = 0; // current angle
/** @internal */
public locked = LockedStates.NONE_LOCKED; // axis/distance locked bit mask
/** @internal */
public indexed = LockedStates.NONE_LOCKED; // axis/distance indexed bit mask
private readonly _distanceRoundOff = new RoundOff(); // distance round off enabled and unit
private readonly _angleRoundOff = new RoundOff(); // angle round off enabled and unit
/** @internal */
public readonly flags = new Flags(); // current state flags
private readonly _fieldLocked: boolean[] = []; // locked state of fields
private readonly _keyinStatus: KeyinStatus[] = []; // state of input field
/** @internal */
public readonly savedStateViewTool = new SavedState(); // Restore point for shortcuts/tools...
/** @internal */
public readonly savedStateInputCollector = new SavedState(); // Restore point for shortcuts/tools...
private readonly _savedCoords = new SavedCoords(); // History of previous angles/distances...
/** @internal */
public readonly baseAxes = new ThreeAxes(); // Used for "context" base rotation to hold arbitrary rotation w/o needing to change ACS...
/** @internal */
public readonly lastAxes = new ThreeAxes(); // Last result from UpdateRotation, replaces cM.rMatrix...
private _lastDistance = 0; // previous saved distance or distance indexing tick
private _tolerance = 0; // computed view based indexing tolerance
private _percentChanged = 0; // Compass animation state
private _threshold = 0; // Threshold for automatic x/y field focus change.
/** @internal */
public readonly planePt = new Point3d(); // same as origin unless non-zero locked z value
private readonly _rawDelta = new Point2d(); // used by rect fix point
private readonly _rawPoint = new Point3d(); // raw uor point passed to fix point
private readonly _rawPointOnPlane = new Point3d(); // adjusted rawPoint by applying hard/soft construction plane
/** @internal */
public readonly point = new Point3d(); // current cursor point
/** @internal */
public readonly vector = Vector3d.unitZ(); // current/last good locked direction
private _xIsNegative = false; // Last delta.x was negative
private _yIsNegative = false; // Last delta.y was negative
private _xIsExplicit = false; // Sign of delta.x established from user input input, don't allow +/- side flip.
private _yIsExplicit = false; // Sign of delta.y established from user input input, don't allow +/- side flip.
/** Disable automatic focus change when user is entering input. */
public dontMoveFocus = false;
/** Set input field to move focus to (X_Item or Y_Item) for automatic focus change. */
public newFocus = ItemField.X_Item;
private readonly _rMatrix = new Matrix3d();
/** @internal */
protected _acsPickId?: string;
// Compass Display Preferences...
/** @internal */
protected _compassSizeInches = 0.44;
/** @internal */
protected _animationFrames = 12;
/** @internal */
protected _indexToleranceInches = 0.11;
/** @internal */
protected readonly _frameColor = ColorDef.create(ColorByName.lightGrey);
/** @internal */
protected readonly _fillColor = ColorDef.create(ColorByName.blue);
/** @internal */
protected readonly _xColor = ColorDef.create(ColorByName.red);
/** @internal */
protected readonly _yColor = ColorDef.create(ColorByName.green);
/** @internal */
protected readonly _indexColor = ColorDef.create(ColorByName.white);
/** @internal */
protected readonly _frameColorNoFocus = ColorDef.create(ColorByName.darkGrey);
/** @internal */
protected readonly _fillColorNoFocus = ColorDef.create(ColorByName.lightGrey);
// User Preference Settings...
public smartKeyin = true;
public floatingOrigin = true;
public stickyZLock = false;
public alwaysShowCompass = false;
public contextSensitive = true;
public axisIndexing = true;
public distanceIndexing = true;
public autoFocusFields = true;
public autoPointPlacement = false;
private static _tempRot = new Matrix3d();
/** @internal */
public onInitialized() { this.enableForSession(); }
/** @internal */
public getRotation(rMatrix?: Matrix3d): Matrix3d {
if (!rMatrix)
rMatrix = this._rMatrix;
Matrix3d.createRows(this.axes.x, this.axes.y, this.axes.z, rMatrix);
return rMatrix;
}
public get isActive(): boolean { return CurrentState.Active === this.currentState; }
public get isEnabled(): boolean { return (this.currentState > CurrentState.NotEnabled); }
public get isInactive(): boolean { return (CurrentState.Inactive === this.currentState); }
public get isDeactivated(): boolean { return (CurrentState.Deactivated === this.currentState); }
/** Get the current lock state for the supplied input field */
public getFieldLock(index: ItemField): boolean { return this._fieldLocked[index]; }
/** @internal */
public getKeyinStatus(index: ItemField): KeyinStatus { return this._keyinStatus[index]; }
/** Implement this method to set focus to the AccuDraw UI. */
public grabInputFocus() { }
/** @internal */
public activate(): void {
// Upgrade state to inactive so upgradeToActiveState knows it is ok to move to active...
if (CurrentState.Deactivated === this.currentState)
this.currentState = CurrentState.Inactive;
this.upgradeToActiveState();
}
/** @internal */
public deactivate() {
this.downgradeInactiveState();
// Don't allow compass to come back until user re-enables it...
if (CurrentState.Inactive === this.currentState)
this.currentState = CurrentState.Deactivated;
}
/** Change current compass input mode to either polar or rectangular */
public setCompassMode(mode: CompassMode): void {
if (mode === this.compassMode)
return;
this.compassMode = mode;
this.onCompassModeChange();
}
/** Change current compass orientation */
public setRotationMode(mode: RotationMode): void {
if (mode === this.rotationMode)
return;
this.rotationMode = mode;
this.onRotationModeChange();
}
/** Change the lock status for the supplied input field */
public setFieldLock(index: ItemField, locked: boolean): void {
if (locked === this._fieldLocked[index])
return;
this._fieldLocked[index] = locked;
this.onFieldLockChange(index);
}
/** @internal */
public setKeyinStatus(index: ItemField, status: KeyinStatus): void {
this._keyinStatus[index] = status;
if (KeyinStatus.Dynamic !== status)
this.dontMoveFocus = true;
if (KeyinStatus.Partial === status)
this._threshold = Math.abs(ItemField.X_Item === index ? this._rawDelta.y : this._rawDelta.x) + this._tolerance;
}
private needsRefresh(vp: Viewport): boolean {
if (!this.isEnabled || this.isDeactivated)
return false;
// Get snap point from AccuSnap/Tentative or use raw point...
let distance = 0.0;
let snapPt = this._rawPoint;
const ptP = this.point;
const snap = TentativeOrAccuSnap.getCurrentSnap();
if (snap) {
snapPt = snap.snapPoint;
distance = ptP.distance(snapPt);
}
const isRectMode = (CompassMode.Rectangular === this.compassMode);
const offsetSnap = ((TentativeOrAccuSnap.isHot || IModelApp.tentativePoint.isActive) && ((this.locked) || (distance > 0.0)));
// XY Offset:
if (offsetSnap) {
if (isRectMode) {
let xIsOffset = false, yIsOffset = false;
const vec = ptP.vectorTo(this._rawPointOnPlane);
const xOffset = vec.dotProduct(this.axes.x);
const yOffset = vec.dotProduct(this.axes.y);
xIsOffset = (Math.abs(xOffset) > 1.0);
yIsOffset = (Math.abs(yOffset) > 1.0);
if (xIsOffset || yIsOffset)
return true;
}
}
const isOnCompassPlane = (!vp.view.is3d() || this.flags.pointIsOnPlane || this.isZLocked(vp));
// Z Offset:
if (offsetSnap) {
if (isOnCompassPlane) {
const zOffset = snapPt.distance(this._rawPointOnPlane);
if (zOffset > Constants.SMALL_ANGLE || zOffset < -Constants.SMALL_ANGLE)
return true;
}
}
// Fat Point:
if (offsetSnap)
return true;
let axisIsIndexed = false;
// Axis Indexing:
if (isRectMode) {
if ((this.indexed & LockedStates.XY_BM) && (this.flags.pointIsOnPlane || this._fieldLocked[ItemField.Z_Item]))
axisIsIndexed = true;
} else {
if ((this.indexed & LockedStates.ANGLE_BM || this.locked & LockedStates.ANGLE_BM) && (this.flags.pointIsOnPlane || this._fieldLocked[ItemField.Z_Item]))
axisIsIndexed = true;
}
if (axisIsIndexed)
return true;
// Distance Indexing:
if (this.indexed & LockedStates.DIST_BM)
return true;
// XY Lock:
if (isRectMode) {
const locked = this.locked & LockedStates.XY_BM;
if ((0 !== locked) && isOnCompassPlane) {
switch (locked) {
case LockedStates.X_BM:
case LockedStates.Y_BM:
case LockedStates.XY_BM:
return true;
}
}
}
return false;
}
/** @internal */
public adjustPoint(pointActive: Point3d, vp: ScreenViewport, fromSnap: boolean): boolean {
if (!this.isEnabled)
return false;
const lastWasIndexed = (0 !== this.indexed);
let pointChanged = false, handled = false;
if (0.0 !== pointActive.z && !vp.isPointAdjustmentRequired)
pointActive.z = 0.0;
if (1.0 !== vp.view.getAspectRatioSkew())
this.downgradeInactiveState(); // Disable AccuDraw if skew is applied with AccuDraw already active...
if (this.isInactive) {
this.point.setFrom(pointActive);
this.currentView = vp;
this.fixPoint(pointActive, vp);
if (!fromSnap && IModelApp.accuSnap.currHit)
this.flags.redrawCompass = true;
} else if (this.isActive) {
const lastPt = this.point.clone();
this.fixPoint(pointActive, vp);
pointChanged = !lastPt.isExactEqual(this.point);
this.processHints();
handled = true;
} else {
this.currentView = vp; // Keep view up to date...
}
// If redraw of compass isn't required (yet!) check if needed...
if (!this.flags.redrawCompass && this.isActive) {
// Redraw required to erase/draw old/new indexing geometry...
if (pointChanged && (lastWasIndexed || this.needsRefresh(vp)))
this.flags.redrawCompass = true;
}
// Redraw is necessary, force decorators to be called...
if (this.flags.redrawCompass)
vp.invalidateDecorations();
return handled;
}
private setDefaultOrigin(vp?: Viewport): void {
if (!vp || this.locked || this._fieldLocked[ItemField.Z_Item])
return;
const view = vp.view;
const rMatrix = view.getRotation();
const acsOrigin = vp.getAuxCoordOrigin();
rMatrix.multiplyVectorInPlace(acsOrigin);
const origin = view.getCenter();
view.getRotation().multiplyVectorInPlace(origin);
origin.z = acsOrigin.z;
view.getRotation().multiplyTransposeVectorInPlace(origin);
this.origin.setFrom(origin); // View center at acs z...
this.planePt.setFrom(origin);
}
/** @internal */
public isZLocked(vp: Viewport): boolean {
if (this._fieldLocked[ItemField.Z_Item])
return true;
if (vp.isSnapAdjustmentRequired) // && TentativeOrAccuSnap.isHot())
return true;
return false;
}
/** @internal */
public accountForAuxRotationPlane(rot: ThreeAxes, plane: RotationMode): void {
// ACS mode now can have "front" and "side" variations...
switch (plane) {
case RotationMode.Top:
return;
case RotationMode.Front:
const temp = rot.y.clone();
rot.y.setFrom(rot.z);
temp.scale(-1.0, rot.z);
return;
case RotationMode.Side:
const temp0 = rot.x.clone();
rot.x.setFrom(rot.y);
rot.y.setFrom(rot.z);
rot.z.setFrom(temp0);
}
}
private accountForACSContextLock(vec: Vector3d): void {
// Base rotation is relative to ACS when ACS context lock is enabled...
if (!this.currentView || !this.currentView.isContextRotationRequired)
return;
const rMatrix = AccuDraw.getStandardRotation(StandardViewId.Top, this.currentView, true);
rMatrix.multiplyTransposeVectorInPlace(vec);
}
private static useACSContextRotation(vp: Viewport, isSnap: boolean): boolean {
if (isSnap) {
if (!vp.isSnapAdjustmentRequired)
return false;
} else {
if (!vp.isContextRotationRequired)
return false;
}
return true;
}
/** Gets X, Y or Z vector from top, front, (right) side, ACS, or View. */
private getStandardVector(whichVec: number): Vector3d {
const vp = this.currentView;
let rMatrix: Matrix3d;
let myAxes: ThreeAxes;
const vecP = Vector3d.createZero();
/* eslint-disable max-statements-per-line */
switch (this.flags.baseRotation) {
case RotationMode.Top:
switch (whichVec) {
case 0: vecP.x = 1.0; break;
case 1: vecP.y = 1.0; break;
case 2: vecP.z = 1.0; break;
}
this.accountForACSContextLock(vecP);
break;
case RotationMode.Front:
switch (whichVec) {
case 0: vecP.x = 1.0; break;
case 1: vecP.z = 1.0; break;
case 2: vecP.y = -1.0; break;
}
this.accountForACSContextLock(vecP);
break;
case RotationMode.Side:
switch (whichVec) {
case 0: vecP.y = 1.0; break;
case 1: vecP.z = 1.0; break;
case 2: vecP.x = 1.0; break;
}
this.accountForACSContextLock(vecP);
break;
case RotationMode.ACS:
rMatrix = vp ? vp.getAuxCoordRotation() : Matrix3d.createIdentity();
myAxes = ThreeAxes.createFromMatrix3d(rMatrix);
this.accountForAuxRotationPlane(myAxes, this.flags.auxRotationPlane);
switch (whichVec) {
case 0: vecP.setFrom(myAxes.x); break;
case 1: vecP.setFrom(myAxes.y); break;
case 2: vecP.setFrom(myAxes.z); break;
}
break;
case RotationMode.View:
rMatrix = vp ? vp.rotation : Matrix3d.createIdentity();
rMatrix.getRow(whichVec, vecP);
break;
case RotationMode.Context:
myAxes = this.baseAxes.clone();
this.accountForAuxRotationPlane(myAxes, this.flags.auxRotationPlane);
switch (whichVec) {
case 0: vecP.setFrom(myAxes.x); break;
case 1: vecP.setFrom(myAxes.y); break;
case 2: vecP.setFrom(myAxes.z); break;
}
break;
}
/* eslint-enable max-statements-per-line */
return vecP;
}
private getBestViewedRotationFromXVector(rotation: ThreeAxes, vp: Viewport): void {
const viewZ = vp.rotation.getRow(2);
const vec1 = this.getStandardVector(2);
const vec2 = this.getStandardVector(1);
const vec3 = this.getStandardVector(0);
const rot1 = vec1.crossProduct(rotation.x);
const rot2 = vec2.crossProduct(rotation.x);
const rot3 = vec3.crossProduct(rotation.x);
const useRot1 = (rot1.normalizeWithLength(rot1).mag > 0.00001);
const useRot2 = (rot2.normalizeWithLength(rot2).mag > 0.00001);
const useRot3 = (rot3.normalizeWithLength(rot3).mag > 0.00001);
const dot1 = (useRot1 ? Math.abs(rotation.x.crossProduct(rot1).dotProduct(viewZ)) : -1.0);
const dot2 = (useRot2 ? Math.abs(rotation.x.crossProduct(rot2).dotProduct(viewZ)) : -1.0);
const dot3 = (useRot3 ? Math.abs(rotation.x.crossProduct(rot3).dotProduct(viewZ)) : -1.0);
const max = Math.max(dot1, dot2, dot3);
if (Geometry.isDistanceWithinTol(dot1 - dot2, 0.1) && (max !== dot3))
rotation.y.setFrom(rot1);
else if (max === dot1)
rotation.y.setFrom(rot1);
else if (max === dot2)
rotation.y.setFrom(rot2);
else
rotation.y.setFrom(rot3);
rotation.z.setFrom(rotation.x.crossProduct(rotation.y));
}
private getRotationFromVector(rotation: ThreeAxes, whichVec: number): void {
let vec: Vector3d;
switch (whichVec) {
case 0:
vec = this.getStandardVector(2);
vec.crossProduct(rotation.x, rotation.y);
if (rotation.y.normalizeWithLength(rotation.y).mag < .00001) {
vec = this.getStandardVector(1);
vec.crossProduct(rotation.x, rotation.y);
rotation.y.normalizeInPlace();
}
rotation.x.crossProduct(rotation.y, rotation.z);
break;
case 1:
vec = this.getStandardVector(2);
vec.crossProduct(rotation.y, rotation.x);
if (rotation.x.normalizeWithLength(rotation.x).mag < .00001) {
vec = this.getStandardVector(0);
vec.crossProduct(rotation.y, rotation.x);
rotation.x.normalizeInPlace();
}
rotation.x.crossProduct(rotation.y, rotation.z);
break;
case 2:
vec = this.getStandardVector(0);
rotation.z.crossProduct(vec, rotation.y);
if (rotation.y.normalizeWithLength(rotation.y).mag < .00001) {
vec = this.getStandardVector(1);
vec.crossProduct(rotation.z, rotation.x);
rotation.x.normalizeInPlace();
rotation.z.crossProduct(rotation.x, rotation.y);
} else {
rotation.y.crossProduct(rotation.z, rotation.x);
}
break;
}
}
/** @internal */
public updateRotation(animate: boolean = false, newRotationIn?: Matrix3d): void {
let clearLocks = true;
const oldRotation = this.axes.clone();
let rMatrix: Matrix3d;
let newRotation: ThreeAxes;
if (!newRotationIn)
newRotation = this.axes.clone(); // for axis based
else
newRotation = ThreeAxes.createFromMatrix3d(newRotationIn); // for animating context rotation change...
const vp = this.currentView;
const useACS = vp ? vp.isContextRotationRequired : false;
switch (this.rotationMode) {
case RotationMode.Top:
// Get standard rotation relative to ACS when ACS context lock is enabled...
newRotation.fromMatrix3d(AccuDraw.getStandardRotation(StandardViewId.Top, vp, useACS));
this.flags.lockedRotation = true;
break;
case RotationMode.Front:
// Get standard rotation relative to ACS when ACS context lock is enabled...
newRotation.fromMatrix3d(AccuDraw.getStandardRotation(StandardViewId.Front, vp, useACS));
this.flags.lockedRotation = true;
break;
case RotationMode.Side:
// Get standard rotation relative to ACS when ACS context lock is enabled...
newRotation.fromMatrix3d(AccuDraw.getStandardRotation(StandardViewId.Right, vp, useACS));
this.flags.lockedRotation = true;
break;
case RotationMode.ACS:
rMatrix = vp ? vp.getAuxCoordRotation() : Matrix3d.createIdentity();
newRotation.fromMatrix3d(rMatrix);
this.accountForAuxRotationPlane(newRotation, this.flags.auxRotationPlane);
this.flags.lockedRotation = true;
break;
case RotationMode.View:
rMatrix = vp ? vp.rotation : Matrix3d.createIdentity();
newRotation.fromMatrix3d(rMatrix);
this.flags.lockedRotation = false;
break;
case RotationMode.Context:
switch (this.flags.contextRotMode) {
case ContextMode.XAxis:
this.getRotationFromVector(newRotation, 0);
clearLocks = (LockedStates.Y_BM !== this.locked || !oldRotation.x.isExactEqual(newRotation.x)); // Try to keep locked axis when tool being unsuspended...
break;
case ContextMode.XAxis2:
if (vp)
this.getBestViewedRotationFromXVector(newRotation, vp); // Use base rotation axis that results in compass being most closely aligned to view direction....
else
this.getRotationFromVector(newRotation, 0);
clearLocks = (LockedStates.Y_BM !== this.locked || !oldRotation.x.isExactEqual(newRotation.x)); // Try to keep locked axis when tool being unsuspended...
break;
case ContextMode.YAxis:
this.getRotationFromVector(newRotation, 1);
clearLocks = (LockedStates.X_BM !== this.locked || !oldRotation.y.isExactEqual(newRotation.y)); // Try to keep locked axis when tool being unsuspended...
break;
case ContextMode.ZAxis:
this.getRotationFromVector(newRotation, 2);
break;
case ContextMode.Locked:
break;
}
break;
}
const isChanged = !oldRotation.equals(newRotation);
// unlock stuff if rotation has changed
if (isChanged && clearLocks && (CompassMode.Rectangular === this.compassMode || !this._fieldLocked[ItemField.DIST_Item] || animate)) {
this.locked = this.indexed = LockedStates.NONE_LOCKED;
this.unlockAllFields();
}
this.axes.setFrom(newRotation);
this.lastAxes.setFrom(newRotation);
this.flags.redrawCompass = true;
// If animate frame preference is set...
if (!animate || !vp)
return;
// AccuDrawAnimatorPtr animator = AccuDrawAnimator:: Create();
// viewport -> SetAnimator(* animator);
// animator -> ChangeOfRotation(Matrix3d:: FromColumnVectors(oldRotation[0], oldRotation[1], oldRotation[2]));
}
/** @internal */
public enableForSession(): void {
if (CurrentState.NotEnabled === this.currentState)
this.currentState = CurrentState.Inactive;
}
/** @internal */
public disableForSession(): void {
this.currentState = CurrentState.NotEnabled;
this.flags.redrawCompass = true; // Make sure decorators are called so we don't draw (i.e. erase AccuDraw compass)
}
/** @internal */
public setLastPoint(pt: Point3d): void {
const viewport = this.currentView;
if (!viewport)
return;
const ev = new BeButtonEvent({ point: pt, rawPoint: pt, viewPoint: viewport.worldToView(pt), viewport });
IModelApp.toolAdmin.setAdjustedDataPoint(ev);
}
/** Emulate a mouse click at the specified location in the supplied view by sending button down/up events. */
public async sendDataPoint(pt: Point3d, viewport: ScreenViewport): Promise<void> {
const ev = new BeButtonEvent({ point: pt, rawPoint: pt, viewPoint: viewport.worldToView(pt), viewport, inputSource: InputSource.Mouse, isDown: true });
// Send both down and up events...
await IModelApp.toolAdmin.sendButtonEvent(ev);
ev.isDown = false;
return IModelApp.toolAdmin.sendButtonEvent(ev);
}
/** @internal */
public clearTentative(): boolean {
if (!IModelApp.tentativePoint.isActive)
return false;
const wasSnapped = IModelApp.tentativePoint.isSnapped;
IModelApp.tentativePoint.clear(true);
return wasSnapped;
}
/** @internal */
public async doAutoPoint(index: ItemField, mode: CompassMode): Promise<void> {
const vp = this.currentView;
if (!vp)
return;
if (CompassMode.Polar === mode) {
if (!this.autoPointPlacement)
return;
if (this._fieldLocked[ItemField.DIST_Item] && (this._fieldLocked[ItemField.ANGLE_Item] || this.indexed & LockedStates.ANGLE_BM) && KeyinStatus.Dynamic === this._keyinStatus[index]) {
this.fixPointPolar(vp);
return this.sendDataPoint(this.point, vp);
}
return;
}
if (this._fieldLocked[ItemField.X_Item] && this._fieldLocked[ItemField.Y_Item]) {
if (!this.isActive) {
if (!vp.view.is3d() || this._fieldLocked[ItemField.Z_Item]) {
const globalOrigin = new Point3d();
if (vp.view.isSpatialView())
globalOrigin.setFrom(vp.view.iModel.globalOrigin);
return this.sendDataPoint(globalOrigin.plus(this.delta), vp);
}
return;
}
if (!this.autoPointPlacement || KeyinStatus.Dynamic !== this._keyinStatus[index])
return;
this.origin.plus3Scaled(this.axes.x, this.delta.x, this.axes.y, this.delta.y, this.axes.z, this.delta.z, this.point);
return this.sendDataPoint(this.point, vp);
}
if (!this.autoPointPlacement || KeyinStatus.Dynamic !== this._keyinStatus[index])
return;
if ((ItemField.X_Item === index && this._fieldLocked[ItemField.X_Item] && (this.indexed & LockedStates.Y_BM)) || (ItemField.Y_Item === index && this._fieldLocked[ItemField.Y_Item] && (this.indexed & LockedStates.X_BM))) {
this.origin.plus3Scaled(this.axes.x, this.delta.x, this.axes.y, this.delta.y, this.axes.z, this.delta.z, this.point);
return this.sendDataPoint(this.point, vp);
}
}
/** Get the current value for the supplied input field */
public getValueByIndex(index: ItemField): number {
switch (index) {
case ItemField.X_Item: return this.delta.x;
case ItemField.Y_Item: return this.delta.y;
case ItemField.Z_Item: return this.delta.z;
case ItemField.DIST_Item: return this._distance;
case ItemField.ANGLE_Item: return this._angle;
default:
return 0.0;
}
}
/** Set the current value for the supplied input field */
public setValueByIndex(index: ItemField, value: number): void {
switch (index) {
case ItemField.X_Item:
this.delta.x = value;
break;
case ItemField.Y_Item:
this.delta.y = value;
break;
case ItemField.Z_Item:
this.delta.z = value;
break;
case ItemField.DIST_Item:
this._distance = value;
break;
case ItemField.ANGLE_Item:
this._angle = value;
break;
}
}
private updateVector(angle: number): void {
this.vector.set(Math.cos(angle), Math.sin(angle), 0.0);
const rMatrix = this.getRotation();
rMatrix.multiplyTransposeVector(this.vector);
}
private stringToDistance(str: string): QuantityParseResult {
const parserSpec = IModelApp.quantityFormatter.findParserSpecByQuantityType(QuantityType.Length);
if (parserSpec)
return parserSpec.parseToQuantityValue(str);
return { ok: false, error: ParseError.InvalidParserSpec };
}
private stringToAngle(inString: string): QuantityParseResult {
// Need to update once there is an official "Bearing" QuantityType. Once available then
// use QuantityType.Angle for isBearing=false and "Bearing" for isBearing=true.
const parserSpec = IModelApp.quantityFormatter.findParserSpecByQuantityType(QuantityType.Angle);