/
ElementGeometry.ts
2273 lines (1889 loc) · 91.1 KB
/
ElementGeometry.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 Geometry
*/
import { flatbuffers } from "flatbuffers";
import { Id64, Id64String } from "@itwin/core-bentley";
import { Angle, AngleSweep, Arc3d, BentleyGeometryFlatBuffer, CurveCollection, FrameBuilder, GeometryQuery, LineString3d, Loop, Matrix3d, Plane3dByOriginAndUnitNormal, Point2d, Point3d, Point3dArray, PointString3d, Polyface, PolyfaceQuery, Range2d, Range3d, SolidPrimitive, Transform, Vector3d, YawPitchRollAngles } from "@itwin/core-geometry";
import { EGFBAccessors } from "./ElementGeometryFB";
import { Base64EncodedString } from "../Base64EncodedString";
import { TextString, TextStringGlyphData, TextStringProps } from "./TextString";
import { ColorDef } from "../ColorDef";
import { BackgroundFill, FillDisplay, GeometryClass, GeometryParams } from "../GeometryParams";
import { Gradient } from "../Gradient";
import { ThematicGradientSettings, ThematicGradientSettingsProps } from "../ThematicDisplay";
import { AreaPattern } from "./AreaPattern";
import { BRepEntity } from "./GeometryStream";
import { ImageGraphic, ImageGraphicCorners, ImageGraphicProps } from "./ImageGraphic";
import { LineStyle } from "./LineStyle";
import { ElementAlignedBox3d, Placement2d, Placement3d } from "./Placement";
import { isPlacement2dProps, PlacementProps } from "../ElementProps";
/** Specifies the type of an entry in a geometry stream.
* @see [[ElementGeometryDataEntry.opcode]].
* @public
* @extensions
*/
export enum ElementGeometryOpcode {
/** Local range of the next geometric primitive in the geometry stream. */
SubGraphicRange = 2,
/** A reference to a [GeometryPart]($backend). */
PartReference = 3,
/** Sets symbology for subsequent geometry to override [SubCategory]($backend) appearance */
BasicSymbology = 4,
/** A line, line string, shape, or point string (automatic simplification of a [CurvePrimitive]($core-geometry) or [CurveCollection]($core-geometry)) */
PointPrimitive = 5,
/** A 2d line, line string, shape, or point string (automatic simplification of a [CurvePrimitive]($core-geometry) or [CurveCollection]($core-geometry)) */
PointPrimitive2d = 6,
/** Arc or ellipse (automatic simplification of a [CurvePrimitive]($core-geometry) or [CurveCollection]($core-geometry)) */
ArcPrimitive = 7,
/** [CurveCollection]($core-geometry) */
// eslint-disable-next-line @typescript-eslint/no-shadow
CurveCollection = 8,
/** [Polyface]($core-geometry) */
// eslint-disable-next-line @typescript-eslint/no-shadow
Polyface = 9,
/** [CurvePrimitive]($core-geometry) */
CurvePrimitive = 10,
/** [SolidPrimitive]($core-geometry) */
// eslint-disable-next-line @typescript-eslint/no-shadow
SolidPrimitive = 11,
/** [BSplineSurface3d]($core-geometry) */
BsplineSurface = 12,
/** Opaque and [[Gradient]] fills. */
Fill = 19,
/** Hatch, cross-hatch, or [[AreaPattern]]. */
Pattern = 20,
/** [[RenderMaterial]] */
Material = 21,
/** [[TextString]] */
// eslint-disable-next-line @typescript-eslint/no-shadow
TextString = 22,
/** Specifies line style overrides as a [[LineStyle.Modifier]] */
LineStyleModifiers = 23,
/** Boundary represention solid, sheet, or wire body as a [[BRepEntity.DataProps]] */
BRep = 25,
/** Small single-tile raster image as an [[ImageGraphic]] */
Image = 28,
}
/** Describes an entry in a geometry stream as an op-code plus the binary flatbuffer representation of the associated data.
* @see [[FlatBufferGeometryStream]].
* @public
* @extensions
*/
export interface ElementGeometryDataEntry {
/** The type of this entry. */
opcode: ElementGeometryOpcode;
/** Zero-based flatbuffer-encoded data. */
data: Uint8Array;
}
/** Information provided to [[ElementGeometryFunction]].
* @beta
*/
export interface ElementGeometryInfo {
/** ID for the [Category]($core-backend), undefined for geometry parts */
categoryId?: Id64String;
/** A row-major storage 4x3 transform to world coordinate, undefined for geometry parts */
sourceToWorld?: Float64Array;
/** The element aligned bounding box for the geometry stream stored as 6 values for low/high */
bbox?: Float64Array;
/** If true, geometry displays oriented to face the camera */
viewIndependent?: boolean;
/** If true, geometry stream contained breps that were omitted or replaced as requested */
brepsPresent?: boolean;
/** The geometry stream data */
entryArray: ElementGeometryDataEntry[];
}
/** A callback function that receives geometry stream data.
* @see [IModelDb.elementGeometryRequest]($core-backend)
* @beta
*/
export type ElementGeometryFunction = (info: ElementGeometryInfo) => void;
/** Parameters for [IModelDb.elementGeometryRequest]($core-backend)
* @beta
*/
export interface ElementGeometryRequest {
/** The source element for the geometry stream */
elementId: Id64String;
/** A function to call for the geometry stream data */
onGeometry: ElementGeometryFunction;
/** Whether to omit BRep data */
skipBReps?: boolean;
/** When not omitting BReps, whether to return a mesh or curve representation instead of the brep data */
replaceBReps?: boolean;
/** Option for replaceBReps, max distance from a face to the original geometry, see [StrokeOptions]($core-geometry) */
chordTol?: number;
/** Option for replaceBReps, max angle difference in radians for approximated face, see [StrokeOptions]($core-geometry) */
angleTol?: number;
/** Option for replaceBReps, max length of any edge in generated faces, see [StrokeOptions]($core-geometry) */
maxEdgeLength?: number;
/** Option for replaceBReps, ignore faces with bounding boxes smaller than this size when facetting */
minBRepFeatureSize?: number;
}
/** Parameters for building the geometry stream of a [[GeometricElement]] using ElementGeometry.Builder
* Note: The geometry stream is always in local coordinates, that is, relative to the element's [[Placement]].
* @beta
*/
export interface ElementGeometryBuilderParams {
/** The geometry stream data. Calling update element with a zero length array will clear the geometry stream and invalidate the placement. */
entryArray: ElementGeometryDataEntry[];
/** If true, create geometry that displays oriented to face the camera */
viewIndependent?: boolean;
}
/** Parameters for building the geometry stream of a [[GeometryPart]] using ElementGeometry.Builder.
* @beta
*/
export interface ElementGeometryBuilderParamsForPart {
/** The geometry stream data */
entryArray: ElementGeometryDataEntry[];
/** If true, create geometry part with 2d geometry */
is2dPart?: boolean;
}
/** Values for [[BRepGeometryCreate.operation]]
* @alpha
*/
export enum BRepGeometryOperation {
/** Unite target (first entry) with one or more tool entities. */
Unite = 0,
/** Subtract one or more tool entities from target entity (first entry) */
Subtract = 1,
/** Intersect target (first entry) with one or more tool entities */
Intersect = 2,
/** Sew the given set of surfaces together by joining those that share edges in common */
Sew = 3,
/** Create a cut in the target (first entry) using a planar region (second entry) and optional depth */
Cut = 4,
/** Create a pad or pocket in the target (first entry) using a planar region (second entry) */
Emboss = 5,
/** Create a solid from a surface by offsetting using the specified forward and backward distances */
Thicken = 6,
/** Create a shelled solid by offsetting all faces by the supplied distance */
Hollow = 7,
/** Create a solid or surface by sweeping a planar profile (first entry) along a path (second entry) */
Sweep = 8,
/** Create a solid or surface by lofting through a set of paths or regions */
Loft = 9,
/** Create a solid or sheet with all non-smooth/non-laminar edges rounded */
Round = 10,
/** Offset all faces of a solid or sheet target by the supplied distance. */
Offset = 11,
}
/** Parameters for [[BRepGeometryOperation.Cut]]
* @alpha
*/
export interface BRepCutProps {
/** Optional cut depth; through solid if not specified */
distance?: number;
/** Optional cut direction; in direction of profile normal if not specified */
bothDirections?: boolean;
}
/** Parameters for [[BRepGeometryOperation.Thicken]]
* @alpha
*/
export interface BRepThickenProps {
/** Offset to apply in surface normal direction; at least one of frontDistance or backDistance must be specified */
frontDistance?: number;
/** Offset to apply in reverse surface normal direction */
backDistance?: number;
}
/** Parameters for [[BRepGeometryOperation.Hollow]]
* @alpha
*/
export interface BRepHollowProps {
/** Offset to apply to all faces; positive value shells outwards, negative value shells inwards */
distance: number;
}
/** Parameters for [[BRepGeometryOperation.Round]]
* @alpha
*/
export interface BRepRoundProps {
/** Radius to apply to all non-laminar/non-smooth edges */
radius: number;
}
/** Parameters for [[BRepGeometryOperation.Offset]]
* @alpha
*/
export interface BRepOffsetProps {
/** Offset to apply to all faces; positive value offsets outwards, negative value offsets inwards */
distance: number;
}
/** Parameters for [IModelDb.createBRepGeometry]($core-backend)
* @alpha
*/
export interface BRepGeometryCreate {
/** The operation to perform on the input geometry */
operation: BRepGeometryOperation;
/** The input target and tool geometry (curves, surfaces, and solids) to perform the given operation on */
entryArray: ElementGeometryDataEntry[];
/** A function to call for the result geometry */
onResult: BRepGeometryFunction;
/** Whether disjoint results should be returned as multiple entries or a single disjoint body */
separateDisjoint?: boolean;
/** Options and parameters for this operation */
parameters?: BRepCutProps | BRepThickenProps | BRepHollowProps | BRepRoundProps | BRepOffsetProps;
}
/** Information provided to [[BRepGeometryFunction]].
* @alpha
*/
export interface BRepGeometryInfo {
/** The result geometry if the operation was successful */
entryArray: ElementGeometryDataEntry[];
}
/** A callback function that receives brep operation result geometry.
* @see [IModelDb.createBRepGeometry]($core-backend)
* @alpha
*/
export type BRepGeometryFunction = (info: BRepGeometryInfo) => void;
/** Provides utility functions for working with [[ElementGeometryDataEntry]].
* @beta
*/
export namespace ElementGeometry {
/** [[ElementGeometry.Builder]] is a helper class for populating a [[ElementGeometryDataEntry]] array needed to create a [[GeometricElement]] or [[GeometryPart]]. */
export class Builder {
private _localToWorld?: Transform;
private _worldToLocal?: Transform;
/** GeometryStream entries */
public readonly entries: ElementGeometryDataEntry[] = [];
/** Current placement transform, converts local coordinate (placement relative) input to world */
public get localToWorld() { return this._localToWorld; }
/** Current inverse placement transform, converts world coordinate input to local (placement relative) */
public get worldToLocal() { return this._worldToLocal; }
/** Supply optional local to world transform. Used to transform world coordinate input relative to element placement.
* For a [[GeometricElement]]'s placement to be meaningful, world coordinate geometry should never be appended to an element with an identity placement.
* Can be called with undefined or identity transform to start appending geometry supplied in local coordinates again.
*/
public setLocalToWorld(localToWorld?: Transform) {
this._localToWorld = (undefined === localToWorld || localToWorld.isIdentity ? undefined : localToWorld.clone());
this._worldToLocal = (undefined === this._localToWorld ? undefined : this._localToWorld.inverse());
}
/** Supply local to world transform from a Point3d and optional YawPitchRollAngles.
* @see [[Placement3d]]
*/
public setLocalToWorld3d(origin: Point3d, angles: YawPitchRollAngles = YawPitchRollAngles.createDegrees(0.0, 0.0, 0.0)) {
this.setLocalToWorld(Transform.createOriginAndMatrix(origin, angles.toMatrix3d()));
}
/** Supply local to world transform from a Point2d and optional Angle.
* @see [[Placement2d]]
*/
public setLocalToWorld2d(origin: Point2d, angle: Angle = Angle.createDegrees(0.0)) {
this.setLocalToWorld(Transform.createOriginAndMatrix(Point3d.createFrom(origin), Matrix3d.createRotationAroundVector(Vector3d.unitZ(), angle)));
}
/** Supply local to world transform from a PlacementProps2d or PlacementProps3d.
* @see [[PlacementProps]]
*/
public setLocalToWorldFromPlacement(props: PlacementProps) {
const placement = isPlacement2dProps(props) ? Placement2d.fromJSON(props) : Placement3d.fromJSON(props);
this.setLocalToWorld(placement.transform);
}
/** Compute angles suitable for passing to [[setLocalToWorld3d]] from an array of 3d points. */
public static placementAnglesFromPoints(pts: Point3d[], defaultUp?: Vector3d, result?: YawPitchRollAngles): YawPitchRollAngles {
const angles = result ? result : new YawPitchRollAngles();
const zVec = defaultUp ? defaultUp.clone() : Vector3d.unitZ();
const matrix = Matrix3d.createRigidHeadsUp(zVec);
YawPitchRollAngles.createFromMatrix3d(matrix, angles);
if (pts.length < 2 || pts[0].isAlmostEqual(pts[1]))
return angles;
// Check if points have a well defined normal to use instead of defaultUp...
const frameTransform = FrameBuilder.createFrameToDistantPoints(pts);
if (undefined !== frameTransform) {
const plane = Plane3dByOriginAndUnitNormal.create(pts[0], frameTransform.matrix.getColumn(2));
if (undefined !== plane && Point3dArray.isCloseToPlane(pts, plane))
zVec.setFrom(plane.getNormalRef());
}
const xVec = Vector3d.createStartEnd(pts[0], pts[1]);
if (xVec.isParallelTo(zVec, true))
return angles;
const yVec = xVec.unitCrossProduct(zVec);
if (undefined === yVec)
return angles;
Matrix3d.createColumns(xVec, yVec, zVec, matrix);
if (undefined === Matrix3d.createRigidFromMatrix3d(matrix, undefined, matrix))
return angles;
YawPitchRollAngles.createFromMatrix3d(matrix, angles);
return angles;
}
/** Compute angle suitable for passing to [[setLocalToWorld2d]] from an array of xy plane points. */
public static placementAngleFromPoints(pts: Point3d[], result?: Angle): Angle {
const angles = ElementGeometry.Builder.placementAnglesFromPoints(pts);
if (undefined === result)
return angles.yaw;
result.setFrom(angles.yaw);
return result;
}
/** Store local ranges for all subsequent geometry appended. Can improve performance of range testing for elements with a GeometryStream
* containing more than one [[GeometryQuery]] differentiable by range. Not useful for a single [[GeometryQuery]] as its range and that of the [[GeometricElement]] are the same.
* Ignored when defining a [[GeometryPart]] and not needed when only appending [[GeometryPart]] instances to a [[GeometricElement]] as these store their own range.
*/
public appendGeometryRanges(): boolean {
const entry = fromSubGraphicRange(Range3d.create()); // Computed on backend, just need opcode...
if (undefined === entry)
return false;
this.entries.push(entry);
return true;
}
/** Change [[GeometryParams]] for subsequent geometry.
* It is not valid to change the sub-category when defining a [[GeometryPart]]. A [[GeometryPart]] inherits the symbology of their instance for anything not explicitly overridden.
*/
public appendGeometryParamsChange(geomParams: GeometryParams): boolean {
return appendGeometryParams(geomParams, this.entries, this._worldToLocal);
}
/** Append a [[GeometryQuery]] supplied in either local or world coordinates to the [[ElementGeometryDataEntry]] array */
public appendGeometryQuery(geometry: GeometryQuery): boolean {
const entry = ElementGeometry.fromGeometryQuery(geometry, this._worldToLocal);
if (undefined === entry)
return false;
this.entries.push(entry);
return true;
}
/** Append a [[TextString]] supplied in either local or world coordinates to the [[ElementGeometryDataEntry]] array */
public appendTextString(text: TextString): boolean {
const entry = ElementGeometry.fromTextString(text.toJSON(), this._worldToLocal);
if (undefined === entry)
return false;
this.entries.push(entry);
return true;
}
/** Append a [[ImageGraphic]] supplied in either local or world coordinates to the [[ElementGeometryDataEntry]] array */
public appendImageGraphic(image: ImageGraphic): boolean {
const entry = ElementGeometry.fromImageGraphic(image.toJSON(), this._worldToLocal);
if (undefined === entry)
return false;
this.entries.push(entry);
return true;
}
/** Append a [[BRepEntity.DataProps]] supplied in either local or world coordinates to the [[ElementGeometryDataEntry]] array.
* Provided for compatibility with GeometryStreamBuilder only.
* Backend code should use IModelDb.createBRepGeometry to create a brep [[ElementGeometryDataEntry]] directly.
*/
public appendBRepData(brep: BRepEntity.DataProps): boolean {
const entry = ElementGeometry.fromBRep(brep, this._worldToLocal);
if (undefined === entry)
return false;
this.entries.push(entry);
return true;
}
/** Append a [[GeometryPart]] instance with relative transform to the [[ElementGeometryDataEntry]] array for creating a [[GeometricElement]].
* Not valid when defining a [[GeometryPart]] as nesting of parts is not supported.
*/
public appendGeometryPart(partId: Id64String, partTransform?: Transform): boolean {
const entry = ElementGeometry.fromGeometryPart(partId, partTransform, this._worldToLocal);
if (undefined === entry)
return false;
this.entries.push(entry);
return true;
}
/** Append a [[GeometryPart]] instance with relative position, orientation, and scale to the [[ElementGeometryDataEntry]] array for creating a [[GeometricElement3d]].
* Not valid when defining a [[GeometryPart]] as nesting of parts is not supported.
*/
public appendGeometryPart3d(partId: Id64String, instanceOrigin?: Point3d, instanceRotation?: YawPitchRollAngles, instanceScale?: number): boolean {
const partTransform = Transform.createOriginAndMatrix(instanceOrigin, instanceRotation ? instanceRotation.toMatrix3d() : Matrix3d.createIdentity());
if (undefined !== instanceScale)
partTransform.matrix.scaleColumnsInPlace(instanceScale, instanceScale, instanceScale);
return this.appendGeometryPart(partId, partTransform);
}
/** Append a [[GeometryPart]] instance with relative position, orientation, and scale to the [[ElementGeometryDataEntry]] array for creating a [[GeometricElement2d]].
* Not valid when defining a [[GeometryPart]] as nesting of parts is not supported.
*/
public appendGeometryPart2d(partId: Id64String, instanceOrigin?: Point2d, instanceRotation?: Angle, instanceScale?: number): boolean {
return this.appendGeometryPart3d(partId, instanceOrigin ? Point3d.createFrom(instanceOrigin) : undefined, instanceRotation ? new YawPitchRollAngles(instanceRotation) : undefined, instanceScale);
}
}
/** Current state information for [[ElementGeometry.Iterator]] */
export interface IteratorData {
/** A [[GeometryParams]] representing the appearance of the current geometric entry */
readonly geomParams: GeometryParams;
/** Placement transform, used for converting placement relative, local coordinate entries to world */
readonly localToWorld?: Transform;
/** Optional stored local range for the current geometric entry */
readonly localRange?: Range3d;
/** The current displayable opcode */
readonly value: ElementGeometryDataEntry;
}
export class IteratorEntry implements IteratorData {
public readonly geomParams: GeometryParams;
public readonly localToWorld?: Transform;
public localRange?: Range3d;
private _value?: ElementGeometryDataEntry;
private readonly _applyLocalToWorld: boolean;
public constructor(geomParams: GeometryParams, localToWorld: Transform, applyLocalToWorld?: boolean) {
this.geomParams = geomParams;
this.localToWorld = localToWorld;
this._applyLocalToWorld = applyLocalToWorld ? !localToWorld.isIdentity : false;
}
public get value() { return this._value!; }
public set value(value: ElementGeometryDataEntry) { this._value = value; }
public get outputTransform(): Transform | undefined {
return this._applyLocalToWorld ? this.localToWorld : undefined;
}
/** Return the [[GeometryQuery]] representation for the current entry */
public toGeometryQuery(): GeometryQuery | undefined {
return toGeometryQuery(this.value, this.outputTransform);
}
/** Return the [[BRepEntity.DataProps]] representation for the current entry for checking brep type and face attachments. */
public toBRepData(wantBRepData: boolean = false): BRepEntity.DataProps | undefined {
return toBRep(this.value, wantBRepData, this.outputTransform);
}
/** Return the [[TextString]] representation for the current entry */
public toTextString(): TextString | undefined {
const props = toTextString(this.value, this.outputTransform);
return (undefined !== props ? new TextString(props) : undefined);
}
/** Return the [[ImageGraphic]] representation for the current entry */
public toImageGraphic(): ImageGraphic | undefined {
const props = toImageGraphic(this.value, this.outputTransform);
return (undefined !== props ? ImageGraphic.fromJSON(props) : undefined);
}
/** Return the GeometryPart information for the current entry */
public toGeometryPart(partToLocal?: Transform, partToWorld?: Transform): Id64String | undefined {
if (undefined === partToLocal && undefined !== partToWorld)
partToLocal = Transform.createIdentity();
const partId = toGeometryPart(this.value, partToLocal);
if (undefined === partId || undefined === partToLocal || undefined === partToWorld)
return partId;
if (undefined !== this.localToWorld)
this.localToWorld.multiplyTransformTransform(partToLocal, partToWorld);
return partId;
}
}
/** [[ElementGeometry.Iterator]] is a helper class for iterating a [[ElementGeometryDataEntry]] array.
* Each [[ElementGeometryDataEntry]] returned by the iterator represents exactly one displayable entry.
*/
export class Iterator implements IterableIterator<IteratorEntry> {
/** GeometryStream entries */
public readonly entryArray: ElementGeometryDataEntry[];
/** The geometric element's placement or geometry part's local range (placement.bbox) */
public readonly placement: Placement3d;
/** If true, geometry displays oriented to face the camera */
public readonly viewIndependent?: boolean;
/** If true, geometry stream contained breps that were omitted or replaced as requested */
public readonly brepsPresent?: boolean;
/** Current entry position */
private _index = 0;
/** Allocated on first call to next() and reused thereafter */
private _entry?: IteratorEntry;
/** Used to initialize this._entry */
private readonly _appearance: GeometryParams;
private readonly _localToWorld: Transform;
/** Whether deserialized entry data is returned in world or local coordinates */
private _applyLocalToWorld = false;
/** Construct a new Iterator given a [[ElementGeometryInfo]] from either a [[GeometricElement3d]], [[GeometricElement2d]], or [[GeometryPart]].
* Supply the optional [[GeometryParams]] and localToWorld transform to iterate a [[GeometryPart]] in the context of a [[GeometricElement]] reference.
*/
public constructor(info: ElementGeometryInfo, categoryOrGeometryParams?: Id64String | GeometryParams, localToWorld?: Transform) {
this.entryArray = info.entryArray;
this.viewIndependent = info.viewIndependent;
this.brepsPresent = info.brepsPresent;
if (undefined !== info.categoryId)
categoryOrGeometryParams = info.categoryId;
if (undefined !== categoryOrGeometryParams)
this._appearance = typeof categoryOrGeometryParams === "string" ? new GeometryParams(categoryOrGeometryParams) : categoryOrGeometryParams;
else
this._appearance = new GeometryParams(Id64.invalid);
if (undefined !== info.sourceToWorld)
localToWorld = ElementGeometry.toTransform(info.sourceToWorld);
if (undefined !== localToWorld)
this._localToWorld = localToWorld;
else
this._localToWorld = Transform.createIdentity();
const orgAng = YawPitchRollAngles.tryFromTransform(this._localToWorld);
if (undefined === orgAng.angles)
orgAng.angles = YawPitchRollAngles.createDegrees(0, 0, 0);
let bbox = (undefined !== info.bbox ? ElementGeometry.toElementAlignedBox3d(info.bbox) : undefined);
if (undefined === bbox)
bbox = Range3d.createNull();
this.placement = new Placement3d(orgAng.origin, orgAng.angles, bbox);
}
/** Call to return deserialized entry data in world coordinates */
public requestWorldCoordinates(): void {
this._applyLocalToWorld = !this._localToWorld.isIdentity;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
private get entry() {
if (undefined === this._entry)
this._entry = new IteratorEntry(this._appearance, this._localToWorld, this._applyLocalToWorld);
return this._entry;
}
/** Advance to next displayable opcode (geometric entry or geometry part) while updating the current [[GeometryParams]] from appearance related opcodes. */
public next(): IteratorResult<IteratorEntry> {
while (this._index < this.entryArray.length) {
const value = this.entryArray[this._index++];
if (ElementGeometry.isAppearanceEntry(value)) {
const localToWorld = (this._applyLocalToWorld ? this._localToWorld : undefined);
ElementGeometry.updateGeometryParams(value, this.entry.geomParams, localToWorld);
} else if (ElementGeometryOpcode.SubGraphicRange === value.opcode) {
// NOTE: localRange remains valid until the next sub-range entry is encountered...
this.entry.localRange = ElementGeometry.toSubGraphicRange(value);
} else if (ElementGeometryOpcode.PartReference === value.opcode) {
this.entry.value = value;
return { value: this.entry, done: false };
} else if (ElementGeometry.isGeometricEntry(value)) {
this.entry.value = value;
return { value: this.entry, done: false };
}
}
return { value: this.entry, done: true };
}
public [Symbol.iterator](): IterableIterator<IteratorEntry> {
return this;
}
}
/** Return whether the supplied entry can be represented as a [[GeometryQuery]] */
export function isGeometryQueryEntry(entry: ElementGeometryDataEntry): boolean {
switch (entry.opcode) {
case ElementGeometryOpcode.PointPrimitive:
case ElementGeometryOpcode.PointPrimitive2d:
case ElementGeometryOpcode.ArcPrimitive:
case ElementGeometryOpcode.CurveCollection:
case ElementGeometryOpcode.Polyface:
case ElementGeometryOpcode.CurvePrimitive:
case ElementGeometryOpcode.SolidPrimitive:
case ElementGeometryOpcode.BsplineSurface:
return true;
default:
return false;
}
}
/** Return whether the supplied entry is displayable geometry [[GeometryQuery]], [[BRepEntity.DataProps]], [[TextString]], or [[ImageGraphic]] */
export function isGeometricEntry(entry: ElementGeometryDataEntry): boolean {
switch (entry.opcode) {
case ElementGeometryOpcode.BRep:
case ElementGeometryOpcode.TextString:
case ElementGeometryOpcode.Image:
return true;
default:
return isGeometryQueryEntry(entry);
}
}
/** Return whether the supplied entry is geometric or a part reference */
export function isDisplayableEntry(entry: ElementGeometryDataEntry): boolean {
switch (entry.opcode) {
case ElementGeometryOpcode.PartReference:
return true;
default:
return isGeometricEntry(entry);
}
}
/** Return whether the supplied entry represents appearance information */
export function isAppearanceEntry(entry: ElementGeometryDataEntry): boolean {
switch (entry.opcode) {
case ElementGeometryOpcode.BasicSymbology:
case ElementGeometryOpcode.Fill:
case ElementGeometryOpcode.Pattern:
case ElementGeometryOpcode.Material:
case ElementGeometryOpcode.LineStyleModifiers:
return true;
default:
return false;
}
}
/** Return whether the supplied entry represents a single open curve or path */
export function isCurve(entry: ElementGeometryDataEntry): boolean {
switch (entry.opcode) {
case ElementGeometryOpcode.PointPrimitive: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.PointPrimitive.getRootAsPointPrimitive(buffer);
return (EGFBAccessors.BoundaryType.Open === ppfb.boundary());
}
case ElementGeometryOpcode.PointPrimitive2d: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.PointPrimitive2d.getRootAsPointPrimitive2d(buffer);
return (EGFBAccessors.BoundaryType.Open === ppfb.boundary());
}
case ElementGeometryOpcode.ArcPrimitive: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.ArcPrimitive.getRootAsArcPrimitive(buffer);
return (EGFBAccessors.BoundaryType.Open === ppfb.boundary());
}
case ElementGeometryOpcode.CurvePrimitive: {
// should never be a point string or closed bcurve...
return true;
}
case ElementGeometryOpcode.CurveCollection: {
const geom = BentleyGeometryFlatBuffer.bytesToGeometry(entry.data, true);
if (undefined === geom || Array.isArray(geom))
return false;
return ("curveCollection" === geom.geometryCategory && !(geom as CurveCollection).isAnyRegionType);
}
default:
return false;
}
}
/** Return whether the supplied entry represents a loop, planar region, open polyface, or sheet body */
export function isSurface(entry: ElementGeometryDataEntry): boolean {
switch (entry.opcode) {
case ElementGeometryOpcode.PointPrimitive: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.PointPrimitive.getRootAsPointPrimitive(buffer);
return (EGFBAccessors.BoundaryType.Closed === ppfb.boundary());
}
case ElementGeometryOpcode.PointPrimitive2d: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.PointPrimitive2d.getRootAsPointPrimitive2d(buffer);
return (EGFBAccessors.BoundaryType.Closed === ppfb.boundary());
}
case ElementGeometryOpcode.ArcPrimitive: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.ArcPrimitive.getRootAsArcPrimitive(buffer);
return (EGFBAccessors.BoundaryType.Closed === ppfb.boundary());
}
case ElementGeometryOpcode.CurvePrimitive: {
// should never be a closed bcurve...
return false;
}
case ElementGeometryOpcode.CurveCollection: {
const geom = BentleyGeometryFlatBuffer.bytesToGeometry(entry.data, true);
if (undefined === geom || Array.isArray(geom))
return false;
return ("curveCollection" === geom.geometryCategory && (geom as CurveCollection).isAnyRegionType);
}
case ElementGeometryOpcode.SolidPrimitive: {
const geom = BentleyGeometryFlatBuffer.bytesToGeometry(entry.data, true);
if (undefined === geom || Array.isArray(geom))
return false;
return ("solid" === geom.geometryCategory && !(geom as SolidPrimitive).isClosedVolume);
}
case ElementGeometryOpcode.Polyface: {
const geom = BentleyGeometryFlatBuffer.bytesToGeometry(entry.data, true);
if (undefined === geom || Array.isArray(geom))
return false;
if ("polyface" !== geom.geometryCategory)
return false;
const polyface = (geom as Polyface);
switch (polyface.expectedClosure) {
case 0:
return !PolyfaceQuery.isPolyfaceClosedByEdgePairing(polyface);
case 1:
return true;
case 2:
default:
return false;
}
}
case ElementGeometryOpcode.BsplineSurface: {
// never treated as a solid even if closed/periodic in u/v...
return true;
}
case ElementGeometryOpcode.BRep: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.BRepData.getRootAsBRepData(buffer);
return (EGFBAccessors.BRepType.Sheet === ppfb.brepType());
}
default:
return false;
}
}
/** Return whether the supplied entry represents a capped solid, closed polyface, or solid body */
export function isSolid(entry: ElementGeometryDataEntry): boolean {
switch (entry.opcode) {
case ElementGeometryOpcode.SolidPrimitive: {
const geom = BentleyGeometryFlatBuffer.bytesToGeometry(entry.data, true);
if (undefined === geom || Array.isArray(geom))
return false;
return ("solid" === geom.geometryCategory && (geom as SolidPrimitive).isClosedVolume);
}
case ElementGeometryOpcode.Polyface: {
const geom = BentleyGeometryFlatBuffer.bytesToGeometry(entry.data, true);
if (undefined === geom || Array.isArray(geom))
return false;
if ("polyface" !== geom.geometryCategory)
return false;
const polyface = (geom as Polyface);
switch (polyface.expectedClosure) {
case 0:
return PolyfaceQuery.isPolyfaceClosedByEdgePairing(polyface);
case 2:
return true;
case 1:
default:
return false;
}
}
case ElementGeometryOpcode.BRep: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.BRepData.getRootAsBRepData(buffer);
return (EGFBAccessors.BRepType.Solid === ppfb.brepType());
}
default:
return false;
}
}
/** Return the body type that would be used to represent the supplied entry */
export function getBRepEntityType(entry: ElementGeometryDataEntry): BRepEntity.Type | undefined {
switch (entry.opcode) {
case ElementGeometryOpcode.PointPrimitive: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.PointPrimitive.getRootAsPointPrimitive(buffer);
if (EGFBAccessors.BoundaryType.None === ppfb.boundary())
return undefined;
return (EGFBAccessors.BoundaryType.Closed === ppfb.boundary() ? BRepEntity.Type.Sheet : BRepEntity.Type.Wire);
}
case ElementGeometryOpcode.PointPrimitive2d: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.PointPrimitive2d.getRootAsPointPrimitive2d(buffer);
if (EGFBAccessors.BoundaryType.None === ppfb.boundary())
return undefined;
return (EGFBAccessors.BoundaryType.Closed === ppfb.boundary() ? BRepEntity.Type.Sheet : BRepEntity.Type.Wire);
}
case ElementGeometryOpcode.ArcPrimitive: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.ArcPrimitive.getRootAsArcPrimitive(buffer);
return (EGFBAccessors.BoundaryType.Closed === ppfb.boundary() ? BRepEntity.Type.Sheet : BRepEntity.Type.Wire);
}
case ElementGeometryOpcode.CurvePrimitive: {
// should never be a point string or closed bcurve...
return BRepEntity.Type.Wire;
}
case ElementGeometryOpcode.CurveCollection: {
const geom = BentleyGeometryFlatBuffer.bytesToGeometry(entry.data, true);
if (undefined === geom || Array.isArray(geom))
return undefined;
if ("curveCollection" !== geom.geometryCategory)
return undefined;
const curves = geom as CurveCollection;
return (curves.isAnyRegionType ? BRepEntity.Type.Sheet : BRepEntity.Type.Wire);
}
case ElementGeometryOpcode.SolidPrimitive: {
const geom = BentleyGeometryFlatBuffer.bytesToGeometry(entry.data, true);
if (undefined === geom || Array.isArray(geom))
return undefined;
if ("solid" !== geom.geometryCategory)
return undefined;
const solid = geom as SolidPrimitive;
return (solid.isClosedVolume ? BRepEntity.Type.Solid : BRepEntity.Type.Sheet);
}
case ElementGeometryOpcode.BsplineSurface: {
// always a surface...
return BRepEntity.Type.Sheet;
}
case ElementGeometryOpcode.Polyface: {
const geom = BentleyGeometryFlatBuffer.bytesToGeometry(entry.data, true);
if (undefined === geom || Array.isArray(geom))
return undefined;
if ("polyface" !== geom.geometryCategory)
return undefined;
const polyface = (geom as Polyface);
switch (polyface.expectedClosure) {
case 0:
return PolyfaceQuery.isPolyfaceClosedByEdgePairing(polyface) ? BRepEntity.Type.Solid : BRepEntity.Type.Sheet;
case 1:
return BRepEntity.Type.Sheet;
case 2:
return BRepEntity.Type.Solid;
default:
return undefined;
}
}
case ElementGeometryOpcode.BRep: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.BRepData.getRootAsBRepData(buffer);
switch (ppfb.brepType()) {
case EGFBAccessors.BRepType.Wire:
return BRepEntity.Type.Wire; // always be persisted as a curve type...
case EGFBAccessors.BRepType.Sheet:
return BRepEntity.Type.Sheet;
case EGFBAccessors.BRepType.Solid:
return BRepEntity.Type.Solid;
default:
return undefined;
}
}
default:
return undefined;
}
}
/** Return entry as a [[GeometryQuery]] */
export function toGeometryQuery(entry: ElementGeometryDataEntry, localToWorld?: Transform): GeometryQuery | undefined {
if (!isGeometryQueryEntry(entry))
return undefined;
switch (entry.opcode) {
case ElementGeometryOpcode.PointPrimitive: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.PointPrimitive.getRootAsPointPrimitive(buffer);
const pts: Point3d[] = [];
for (let i = 0; i < ppfb.coordsLength(); i++)
pts.push(Point3d.create(ppfb.coords(i)!.x(), ppfb.coords(i)!.y(), ppfb.coords(i)!.z()));
if (0 === pts.length)
return undefined;
if (undefined !== localToWorld)
localToWorld.multiplyPoint3dArrayInPlace(pts);
switch (ppfb.boundary()) {
case EGFBAccessors.BoundaryType.Open:
return LineString3d.createPoints(pts);
case EGFBAccessors.BoundaryType.Closed:
return Loop.createPolygon(pts);
default:
return PointString3d.createPoints(pts);
}
}
case ElementGeometryOpcode.PointPrimitive2d: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.PointPrimitive2d.getRootAsPointPrimitive2d(buffer);
const pts: Point3d[] = [];
for (let i = 0; i < ppfb.coordsLength(); i++)
pts.push(Point3d.create(ppfb.coords(i)!.x(), ppfb.coords(i)!.y()));
if (0 === pts.length)
return undefined;
if (undefined !== localToWorld)
localToWorld.multiplyPoint3dArrayInPlace(pts);
switch (ppfb.boundary()) {
case EGFBAccessors.BoundaryType.Open:
return LineString3d.createPoints(pts);
case EGFBAccessors.BoundaryType.Closed:
return Loop.createPolygon(pts);
default:
return PointString3d.createPoints(pts);
}
}
case ElementGeometryOpcode.ArcPrimitive: {
const buffer = new flatbuffers.ByteBuffer(entry.data);
const ppfb = EGFBAccessors.ArcPrimitive.getRootAsArcPrimitive(buffer);
const center = Point3d.create(ppfb.center()!.x(), ppfb.center()!.y(), ppfb.center()!.z());
const vector0 = Vector3d.create(ppfb.vector0()!.x(), ppfb.vector0()!.y(), ppfb.vector0()!.z());
const vector90 = Vector3d.create(ppfb.vector90()!.x(), ppfb.vector90()!.y(), ppfb.vector90()!.z());
const arc = Arc3d.create(center, vector0, vector90, AngleSweep.createStartSweepRadians(ppfb.start(), ppfb.sweep()));
if (undefined !== localToWorld && !arc.tryTransformInPlace(localToWorld))
return undefined;
return (EGFBAccessors.BoundaryType.Closed === ppfb.boundary() ? Loop.create(arc) : arc);
}
case ElementGeometryOpcode.CurvePrimitive:
case ElementGeometryOpcode.CurveCollection:
case ElementGeometryOpcode.SolidPrimitive:
case ElementGeometryOpcode.BsplineSurface:
case ElementGeometryOpcode.Polyface:
const geom = BentleyGeometryFlatBuffer.bytesToGeometry(entry.data, true);
if (undefined === geom || Array.isArray(geom))
return undefined; // Should always be a single entry not an array...
if (undefined !== localToWorld && !geom.tryTransformInPlace(localToWorld))
return undefined;
return geom;
default:
return undefined; // Not a GeometryQuery, need to be handled explicitly...
}
}
/** Create entry from a [[GeometryQuery]] */
export function fromGeometryQuery(geom: GeometryQuery, worldToLocal?: Transform): ElementGeometryDataEntry | undefined {
let opcode;
switch (geom.geometryCategory) {
case "bsurf":
opcode = ElementGeometryOpcode.BsplineSurface;
break;
case "curveCollection":
opcode = ElementGeometryOpcode.CurveCollection;
break;
case "curvePrimitive":