forked from jscad/OpenJSCAD.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csg.js
6002 lines (5521 loc) · 193 KB
/
csg.js
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
'use strict';
/*
## License
Copyright (c) 2013 Eduard Bespalov ([email protected]): .solidFromSlices()
Copyright (c) 2013 Rene K. Mueller (http://OpenJSCAD.org): AMF export added, CSG.center([flag,flag,flag]);
Copyright (c) 2012 Joost Nieuwenhuijse ([email protected])
Copyright (c) 2012 Alexandre Girard (https://github.com/alx)
Copyright (c) 2011 Evan Wallace (http://evanw.github.com/csg.js/) -- original csg.js
All code released under MIT license
## Overview
For an overview of the CSG process see the original csg.js code:
http://evanw.github.com/csg.js/
CSG operations through BSP trees suffer from one problem: heavy fragmentation
of polygons. If two CSG solids of n polygons are unified, the resulting solid may have
in the order of n*n polygons, because each polygon is split by the planes of all other
polygons. After a few operations the number of polygons explodes.
This version of CSG.js solves the problem in 3 ways:
1. Every polygon split is recorded in a tree (CSG.PolygonTreeNode). This is a separate
tree, not to be confused with the CSG tree. If a polygon is split into two parts but in
the end both fragments have not been discarded by the CSG operation, we can retrieve
the original unsplit polygon from the tree, instead of the two fragments.
This does not completely solve the issue though: if a polygon is split multiple times
the number of fragments depends on the order of subsequent splits, and we might still
end up with unncessary splits:
Suppose a polygon is first split into A and B, and then into A1, B1, A2, B2. Suppose B2 is
discarded. We will end up with 2 polygons: A and B1. Depending on the actual split boundaries
we could still have joined A and B1 into one polygon. Therefore a second approach is used as well:
2. After CSG operations all coplanar polygon fragments are joined by a retesselating
operation. See CSG.reTesselated(). Retesselation is done through a
linear sweep over the polygon surface. The sweep line passes over the y coordinates
of all vertices in the polygon. Polygons are split at each sweep line, and the fragments
are joined horizontally and vertically into larger polygons (making sure that we
will end up with convex polygons).
This still doesn't solve the problem completely: due to floating point imprecisions
we may end up with small gaps between polygons, and polygons may not be exactly coplanar
anymore, and as a result the retesselation algorithm may fail to join those polygons.
Therefore:
3. A canonicalization algorithm is implemented: it looks for vertices that have
approximately the same coordinates (with a certain tolerance, say 1e-5) and replaces
them with the same vertex. If polygons share a vertex they will actually point to the
same CSG.Vertex instance. The same is done for polygon planes. See CSG.canonicalized().
Performance improvements to the original CSG.js:
Replaced the flip() and invert() methods by flipped() and inverted() which don't
modify the source object. This allows to get rid of all clone() calls, so that
multiple polygons can refer to the same CSG.Plane instance etc.
The original union() used an extra invert(), clipTo(), invert() sequence just to remove the
coplanar front faces from b; this is now combined in a single b.clipTo(a, true) call.
Detection whether a polygon is in front or in back of a plane: for each polygon
we are caching the coordinates of the bounding sphere. If the bounding sphere is
in front or in back of the plane we don't have to check the individual vertices
anymore.
Other additions to the original CSG.js:
CSG.Vector class has been renamed into CSG.Vector3D
Classes for 3D lines, 2D vectors, 2D lines, and methods to find the intersection of
a line and a plane etc.
Transformations: CSG.transform(), CSG.translate(), CSG.rotate(), CSG.scale()
Expanding or contracting a solid: CSG.expand() and CSG.contract(). Creates nice
smooth corners.
The vertex normal has been removed since it complicates retesselation. It's not needed
for solid CAD anyway.
*/
(function(module){
var _CSGDEBUG = false;
function fnNumberSort(a, b) {
return a - b;
}
// # class CSG
// Holds a binary space partition tree representing a 3D solid. Two solids can
// be combined using the `union()`, `subtract()`, and `intersect()` methods.
var CSG = function() {
this.polygons = [];
this.properties = new CSG.Properties();
this.isCanonicalized = true;
this.isRetesselated = true;
};
CSG.defaultResolution2D = 32;
CSG.defaultResolution3D = 12;
// Construct a CSG solid from a list of `CSG.Polygon` instances.
CSG.fromPolygons = function(polygons) {
var csg = new CSG();
csg.polygons = polygons;
csg.isCanonicalized = false;
csg.isRetesselated = false;
return csg;
};
// Construct a CSG solid from generated slices.
// Look at CSG.Polygon.prototype.solidFromSlices for details
CSG.fromSlices = function(options) {
return (new CSG.Polygon.createFromPoints([
[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]
])).solidFromSlices(options);
};
// create from an untyped object with identical property names:
CSG.fromObject = function(obj) {
var polygons = obj.polygons.map(function(p) {
return CSG.Polygon.fromObject(p);
});
var csg = CSG.fromPolygons(polygons);
csg = csg.canonicalized();
return csg;
};
// Reconstruct a CSG from the output of toCompactBinary()
CSG.fromCompactBinary = function(bin) {
if(bin['class'] != "CSG") throw new Error("Not a CSG");
var planes = [],
planeData = bin.planeData,
numplanes = planeData.length / 4,
arrayindex = 0,
x, y, z, w, normal, plane;
for(var planeindex = 0; planeindex < numplanes; planeindex++) {
x = planeData[arrayindex++];
y = planeData[arrayindex++];
z = planeData[arrayindex++];
w = planeData[arrayindex++];
normal = new CSG.Vector3D(x, y, z);
plane = new CSG.Plane(normal, w);
planes.push(plane);
}
var vertices = [],
vertexData = bin.vertexData,
numvertices = vertexData.length / 3,
pos, vertex;
arrayindex = 0;
for(var vertexindex = 0; vertexindex < numvertices; vertexindex++) {
x = vertexData[arrayindex++];
y = vertexData[arrayindex++];
z = vertexData[arrayindex++];
pos = new CSG.Vector3D(x, y, z);
vertex = new CSG.Vertex(pos);
vertices.push(vertex);
}
var shareds = bin.shared.map(function(shared) {
return CSG.Polygon.Shared.fromObject(shared);
});
var polygons = [],
numpolygons = bin.numPolygons,
numVerticesPerPolygon = bin.numVerticesPerPolygon,
polygonVertices = bin.polygonVertices,
polygonPlaneIndexes = bin.polygonPlaneIndexes,
polygonSharedIndexes = bin.polygonSharedIndexes,
numpolygonvertices, polygonvertices, shared, polygon;//already defined plane,
arrayindex = 0;
for(var polygonindex = 0; polygonindex < numpolygons; polygonindex++) {
numpolygonvertices = numVerticesPerPolygon[polygonindex];
polygonvertices = [];
for(var i = 0; i < numpolygonvertices; i++) {
polygonvertices.push(vertices[polygonVertices[arrayindex++]]);
}
plane = planes[polygonPlaneIndexes[polygonindex]];
shared = shareds[polygonSharedIndexes[polygonindex]];
polygon = new CSG.Polygon(polygonvertices, shared, plane);
polygons.push(polygon);
}
var csg = CSG.fromPolygons(polygons);
csg.isCanonicalized = true;
csg.isRetesselated = true;
return csg;
};
CSG.prototype = {
toPolygons: function() {
return this.polygons;
},
// Return a new CSG solid representing space in either this solid or in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
//
// A.union(B)
//
// +-------+ +-------+
// | | | |
// | A | | |
// | +--+----+ = | +----+
// +----+--+ | +----+ |
// | B | | |
// | | | |
// +-------+ +-------+
//
union: function(csg) {
var csgs;
if(csg instanceof Array) {
csgs = csg;
} else {
csgs = [csg];
}
var result = this;
for(var i = 0; i < csgs.length; i++) {
var islast = (i == (csgs.length - 1));
result = result.unionSub(csgs[i], islast, islast);
}
return result;
},
unionSub: function(csg, retesselate, canonicalize) {
if(!this.mayOverlap(csg)) {
return this.unionForNonIntersecting(csg);
} else {
var a = new CSG.Tree(this.polygons);
var b = new CSG.Tree(csg.polygons);
a.clipTo(b, false);
// b.clipTo(a, true); // ERROR: this doesn't work
b.clipTo(a);
b.invert();
b.clipTo(a);
b.invert();
var newpolygons = a.allPolygons().concat(b.allPolygons());
var result = CSG.fromPolygons(newpolygons);
result.properties = this.properties._merge(csg.properties);
if(retesselate) result = result.reTesselated();
if(canonicalize) result = result.canonicalized();
return result;
}
},
// Like union, but when we know that the two solids are not intersecting
// Do not use if you are not completely sure that the solids do not intersect!
unionForNonIntersecting: function(csg) {
var newpolygons = this.polygons.concat(csg.polygons);
var result = CSG.fromPolygons(newpolygons);
result.properties = this.properties._merge(csg.properties);
result.isCanonicalized = this.isCanonicalized && csg.isCanonicalized;
result.isRetesselated = this.isRetesselated && csg.isRetesselated;
return result;
},
// Return a new CSG solid representing space in this solid but not in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
//
// A.subtract(B)
//
// +-------+ +-------+
// | | | |
// | A | | |
// | +--+----+ = | +--+
// +----+--+ | +----+
// | B |
// | |
// +-------+
//
subtract: function(csg) {
var csgs;
if(csg instanceof Array) {
csgs = csg;
} else {
csgs = [csg];
}
var result = this;
for(var i = 0; i < csgs.length; i++) {
var islast = (i == (csgs.length - 1));
result = result.subtractSub(csgs[i], islast, islast);
}
return result;
},
subtractSub: function(csg, retesselate, canonicalize) {
var a = new CSG.Tree(this.polygons);
var b = new CSG.Tree(csg.polygons);
a.invert();
a.clipTo(b);
b.clipTo(a, true);
a.addPolygons(b.allPolygons());
a.invert();
var result = CSG.fromPolygons(a.allPolygons());
result.properties = this.properties._merge(csg.properties);
if(retesselate) result = result.reTesselated();
if(canonicalize) result = result.canonicalized();
return result;
},
// Return a new CSG solid representing space both this solid and in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
//
// A.intersect(B)
//
// +-------+
// | |
// | A |
// | +--+----+ = +--+
// +----+--+ | +--+
// | B |
// | |
// +-------+
//
intersect: function(csg) {
var csgs;
if(csg instanceof Array) {
csgs = csg;
} else {
csgs = [csg];
}
var result = this;
for(var i = 0; i < csgs.length; i++) {
var islast = (i == (csgs.length - 1));
result = result.intersectSub(csgs[i], islast, islast);
}
return result;
},
intersectSub: function(csg, retesselate, canonicalize) {
var a = new CSG.Tree(this.polygons);
var b = new CSG.Tree(csg.polygons);
a.invert();
b.clipTo(a);
b.invert();
a.clipTo(b);
b.clipTo(a);
a.addPolygons(b.allPolygons());
a.invert();
var result = CSG.fromPolygons(a.allPolygons());
result.properties = this.properties._merge(csg.properties);
if(retesselate) result = result.reTesselated();
if(canonicalize) result = result.canonicalized();
return result;
},
// Return a new CSG solid with solid and empty space switched. This solid is
// not modified.
inverse: function() {
var flippedpolygons = this.polygons.map(function(p) {
return p.flipped();
});
return CSG.fromPolygons(flippedpolygons);
// TODO: flip properties
},
// Affine transformation of CSG object. Returns a new CSG object
transform1: function(matrix4x4) {
var newpolygons = this.polygons.map(function(p) {
return p.transform(matrix4x4);
});
var result = CSG.fromPolygons(newpolygons);
result.properties = this.properties._transform(matrix4x4);
result.isRetesselated = this.isRetesselated;
return result;
},
transform: function(matrix4x4) {
var ismirror = matrix4x4.isMirroring();
var transformedvertices = {};
var transformedplanes = {};
var newpolygons = this.polygons.map(function(p) {
var newplane;
var plane = p.plane;
var planetag = plane.getTag();
if(planetag in transformedplanes) {
newplane = transformedplanes[planetag];
} else {
newplane = plane.transform(matrix4x4);
transformedplanes[planetag] = newplane;
}
var newvertices = p.vertices.map(function(v) {
var newvertex;
var vertextag = v.getTag();
if(vertextag in transformedvertices) {
newvertex = transformedvertices[vertextag];
} else {
newvertex = v.transform(matrix4x4);
transformedvertices[vertextag] = newvertex;
}
return newvertex;
});
if(ismirror) newvertices.reverse();
return new CSG.Polygon(newvertices, p.shared, newplane);
});
var result = CSG.fromPolygons(newpolygons);
result.properties = this.properties._transform(matrix4x4);
result.isRetesselated = this.isRetesselated;
result.isCanonicalized = this.isCanonicalized;
return result;
},
toStlString: function() {
var result = "solid csg.js\n";
this.polygons.map(function(p) {
result += p.toStlString();
});
result += "endsolid csg.js\n";
return result;
},
toAMFString: function(m) {
var result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<amf"+(m&&m.unit?" unit=\"+m.unit\"":"")+">\n";
for(var k in m) {
result += "<metadata type=\""+k+"\">"+m[k]+"</metadata>\n";
}
result += "<object id=\"0\">\n<mesh>\n<vertices>\n";
this.polygons.map(function(p) { // first we dump all vertices of all polygons
for(var i=0; i<p.vertices.length; i++) {
result += p.vertices[i].toAMFString();
}
});
result += "</vertices>\n";
var n = 0;
this.polygons.map(function(p) { // then we dump all polygons
result += "<volume>\n";
if(p.vertices.length<3)
return;
var r = 1, g = 0.4, b = 1, a = 1, colorSet = false;
if(p.shared && p.shared.color) {
r = p.shared.color[0];
g = p.shared.color[1];
b = p.shared.color[2];
a = p.shared.color[3];
colorSet = true;
} else if(p.color) {
r = p.color[0];
g = p.color[1];
b = p.color[2];
if(p.color.length()>3) a = p.color[3];
colorSet = true;
}
result += "<color><r>"+r+"</r><g>"+g+"</g><b>"+b+"</b>"+(a!==undefined?"<a>"+a+"</a>":"")+"</color>";
for(var i=0; i<p.vertices.length-2; i++) { // making sure they are all triangles (triangular polygons)
result += "<triangle>";
result += "<v1>" + (n) + "</v1>";
result += "<v2>" + (n+i+1) + "</v2>";
result += "<v3>" + (n+i+2) + "</v3>";
result += "</triangle>\n";
}
n += p.vertices.length;
result += "</volume>\n";
});
result += "</mesh>\n</object>\n";
result += "</amf>\n";
return result;
},
toX3D: function() {
// materialPolygonLists
// key: a color string (e.g. "0 1 1" for yellow)
// value: an array of strings specifying polygons of this color
// (as space-separated indices into vertexCoords)
var materialPolygonLists = {},
// list of coordinates (as "x y z" strings)
vertexCoords = [],
// map to look up the index in vertexCoords of a given vertex
vertexTagToCoordIndexMap = {};
this.polygons.map(function(p) {
var red = 0,
green = 0,
blue = 1; // default color is blue
if(p.shared && p.shared.color) {
red = p.shared.color[0];
green = p.shared.color[1];
blue = p.shared.color[2];
}
var polygonVertexIndices = [],
numvertices = p.vertices.length,
vertex;
for(var i = 0; i < numvertices; i++) {
vertex = p.vertices[i];
if(!(vertex.getTag() in vertexTagToCoordIndexMap)) {
vertexCoords.push(vertex.pos._x.toString() + " " +
vertex.pos._y.toString() + " " +
vertex.pos._z.toString()
);
vertexTagToCoordIndexMap[vertex.getTag()] = vertexCoords.length - 1;
}
polygonVertexIndices.push(vertexTagToCoordIndexMap[vertex.getTag()]);
}
var polygonString = polygonVertexIndices.join(" ");
var colorString = red.toString() + " " + green.toString() + " " + blue.toString();
if(!(colorString in materialPolygonLists)) {
materialPolygonLists[colorString] = [];
}
// add this polygonString to the list of colorString-colored polygons
materialPolygonLists[colorString].push(polygonString);
});
// create output document
var docType = document.implementation.createDocumentType("X3D",
'ISO//Web3D//DTD X3D 3.1//EN" "http://www.web3d.org/specifications/x3d-3.1.dtd', null);
var exportDoc = document.implementation.createDocument(null, "X3D", docType);
exportDoc.insertBefore(
exportDoc.createProcessingInstruction('xml', 'version="1.0" encoding="UTF-8"'),
exportDoc.doctype);
var exportRoot = exportDoc.getElementsByTagName("X3D")[0];
exportRoot.setAttribute("profile", "Interchange");
exportRoot.setAttribute("version", "3.1");
exportRoot.setAttribute("xsd:noNamespaceSchemaLocation","http://www.web3d.org/specifications/x3d-3.1.xsd");
exportRoot.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema-instance");
var exportScene = exportDoc.createElement("Scene");
exportRoot.appendChild(exportScene);
/*
For each color, create a shape made of an appropriately colored
material which contains all polygons that are this color.
The first shape will contain the definition of all vertices,
(<Coordinate DEF="coords_mesh"/>), which will be referenced by
subsequent shapes.
*/
var coordsMeshDefined = false;
for(var colorString in materialPolygonLists) {
var polygonList = materialPolygonLists[colorString];
var shape = exportDoc.createElement("Shape");
exportScene.appendChild(shape);
var appearance = exportDoc.createElement("Appearance");
shape.appendChild(appearance);
var material = exportDoc.createElement("Material");
appearance.appendChild(material);
material.setAttribute("diffuseColor", colorString);
material.setAttribute("ambientIntensity", "1.0");
var ifs = exportDoc.createElement("IndexedFaceSet");
shape.appendChild(ifs);
ifs.setAttribute("solid", "true");
ifs.setAttribute("coordIndex", polygonList.join(" -1 ") + " -1");
var coordinate = exportDoc.createElement("Coordinate");
ifs.appendChild(coordinate);
if(coordsMeshDefined) {
coordinate.setAttribute("USE", "coords_mesh");
} else {
coordinate.setAttribute("DEF", "coords_mesh");
coordinate.setAttribute("point", vertexCoords.join(" "));
coordsMeshDefined = true;
}
}
var x3dstring = (new XMLSerializer()).serializeToString(exportDoc);
return new Blob([x3dstring], {
type: "model/x3d+xml"
});
},
// see http://en.wikipedia.org/wiki/STL_%28file_format%29#Binary_STL
toStlBinary: function(p) {
// first check if the host is little-endian:
var buffer = new ArrayBuffer(4);
var int32buffer = new Int32Array(buffer, 0, 1);
var int8buffer = new Int8Array(buffer, 0, 4);
int32buffer[0] = 0x11223344;
if(int8buffer[0] != 0x44) {
throw new Error("Binary STL output is currently only supported on little-endian (Intel) processors");
}
var numtriangles = 0;
this.polygons.map(function(p) {
var numvertices = p.vertices.length;
var thisnumtriangles = (numvertices >= 3) ? numvertices - 2 : 0;
numtriangles += thisnumtriangles;
});
var headerarray = new Uint8Array(80);
for(var i = 0; i < 80; i++) {
headerarray[i] = 65;
}
var ar1 = new Uint32Array(1);
ar1[0] = numtriangles;
// write the triangles to allTrianglesBuffer:
var allTrianglesBuffer = new ArrayBuffer(50 * numtriangles);
var allTrianglesBufferAsInt8 = new Int8Array(allTrianglesBuffer);
// a tricky problem is that a Float32Array must be aligned at 4-byte boundaries (at least in certain browsers)
// while each triangle takes 50 bytes. Therefore we write each triangle to a temporary buffer, and copy that
// into allTrianglesBuffer:
var triangleBuffer = new ArrayBuffer(50);
var triangleBufferAsInt8 = new Int8Array(triangleBuffer);
// each triangle consists of 12 floats:
var triangleFloat32array = new Float32Array(triangleBuffer, 0, 12);
// and one uint16:
var triangleUint16array = new Uint16Array(triangleBuffer, 48, 1);
var byteoffset = 0;
this.polygons.map(function(p) {
var numvertices = p.vertices.length;
for(var i = 0; i < numvertices - 2; i++) {
var normal = p.plane.normal;
triangleFloat32array[0] = normal._x;
triangleFloat32array[1] = normal._y;
triangleFloat32array[2] = normal._z;
var arindex = 3;
for(var v = 0; v < 3; v++) {
var vv = v + ((v > 0) ? i : 0);
var vertexpos = p.vertices[vv].pos;
triangleFloat32array[arindex++] = vertexpos._x;
triangleFloat32array[arindex++] = vertexpos._y;
triangleFloat32array[arindex++] = vertexpos._z;
}
triangleUint16array[0] = 0;
// copy the triangle into allTrianglesBuffer:
allTrianglesBufferAsInt8.set(triangleBufferAsInt8, byteoffset);
byteoffset += 50;
}
});
if(p&&p.webBlob) { // -- want a blob direct
return new Blob([headerarray.buffer, ar1.buffer, allTrianglesBuffer], {
type: "application/sla"
});
} else {
// we differentiate, as binary string blobbing gives bad blob in web, we need binary string for CLI
// perhaps there is a way to make it working (see openjscad for stlb)\
//
// concat 3 buffers together -- don't make blob so early, we want data (non-blob) for nodejs too
// must be string data direct to write
var stl = new Uint8Array(headerarray.buffer.byteLength + ar1.buffer.byteLength + allTrianglesBuffer.byteLength);
var j = 0;
for(i=0; i<headerarray.buffer.byteLength; i++) { stl.buffer[j++] = headerarray.buffer[i]; }
for(i=0; i<ar1.buffer.byteLength; i++) { stl.buffer[j++] = ar1.buffer[i]; }
for(i=0; i<allTrianglesBuffer.byteLength; i++) { stl.buffer[j++] = allTrianglesBuffer[i]; }
return String.fromCharCode.apply(null, new Uint8Array(stl.buffer));
}
},
toString: function() {
var result = "CSG solid:\n";
this.polygons.map(function(p) {
result += p.toString();
});
return result;
},
center: function(c) {
if(!c.length) c = [c,c,c];
var b = this.getBounds();
return this.translate([
c[0]?-(b[1].x-b[0].x)/2-b[0].x:0,
c[1]?-(b[1].y-b[0].y)/2-b[0].y:0,
c[2]?-(b[1].z-b[0].z)/2-b[0].z:0]);
},
// Expand the solid
// resolution: number of points per 360 degree for the rounded corners
expand: function(radius, resolution) {
var result = this.expandedShell(radius, resolution, true);
result = result.reTesselated();
result.properties = this.properties; // keep original properties
return result;
},
// Contract the solid
// resolution: number of points per 360 degree for the rounded corners
contract: function(radius, resolution) {
var expandedshell = this.expandedShell(radius, resolution, false);
var result = this.subtract(expandedshell);
result = result.reTesselated();
result.properties = this.properties; // keep original properties
return result;
},
// Create the expanded shell of the solid:
// All faces are extruded to get a thickness of 2*radius
// Cylinders are constructed around every side
// Spheres are placed on every vertex
// unionWithThis: if true, the resulting solid will be united with 'this' solid;
// the result is a true expansion of the solid
// If false, returns only the shell
expandedShell: function(radius, resolution, unionWithThis) {
var i, iMax;
var csg = this.reTesselated();
var result;
var angle;
var si, co;
if(unionWithThis) {
result = csg;
} else {
result = new CSG();
}
// first extrude all polygons:
csg.polygons.map(function(polygon) {
var extrudevector = polygon.plane.normal.unit().times(2 * radius);
var translatedpolygon = polygon.translate(extrudevector.times(-0.5));
var extrudedface = translatedpolygon.extrude(extrudevector);
result = result.unionSub(extrudedface, false, false);
});
// Make a list of all unique vertex pairs (i.e. all sides of the solid)
// For each vertex pair we collect the following:
// v1: first coordinate
// v2: second coordinate
// planenormals: array of normal vectors of all planes touching this side
var vertexpairs = {}; // map of 'vertex pair tag' to {v1, v2, planenormals}
csg.polygons.map(function(polygon) {
var numvertices = polygon.vertices.length;
var prevvertex = polygon.vertices[numvertices - 1];
var prevvertextag = prevvertex.getTag();
for(i = 0; i < numvertices; i++) {
var vertex = polygon.vertices[i];
var vertextag = vertex.getTag();
var vertextagpair;
if(vertextag < prevvertextag) {
vertextagpair = vertextag + "-" + prevvertextag;
} else {
vertextagpair = prevvertextag + "-" + vertextag;
}
var obj;
if(vertextagpair in vertexpairs) {
obj = vertexpairs[vertextagpair];
} else {
obj = {
v1: prevvertex,
v2: vertex,
planenormals: []
};
vertexpairs[vertextagpair] = obj;
}
obj.planenormals.push(polygon.plane.normal);
prevvertextag = vertextag;
prevvertex = vertex;
}
});
// now construct a cylinder on every side
// The cylinder is always an approximation of a true cylinder: it will have <resolution> polygons
// around the sides. We will make sure though that the cylinder will have an edge at every
// face that touches this side. This ensures that we will get a smooth fill even
// if two edges are at, say, 10 degrees and the resolution is low.
// Note: the result is not retesselated yet but it really should be!
for(var vertextagpair in vertexpairs) {
var vertexpair = vertexpairs[vertextagpair],
startpoint = vertexpair.v1.pos,
endpoint = vertexpair.v2.pos,
// our x,y and z vectors:
zbase = endpoint.minus(startpoint).unit(),
xbase = vertexpair.planenormals[0].unit(),
ybase = xbase.cross(zbase),
// make a list of angles that the cylinder should traverse:
angles = [];
// first of all equally spaced around the cylinder:
for(i = 0; i < resolution; i++) {
angles.push(i * Math.PI * 2 / resolution);
}
// and also at every normal of all touching planes:
for(i = 0, iMax = vertexpair.planenormals.length; i < iMax; i++) {
var planenormal = vertexpair.planenormals[i];
si = ybase.dot(planenormal);
co = xbase.dot(planenormal);
angle = Math.atan2(si, co);
if(angle < 0) angle += Math.PI * 2;
angles.push(angle);
angle = Math.atan2(-si, -co);
if(angle < 0) angle += Math.PI * 2;
angles.push(angle);
}
// this will result in some duplicate angles but we will get rid of those later.
// Sort:
angles = angles.sort(fnNumberSort);
// Now construct the cylinder by traversing all angles:
var numangles = angles.length,
prevp1, prevp2, p,
startfacevertices = [],
endfacevertices = [],
polygons = [];
for(i = -1; i < numangles; i++) {
angle = angles[(i < 0) ? (i + numangles) : i];
si = Math.sin(angle);
co = Math.cos(angle);
p = xbase.times(co * radius).plus(ybase.times(si * radius)),
p1 = startpoint.plus(p),
p2 = endpoint.plus(p),
skip = false;
if(i >= 0) {
if(p1.distanceTo(prevp1) < 1e-5) {
skip = true;
}
}
if(!skip) {
if(i >= 0) {
startfacevertices.push(new CSG.Vertex(p1));
endfacevertices.push(new CSG.Vertex(p2));
var polygonvertices = [
new CSG.Vertex(prevp2),
new CSG.Vertex(p2),
new CSG.Vertex(p1),
new CSG.Vertex(prevp1)];
var polygon = new CSG.Polygon(polygonvertices);
polygons.push(polygon);
}
prevp1 = p1;
prevp2 = p2;
}
}
endfacevertices.reverse();
polygons.push(new CSG.Polygon(startfacevertices));
polygons.push(new CSG.Polygon(endfacevertices));
var cylinder = CSG.fromPolygons(polygons);
result = result.unionSub(cylinder, false, false);
}
// make a list of all unique vertices
// For each vertex we also collect the list of normals of the planes touching the vertices
var vertexmap = {};
csg.polygons.map(function(polygon) {
polygon.vertices.map(function(vertex) {
var vertextag = vertex.getTag();
var obj;
if(vertextag in vertexmap) {
obj = vertexmap[vertextag];
} else {
obj = {
pos: vertex.pos,
normals: []
};
vertexmap[vertextag] = obj;
}
obj.normals.push(polygon.plane.normal);
});
});
// and build spheres at each vertex
// We will try to set the x and z axis to the normals of 2 planes
// This will ensure that our sphere tesselation somewhat matches 2 planes
for(var vertextag in vertexmap) {
var vertexobj = vertexmap[vertextag];
// use the first normal to be the x axis of our sphere:
var xaxis = vertexobj.normals[0].unit();
// and find a suitable z axis. We will use the normal which is most perpendicular to the x axis:
var bestzaxis = null;
var bestzaxisorthogonality = 0;
for(i = 1; i < vertexobj.normals.length; i++) {
var normal = vertexobj.normals[i].unit();
var cross = xaxis.cross(normal);
var crosslength = cross.length();
if(crosslength > 0.05) {
if(crosslength > bestzaxisorthogonality) {
bestzaxisorthogonality = crosslength;
bestzaxis = normal;
}
}
}
if(!bestzaxis) {
bestzaxis = xaxis.randomNonParallelVector();
}
var yaxis = xaxis.cross(bestzaxis).unit();
var zaxis = yaxis.cross(xaxis);
var sphere = CSG.sphere({
center: vertexobj.pos,
radius: radius,
resolution: resolution,
axes: [xaxis, yaxis, zaxis]
});
result = result.unionSub(sphere, false, false);
}
return result;
},
canonicalized: function() {
if(this.isCanonicalized) {
return this;
} else {
var factory = new CSG.fuzzyCSGFactory();
var result = factory.getCSG(this);
result.isCanonicalized = true;
result.isRetesselated = this.isRetesselated;
result.properties = this.properties; // keep original properties
return result;
}
},
reTesselated: function() {
if(this.isRetesselated) {
return this;
} else {
var csg = this.canonicalized();
var polygonsPerPlane = {};
csg.polygons.map(function(polygon) {
var planetag = polygon.plane.getTag();
var sharedtag = polygon.shared.getTag();
planetag += "/" + sharedtag;
if(!(planetag in polygonsPerPlane)) {
polygonsPerPlane[planetag] = [];
}
polygonsPerPlane[planetag].push(polygon);
});
var destpolygons = [];
for(var planetag in polygonsPerPlane) {
var sourcepolygons = polygonsPerPlane[planetag];
if(sourcepolygons.length < 2) {
destpolygons = destpolygons.concat(sourcepolygons);
} else {
var retesselayedpolygons = [];
CSG.reTesselateCoplanarPolygons(sourcepolygons, retesselayedpolygons);
destpolygons = destpolygons.concat(retesselayedpolygons);
}
}
var result = CSG.fromPolygons(destpolygons);
result.isRetesselated = true;
result = result.canonicalized();
// result.isCanonicalized = true;
result.properties = this.properties; // keep original properties
return result;
}
},
// returns an array of two CSG.Vector3Ds (minimum coordinates and maximum coordinates)
getBounds: function() {
if(!this.cachedBoundingBox) {
var minpoint = new CSG.Vector3D(0, 0, 0);
var maxpoint = new CSG.Vector3D(0, 0, 0);
var polygons = this.polygons;
var numpolygons = polygons.length;
for(var i = 0; i < numpolygons; i++) {
var polygon = polygons[i];
var bounds = polygon.boundingBox();
if(i === 0) {
minpoint = bounds[0];
maxpoint = bounds[1];
} else {
minpoint = minpoint.min(bounds[0]);
maxpoint = maxpoint.max(bounds[1]);
}
}
this.cachedBoundingBox = [minpoint, maxpoint];
}
return this.cachedBoundingBox;
},
// returns true if there is a possibility that the two solids overlap
// returns false if we can be sure that they do not overlap
mayOverlap: function(csg) {
if((this.polygons.length === 0) || (csg.polygons.length === 0)) {
return false;
} else {
var mybounds = this.getBounds();
var otherbounds = csg.getBounds();
// [0].x/y
// +-----+
// | |
// | |
// +-----+
// [1].x/y
//return false;
//echo(mybounds,"=",otherbounds);
if(mybounds[1].x < otherbounds[0].x) return false;
if(mybounds[0].x > otherbounds[1].x) return false;
if(mybounds[1].y < otherbounds[0].y) return false;
if(mybounds[0].y > otherbounds[1].y) return false;
if(mybounds[1].z < otherbounds[0].z) return false;
if(mybounds[0].z > otherbounds[1].z) return false;
return true;
}
},
// Cut the solid by a plane. Returns the solid on the back side of the plane
cutByPlane: function(plane) {
if(this.polygons.length === 0) {
return new CSG();
}