-
Notifications
You must be signed in to change notification settings - Fork 1
/
jscad-utils.jscad
1734 lines (1499 loc) · 60.3 KB
/
jscad-utils.jscad
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
/**
* @module CSG
*/
/**
* jscad-utils
* @type {Object}
* @exports util
*/
util = {
/**
* A function that reutrns the first argument. Useful when
* passing in a callback to modify something, and you want a
* default functiont hat does nothing.
* @param {object} solid an object that will be returned
* @return {object} the first parameter passed into the function.
*/
identity: function (solid) {
return solid;
},
/**
* If `f` is a funciton, it is executed with `object` as the parameter. This is used in
* `CSG.unionIf` and `CSG.subtractIf`, allowing you to pass a function instead of an object. Since the
* function isn't exeuted until called, the object to `union` or `subtract` can be assembled only if
* the conditional is true.
* @param {object} object the context to run the function with.
* @param {function|object} f if a funciton it is executed, othewise the object is returned.
* @return {object} the result of the function or the object.
*/
result: function (object, f) {
if (typeof (f) === 'function') {
return f.call(object);
} else {
return f;
}
},
/**
* Returns target object with default values assigned. If values already exist, they are not set.
* @param {object} target The target object to return.
* @param {object} defaults Defalut values to add to the object if they don't already exist.
* @return {object} Target object with default values assigned.
*/
defaults: function (target, defaults) {
return Object.assign(defaults, target);
},
isEmpty: function (variable) {
return typeof variable === 'undefined' || variable === null;
},
isNegative: function (n) {
return ((n = +n) || 1 / n) < 0;
},
/**
* Print a message and CSG object bounds and size to the conosle.
* @param {String} msg Message to print
* @param {CSG} o A CSG object to print the bounds and size of.
*/
print: function (msg, o) {
echo(msg, JSON.stringify(o.getBounds()), JSON.stringify(this.size(o.getBounds())));
},
error: function (msg) {
if (console && console.error) console.error(msg); // eslint-disable-line no-console
throw new Error(msg);
},
depreciated: function (method, error, message) {
var msg = method + ' is depreciated.' + ((' ' + message) || '');
if (console && console.error) console[error ? 'error' : 'warn'](msg); // eslint-disable-line no-console
if (error) throw new Error(msg);
},
/**
* Convert an imperial `inch` to metric `mm`.
* @param {Number} x Value in inches
* @return {Number} Result in mm
*/
inch: function inch(x) {
return x * 25.4;
},
/**
* Convert metric `mm` to imperial `inch`.
* @param {Number} x Value in cm
* @return {Number} Result in inches
*/
mm: function mm(x) {
return x / 25.4;
},
label: function label(text, x, y, width, height) {
var l = vector_text(x || 0, y || 0, text); // l contains a list of polylines to draw
var o = [];
l.forEach(function (pl) { // pl = polyline (not closed)
o.push(rectangular_extrude(pl, {
w: width || 2,
h: height || 2
})); // extrude it to 3D
});
return this.center(union(o));
},
text: function text(text) {
var l = vector_char(0, 0, text); // l contains a list of polylines to draw
var char = l.segments.reduce(function (result, segment) {
var path = new CSG.Path2D(segment);
var cag = path.expandToCAG(2);
// console.log('reduce', result, segment, path, cag);
return result ? result.union(cag) : cag;
}, undefined);
return char;
},
unitCube: function (length, radius) {
radius = radius || 0.5;
return CSG.cube({
center: [0, 0, 0],
radius: [radius, radius, length || 0.5]
}).setColor(1, 0, 0);
},
unitAxis: function (length, radius, centroid) {
// echo(length, JSON.stringify(centroid));
centroid = centroid || [0, 0, 0];
return util.unitCube(length, radius)
.union([
util.unitCube(length, radius).rotateY(90).setColor(0, 1, 0),
util.unitCube(length, radius).rotateX(90).setColor(0, 0, 1)
]).translate(centroid);
},
triangle: {
toRadians: function toRadians(deg) {
return deg / 180 * Math.PI;
},
toDegrees: function toDegrees(rad) {
return rad * (180 / Math.PI);
},
solve: function (p1, p2) {
var r = {
c: 90,
A: Math.abs(p2.x - p1.x),
B: Math.abs(p2.y - p1.y)
};
var brad = Math.atan2(r.B, r.A);
r.b = util.triangle.toDegrees(brad);
// r.C = Math.sqrt(Math.pow(r.B, 2) + Math.pow(r.A, 2));
r.C = r.B / Math.sin(brad);
r.a = 90 - r.b;
return r;
},
solve90SA: function (r) {
r = Object.assign(r, {
C: 90
});
r.A = r.A || 90 - r.B;
r.B = r.B || 90 - r.A;
var arad = util.triangle.toRadians(r.A);
// sinA = a/c
// a = c * sinA
// tanA = a/b
// a = b * tanA
r.a = r.a || (r.c ? r.c * Math.sin(arad) : r.b * Math.tan(arad));
// sinA = a/c
r.c = r.c || (r.a / Math.sin(arad));
// tanA = a/b
r.b = r.b || (r.a / Math.tan(arad));
return r;
}
},
toArray: function (a) {
return Array.isArray(a) ? a : [a];
},
ifArray: function (a, cb) {
return Array.isArray(a) ? a.map(cb) : cb(a);
},
array: {
div: function (a, f) {
return a.map(function (e) {
return e / f;
});
},
addValue: function (a, f) {
return a.map(function (e) {
return e + f;
});
},
addArray: function (a, f) {
return a.map(function (e, i) {
return e + f[i];
});
},
add: function (a) {
return Array.prototype.slice.call(arguments, 1).reduce(function (result, arg) {
if (Array.isArray(arg)) {
result = util.array.addArray(result, arg);
} else {
result = util.array.addValue(result, arg);
}
return result;
}, a);
},
fromxyz: function (object) {
return Array.isArray(object) ? object : [object.x, object.y, object.z];
},
toxyz: function (a) {
return {
x: a[0],
y: a[1],
z: a[2]
};
},
first: function (a) {
return a ? a[0] : undefined;
},
last: function (a) {
return a && a.length > 0 ? a[a.length - 1] : undefined;
},
min: function (a) {
return a.reduce(function (result, value) {
return value < result ? value : result;
}, Number.MAX_VALUE);
},
range: function (a, b) {
var result = [];
for (var i = a; i < b; i++) {
result.push(i);
}
return result;
}
},
/**
* Returns an array of positions along an object on a given axis.
* @param {CSG} object The object to calculate the segments on.
* @param {number} segments The number of segments to create.
* @param {string} axis Axis to create the sgements on.
* @return {Array} An array of segment positions.
*/
segment: function (object, segments, axis) {
var size = object.size()[axis];
var width = size / segments;
var result = [];
for (var i = width; i < size; i += width) {
result.push(i);
}
return result;
},
zipObject: function (names, values) {
return names.reduce(function (result, value, idx) {
result[value] = values[idx];
return result;
}, {});
},
// map: function (o, callback) {
// _.forIn(o, function (value, key) {
// // echo('util.map', key);
// if (value instanceof CSG) {
// // echo('key', value instanceof CSG);
// return value = callback(value, key);
// }
// return value;
// });
// return o;
// },
/**
* Object map function, returns an array of the object mapped into an array.
* @param {object} o Object to map
* @param {function} f function to apply on each key
* @return {array} an array of the mapped object.
*/
map: function (o, f) {
return Object.keys(o).map(function (key) {
return f(o[key], key, o);
});
},
mapValues: function (o, f) {
return Object.keys(o).map(function (key) {
return f(o[key], key);
});
},
pick: function (o, names) {
return names.reduce(function (result, name) {
result[name] = o[name];
return result;
}, {});
},
mapPick: function (o, names, f) {
return names.reduce(function (result, name) {
result.push(f ? f(o[name]) : o[name]);
return result;
}, []);
},
divA: function divA(a, f) {
return this.array.div(a, f);
},
divxyz: function (size, x, y, z) {
return {
x: size.x / x,
y: size.y / y,
z: size.z / z
};
},
div: function (size, d) {
return this.divxyz(size, d, d, d);
},
mulxyz: function (size, x, y, z) {
return {
x: size.x * x,
y: size.y * y,
z: size.z * z
};
},
mul: function (size, d) {
return this.divxyz(size, d, d, d);
},
xyz2array: function xyz2array(size) {
return [size.x, size.y, size.z];
},
rotationAxes: {
'x': [1, 0, 0],
'y': [0, 1, 0],
'z': [0, 0, 1]
},
/**
* Returns a `Vector3D` with the size of the object.
* @param {CSG} o A `CSG` like object or an array of `CSG.Vector3D` objects (the result of getBounds()).
* @return {CSG.Vector3D} Vector3d with the size of the object
*/
size: function size(o) {
var bbox = o.getBounds ? o.getBounds() : o;
var foo = bbox[1].minus(bbox[0]);
return foo;
},
/**
* Returns a scale factor (0.0-1.0) for an object
* that will resize it by a value in size units instead
* of percentages.
* @param {number} size Object size
* @param {number} value Amount to add (negative values subtract) from the size of the object.
* @return {number} Scale factor
*/
scale: function scale(size, value) {
if (value == 0) return 1;
return 1 + ((100 / (size / value)) / 100);
},
center: function center(object, size) {
size = size || this.size(object.getBounds());
return this.centerY(this.centerX(object, size), size);
},
centerY: function centerY(object, size) {
size = size || this.size(object.getBounds());
return object.translate([0, -size.y / 2, 0]);
},
centerX: function centerX(object, size) {
size = size || this.size(object.getBounds());
return object.translate([-size.x / 2, 0, 0]);
},
/**
* Enlarge an object by scale units, while keeping the same
* centroid. For example util.enlarge(o, 1, 1, 1) enlarges
* object o by 1mm in each access, while the centroid stays the same.
* @param {CSG} object [description]
* @param {number} x [description]
* @param {number} y [description]
* @param {number} z [description]
* @return {CSG} [description]
*/
enlarge: function enlarge(object, x, y, z) {
var a;
if (Array.isArray(x)) {
a = x;
} else {
a = [x, y, z];
}
var size = util.size(object);
var centroid = util.centroid(object, size);
var idx = 0;
var t = util.map(size, function (i) {
return util.scale(i, a[idx++]);
});
var new_object = object.scale(t);
var new_centroid = util.centroid(new_object);
/// Calculate the difference between the original centroid and the new
var delta = new_centroid.minus(centroid).times(-1);
return new_object.translate(delta);
},
/**
* Fit an object inside a bounding box. Often used
* with text labels.
* @param {CSG} object [description]
* @param {number | array} x [description]
* @param {number} y [description]
* @param {number} z [description]
* @param {boolean} keep_aspect_ratio [description]
* @return {CSG} [description]
*/
fit: function fit(object, x, y, z, keep_aspect_ratio) {
var a;
if (Array.isArray(x)) {
a = x;
keep_aspect_ratio = y;
x = a[0];
y = a[1];
z = a[2];
} else {
a = [x, y, z];
}
// var c = util.centroid(object);
var size = this.size(object.getBounds());
function scale(size, value) {
if (value == 0) return 1;
return value / size;
}
var s = [scale(size.x, x), scale(size.y, y), scale(size.z, z)];
var min = util.array.min(s);
return util.centerWith(object.scale(s.map(function (d, i) {
if (a[i] === 0) return 1; // don't scale when value is zero
return keep_aspect_ratio ? min : d;
})), 'xyz', object);
},
shift: function shift(object, x, y, z) {
var hsize = this.div(this.size(object.getBounds()), 2);
return object.translate(this.xyz2array(this.mulxyz(hsize, x, y, z)));
},
zero: function shift(object) {
var bounds = object.getBounds();
return object.translate([0, 0, -bounds[0].z]);
},
mirrored4: function mirrored4(x) {
return x.union([x.mirroredY(90), x.mirroredX(90), x.mirroredY(90).mirroredX(90)]);
},
flushSide: {
'above-outside': [1, 0],
'above-inside': [1, 1],
'below-outside': [0, 1],
'below-inside': [0, 0],
'outside+': [0, 1],
'outside-': [1, 0],
'inside+': [1, 1],
'inside-': [0, 0],
'center+': [-1, 1],
'center-': [-1, 0]
},
calcFlush: function calcFlush(moveobj, withobj, axes, mside, wside) {
util.depreciated('calcFlush', false, 'Use util.calcSnap instead.');
var side;
if (mside === 0 || mside === 1) {
// wside = wside !== undefined ? wside : mside;
side = [wside !== undefined ? wside : mside, mside];
} else {
side = util.flushSide[mside];
if (!side) util.error('invalid side: ' + mside);
}
var m = moveobj.getBounds();
var w = withobj.getBounds();
// Add centroid if needed
if (side[0] === -1) {
w[-1] = util.array.toxyz(withobj.centroid());
}
return this.axisApply(axes, function (i, axis) {
return w[side[0]][axis] - m[side[1]][axis];
});
},
calcSnap: function calcSnap(moveobj, withobj, axes, orientation, delta) {
var side = util.flushSide[orientation];
if (!side) {
var fix = {
'01': 'outside+',
'10': 'outside-',
'11': 'inside+',
'00': 'inside-',
'-11': 'center+',
'-10': 'center-'
};
util.error('util.calcSnap: invalid side: ' + orientation + ' should be ' + fix['' + orientation + delta]);
}
var m = moveobj.getBounds();
var w = withobj.getBounds();
// Add centroid if needed
if (side[0] === -1) {
w[-1] = withobj.centroid();
}
var t = this.axisApply(axes, function (i, axis) {
return w[side[0]][axis] - m[side[1]][axis];
});
return delta ? this.axisApply(axes, function (i) {
return t[i] + delta;
}) : t;
},
snap: function snap(moveobj, withobj, axis, orientation, delta) {
return moveobj.translate(util.calcSnap(moveobj, withobj, axis, orientation, delta));
},
/**
* Moves an object flush with another object
* @param {CSG} moveobj Object to move
* @param {CSG} withobj Object to make flush with
* @param {String} axis Which axis: 'x', 'y', 'z'
* @param {Number} mside 0 or 1
* @param {Number} wside 0 or 1
* @return {CSG} [description]
*/
flush: function flush(moveobj, withobj, axis, mside, wside) {
return moveobj.translate(util.calcFlush(moveobj, withobj, axis, mside, wside));
},
axisApply: function (axes, valfun, a) {
var retval = a || [0, 0, 0];
var lookup = {
x: 0,
y: 1,
z: 2
};
axes.split('').forEach(function (axis) {
retval[lookup[axis]] = valfun(lookup[axis], axis);
});
return retval;
},
axis2array: function (axes, valfun) {
util.depreciated('axis2array');
var a = [0, 0, 0];
var lookup = {
x: 0,
y: 1,
z: 2
};
axes.split('').forEach(function (axis) {
var i = lookup[axis];
a[i] = valfun(i, axis);
});
return a;
},
centroid: function (o, size) {
var bounds = o.getBounds();
size = size || util.size(bounds);
return bounds[0].plus(size.dividedBy(2));
},
calcmidlineTo: function midlineTo(o, axis, to) {
var bounds = o.getBounds();
var size = util.size(bounds);
// var centroid = bounds[0].plus(size.dividedBy(2));
// console.log('bounds', JSON.stringify(bounds), 'size', size, 'centroid', centroid);
return util.axisApply(axis, function (i, a) {
return to - (size[a] / 2);
});
},
midlineTo: function midlineTo(o, axis, to) {
return o.translate(util.calcmidlineTo(o, axis, to));
},
translator: function translator(o, axis, withObj) {
var centroid = util.centroid(o);
var withCentroid = util.centroid(withObj);
// echo('centerWith', centroid, withCentroid);
var t = util.axisApply(axis, function (i) {
return withCentroid[i] - centroid[i];
});
return t;
},
calcCenterWith: function calcCenterWith(o, axes, withObj, delta) {
var centroid = util.centroid(o);
var withCentroid = util.centroid(withObj);
var t = util.axisApply(axes, function (i, axis) {
return withCentroid[axis] - centroid[axis];
});
return delta ? util.array.add(t, delta) : t;
},
centerWith: function centerWith(o, axis, withObj) {
return o.translate(util.calcCenterWith(o, axis, withObj));
},
/**
* Creates a `group` object given a comma separated
* list of names, and an array or object. If an object
* is given, then the names list is used as the default
* parts used when the `combine()` function is called.
*
* You can call the `combine()` function with a list of parts you want combined into one.
*
* The `map()` funciton allows you to modify each part
* contained in the group object.
*
* @param {string} names Comma separated list of part names.
* @param {array | object} objects Array or object of parts. If Array, the names list is used as names for each part.
* @return {object} An object that has a parts dictionary, a `combine()` and `map()` function.
*/
group: function group(names, objects) {
var self = {};
self.names = names && names.length > 0 && names.split(',') || [];
if (Array.isArray(objects)) {
self.parts = util.zipObject(self.names, objects);
} else if (objects instanceof CSG) {
self.parts = util.zipObject(self.names, [objects]);
} else {
self.parts = objects || {};
}
/**
* Apply a function to each element in the group.
* @param {Function} cb Callback founction applied to each part.
* It is called with the parameters `(value, key)`
* @return {Object} Returns this object so it can be chained
*/
self.map = function (cb) {
self.parts = Object.keys(self.parts).reduce(function (result, key) {
result[key] = cb(self.parts[key], key);
return result;
}, {});
if (self.holes) {
if (Array.isArray(self.holes)) {
self.holes = self.holes.map(function (hole, idx) {
return cb(hole, idx);
});
} else {
self.holes = cb(self.holes, 'holes');
}
}
return self;
};
/**
* Add a CSG object to the current group.
* @param {CSG} object Object to add the parts dictionary.
* @param {string} name Name of the part
* @param {boolean} hidden If true, then the part not be added during a default `combine()`
* @param {string} subparts Prefix for subparts if adding a group
* @param {string} parts When adding a group, you can pick the parts you want to include as the named part.
*/
self.add = function (object, name, hidden, subparts, parts) {
if (object.parts) {
if (name) {
// add the combined part
if (!hidden) self.names.push(name);
self.parts[name] = object.combine(parts);
if (subparts) {
Object.keys(object.parts).forEach(function (key) {
self.parts[subparts + key] = object.parts[key];
});
}
} else {
Object.assign(self.parts, object.parts);
self.names = self.names.concat(object.names);
}
} else {
if (!hidden) self.names.push(name);
self.parts[name] = object;
}
return self;
};
self.clone = function (map) {
if (!map) map = util.identity;
// console.warn('clone() has been refactored');
var group = util.group();
Object.keys(self.parts).forEach(function (key) {
var part = self.parts[key];
var hidden = self.names.indexOf(key) == -1;
group.add(map(CSG.fromPolygons(part.toPolygons())), key, hidden);
});
if (self.holes) {
group.holes = util.toArray(self.holes).map(function (part) {
return map(CSG.fromPolygons(part.toPolygons()), 'holes');
});
}
return group;
};
/**
* Rotate the group around a solids centroid. This mutates the group.
* @param {CSG} solid The solid to rotate the group around
* @param {String} axis Axis to rotate
* @param {Number} angle Angle in degrees
* @return {Group} The rotoated group.
*/
self.rotate = function (solid, axis, angle) {
var axes = {
'x': [1, 0, 0],
'y': [0, 1, 0],
'z': [0, 0, 1]
};
var rotationCenter = solid.centroid();
var rotationAxis = axes[axis];
self.map(function (part) {
return part.rotate(rotationCenter, rotationAxis, angle);
});
if (self.holes) self.holes = util.ifArray(self.holes, function (hole) {
return hole.rotate(rotationCenter, rotationAxis, angle);
});
return self;
};
self.combine = function (pieces, options, map) {
options = Object.assign({
noholes: false
}, options);
pieces = pieces ? pieces.split(',') : self.names;
// console.log('pieces', pieces);
var g = union(util.mapPick(this.parts, pieces, function (value, key, object) {
return map ? map(value, key, object) : util.identity(value);
}));
// console.log(self.holes)
return g.subtractIf(self.holes && Array.isArray(self.holes) ? union(self.holes) : self.holes, self.holes && !options.noholes);
};
self.combineAll = function (options, map) {
return self.combine(Object.keys(self.parts).join(','), options, map);
};
self.toArray = function (pieces) {
pieces = pieces ? pieces.split(',') : self.names;
return pieces.map(function (piece) {
if (!self.parts[piece]) console.error(`Cannot find ${piece} in ${self.names}`);
return self.parts[piece];
});
};
self.snap = function snap(part, to, axis, orientation, delta) {
// console.log('group.snap', part, self);
var t = util.calcSnap(self.combine(part), to, axis, orientation, delta);
self.map(function (part) {
return part.translate(t);
});
if (self.holes) self.holes = util.ifArray(self.holes, function (hole) {
return hole.translate(t);
});
return self;
};
self.align = function align(part, to, axis, delta) {
// console.log('group.snap', part, self);
var t = util.calcCenterWith(self.combine(part), axis, to, delta);
self.map(function (part) {
return part.translate(t);
});
if (self.holes) self.holes = util.ifArray(self.holes, function (hole) {
return hole.translate(t);
});
return self;
};
self.midlineTo = function midlineTo(part, axis, to) {
var size = self.combine(part).size();
var t = util.axisApply(axis, function (i, a) {
return to - (size[a] / 2);
});
// console.log('group.midlineTo', part, t);
// var t = util.calcCenterWith(self.combine(part), axis, to, delta);
self.map(function (part) {
return part.translate(t);
});
if (self.holes) self.holes = util.ifArray(self.holes, function (hole) {
return hole.translate(t);
});
return self;
};
self.translate = function translate() {
var t = Array.prototype.slice.call(arguments, 0).reduce(function (result, arg) {
// console.log('arg', arg);
result = util.array.addArray(result, arg);
return result;
}, [0, 0, 0]);
// console.log('group.translate', t);
self.map(function (part) {
return part.translate(t);
});
if (self.holes) self.holes = util.ifArray(self.holes, function (hole) {
return hole.translate(t);
});
return self;
};
self.pick = function (parts, map) {
var p = parts && parts.length > 0 && parts.split(',') || self.names;
if (!map) map = util.identity;
var g = util.group();
p.forEach(function (name) {
g.add(map(CSG.fromPolygons(self.parts[name].toPolygons()), name), name);
});
return g;
};
self.array = function (parts, map) {
var p = parts && parts.length > 0 && parts.split(',') || self.names;
if (!map) map = util.identity;
var a = [];
p.forEach(function (name) {
a.push(map(CSG.fromPolygons(self.parts[name].toPolygons()), name));
});
return a;
};
return self;
},
/**
* Given an size, bounds and an axis, a Point
* along the axis will be returned. If no `offset`
* is given, then the midway point on the axis is returned.
* When the `offset` is positive, a point `offset` from the
* mininum axis is returned. When the `offset` is negative,
* the `offset` is subtracted from the axis maximum.
* @param {Size} size Size array of the object
* @param {Bounds} bounds Bounds of the object
* @param {String} axis Axis to find the point on
* @param {Number} offset Offset from either end
* @param {Boolean} nonzero When true, no offset values under 1e-4 are allowed.
* @return {Point} The point along the axis.
*/
getDelta: function getDelta(size, bounds, axis, offset, nonzero) {
if (!util.isEmpty(offset) && nonzero) {
if (Math.abs(offset) < 1e-4) {
offset = 1e-4 * (util.isNegative(offset) ? -1 : 1);
}
}
// if the offset is negative, then it's an offset from
// the positive side of the axis
var dist = util.isNegative(offset) ? offset = size[axis] + offset : offset;
return util.axisApply(axis, function (i, a) {
return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist);
});
},
/**
* Cut an object into two pieces, along a given axis. The offset
* allows you to move the cut plane along the cut axis. For example,
* a 10mm cube with an offset of 2, will create a 2mm side and an 8mm side.
*
* Negative offsets operate off of the larger side of the axes. In the previous example, an offset of -2 creates a 8mm side and a 2mm side.
*
* You can angle the cut plane and poistion the rotation point.
*
* ![bisect example](jsdoc2md/bisect.png)
* @param {CSG} object object to bisect
* @param {string} axis axis to cut along
* @param {number} offset offset to cut at
* @param {number} angle angle to rotate the cut plane to
* @return {object} Returns a group object with a parts object.
*/
bisect: function bisect(object, axis, offset, angle, rotateaxis, rotateoffset, options) {
options = util.defaults(options, {
addRotationCenter: false
});
angle = angle || 0;
var info = util.normalVector(axis);
var bounds = object.getBounds();
var size = util.size(object);
rotateaxis = rotateaxis || {
x: 'y',
y: 'x',
z: 'x'
}[axis];
// function getDelta(axis, offset) {
// // if the offset is negative, then it's an offset from
// // the positive side of the axis
// var dist = util.isNegative(offset) ? offset = size[axis] + offset : offset;
// return util.axisApply(axis, function (i, a) {
// return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist);
// });
// }
var cutDelta = options.cutDelta || util.getDelta(size, bounds, axis, offset);
var rotateOffsetAxis = {
'xy': 'z',
'yz': 'x',
'xz': 'y'
}[
[axis, rotateaxis].sort().join('')
];
var centroid = object.centroid();
var rotateDelta = util.getDelta(size, bounds, rotateOffsetAxis, rotateoffset);