-
Notifications
You must be signed in to change notification settings - Fork 2
/
frame.fs
2159 lines (1916 loc) · 91.9 KB
/
frame.fs
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
FeatureScript ✨; /* Automatically generated version */
// This module is part of the FeatureScript Standard Library and is distributed under the MIT License.
// See the LICENSE tab for the license text.
// Copyright (c) 2013-Present PTC Inc.
import(path : "onshape/std/attributes.fs", version : "✨");
import(path : "onshape/std/booleanoperationtype.gen.fs", version : "✨");
import(path : "onshape/std/bridgingCurve.fs", version : "✨");
import(path : "onshape/std/containers.fs", version : "✨");
import(path : "onshape/std/coordSystem.fs", version : "✨");
import(path : "onshape/std/curveGeometry.fs", version : "✨");
import(path : "onshape/std/error.fs", version : "✨");
import(path : "onshape/std/evaluate.fs", version : "✨");
import(path : "onshape/std/feature.fs", version : "✨");
import(path : "onshape/std/frameAttributes.fs", version : "✨");
import(path : "onshape/std/instantiator.fs", version : "✨");
import(path : "onshape/std/manipulator.fs", version : "✨");
import(path : "onshape/std/path.fs", version : "✨");
import(path : "onshape/std/surfaceGeometry.fs", version : "✨");
import(path : "onshape/std/tabReferences.fs", version : "✨");
import(path : "onshape/std/tagProfile.fs", version : "✨");
import(path : "onshape/std/tool.fs", version : "✨");
import(path : "onshape/std/topologyUtils.fs", version : "✨");
import(path : "onshape/std/transform.fs", version : "✨");
import(path : "onshape/std/valueBounds.fs", version : "✨");
import(path : "onshape/std/vector.fs", version : "✨");
export import(path : "onshape/std/frameUtils.fs", version : "✨");
/** @internal */
export const FRAME_NINE_POINT_COUNT =
{
(unitless) : [0, 4, 100]
}
as IntegerBoundSpec;
/** @internal */
export const FRAME_NINE_POINT_CENTER_INDEX = 4;
// in `extendFrames` we pad our frame extrusion length to help avoid non-manifold cases in boolean operations
const EXTEND_FRAMES_PAD_LENGTH = .1 * millimeter;
/**
* Create frames from a profile and set of path selections.
*/
annotation {
"Feature Type Name" : "Frame",
"Manipulator Change Function" : "frameManipulators",
"Filter Selector" : "allparts",
"Editing Logic Function" : "frameEditLogicFunction"
}
export const frame = defineFeature(function(context is Context, id is Id, definition is map)
precondition
{
annotation {
"Library Definition" : "65dcc2a02c4ff1c239467ec9", // This is the id of the Onshape Frame Profile Library definition
"Name" : "Sketch profile",
"Filter" : PartStudioItemType.SKETCH,
"MaxNumberOfPicks" : 1,
"UIHint" : UIHint.REMEMBER_PREVIOUS_VALUE
}
definition.profileSketch is PartStudioData;
annotation {
"Name" : "Selections",
"Description" : "Faces, edges, and vertices that define sweep paths",
"Filter" : ((EntityType.FACE && ConstructionObject.NO) || EntityType.EDGE || (EntityType.VERTEX && AllowEdgePoint.NO) || (EntityType.BODY && BodyType.WIRE && SketchObject.NO))
}
definition.selections is Query;
annotation { "Name" : "Merge tangent segments", "Default" : true }
definition.mergeTangentSegments is boolean;
annotation { "Name" : "Angle" }
isAngle(definition.angle, ANGLE_360_ZERO_DEFAULT_BOUNDS);
annotation {
"Name" : "Mirror across Y axis",
"UIHint" : UIHint.OPPOSITE_DIRECTION
}
definition.mirrorProfile is boolean;
annotation { "Name" : "Angle reference", "Filter" : QueryFilterCompound.ALLOWS_DIRECTION || BodyType.MATE_CONNECTOR, "MaxNumberOfPicks" : 1 }
definition.angleReference is Query;
annotation { "Name" : "Default corner type", "UIHint" : UIHint.SHOW_LABEL }
definition.defaultCornerType is FrameCornerType;
if (definition.defaultCornerType == FrameCornerType.BUTT || definition.defaultCornerType == FrameCornerType.COPED_BUTT)
{
annotation {
"Name" : "Flip corner",
"UIHint" : UIHint.OPPOSITE_DIRECTION
}
definition.defaultButtFlip is boolean;
}
annotation {
"Name" : "Corner overrides",
"Item name" : "vertex",
"Driven query" : "vertex",
"Item label template" : "#vertex [#cornerType]"
}
definition.cornerOverrides is array;
for (var corner in definition.cornerOverrides)
{
annotation {
"Name" : "Vertex",
"Filter" : EntityType.VERTEX && ConstructionObject.NO,
"MaxNumberOfPicks" : 1,
"UIHint" : UIHint.ALWAYS_HIDDEN
}
corner.vertex is Query;
annotation {
"Name" : "Corner type",
"UIHint" : UIHint.SHOW_LABEL
}
corner.cornerType is FrameCornerType;
if (corner.cornerType == FrameCornerType.BUTT || corner.cornerType == FrameCornerType.COPED_BUTT)
{
annotation {
"Name" : "Flip corner",
"UIHint" : UIHint.OPPOSITE_DIRECTION
}
corner.cornerButtFlip is boolean;
}
}
annotation {
"Name" : "Limit frame ends",
"Default" : false
}
definition.trim is boolean;
if (definition.trim)
{
annotation {
"Group Name" : "Trimming",
"Collapsed By Default" : false,
"Driving Parameter" : "trim"
}
{
annotation {
"Name" : "Faces to trim to",
"Description" : "Planes and planar faces to use as trim tools",
"Filter" : (EntityType.FACE && GeometryType.PLANE)
}
definition.trimPlanes is Query;
annotation {
"Name" : "Parts to trim to",
"Description" : "Parts to use as trim tools",
"Filter" : EntityType.BODY && BodyType.SOLID
}
definition.trimBodies is Query;
}
}
annotation { "Name" : "Index", "UIHint" : UIHint.ALWAYS_HIDDEN }
isInteger(definition.index, FRAME_NINE_POINT_COUNT); // for points manipulator
}
{
doFrame(context, id, definition);
},
{
mirrorProfile : false,
defaultCornerType : FrameCornerType.MITER,
index : FRAME_NINE_POINT_CENTER_INDEX,
angle : 0 * degree,
cornerOverrides : [],
trim : false,
mergeTangentSegments : true,
angleReference : qNothing()
});
/** @internal */
export function frameEditLogicFunction(context is Context, id is Id, oldDefinition is map, definition is map, isCreating is boolean) returns map
{
if (oldDefinition.cornerOverrides != undefined)
{
definition = handleNewCornerOverride(context, oldDefinition, definition);
}
return definition;
}
/** @internal */
export function frameManipulators(context is Context, definition is map, newManipulators is map) returns map
{
try silent
{
var newAngle is ValueWithUnits = newManipulators["angleManipulator"].angle;
definition.angle = newAngle;
}
try silent
{
definition.index = newManipulators["points"].index;
}
for (var i = 0; i < size(definition.cornerOverrides); i += 1)
{
if (newManipulators["flip" ~ i] != undefined)
{
definition.cornerOverrides[i].cornerButtFlip = newManipulators["flip" ~ i].flipped;
}
}
return definition;
}
/** @internal */
export function setFrameAttributes(context is Context, frame is Query, profileData is map, frameData is map)
{
setFrameProfileAttribute(context, frame, profileData.profileAttribute);
setFrameTopologyAttribute(context, frameData.sweptFaces, frameTopologyAttributeForSwept(FrameTopologyType.SWEPT_FACE));
if (!isQueryEmpty(context, frameData.sweptEdges))
{
setFrameTopologyAttribute(context, frameData.sweptEdges, frameTopologyAttributeForSwept(FrameTopologyType.SWEPT_EDGE));
}
setFrameTopologyAttribute(context, frameData.startFace, frameTopologyAttributeForCapFace(true, false, false));
setFrameTopologyAttribute(context, frameData.endFace, frameTopologyAttributeForCapFace(false, false, false));
}
/** @internal */
export function setFrameTerminusAttributes(context is Context, startFace is Query, endFace is Query)
{
setFrameTopologyAttribute(context, startFace, frameTopologyAttributeForCapFace(true, true, false));
setFrameTopologyAttribute(context, endFace, frameTopologyAttributeForCapFace(false, true, false));
}
function handleNewCornerOverride(context is Context, oldDefinition is map, definition is map) returns map
{
// on joint override creation, set the starting value to the global default
const newOverrideSize = size(definition.cornerOverrides);
const oldOverrideSize = size(oldDefinition.cornerOverrides);
if (newOverrideSize == oldOverrideSize + 1)
{
var newOverride = last(definition.cornerOverrides);
newOverride.cornerType = definition.defaultCornerType;
if (isButtCorner(newOverride.cornerType))
{
newOverride.cornerButtFlip = definition.defaultButtFlip;
}
definition.cornerOverrides[newOverrideSize - 1] = newOverride;
}
return definition;
}
function doFrame(context is Context, id is Id, definition is map)
{
var bodiesToDelete = new box([]);
const profileData = getProfile(context, id, definition, bodiesToDelete);
const sweepData = (isAtVersionOrLater(context, FeatureScriptVersionNumber.V1742_STABLE_FRAME_SWEEP))
? sweepFrames(context, id, definition, profileData, bodiesToDelete)
: sweepFrames_PRE_V1742(context, id, definition, profileData, bodiesToDelete);
addManipulators(context, id, sweepData.manipulators);
trimFrame(context, id, definition, sweepData.trimEnds, sweepData.sweepBodies, bodiesToDelete);
createComposites(context, id, definition.mergeTangentSegments, sweepData.compositeGroups, profileData);
cleanUpBodies(context, id, bodiesToDelete);
const remainingTransform = getRemainderPatternTransform(context, { "references" : definition.selections });
transformResultIfNecessary(context, id, remainingTransform);
}
function createComposites(context is Context, id is Id, mergeSegments is boolean, compositeGroups is array, profileData is map)
{
if (!mergeSegments)
{
return;
}
var index = 0;
for (var group in compositeGroups)
{
if (size(group.segments) < 2)
{
continue;
}
const bodyQuery = qUnion(group.segments);
// BEL-209918 Disambiguate between frames created in the same operation to improve downstream stability-under-edit.
var compositeId;
if (isAtVersionOrLater(context, FeatureScriptVersionNumber.V2123_COMPOSITE_SEGMENT_DISAMBIGUATION))
{
compositeId = id + "compositePart" + unstableIdComponent(index);
setExternalDisambiguation(context, compositeId, bodyQuery);
}
else
{
compositeId = id + "compositePart" + index;
}
index += 1;
opCreateCompositePart(context, compositeId, {
"bodies" : bodyQuery,
"closed" : true
});
//update composite frame segment terminus attributes
const startFaceQuery = qFrameStartFace(group.startTerminus);
var startFaceAttributes = getFrameTopologyAttribute(context, startFaceQuery);
startFaceAttributes.isCompositeTerminus = true;
setFrameTopologyAttribute(context, startFaceQuery, startFaceAttributes);
//update end attributes
const endFaceQuery = qFrameEndFace(group.endTerminus);
var endFaceAttributes = getFrameTopologyAttribute(context, endFaceQuery);
endFaceAttributes.isCompositeTerminus = true;
setFrameTopologyAttribute(context, endFaceQuery, endFaceAttributes);
//set composite body attribute
const closedCompositeBodyQuery = qCreatedBy(compositeId, EntityType.BODY)->qCompositePartTypeFilter(CompositePartType.CLOSED);
setFrameProfileAttribute(context, closedCompositeBodyQuery, profileData.profileAttribute);
}
}
function sweepFrames(context is Context, topLevelId is Id, definition is map, profileData is map, bodiesToDelete is box) returns map
{
verify(!isQueryEmpty(context, definition.selections), ErrorStringEnum.FRAME_SELECT_PATH, { "faultyParameters" : ["selections"] });
const cornerOverrides = gatherCornerOverrides(context, definition.cornerOverrides);
const selectionData = createPathsFromSelections(context, topLevelId, definition.selections, bodiesToDelete);
const frameManipulators = createStableFrameManipulators(context, topLevelId, definition, selectionData.manipulatorEdge, profileData);
// The points manipulator _must_ succeed because there is no mapping for the points manipulator back to any user-editable field in the UI.
// Therefore the points manipulator *may* modify the index as required.
definition.index = frameManipulators.points.index;
// Immediately display the manipulators before the sweep operation is performed.
// This guarantees the point and angle manipulator show even in the event of failure.
// The user thus always has a way to undo the fail state.
addManipulators(context, topLevelId, frameManipulators);
const sweepData = doStablePaths(context, topLevelId, definition, profileData, cornerOverrides, selectionData.paths, selectionData.stableEdges, bodiesToDelete);
return {
"trimEnds" : sweepData.trimEnds,
"manipulators" : mergeMaps(sweepData.manipulators, frameManipulators),
"sweepBodies" : sweepData.sweepBodies,
"compositeGroups" : sweepData.compositeGroups
};
}
function createStableFrameManipulators(context is Context, topLevelId is Id, definition is map, manipulatorEdge is Query, profileData is map) returns map
{
// Desired behavior is to set the frames manipulator at the middle of the first user-selected swept segment.
// Due to the heuristic for creating planes the manipulators can lose correct orientation with the frame.
// Detect this case and use the mid-segment manipulator plane if possible.
// Otherwise use the start of the manipulator edge which is always correct.
const manipulatorStart = evaluatePathEdge(context, manipulatorEdge, false, 0);
const manipulatorMid = evaluatePathEdge(context, manipulatorEdge, false, 0.5);
const startXDir = getXDirFromHeuristic(manipulatorStart);
const midXDir = getXDirFromHeuristic(manipulatorMid);
return tolerantEquals(startXDir, midXDir)
? createFrameManipulators(context, topLevelId, definition, manipulatorMid, profileData)
: createFrameManipulators(context, topLevelId, definition, manipulatorStart, profileData);
}
function doStablePaths(context is Context, topLevelId is Id, definition is map, profileData is map, cornerOverrides is array,
paths is array, stableEdges is array, bodiesToDelete is box) returns map
{
const createPathId = getUnstableIncrementingId(topLevelId);
var allManipulators = {};
var allTrimEnds = [];
var allSweepBodies = [];
var allCompositeGroups = [];
for (var pathIndex = 0; pathIndex < size(paths); pathIndex += 1)
{
const path = paths[pathIndex];
const stableEdge = stableEdges[pathIndex];
const pathData = doStablePath(context, topLevelId, createPathId(), definition, profileData, cornerOverrides, path, stableEdge, bodiesToDelete);
// aggregate data
allTrimEnds = concatenateArrays([allTrimEnds, pathData.trimEnds]);
allSweepBodies = concatenateArrays([allSweepBodies, pathData.sweepBodies]);
allManipulators = mergeMaps(allManipulators, pathData.manipulators);
allCompositeGroups = concatenateArrays([allCompositeGroups, pathData.compositeGroups]);
}
return {
"trimEnds" : allTrimEnds,
"manipulators" : allManipulators,
"sweepBodies" : allSweepBodies,
"compositeGroups" : allCompositeGroups
};
}
function doStablePath(context is Context, topLevelId is Id, pathId is Id, definition is map, profileData is map,
cornerOverrides is array, path is Path, stableEdge is map, bodiesToDelete is box) returns map
{
// A "stable path" is geometrically stable while the user edits the path.
// If the user selects additional segments, the path can grow but it won't twist or change orientation.
// This is needed to prevent BEL-179102 (downstream trim fails after editing upstream frames).
// To achieve this, each frame is "stabilized" around the first selected edge.
// case 1: path is closed
// rotate path till stable edge becomes 1st element of the path then sweep as normal
if (path.closed)
{
const currentIndex = stableEdge.pathIndex;
verify(currentIndex >= 0, "Can't find manipulator index");
path.edges = rotateArray(path.edges, -currentIndex);
path.flipped = rotateArray(path.flipped, -currentIndex);
return doOneStablePath(context, topLevelId, definition, pathId, profileData, cornerOverrides, path, bodiesToDelete);
}
// case 2: stableEdge is first segment of path
// sweep as normal
if (path.edges[0] == stableEdge.edge)
{
return doOneStablePath(context, topLevelId, definition, pathId, profileData, cornerOverrides, path, bodiesToDelete);
}
// case 3: stableEdge is intermediate segment along an open path
return doSplitPath(context, topLevelId, pathId, definition, profileData, cornerOverrides, path, stableEdge, bodiesToDelete);
}
function doOneStablePath(context is Context, topLevelId is Id, definition is map, pathId is Id, profileData is map, cornerOverrides is array, path is Path, bodiesToDelete is box) returns map
{
const createSweepId = getDisambiguatedIncrementingId(context, pathId);
const pathData = sweepOnePath(context, topLevelId, createSweepId, definition, profileData, cornerOverrides, path, bodiesToDelete);
setAttributesOnPath(context, profileData, pathData.sweepData);
const createCornerId = isAtVersionOrLater(context, FeatureScriptVersionNumber.V2149_DEPRECATE_INCREMENTING_ID_GENERATOR)
? getUnstableIncrementingId(pathId + "corner")
: getIncrementingId(pathId + "corner");
createCorners(context, topLevelId, createCornerId, pathData.sweepData, pathData.cornerData, bodiesToDelete);
const compositeGroups = groupTangentSegments(context, pathData.sweepData, pathData.cornerData);
return {
"trimEnds" : [pathData.sweepData[0].startFace, last(pathData.sweepData).endFace],
"manipulators" : pathData.manipulators,
"sweepBodies" : getSweepBodies(pathData),
"compositeGroups" : compositeGroups
};
}
function groupTangentSegments(context, sweepData is array, cornerData is array) returns array
{
const numCorners = size(cornerData);
const numSegments = size(sweepData);
const isClosed = (numCorners == numSegments);
//create lookup for checking if a beam is ungrouped.
//the value doesnt matter - only key existence is used.
var ungroupedSegment = {};
for (var index = 0; index < numSegments; index += 1)
{
ungroupedSegment[index] = true;
}
var allGroups = [];
while (size(ungroupedSegment) > 0)
{
// this algorithm starts at and index and explores segments "before" (lower index) and "after" (higher index)
// to find the extents of the composite segment group.
//it also tracks the starting and ending indexes of the composite beam for later attribution.
const startBeamIndex = getFirstKey(ungroupedSegment);
var compositeSegments = [];
var startTerminus;
var endTerminus;
//search lower index to limit
var beamIndex = startBeamIndex;
while (true)
{
ungroupedSegment[beamIndex] = undefined;
compositeSegments = append(compositeSegments, beamIndex);
var cornerIndex = beamIndex - 1;
if (cornerIndex < 0)
{
//handles wrap case for closed beams
if (isClosed)
{
cornerIndex = numCorners - 1;
}
else
{
break;
}
}
if (cornerData[cornerIndex].cornerType == FrameCornerType.TANGENT && ungroupedSegment[cornerIndex] != undefined)
{
beamIndex = cornerIndex;
continue;
}
else
{
break;
}
}
startTerminus = beamIndex;
//search upper indexes
beamIndex = startBeamIndex;
while (true)
{
var cornerIndex = beamIndex;
// the closed path wraparound is handled in the lower index loop so if now encountered just exit
if (cornerIndex == numCorners)
{
break;
}
if (cornerData[cornerIndex].cornerType != FrameCornerType.TANGENT)
{
//not a tangent corner - end of composite segment
break;
}
beamIndex = (beamIndex + 1) % numSegments;
if (ungroupedSegment[beamIndex] != undefined)
{
//add to current composite group
compositeSegments = append(compositeSegments, beamIndex);
ungroupedSegment[beamIndex] = undefined;
continue;
}
else
{
//already a part of this composite segment (in event of closed path)
break;
}
}
endTerminus = beamIndex;
const compositeBodies = mapArray(compositeSegments, function(index) { return sweepData[index].body; });
const currentGroup = {
"segments" : compositeBodies,
"startTerminus" : sweepData[startTerminus].body,
"endTerminus" : sweepData[endTerminus].body
};
allGroups = append(allGroups, currentGroup);
}
return allGroups;
}
// This function retrieves the first available key in a map.
function getFirstKey(keys is map)
{
for (var k, _ in keys)
{
return k;
}
return undefined;
}
function doSplitPath(context is Context, topLevelId is Id, pathId is Id, definition is map, profileData is map, cornerOverrides is array, path is Path, stableEdge is map, bodiesToDelete is box) returns map
{
// 1. The path is split in to a frontPath and a backPath, both starting at the stable edge start.
// frontPath is subpath [stableEdge.pathIndex, last segment of path)
// backPath is subpath [0, stableEdge.pathIndex)
// 2. sweep frontPath as normal
// 3. sweep backPath in reverse from first face of frontPath
// 4. fix up attribution so frame appears as if it was a swept from start to finish segment.
const splitPaths = splitPathAtEdge(path, stableEdge);
const createSweepId = getDisambiguatedIncrementingId(context, pathId);
const frontPathData = sweepOnePath(context, topLevelId, createSweepId, definition, profileData, cornerOverrides, splitPaths.frontPath, bodiesToDelete);
for (var sweepData in frontPathData.sweepData)
{
const frameData = getFrameData(context, sweepData.id, sweepData);
setFrameAttributes(context, qCreatedBy(sweepData.id, EntityType.BODY), profileData, frameData);
}
// Backpath sweep is complicated.
// The backpath is swept from some intermediate segment "backward" to its end.
// This then requires some manual reorganization of the attribution to make the beam appear to be swept in one continuous sequence.
const backPath = splitPaths.backPath;
// the backPath needs a starting face and direction
const previousFace = frontPathData.sweepData[0].startFace;
var previousEdgeEnd = evaluatePathEdge(context, stableEdge.edge, false, 0);
previousEdgeEnd.direction = -previousEdgeEnd.direction;
var backPathSweepData = sweepContinuingPath(context, definition, createSweepId, backPath.edges, backPath.flipped, previousEdgeEnd, previousFace, cornerOverrides, profileData, bodiesToDelete);
// because the backPath was swept backward, swap the attribution on the ends.
for (var sweepData in backPathSweepData.sweepData)
{
var frameData = getFrameData(context, sweepData.id, sweepData);
const temp = frameData.endFace;
frameData.endFace = frameData.startFace;
frameData.startFace = temp;
setFrameAttributes(context, qCreatedBy(sweepData.id, EntityType.BODY), profileData, frameData);
}
// the last face of the last element of the backpath is the 'start' of the frame
setFrameTerminusAttributes(context, last(backPathSweepData.sweepData).endFace, last(frontPathData.sweepData).endFace);
// the createCorners function requires the 'previous face' so insert it at the front of the array here
const tempBackSweepData = concatenateArrays([
[{ "endFace" : frontPathData.sweepData[0].startFace }],
backPathSweepData.sweepData]);
const createCornerId = isAtVersionOrLater(context, FeatureScriptVersionNumber.V2149_DEPRECATE_INCREMENTING_ID_GENERATOR)
? getUnstableIncrementingId(pathId + "corner")
: getIncrementingId(pathId + "corner");
createCorners(context, topLevelId, createCornerId, frontPathData.sweepData, frontPathData.cornerData, bodiesToDelete);
createCorners(context, topLevelId, createCornerId, tempBackSweepData, backPathSweepData.cornerData, bodiesToDelete);
// to create composite groups, the cornerData and sweepPath data need to be ordered correctly
const totalPathSweepData = concatenateArrays([reverse(backPathSweepData.sweepData), frontPathData.sweepData]);
const totalPathCornerData = concatenateArrays([reverse(backPathSweepData.cornerData), frontPathData.cornerData]);
const compositeGroups = groupTangentSegments(context, totalPathSweepData, totalPathCornerData);
// Versioned bugfix: Selecting wrong trim ends during frame trims
const trimEnds = isAtVersionOrLater(context, FeatureScriptVersionNumber.V1770_TRIM_END_FIX)
? [last(backPathSweepData.sweepData).endFace, last(frontPathData.sweepData).endFace]
: [previousFace, last(frontPathData.sweepData).endFace];
return {
"trimEnds" : trimEnds,
"manipulators" : mergeMaps(frontPathData.manipulators, backPathSweepData.manipulators),
"sweepBodies" : concatenateArrays([getSweepBodies(frontPathData), backPathSweepData.sweepBodies]),
"compositeGroups" : compositeGroups
};
}
function sweepOnePath(context is Context, topLevelId is Id, createSweepId is function, definition is map, profileData is map, cornerOverrides is array, path is Path, bodiesToDelete is box) returns map
{
// sweep start edge
var sweepData = [];
const startEdgeSweepData = sweepStartingEdge(context, definition, createSweepId(path.edges[0]), path, profileData, bodiesToDelete);
sweepData = append(sweepData, startEdgeSweepData);
const previousEdgeEnd = evaluatePathEdge(context, path.edges[0], path.flipped[0], 1);
const previousFace = startEdgeSweepData.endFace;
// sweep continuing edges
const continuingEdges = subArray(path.edges, 1, size(path.edges));
const continuingFlips = subArray(path.flipped, 1, size(path.flipped));
const continuingData = sweepContinuingPath(context, definition, createSweepId, continuingEdges, continuingFlips, previousEdgeEnd, previousFace, cornerOverrides, profileData, bodiesToDelete);
sweepData = concatenateArrays([sweepData, continuingData.sweepData]);
var manipulators = continuingData.manipulators;
var cornerData = continuingData.cornerData;
if (path.closed)
{
const closedLoopCornerData = handleCornerForClosedLoop(context, definition, cornerOverrides, sweepData, path, size(path.edges) - 1);
manipulators = updateManipulators(manipulators, closedLoopCornerData.manipulator);
cornerData = updateCornerData(cornerData, closedLoopCornerData);
}
return {
"sweepData" : sweepData,
"cornerData" : cornerData,
"manipulators" : manipulators
};
}
function sweepContinuingPath(context is Context, definition is map, createSweepId is function, edges is array, flips is array,
previousEdgeEnd is Line, previousFace is Query, cornerOverrides is array, profileData is map, bodiesToDelete is box) returns map
{
verify(size(edges) == size(flips), "Bad path data");
var sweepData = [];
var cornerData = [];
var manipulators = {};
var sweepBodies = [];
for (var index = 0; index < size(edges); index += 1)
{
const edge = edges[index];
const flipped = flips[index];
const edgeStart = evaluatePathEdge(context, edge, flipped, 0);
const currentEdgeData = sweepContinuingEdge(context, definition, createSweepId(edge), edge, edgeStart, previousEdgeEnd, previousFace, cornerOverrides, profileData, bodiesToDelete);
previousEdgeEnd = evaluatePathEdge(context, edge, flipped, 1);
previousFace = currentEdgeData.sweepData.endFace;
// aggregation
sweepData = append(sweepData, currentEdgeData.sweepData);
cornerData = append(cornerData, currentEdgeData.cornerData);
manipulators = updateManipulators(manipulators, currentEdgeData.cornerData.manipulator);
sweepBodies = append(sweepBodies, currentEdgeData.sweepData.body);
}
return {
"sweepData" : sweepData,
"cornerData" : cornerData,
"manipulators" : manipulators,
"sweepBodies" : sweepBodies
};
}
function sweepStartingEdge(context is Context, definition is map, edgeId is Id, edgePath is Path, profileData is map, bodiesToDelete is box) returns map
{
const edge = edgePath.edges[0]; // by definition the starting edge has index 0
const edgeLine = evaluatePathEdge(context, edge, edgePath.flipped[0], 0);
const planeAtEdgeStart = getPlaneAtLineStart(context, definition, edgeLine);
const profilePlane = getProfilePlane(profileData, definition);
const mirrorAndAngleTransform = getMirrorAndAngleTransform(definition.mirrorProfile, edgeLine, planeAtEdgeStart, definition.angle);
const profileTransform = mirrorAndAngleTransform * transform(profilePlane, planeAtEdgeStart);
const profileId = edgeId + "profile";
opPattern(context, profileId, {
"entities" : profileData.profileBody,
"transforms" : [profileTransform],
"instanceNames" : ["1"]
});
cleanUpAtEndOfFeature(bodiesToDelete, qCreatedBy(profileId, EntityType.BODY));
const sweepId = edgeId + "sweep";
const sweepData = sweepOneEdge(context, sweepId, qCreatedBy(profileId, EntityType.FACE), edge);
return sweepData;
}
function sweepContinuingEdge(context, definition, edgeId, edge is Query, edgeStart is Line, previousEdgeEnd is Line, previousFace, cornerOverrides is array, profileData is map, bodiesToDelete is box)
{
opExtractSurface(context, edgeId + "extract", { "faces" : previousFace });
const extractedBody = qCreatedBy(edgeId + "extract", EntityType.BODY);
cleanUpAtEndOfFeature(bodiesToDelete, extractedBody);
const sweepProfileTransform = transform(line(previousEdgeEnd.origin, previousEdgeEnd.direction), line(edgeStart.origin,
edgeStart.direction));
const profileId = edgeId + "profile";
opTransform(context, profileId, {
"bodies" : extractedBody,
"transform" : sweepProfileTransform
});
cleanUpAtEndOfFeature(bodiesToDelete, qCreatedBy(profileId, EntityType.BODY));
const faceToSweep = qOwnedByBody(extractedBody, EntityType.FACE);
const cornerData = getCurrentCornerData(context, previousEdgeEnd, edgeStart, cornerOverrides, definition, faceToSweep, previousFace);
const sweepId = edgeId + "sweep";
const sweepData = sweepOneEdge(context, sweepId, faceToSweep, edge);
return {
"sweepData" : sweepData,
"cornerData" : cornerData
};
}
function splitPathAtEdge(path is Path, stableEdge is map) returns map
{
// split the path path in to two paths.
// This creates two paths that both start at the start point of the path edge.
// backPath: path.edges[0, splitIndex)
// frontPath: path.edges[splitIndex, N)
// backPath is then reversed.
const pathLength = size(path.edges);
verify(pathLength > 0, "Can't split a zero length path");
verify(!path.closed, "Can't split a closed path");
const splitIndex = stableEdge.pathIndex;
var backPath = {
"edges" : subArray(path.edges, 0, splitIndex),
"flipped" : subArray(path.flipped, 0, splitIndex),
"closed" : false
} as Path;
backPath = reverse(backPath);
const frontPath = {
"edges" : subArray(path.edges, splitIndex, pathLength),
"flipped" : subArray(path.flipped, splitIndex, pathLength),
"closed" : false
} as Path;
return {
"frontPath" : frontPath,
"backPath" : backPath
};
}
function createFrameManipulators(context is Context, topLevelId is Id, definition is map, manipulatorLine is Line, profileData is map) returns map
{
var manipulatorPlane = getPlaneAtLineStart(context, definition, manipulatorLine);
// The manipulator plane "x" is the base of the manipulator widget so we dont want to "rotate" the manipulator plane.
// We also want to keep the "y" axis in the same direction after the flip so that the "drag" behaves properly.
// To achieve both requirements with a mirrored profile we reverse both the X and Z axis.
if (definition.mirrorProfile)
{
manipulatorPlane = plane(manipulatorPlane.origin, -manipulatorPlane.normal, -manipulatorPlane.x);
}
const angleManipulator = angularManipulator({
"primaryParameterId" : "angle",
"axisOrigin" : manipulatorPlane.origin,
"axisDirection" : manipulatorPlane.normal,
"angle" : definition.angle,
"minValue" : 0 * degree,
"maxValue" : 360 * degree,
"rotationOrigin" : manipulatorPlane.origin + manipulatorPlane.x * profileData.pointsManipulatorData.halfExtents[0] * 2
});
const pointsManipulator = createPointsManipulator(context, topLevelId, definition.index, profileData, manipulatorPlane, definition.angle);
return { "angleManipulator" : angleManipulator, "points" : pointsManipulator };
}
function getProfilePlane(profileData is map, definition is map) returns Plane
{
// We create the profile plane centered at the center communicated from the point data, rather than the profilePlane's default center.
const profilePlaneOrigin = profileData.pointsManipulatorData.center + profileData.pointsManipulatorData.offset[definition.index];
const centeredProfilePlaneInWorld = plane(planeToWorld(profileData.profilePlane, vector(profilePlaneOrigin[0], profilePlaneOrigin[1])), profileData.profilePlane.normal, profileData.profilePlane.x);
return centeredProfilePlaneInWorld;
}
function evaluatePathEdge(context is Context, edge is Query, isFlipped is boolean, parameter is number) returns Line
{
parameter = isFlipped ? 1 - parameter : parameter;
verify(parameter >= 0 && parameter <= 1, ErrorStringEnum.FRAME_BAD_PATH);
var edgeLine;
try
{
edgeLine = evEdgeTangentLine(context, {
"edge" : edge,
"parameter" : parameter
});
edgeLine.direction = isFlipped ? -edgeLine.direction : edgeLine.direction;
}
catch
{
throw regenError(ErrorStringEnum.FRAME_BAD_PATH, edge);
}
return edgeLine;
}
function evaluatePathEdgeFromIndex(context is Context, path is Path, edgeIndex is number, parameter is number) returns Line
{
const edge = path.edges[edgeIndex];
const isFlipped = path.flipped[edgeIndex];
return evaluatePathEdge(context, edge, isFlipped, parameter);
}
function getMirrorAndAngleTransform(mirrorProfile is boolean, edgeLine is Line, planeAtEdgeStart is Plane, angle is ValueWithUnits) returns Transform
{
if (mirrorProfile)
{
// the desired behavior is to mirror the profile sketch across its Y-axis.
// But to keep the "twist" direction correct, we also negate the angle.
const mirrorPlane = plane(edgeLine.origin, planeAtEdgeStart.x);
return rotationAround(edgeLine, -angle) * mirrorAcross(mirrorPlane);
}
else
{
return rotationAround(edgeLine, angle);
}
}
function sweepOneEdge(context is Context, sweepId is Id, face is Query, edge is Query) returns map
{
try silent
{
opSweep(context, sweepId, { "profiles" : face, "path" : edge });
}
catch
{
throw regenError(ErrorStringEnum.FRAME_SWEEP_FAILED, edge);
}
const startFaceQuery = qCapEntity(sweepId, CapType.START, EntityType.FACE);
const endFaceQuery = qCapEntity(sweepId, CapType.END, EntityType.FACE);
verify(!isQueryEmpty(context, startFaceQuery) && !isQueryEmpty(context, endFaceQuery),
ErrorStringEnum.FRAME_CANDIDATE_FACES, { "entities" : edge });
const sweepData = {
"id" : sweepId,
"startFace" : startFaceQuery,
"endFace" : endFaceQuery,
"body" : qCreatedBy(sweepId, EntityType.BODY)
};
return sweepData;
}
function handleCornerForClosedLoop(context is Context, definition is map, cornerOverrides is array, sweepData is array,
edgePath is Path, edgeIndex is number) returns map
{
if (edgePath.closed && size(edgePath.edges) - 1 == edgeIndex)
{
return createAdditionalCornerForClosedLoop(context, definition, cornerOverrides, sweepData, edgePath, edgeIndex);
}
else
{
return {};
}
}
function createAdditionalCornerForClosedLoop(context is Context, definition is map, cornerOverrides is array,
sweepData is array, edgePath is Path, edgeIndex is number) returns map
{
const prevEdgeEnd = evaluatePathEdgeFromIndex(context, edgePath, edgeIndex, 1);
const lineAtStart = evaluatePathEdgeFromIndex(context, edgePath, 0, 0);
return getCurrentCornerData(context, prevEdgeEnd, lineAtStart, cornerOverrides, definition, sweepData[0].startFace, sweepData[edgeIndex].endFace);
}
function updateManipulators(manipulators is map, currentManipulators) returns map
{
if (currentManipulators != undefined)
{
return mergeMaps(manipulators, currentManipulators);
}
else
{
return manipulators;
}
}
function updateCornerData(cornerData is array, currentCornerData is map) returns array
{
if (currentCornerData != {})
{
return append(cornerData, currentCornerData);
}
else
{
return cornerData;
}
}
// Bodies added to the `bodiesToDelete` box will be deleted at the very end of the frame feature
function cleanUpAtEndOfFeature(bodiesToDelete is box, bodies is Query)
{
bodiesToDelete[] = append(bodiesToDelete[], bodies);
}
// Called at end of feature to clean up the collected helper bodies
function cleanUpBodies(context is Context, topLevelId is Id, bodiesToDelete is box)
{
if (bodiesToDelete[] != [])
{
opDeleteBodies(context, topLevelId + "cleanup", { "entities" : qUnion(bodiesToDelete[]) });
}
}
function trimFrame(context is Context, topLevelId is Id, definition is map, trimEnds is array, sweepBodies is array,
bodiesToDelete is box)
{
if (definition.trim)
{
const trimData = preprocessForTrim(context, topLevelId, definition, trimEnds, sweepBodies);
extendFrames(context, topLevelId, trimData);
trimFramesByPlanes(context, topLevelId, trimData.capFaceToTrimPlane);
trimFramesByBodies(context, topLevelId, trimData.frameToTrimFrameData, bodiesToDelete);
}
}
function preprocessForTrim(context is Context, id is Id, definition is map, trimEnds is array, sweepBodies is array) returns map
{
const collisions = getTrimCandidates(context, definition.trimPlanes, definition.trimBodies, trimEnds, sweepBodies);
const collisionData = isAtVersionOrLater(context, FeatureScriptVersionNumber.V2057_FRAME_TRIM_GROUP_BY_TRANSIENT_QUERY)
? groupCollisionResults(context, collisions)
: groupCollisionResults_PRE_2057(context, collisions);
var capFaceToToolBodies = collisionData.capFaceToToolBodies;
const framesToBodies = collisionData.framesToBodies;
var capFaceToTrimPlane = {};
var frameToTrimFrameData = {};
for (var entry in framesToBodies)
{
const target = entry.key;
const tools = entry.value;
// get trimmable ends of frames, where a cap face is "trimmable" if it is an open end of a frame (not at a corner)
const capFaces = getTrimmableCapFaces(context, target, trimEnds);
const toolsPerSide = groupToolsPerSide(context, capFaces, tools);
// process plane selections
for (var side in ["start", "end"])
{
if (isQueryEmpty(context, toolsPerSide[side]))
{
continue;
}
var trimPlanesQ = qIntersection([qOwnedByBody(toolsPerSide[side], EntityType.FACE), definition.trimPlanes]);
var trimPlanes = evaluateQuery(context, trimPlanesQ);
if (trimPlanes == [])
{
continue;
}
if (foundMultiplePlanes(context, trimPlanes))
{
setErrorEntities(context, id, { "entities" : qOwnerBody(target) });
reportFeatureWarning(context, id, ErrorStringEnum.FRAME_MULTIPLE_TRIM_PLANES);
capFaceToToolBodies[capFaces[side]] = undefined; // skip extending
}
else
{
const trackedCapFace = qUnion([capFaces[side], startTracking(context, capFaces[side])]);
capFaceToTrimPlane[trackedCapFace] = trimPlanes[0];
}
}
// The "target" body queries are dependent on cap faces which may get replaced as part of the plane trim.
// Operations ahead of a boolean trim would not invalidate a transient bodyId (face extension uses opMoveFace, and trimToPlane uses opReplaceFace)
// but the most robust solution is a robust query.
const robustTarget = makeRobustQuery(context, target);
frameToTrimFrameData[robustTarget] = {
"startFrames" : qIntersection([toolsPerSide.start, definition.trimBodies]),
"endFrames" : qIntersection([toolsPerSide.end, definition.trimBodies])
};
}
return {
"capFaceToTrimPlane" : capFaceToTrimPlane,
"frameToTrimFrameData" : frameToTrimFrameData,
"capFaceToToolBodies" : capFaceToToolBodies
};
}
function groupCollisionResults(context is Context, collisions is array) returns map