-
Notifications
You must be signed in to change notification settings - Fork 2
/
boolean.fs
1800 lines (1662 loc) · 75.7 KB
/
boolean.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.
// Imports used in interface
export import(path : "onshape/std/booleanoperationtype.gen.fs", version : "✨");
export import(path : "onshape/std/query.fs", version : "✨");
export import(path : "onshape/std/tool.fs", version : "✨");
// Imports used internally
import(path : "onshape/std/attributes.fs", version : "✨");
import(path : "onshape/std/box.fs", version : "✨");
import(path : "onshape/std/boundingtype.gen.fs", version : "✨");
import(path : "onshape/std/clashtype.gen.fs", version : "✨");
import(path : "onshape/std/containers.fs", version : "✨");
import(path : "onshape/std/evaluate.fs", version : "✨");
import(path : "onshape/std/feature.fs", version : "✨");
import(path : "onshape/std/math.fs", version : "✨");
import(path : "onshape/std/patternCommon.fs", version : "✨");
import(path : "onshape/std/primitives.fs", version : "✨");
import(path : "onshape/std/sheetMetalAttribute.fs", version : "✨");
import(path : "onshape/std/sheetMetalUtils.fs", version : "✨");
import(path : "onshape/std/string.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 : "✨");
/**
* The boolean feature. Performs an [opBoolean] after a possible [opOffsetFace] if the operation is subtraction.
*/
annotation { "Feature Type Name" : "Boolean", "Filter Selector" : "allparts" }
export const booleanBodies = defineFeature(function(context is Context, id is Id, definition is map)
precondition
{
annotation { "Name" : "Operation type", "UIHint" : UIHint.HORIZONTAL_ENUM }
definition.operationType is BooleanOperationType;
annotation { "Name" : "Tools", "Filter" : EntityType.BODY &&
(BodyType.SOLID || (BodyType.SHEET && ConstructionObject.NO && SketchObject.NO)) && AllowMeshGeometry.YES,
"UIHint" : UIHint.ALLOW_QUERY_ORDER }
definition.tools is Query;
if (definition.operationType == BooleanOperationType.SUBTRACTION)
{
annotation { "Name" : "Targets", "Filter" : EntityType.BODY && ModifiableEntityOnly.YES &&
(BodyType.SOLID || (BodyType.SHEET && ConstructionObject.NO && SketchObject.NO)) && AllowMeshGeometry.YES }
definition.targets is Query;
annotation { "Name" : "Offset" }
definition.offset is boolean;
if (definition.offset)
{
annotation { "Name" : "Offset all" }
definition.offsetAll is boolean;
if (!definition.offsetAll)
{
annotation { "Name" : "Faces to offset",
"Filter" : (EntityType.FACE && BodyType.SOLID) }
definition.entitiesToOffset is Query;
}
annotation { "Name" : "Offset distance" }
isLength(definition.offsetDistance, ZERO_INCLUSIVE_OFFSET_BOUNDS);
annotation { "Name" : "Opposite direction", "UIHint" : UIHint.OPPOSITE_DIRECTION }
definition.oppositeDirection is boolean;
annotation { "Name" : "Reapply fillet" }
definition.reFillet is boolean;
}
}
annotation { "Name" : "Keep tools", "UIHint" : UIHint.REMEMBER_PREVIOUS_VALUE }
definition.keepTools is boolean;
}
{
if (isAtVersionOrLater(context, FeatureScriptVersionNumber.V1197_DETECT_SURFACE_JOIN_CPP))
{
const hasSheetsAsTools = !isQueryEmpty(context, qModifiableSurface(definition.tools));
if (definition.operationType != BooleanOperationType.UNION)
{
if (hasSheetsAsTools)
{
throw regenError(ErrorStringEnum.BOOLEAN_TOOL_INPUTS_NOT_SOLID, ["tools"]);
}
}
else if (hasSheetsAsTools)
{
if (!isQueryEmpty(context, qBodyType(definition.tools, BodyType.SOLID)))
{
throw regenError(ErrorStringEnum.BOOLEAN_CANNOT_MIX_SOLIDS_AND_SURFACES, ["tools"]);
}
try
{
const noImpliedDetection =
!isAtVersionOrLater(context, FeatureScriptVersionNumber.V1417_IMPLIED_DETECT_ADJACENCY);
opBoolean(context, id, {
"operationType" : BooleanOperationType.UNION,
"makeSolid" : true,
"eraseImprintedEdges" : true,
"detectAdjacencyForSheets" : noImpliedDetection,
"recomputeMatches" : true,
"tools" : definition.tools,
"keepTools" : definition.keepTools
});
}
return;
}
}
var doOffset = definition.offset && definition.operationType == BooleanOperationType.SUBTRACTION;
if (doOffset && tolerantEquals(definition.offsetDistance, 0 * meter))
{
if (isAtVersionOrLater(context, FeatureScriptVersionNumber.V1700_BOOLEAN_ZERO_OFFSET))
{
doOffset = false;
}
else
{
throw regenError(ErrorStringEnum.DIRECT_EDIT_NO_OFFSET, ["offsetDistance"]);
}
}
if (doOffset)
{
if (definition.oppositeDirection)
{
definition.offsetDistance = -definition.offsetDistance;
}
const suffix = "offsetTempBody";
const transformMatrix = identityTransform();
opPattern(context, id + suffix,
{ "entities" : definition.tools,
"transforms" : [transformMatrix],
"instanceNames" : ["1"] });
var faceQuery;
if (definition.offsetAll)
{
faceQuery = qCreatedBy(id + suffix, EntityType.FACE);
}
else
{
faceQuery = wrapFaceQueryInCopy(definition.entitiesToOffset, id + suffix);
if (isQueryEmpty(context, faceQuery))
throw regenError(ErrorStringEnum.BOOLEAN_OFFSET_NO_FACES, ["entitiesToOffset"]);
}
const tempMoveFaceSuffix = "offsetMoveFace";
const moveFaceDefinition = {
"moveFaces" : faceQuery,
"moveFaceType" : MoveFaceType.OFFSET,
"offsetDistance" : definition.offsetDistance,
"reFillet" : definition.reFillet };
opOffsetFace(context, id + tempMoveFaceSuffix, moveFaceDefinition);
const doSheetMetalBooleans = shouldPerformSheetMetalAwareBooleans(context, definition);
const toolBodies = qCreatedBy(id + suffix, EntityType.BODY);
const tempBooleanDefinition = {
"operationType" : definition.operationType,
"tools" : toolBodies,
"targets" : definition.targets,
"keepTools" : doSheetMetalBooleans };
const tempBooleanSuffix = "tempBoolean";
if (doSheetMetalBooleans)
{
try(sheetMetalAwareBoolean(context, id + tempBooleanSuffix, tempBooleanDefinition));
}
else
{
try(opBoolean(context, id + tempBooleanSuffix, tempBooleanDefinition));
}
processSubfeatureStatus(context, id, { "subfeatureId" : id + tempBooleanSuffix, "propagateErrorDisplay" : true });
if (doSheetMetalBooleans)
{
opDeleteBodies(context, id + "deleteTemp", { "entities" : toolBodies });
}
if (!definition.keepTools)
{
opDeleteBodies(context, id + "delete", { "entities" : definition.tools });
}
}
else
{
//Between versions 179 and 1017 SUBTRACT_COMPLEMENT processing was handled on FS side
var isSubtractComplement = false;
if (definition.operationType == BooleanOperationType.SUBTRACT_COMPLEMENT &&
isAtVersionOrLater(context, FeatureScriptVersionNumber.V179_SUBTRACT_COMPLEMENT_HANDLED_IN_FS) &&
!isAtVersionOrLater(context, FeatureScriptVersionNumber.V1017_SUBTRACT_COMPLEMENT))
{
isSubtractComplement = true;
definition.tools = constructToolsComplement(context, id, definition);
definition.operationType = BooleanOperationType.SUBTRACTION;
definition.keepTools = false;
}
if (shouldPerformSheetMetalAwareBooleans(context, definition))
{
sheetMetalAwareBoolean(context, id, definition);
}
else
{
opBoolean(context, id, definition);
}
if (isSubtractComplement)
{
var errorMessage = getFeatureInfo(context, id);
if (errorMessage == ErrorStringEnum.BOOLEAN_SUBTRACT_NO_OP)
{
reportFeatureInfo(context, id, ErrorStringEnum.BOOLEAN_INTERSECT_NO_OP);
}
}
}
}, { keepTools : false, offset : false, oppositeDirection : false, offsetAll : false, reFillet : false });
function shouldPerformSheetMetalAwareBooleans(context is Context, definition is map) returns boolean
{
return definition.targets != undefined && isAtVersionOrLater(context, FeatureScriptVersionNumber.V440_SYNTAX_ERRORS);
}
function wrapFaceQueryInCopy(query is Query, id is Id) returns Query
{
if (query.queryType == QueryType.UNION)
{
return qUnion(mapArray(query.subqueries, function(q)
{
return wrapFaceQueryInCopy(q, id);
}));
}
return makeQuery(id, "COPY", EntityType.FACE, { "derivedFrom" : query, "instanceName" : "1" });
}
/**
* Build a block large enough to contain all tools and targets. Subtract tools from it.
*/
function constructToolsComplement(context is Context, id is Id, booleanDefinition is map) returns Query
{
const inputTools = evaluateQuery(context, booleanDefinition.tools); // save tools here to avoid qCreatedBy confusion
const boxResult = evBox3d(context, { "topology" : qUnion([booleanDefinition.tools, booleanDefinition.targets]) });
const extendedBox is Box3d = extendBox3d(boxResult, 0. * meter, 0.1);
const boxId is Id = id + "containingBox";
fCuboid(context, boxId, { "corner1" : extendedBox.minCorner, "corner2" : extendedBox.maxCorner });
const complementId = id + "toolComplement";
const complementDefinition = {
"operationType" : BooleanOperationType.SUBTRACTION,
"tools" : qUnion(inputTools),
"targets" : qCreatedBy(boxId, EntityType.BODY),
"keepTools" : booleanDefinition.keepTools };
opBoolean(context, complementId, complementDefinition);
return qCreatedBy(boxId, EntityType.BODY); // Subtraction modifies target tool
}
/**
* Maps a [NewBodyOperationType] (used in features like [extrude]) to its corresponding [BooleanOperationType].
*/
export function convertNewBodyOpToBoolOp(operationType is NewBodyOperationType) returns BooleanOperationType
{
return {
NewBodyOperationType.ADD : BooleanOperationType.UNION,
NewBodyOperationType.REMOVE : BooleanOperationType.SUBTRACTION,
NewBodyOperationType.INTERSECT : BooleanOperationType.SUBTRACT_COMPLEMENT
}[operationType];
}
/**
* Predicate which specifies a field `operationType` of type [NewBodyOperationType].
* Used by body-creating feature preconditions such as extrude, revolve, sweep or loft.
*
* When used in a precondition, [NewBodyOperationType] creates UI like the extrude
* feature, with a horizontal list of the words "New", "Add", etc. When using this
* predicate in features, make sure to export an import of `tool.fs` so that [NewBodyOperationType]
* is visible to the Part Studios:
* ```
* export import(path : "onshape/std/tool.fs", version : "");
* ```
*
* @param booleanDefinition : @autocomplete `definition`
*/
export predicate booleanStepTypePredicate(booleanDefinition is map)
{
annotation { "Name" : "Result body operation type", "UIHint" : UIHint.HORIZONTAL_ENUM }
booleanDefinition.operationType is NewBodyOperationType;
}
/**
* Used by body-creating feature preconditions to allow post-creation booleans,
* specifying the merge scope (or "Merge with all") for that boolean.
*
* Designed to be used together with [booleanStepTypePredicate].
*
* @param booleanDefinition : @autocomplete `definition`
*/
export predicate booleanStepScopePredicate(booleanDefinition is map)
{
if (booleanDefinition.operationType != NewBodyOperationType.NEW)
{
if (booleanDefinition.defaultScope != undefined)
{
annotation { "Name" : "Merge with all", "Default" : false }
booleanDefinition.defaultScope is boolean;
if (booleanDefinition.defaultScope != true)
{
annotation { "Name" : "Merge scope", "Filter" : EntityType.BODY && BodyType.SOLID && ModifiableEntityOnly.YES && AllowMeshGeometry.YES }
booleanDefinition.booleanScope is Query;
}
}
}
}
/**
* Used by body-creating pattern feature preconditions to allow post-creation booleans with surfaces or solids,
* specifying the merge scope (or "Merge with all") for that boolean.
*
* @param booleanDefinition : @autocomplete `definition`
*/
export predicate booleanPatternScopePredicate(booleanDefinition is map)
{
if (booleanDefinition.operationType != NewBodyOperationType.NEW)
{
if (booleanDefinition.defaultScope != undefined)
{
annotation { "Name" : "Merge with all", "Default" : false }
booleanDefinition.defaultScope is boolean;
if (booleanDefinition.defaultScope != true)
{
// In reality surfaces are allowed as targets only in
// surface + surfaces and surface - solid.
// Unfortunately, we can't check for that in precondition
// It will be enforced during execution
annotation { "Name" : "Merge scope", "Filter" : (EntityType.BODY && AllowMeshGeometry.YES) &&
(BodyType.SOLID || (BodyType.SHEET && ConstructionObject.NO && SketchObject.NO))
&& ModifiableEntityOnly.YES }
booleanDefinition.booleanScope is Query;
}
}
}
}
/**
* Constructs a map with tools and targets queries for boolean operations. For operations where
* seed needs to be part of the tools for the boolean, set the "seed" parameter in the definition.
*
* @param context {Context}
* @param id {Id}: identifier of the tools feature
* @param definition {map} : See `definition` of [preocessNewBodyIfNeeded] for details.
* @returns {{
* @field targets {Query}: targets to use
* @field tools {Query}: tools to use
* @field targetsAndToolsNeedGrouping {boolean}: target and tool grouping to use in [opBoolean]
* }}
*/
function subfeatureToolsTargets(context is Context, id is Id, definition is map) returns map
{
// Fill defaults
definition = mergeMaps({ "seed" : qNothing(), "defaultScope" : true }, definition);
const resultQuery = qBodyType(qCreatedBy(id, EntityType.BODY), BodyType.SOLID);
var seedQuery = definition.seed;
if (isAtVersionOrLater(context, FeatureScriptVersionNumber.V263_SURFACE_PATTERN_BOOLEAN))
seedQuery = qBodyType(definition.seed, BodyType.SOLID);
const defaultTools = qUnion([seedQuery, resultQuery]);
var output = {};
output.tools = defaultTools;
if (definition.defaultScope != false)
{
if (isAtInitialMixedModelingReleaseVersionOrLater(context))
{
output.targets = qAllModifiableSolidBodies();
}
else
{
output.targets = qAllModifiableSolidBodiesNoMesh();
}
}
else
{
output.targets = definition.booleanScope;
}
output.targets = qSubtraction(output.targets, defaultTools);
output.targetsAndToolsNeedGrouping = true;
// We treat boolean slightly differently, as tools/targets are in select cases interchangeable.
// (This logic comes from the fact that grouping of tools/targets has a significant effect on output.)
if (definition.operationType == NewBodyOperationType.ADD &&
isQueryEmpty(context, output.targets))
{
if (!isAtVersionOrLater(context, FeatureScriptVersionNumber.V712_SKIP_TARGET_BOOLEAN))
{
// BEL-37474 made this behave as if we were just using all tools and targets as tools with no grouping
output.tools = resultQuery;
output.targets = definition.seed;
}
else
{
// Always keep the seed in the tools. Do not group if we have seeds.
if (!isQueryEmpty(context, seedQuery))
{
output.targetsAndToolsNeedGrouping = false;
}
}
}
return output;
}
/**
* This function is designed to be used by body-creating features (like [extrude]) as a boolean post-processing
* step with options from [booleanStepTypePredicate] and [booleanStepScopePredicate] in the case where the preceding
* operations of the feature have created new solid or surface bodies.
* On top of the regular boolean operation, converts the `operationType` and creates error bodies on failure.
* @param id : identifier of the main feature
* @param definition {{
* @field operationType {NewBodyOperationType}:
* @eg `NewBodyOperationType.ADD` performs a boolean union
* @eg `NewBodyOperationType.NEW` does nothing
* @field defaultScope {boolean}: @optional
* @eg `true` indicates merge scope of "everything else" (default)
* @eg `false` indicates merge scope is specified in `booleanScope`
* @field booleanScope {Query}: targets to use if `defaultScope` is false
* @field seed {Query}: @optional
* If set, will be included in the tools section of the boolean.
* }}
* @param reconstructOp {function}: A function which takes in an Id, and reconstructs the input to show to the user
* as error geometry in case the input is problematic or the boolean itself fails.
* @eg `function() {}`. For a more elaborate example see the source code of revolve feature in the Standard Library.
*/
export function processNewBodyIfNeeded(context is Context, id is Id, definition is map, reconstructOp is function)
{
if (definition.operationType == NewBodyOperationType.NEW)
return;
const solidsQuery = qModifiableEntityFilter(qBodyType(qCreatedBy(id, EntityType.BODY), BodyType.SOLID));
var booleanDefinition = subfeatureToolsTargets(context, id, definition);
if (definition.operationType != NewBodyOperationType.REMOVE && queryContainsActiveSheetMetal(context, booleanDefinition.targets))
{
throw regenError(ErrorStringEnum.SHEET_METAL_CAN_ONLY_REMOVE, [], booleanDefinition.targets);
}
booleanDefinition.eraseImprintedEdges = definition.eraseImprintedEdges;
booleanDefinition.operationType = convertNewBodyOpToBoolOp(definition.operationType);
booleanDefinition.allowSheets = definition.allowSheets;
if (isQueryEmpty(context, booleanDefinition.tools))
{
var errorEnum = ErrorStringEnum.BOOLEAN_NEED_ONE_SOLID;
if (isAtVersionOrLater(context, FeatureScriptVersionNumber.V263_SURFACE_PATTERN_BOOLEAN))
{
errorEnum = ErrorStringEnum.FEATURE_NO_SOLIDS;
}
throw regenError(errorEnum, solidsQuery);
}
if (booleanDefinition.targetsAndToolsNeedGrouping && isQueryEmpty(context, booleanDefinition.targets))
throw regenError(ErrorStringEnum.BOOLEAN_NEED_ONE_SOLID, ["booleanScope"], solidsQuery);
const boolId = id + "boolean";
try(booleanBodies(context, boolId, booleanDefinition));
processSubfeatureStatus(context, id, { "subfeatureId" : boolId, "propagateErrorDisplay" : true });
if (featureHasNonTrivialStatus(context, boolId))
{
const errorId = id + "errorEntities";
try
{
reconstructOp(errorId);
var qError = qCreatedBy(errorId, EntityType.BODY);
// For the needs of pattern processPatternBooleansIfNeeded we need to highlight just solids
// in case of info and warning but everything in case of true error
if (getFeatureError(context, boolId) == undefined &&
definition.operationType == NewBodyOperationType.ADD)
{
qError = qBodyType(qError, BodyType.SOLID);
}
setErrorEntities(context, id, { "entities" : qError });
opDeleteBodies(context, id + "delete", { "entities" : qCreatedBy(errorId, EntityType.BODY) });
}
catch (e)
{
if (!isAtVersionOrLater(context, FeatureScriptVersionNumber.V736_SM_74))
throw e;
}
}
}
/**
* Predicate which specifies a field `surfaceOperationType` of type [NewSurfaceOperationType].
* Used by surface-creating feature preconditions such as revolve, sweep or loft.
*
* When used in a precondition, [NewSurfaceOperationType] creates UI like the sweep
* feature, with a horizontal list of the words "New" and "Add". When using this
* predicate in features, make sure to export an import of `tool.fs` so that [NewSurfaceOperationType]
* is visible to the Part Studios:
* ```
* export import(path : "onshape/std/tool.fs", version : "");
* ```
*
* @param surfaceDefinition : @autocomplete `definition`
*/
export predicate surfaceOperationTypePredicate(surfaceDefinition is map)
{
annotation { "Name" : "Result body operation type", "UIHint" : UIHint.HORIZONTAL_ENUM }
surfaceDefinition.surfaceOperationType is NewSurfaceOperationType;
}
/**
* Used by surface-creating feature preconditions to allow post-creation booleans,
* specifying the merge scope (or "Merge with all") for that boolean.
*
* Designed to be used together with [surfaceOperationTypePredicate].
*
* @param definition : @autocomplete `definition`
*/
export predicate surfaceJoinStepScopePredicate(definition is map)
{
if (definition.surfaceOperationType != NewSurfaceOperationType.NEW)
{
if (definition.defaultSurfaceScope != undefined)
{
annotation { "Name" : "Merge with all", "Default" : true }
definition.defaultSurfaceScope is boolean;
if (definition.defaultSurfaceScope != true)
{
annotation { "Name" : "Merge scope", "Filter" : EntityType.BODY && BodyType.SHEET && ModifiableEntityOnly.YES &&
AllowMeshGeometry.YES && SketchObject.NO }
definition.booleanSurfaceScope is Query;
}
}
}
}
/**
* @internal
* Used by features using surface boolean heuristics
*/
export function filterJoinableSurfaceEdges(edges is Query) returns Query
{
return qEdgeTopologyFilter(qSketchFilter(edges, SketchObject.NO), EdgeTopology.ONE_SIDED);
}
/**
* @internal
*/
function filterOverlappingEdges(context is Context, targetEdge is Query, edges is Query, transform is Transform) returns Query
{
var useTolerantCheck = isAtVersionOrLater(context, FeatureScriptVersionNumber.V607_HOLE_FEATURE_FIT_UPDATE);
var midPoint = transform * evEdgeTangentLine(context, {
"edge" : targetEdge,
"parameter" : 0.5,
"arcLengthParameterization" : !useTolerantCheck
}).origin;
if (useTolerantCheck)
{
return qWithinRadius(edges, midPoint, TOLERANCE.booleanDefaultTolerance * meter);
}
else
{
return qContainsPoint(edges, midPoint);
}
}
/**
* @internal
*/
function getJoinableSurfaceEdgeFromParentEdge(context is Context, id is Id, parentEdge is Query, transform is Transform) returns Query
{
var track = filterOverlappingEdges(context, parentEdge, filterJoinableSurfaceEdges(startTracking(context,
{ "subquery" : parentEdge, "trackPartialDependency" : true, "lastOperationId" : lastModifyingOperationId(context, parentEdge) })), transform);
if (isAtVersionOrLater(context, FeatureScriptVersionNumber.V776_SURFACE_JOIN_BUG_FIX))
{
return qSubtraction(track, qCreatedBy(id));
}
var trackedEdges = evaluateQuery(context, qSubtraction(track, qCreatedBy(id)));
if (size(trackedEdges) == 1)
{
return trackedEdges[0];
}
return qNothing();
}
/**
* @internal
*/
function createJoinMatch(topology1 is Query, topology2 is Query) returns map
{
return { "topology1" : topology1, "topology2" : topology2, "matchType" : TopologyMatchType.COINCIDENT };
}
/**
* @internal
* Used by features using surface boolean heuristics
*/
export function surfaceOperationTypeEditLogic(context is Context, id is Id, definition is map,
specifiedParameters is map, inputEdges is Query, hiddenBodies is Query)
{
if (!specifiedParameters.surfaceOperationType)
{
var joinableEdges = evaluateQuery(context, filterJoinableSurfaceEdges(inputEdges));
var anyJoinable = size(joinableEdges) > 0;
if (!anyJoinable)
{
var otherEdges;
if (isAtVersionOrLater(context, FeatureScriptVersionNumber.V576_GET_WIRE_LAMINAR_DEPENDENCIES))
{
otherEdges = evaluateQuery(context, qEntityFilter(inputEdges, EntityType.EDGE));
}
else
{
otherEdges = evaluateQuery(context, qSketchFilter(inputEdges, SketchObject.YES));
}
for (var i = 0; i < size(otherEdges); i += 1)
{
var siblingEdges = getJoinableSurfaceEdgeFromParentEdge(context, id, otherEdges[i], identityTransform());
if (!isQueryEmpty(context, qSubtraction(siblingEdges, qOwnedByBody(hiddenBodies, EntityType.EDGE))))
{
anyJoinable = true;
break;
}
}
}
definition.surfaceOperationType = anyJoinable ? NewSurfaceOperationType.ADD : NewSurfaceOperationType.NEW;
}
return definition;
}
function filterByOwnerBody(context is Context, edges is Query, bodies is Query) returns Query
{
var allEdges = evaluateQuery(context, edges);
var filteredEdges = [];
for (var edge in allEdges)
{
if (isQueryEmpty(context, qSubtraction(qOwnerBody(edge), bodies)))
{
filteredEdges = append(filteredEdges, edge);
}
}
return qUnion(filteredEdges);
}
/**
* @internal
* Used by features using surface boolean.
* Designed to be used together with [surfaceJoinStepScopePredicate].
* @param context {Context}
* @param id {Id}: Identifier of the feature
* @param definition {{
* @field defaultSurfaceScope {boolean}: @optional
* @eg `true` indicates merge scope of all the original and related surfaces used as input to create this surface (default)
* @eg `false` indicates merge scope is specified in `booleanSurfaceScope`
* @field booleanSurfaceScope {Query}: targets to use if `defaultSurfaceScope` is false
* }}
* @param created {Query}: All newly created edges to be considered in matching.
* @param originating {Query} : All original input edges that were used to create the edges.
* @param transform {Transform} : Remaining feature pattern transform
*/
export function createTopologyMatchesForSurfaceJoin(context is Context, id is Id, definition is map, created is Query, originating is Query, transform is Transform) returns array
{
var createdEdges = evaluateQuery(context, qEdgeTopologyFilter(created, EdgeTopology.ONE_SIDED));
var originatingEdges = filterJoinableSurfaceEdges(originating);
var nonMatchedOriginatingEdges;
if (isAtVersionOrLater(context, FeatureScriptVersionNumber.V576_GET_WIRE_LAMINAR_DEPENDENCIES))
{
// Any edge that we didn't already match is a candidate
nonMatchedOriginatingEdges = qSubtraction(qEntityFilter(originating, EntityType.EDGE), originatingEdges);
}
else
{
nonMatchedOriginatingEdges = qSketchFilter(originating, SketchObject.YES);
}
if (definition.defaultSurfaceScope == false)
{
if (isQueryEmpty(context, definition.booleanSurfaceScope))
{
throw regenError(ErrorStringEnum.BOOLEAN_NO_SURFACE_IN_MERGE_SCOPE, ["booleanSurfaceScope"], qCreatedBy(id, EntityType.BODY));
}
originatingEdges = filterByOwnerBody(context, originatingEdges, definition.booleanSurfaceScope);
}
var nCreatedEdges = size(createdEdges);
const filterMatchesByOverlap = isAtVersionOrLater(context, FeatureScriptVersionNumber.V1031_BODY_NET_IN_LOFT);
var matches = makeArray(nCreatedEdges);
var nMatches = 0;
for (var i = 0; i < nCreatedEdges; i += 1)
{
var dependencies = qDependency(createdEdges[i]);
var originals = evaluateQuery(context, filterOverlappingEdges(context, createdEdges[i], qIntersection([originatingEdges, dependencies]), identityTransform()));
var nOriginalMatches = size(originals);
var matchedEdge = undefined;
if (nOriginalMatches == 1)
{
matchedEdge = originals[0];
}
else if (nOriginalMatches == 0)
{
var originalEdges = evaluateQuery(context, filterOverlappingEdges(context, createdEdges[i], qIntersection([nonMatchedOriginatingEdges, dependencies]), inverse(transform)));
if (size(originalEdges) == 1)
{
var siblingEdges = getJoinableSurfaceEdgeFromParentEdge(context, id, originalEdges[0], transform);
if (definition.defaultSurfaceScope == false)
{
siblingEdges = filterByOwnerBody(context, siblingEdges, definition.booleanSurfaceScope);
}
if (filterMatchesByOverlap)
{
siblingEdges = filterOverlappingEdges(context, createdEdges[i], siblingEdges, identityTransform());
}
const edges = evaluateQuery(context, siblingEdges);
const nEdges = size(edges);
const nBodies = size(evaluateQuery(context, qOwnerBody(siblingEdges)));
if (nEdges == 1 ||
(nEdges > 0 && nBodies == 1 && filterMatchesByOverlap))
{
matchedEdge = edges[0];
}
}
}
if (matchedEdge != undefined)
{
matches[nMatches] = createJoinMatch(matchedEdge, createdEdges[i]);
nMatches += 1;
}
}
return resize(matches, nMatches);
}
/**
* @internal
* Throws error if booleanSurfaceScope contains a surface that is not present in matches
* Used by features using surface boolean.
* Designed to be used together with [createTopologyMatchesForSurfaceJoin].
*/
export function checkForNotJoinableSurfacesInScope(context is Context, id is Id, definition is map, matches is array)
{
if (definition.defaultSurfaceScope == false)
{
var allMatchTargets = [];
for (var i = 0; i < size(matches); i += 1)
{
allMatchTargets = append(allMatchTargets, qOwnerBody(matches[i].topology1));
}
var notJoinableSurfacesInScope = qSubtraction(definition.booleanSurfaceScope, qUnion(allMatchTargets));
if (!isQueryEmpty(context, notJoinableSurfacesInScope))
{
setErrorEntities(context, id, { "entities" : notJoinableSurfacesInScope });
reportFeatureWarning(context, id, ErrorStringEnum.BOOLEAN_NO_SHARED_EDGE_WITH_SURFACE_IN_MERGE_SCOPE);
}
}
}
/**
* @internal
* Joins surface bodies at the matching edges.
* @param context {Context}
* @param id {Id}: identifier of the feature
* @param matches {array}: Matching edges of the sheet bodies. Each matching element is a map with fields `topology1`, `topology2`
* and `matchType`; where `topology1` and `topology2` are a pair of matching edges of two sheet bodies and
* `matchType` is the type of match [TopologyMatchType] between them. Owner body of `matches[0].topology1` survives in the join operation.
* @param reconstructOp {function}: A function which takes in an Id, and reconstructs the input to show to the user as error geometry
* in case the input is problematic or the join itself fails.
* @param makeSolid {boolean}: Tries to join the surfaces into a solid
*/
export function joinSurfaceBodies(context is Context, id is Id, matches is array, makeSolid is boolean, reconstructOp is function)
{
const joinId = id + "join";
var nMatches = size(matches);
if (nMatches == 0)
{
if (!featureHasNonTrivialStatus(context, id))
{
reportFeatureWarning(context, id, ErrorStringEnum.BOOLEAN_NO_TARGET_SURFACE);
}
}
else
{
var tools = makeArray(nMatches * 2);
for (var i = 0; i < nMatches; i += 1)
{
tools[i] = qOwnerBody(matches[i].topology1);
tools[nMatches + i] = qOwnerBody(matches[i].topology2);
}
try
(
opBoolean(context, joinId, {
"allowSheets" : true,
"tools" : qUnion(tools),
"operationType" : BooleanOperationType.UNION,
"makeSolid" : makeSolid,
"eraseImprintedEdges" : true,
"matches" : matches,
"recomputeMatches" : true
}));
processSubfeatureStatus(context, id, { "subfeatureId" : joinId, "propagateErrorDisplay" : true });
}
if (nMatches == 0 || featureHasNonTrivialStatus(context, joinId))
{
const errorId = id + "errorEntities";
reconstructOp(errorId);
setErrorEntities(context, id, { "entities" : qCreatedBy(errorId, EntityType.BODY) });
opDeleteBodies(context, id + "delete", { "entities" : qCreatedBy(errorId, EntityType.BODY) });
}
}
/**
* @internal
* A query that filters out non-modifiable or non-surface entities in subquery
*/
export function qModifiableSurface(subquery is Query) returns Query
{
return qModifiableEntityFilter(
qSketchFilter(
qConstructionFilter(
qBodyType(
qEntityFilter(subquery, EntityType.BODY),
BodyType.SHEET),
ConstructionObject.NO),
SketchObject.NO));
}
/**
* This function is designed to be used by surface-body-creating features (like [extrude]) as a boolean post-processing
* step with options from [surfaceOperationTypePredicate ] and [surfaceJoinStepScopePredicate]. It detects matching edges of adjacent
* bodies and joins surface bodies at these edges.
* @param context {Context}
* @param id {Id}: identifier of the feature
* @param definition {{
* @field defaultSurfaceScope {boolean}: @optional
* @eg `true` indicates merge scope of all the original and related surfaces used as input to create this surface (default)
* @eg `false` indicates merge scope is specified in `booleanSurfaceScope`
* @field booleanSurfaceScope {Query}: @optional targets to use if `defaultSurfaceScope` is false
* Default is `qNothing()`
* @field seed {Query}: @optional
* Default is `qNothing()` If set, will be included in the tools section of the boolean.
* }}
* @param makeSolid {boolean}: Tries to join the surfaces into a solid
* @param reconstructOp {function}: A function which takes in an Id, and reconstructs the input to show to the user as error geometry
* in case the input is problematic or the join itself fails.
* @eg `function() {}`. For a more elaborate example see the source code of revolve feature in the Standard Library.
*/
export function joinSurfaceBodiesWithAutoMatching(context is Context, id is Id, definition is map, makeSolid is boolean, reconstructOp is function)
{
const seeded = definition.seed != undefined;
if (!isAtVersionOrLater(context, FeatureScriptVersionNumber.V1215_BOOLEANS_OF_SURFACES) &&
definition.defaultSurfaceScope == undefined && !seeded)
{
return;
}
const joinId = id + "join";
// Need to add seed surfaces if defined.
const entities = seeded ? qUnion([definition.seed, qCreatedBy(id)]) : qCreatedBy(id);
const tools = qModifiableSurface(entities);
const contextTargets = qSubtraction(qModifiableSurface(qEverything()), tools);
var targets = undefined;
if (definition.defaultSurfaceScope != false)
{
if (!isQueryEmpty(context, contextTargets))
{
targets = contextTargets;
}
}
else if (definition.booleanSurfaceScope != undefined &&
!isQueryEmpty(context, qModifiableSurface(definition.booleanSurfaceScope)))
{
targets = qModifiableSurface(definition.booleanSurfaceScope);
}
// otherwise join feature surfaces between themselves but not to merge scope.
if (!seeded)
{
if (definition.defaultSurfaceScope == true)
{
if (targets == undefined)
{
throw regenError(ErrorStringEnum.BOOLEAN_NO_SURFACE_TO_MERGE_WITH, qCreatedBy(id, EntityType.BODY));
}
}
else if (targets == undefined)
{
throw regenError(ErrorStringEnum.BOOLEAN_NO_SURFACE_IN_MERGE_SCOPE,
["booleanSurfaceScope"], qCreatedBy(id, EntityType.BODY));
}
}
try
{
const noImpliedDetection =
!isAtVersionOrLater(context, FeatureScriptVersionNumber.V1417_IMPLIED_DETECT_ADJACENCY);
opBoolean(context, joinId, {
"operationType" : BooleanOperationType.UNION,
"makeSolid" : makeSolid,
"eraseImprintedEdges" : true,
"detectAdjacencyForSheets" : noImpliedDetection,
"recomputeMatches" : true,
"tools" : tools,
"targets" : targets,
"targetsAndToolsNeedGrouping" : targets != undefined
});
}
processSubfeatureStatus(context, id, { "subfeatureId" : joinId, "propagateErrorDisplay" : true });
if (featureHasNonTrivialStatus(context, joinId))
{
const errorId = id + "errorSurfaces";
reconstructOp(errorId);
// For the needs of pattern processPatternBooleansIfNeeded we need to highlight just surfaces
// in case of info and warning but everything in case of true error
var qError = qCreatedBy(errorId, EntityType.BODY);
if (getFeatureError(context, joinId) == undefined) // no need to version display data
{
qError = qModifiableSurface(qError);
}
setErrorEntities(context, id, { "entities" : qError });
opDeleteBodies(context, id + "deleteSurfaces", { "entities" : qCreatedBy(errorId, EntityType.BODY) });
}
}
function performRegularBoolean(context is Context, id is Id, definition is map)
{
try(opBoolean(context, id, definition));
}
function copyBodies(context is Context, id is Id, bodies is Query) returns Query
{
const copyId = id + "bodyCopy";
opPattern(context, copyId, {
"entities" : bodies,
"transforms" : [identityTransform()],
"instanceNames" : ["copy"]
});
return qCreatedBy(copyId, EntityType.BODY);
}
function sheetMetalAwareBoolean(context is Context, id is Id, definition is map)
{
const parts = partitionSheetMetalParts(context, definition.targets);
if (size(parts.sheetMetalPartsMap) == 0)
{
performRegularBoolean(context, id, definition);
}
else if (definition.operationType != BooleanOperationType.SUBTRACTION)
{
throw regenError(ErrorStringEnum.SHEET_METAL_CAN_ONLY_SUBTRACT);
}
else
{
const handleNoOpResults = isAtVersionOrLater(context, FeatureScriptVersionNumber.V630_SM_BOOLEAN_NOOP_HANDLING);
const deleteToolsAtEnd = !definition.keepTools;
definition.keepTools = true;
var evaluatedOriginalTools = qUnion(evaluateQuery(context, definition.tools));
var booleanWasNoOp = true;
if (!isQueryEmpty(context, parts.nonSheetMetalPartsQuery))
{
definition.targets = parts.nonSheetMetalPartsQuery;
performRegularBoolean(context, id, definition);
if (!statusIsNoOp(context, id))
{
booleanWasNoOp = false;
}
}
// The query for the tools could change if it uses qCreatedBy(top-level-id), for example
// because subsequent operations are adding more bodies with different IDs
// so substitute the evaluated original tools
definition.tools = evaluatedOriginalTools;
checkNotInFeaturePattern(context, definition.targets, ErrorStringEnum.SHEET_METAL_BLOCKED_PATTERN);
var index = 0;
for (var idAndParts in parts.sheetMetalPartsMap)
{
const subId = id + unstableIdComponent(index);
index += 1;
const booleanId = subId + "tempSMBoolean";
definition.sheetMetalPart = qUnion(idAndParts.value);