-
Notifications
You must be signed in to change notification settings - Fork 676
/
Copy pathbasic-cad-tool-merge-lines.js
341 lines (307 loc) · 11.3 KB
/
basic-cad-tool-merge-lines.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
// Note to self. Select "line" items in Doc tree > run addMergedLines
// No tolerance yet
// operator has to select lines that belong to the same "shape"
// manually - sorted needs to learn to find all that has matching start/end - then reprocess remainders again creating multiple polylines as it goes so you
// can even use Select All, it should filter for 2-point vectors (lines), etc
function addMergedLines() {
// var lines = []
var toolpath = new THREE.Group();
for (i = 0; i < objectsInScene.length; i++) {
var obj = objectsInScene[i];
obj.traverse(function(child) {
if (child.userData.selected) {
var copy = child.clone()
//console.log("copy:", copy)
if (copy.geometry.vertices.length < 3) {
copy.userData.closed = false
} else if (copy.geometry.vertices.length > 2) {
var d = distanceFormula(copy.geometry.vertices[0].x, copy.geometry.vertices[copy.geometry.vertices.length - 1].x, copy.geometry.vertices[0].y, copy.geometry.vertices[copy.geometry.vertices.length - 1].y)
console.log(d)
if (d < 0.1) {
copy.userData.closed = true
} else {
copy.userData.closed = false
}
}
copy.position.copy(obj.position);
toolpath.add(copy);
// lines.push(copy)
}
});
};
// get it as Clipper paths
var newClipperPaths = getClipperPaths(toolpath);
console.log(JSON.stringify(newClipperPaths))
var sortedPaths = sortClipperPaths(newClipperPaths)
console.log(JSON.stringify(sortedPaths))
var fileObject = new THREE.Group();
// Create a new geometry
var mergedGeometry = new THREE.Geometry();
sortedPaths.forEach(function(coord) {
mergedGeometry.vertices.push(new THREE.Vector3(coord.X, coord.Y, 0));
});
// add geometry
var material = new THREE.MeshBasicMaterial({
color: 0xffff00,
side: THREE.DoubleSide
});
var mergedPath = new THREE.Line(mergedGeometry, material);
mergedPath.name = "Merged Lines"
fileObject.add(mergedPath);
fileObject.name = "Merged Lines" + Math.random()
objectsInScene.push(fileObject)
setTimeout(function() {
fillTree();
changePositionToGeoTranslate();
resetView();
}, 250);
}
// function sortClipperPath(clipperPath) {
// // Create a map to store the starting and ending points of each segment
// const startPoints = new Map();
// const endPoints = new Map();
//
// // Iterate through each segment and store their start and end points
// clipperPath.forEach(segment => {
// console.log(segment)
// const startPoint = segment[0];
// const endPoint = segment[1];
//
// const startPointKey = `${startPoint.X},${startPoint.Y}`;
// const endPointKey = `${endPoint.X},${endPoint.Y}`;
//
// // Store start and end points in respective maps
// if (!startPoints.has(startPointKey)) {
// startPoints.set(startPointKey, segment);
// }
// if (!endPoints.has(endPointKey)) {
// endPoints.set(endPointKey, segment);
// }
// });
//
// // Reorder the segments to form a continuous path
// const sortedPath = [];
// let currentSegment = clipperPath[0];
// sortedPath.push(currentSegment);
// clipperPath.splice(0, 1); // Remove the first segment from the original array
//
// while (clipperPath.length > 0) {
// const endPoint = currentSegment[1];
// const endPointKey = `${endPoint.X},${endPoint.Y}`;
//
// // Find the next segment whose start point matches the current segment's end point
// const nextSegment = startPoints.get(endPointKey);
//
// // If next segment is found, add it to the sorted path and remove it from the original array
// if (nextSegment) {
// sortedPath.push(nextSegment);
// clipperPath.splice(clipperPath.indexOf(nextSegment), 1);
// currentSegment = nextSegment;
// } else {
// // If no next segment is found, break the loop
// break;
// }
// }
//
// // Flatten the sorted path into a single array
// const flattenedPath = sortedPath.reduce((acc, segment) => {
// acc.push(segment[0], segment[1]);
// return acc;
// }, []);
//
// return flattenedPath;
// }
// function sortClipperPath(clipperPath, threshold = 0.1) {
// // Create a map to store the starting and ending points of each segment
// const startPoints = new Map();
// const endPoints = new Map();
//
// // Helper function to check if two points are approximately equal within the threshold
// const arePointsApproximatelyEqual = (point1, point2) => {
// return Math.abs(point1.X - point2.X) < threshold && Math.abs(point1.Y - point2.Y) < threshold;
// };
//
// // Iterate through each segment and store their start and end points
// clipperPath.forEach(segment => {
// const startPoint = segment[0];
// const endPoint = segment[1];
//
// const startPointKey = `${startPoint.X},${startPoint.Y}`;
// const endPointKey = `${endPoint.X},${endPoint.Y}`;
//
// // Store start and end points in respective maps
// if (!startPoints.has(startPointKey)) {
// startPoints.set(startPointKey, segment);
// }
// if (!endPoints.has(endPointKey)) {
// endPoints.set(endPointKey, segment);
// }
// });
//
// // Reorder the segments to form a continuous path
// const sortedPath = [];
// let currentSegment = clipperPath[0];
// sortedPath.push(currentSegment);
// clipperPath.splice(0, 1); // Remove the first segment from the original array
//
// while (clipperPath.length > 0) {
// const endPoint = currentSegment[1];
// const endPointKey = `${endPoint.X},${endPoint.Y}`;
//
// // Find the next segment whose start point approximately matches the current segment's end point
// let nextSegment = null;
// for (const [key, segment] of startPoints) {
// const startPoint = segment[0];
// if (arePointsApproximatelyEqual(startPoint, endPoint)) {
// nextSegment = segment;
// break;
// }
// }
//
// // If next segment is found, add it to the sorted path and remove it from the original array
// if (nextSegment) {
// sortedPath.push(nextSegment);
// clipperPath.splice(clipperPath.indexOf(nextSegment), 1);
// currentSegment = nextSegment;
// } else {
// // If no next segment is found, break the loop
// break;
// }
// }
//
// // Flatten the sorted path into a single array
// const flattenedPath = sortedPath.reduce((acc, segment) => {
// acc.push(segment[0], segment[1]);
// return acc;
// }, []);
//
// return flattenedPath;
// }
function sortClipperPaths(clipperPaths, threshold = 0.1) {
// Create a map to store the starting and ending points of each segment
const startPoints = new Map();
const endPoints = new Map();
// Helper function to check if two points are approximately equal within the threshold
const arePointsApproximatelyEqual = (point1, point2) => {
return point1 && point2 && Math.abs(point1.X - point2.X) < threshold && Math.abs(point1.Y - point2.Y) < threshold;
};
// Populate startPoints and endPoints maps for all segments
clipperPaths.forEach(path => {
path.forEach(segment => {
const startPoint = segment[0];
const endPoint = segment[1];
const startPointKey = startPoint ? `${startPoint.X},${startPoint.Y}` : null;
const endPointKey = endPoint ? `${endPoint.X},${endPoint.Y}` : null;
// Store start and end points in respective maps
if (startPointKey && !startPoints.has(startPointKey)) {
startPoints.set(startPointKey, segment);
}
if (endPointKey && !endPoints.has(endPointKey)) {
endPoints.set(endPointKey, segment);
}
});
});
// Reorder the segments to form continuous paths
const sortedPaths = [];
// Function to find the closest unmatched point
const findClosestUnmatchedPoint = (point, pointsMap, usedSegments) => {
let closestDistance = Infinity;
let closestSegment = null;
for (const [key, segment] of pointsMap) {
if (!usedSegments.has(segment)) {
const startPoint = segment[0];
if (!startPoint) continue; // Skip if startPoint is undefined
const distance = Math.sqrt(Math.pow(startPoint.X - point.X, 2) + Math.pow(startPoint.Y - point.Y, 2));
if (distance < closestDistance) {
closestDistance = distance;
closestSegment = segment;
}
}
}
return closestSegment;
};
// Iterate through each path
clipperPaths.forEach(path => {
const usedSegments = new Set(); // Tracks used segments in the current path
const sortedPath = [];
let currentSegment = path[0];
sortedPath.push(currentSegment);
usedSegments.add(currentSegment);
// Process each segment in the path
while (sortedPath.length < path.length) {
const endPoint = currentSegment[1];
if (!endPoint) break; // Exit loop if endPoint is undefined
const endPointKey = `${endPoint.X},${endPoint.Y}`;
// Find the next segment whose start point approximately matches the current segment's end point
let nextSegment = null;
if (startPoints.has(endPointKey)) {
nextSegment = startPoints.get(endPointKey);
} else {
// If no exact match found, find the closest unmatched point
nextSegment = findClosestUnmatchedPoint(endPoint, startPoints, usedSegments);
}
// If next segment is found, add it to the sorted path
if (nextSegment) {
sortedPath.push(nextSegment);
usedSegments.add(nextSegment);
currentSegment = nextSegment;
} else {
// If no next segment is found, break the loop
break;
}
}
sortedPaths.push(sortedPath);
});
// Flatten the sorted paths into single arrays
const flattenedPaths = sortedPaths.map(path => {
return path.reduce((acc, segment) => {
acc.push(segment[0], segment[1]);
return acc;
}, []);
});
return flattenedPaths;
}
function tryFixGeometry(object) {
getClipperPaths(object)
console.log("Clipper Path", JSON.stringify(clipperPaths));
var sortedPaths = sortClipperPath(clipperPaths)
console.log("Clipper Path", JSON.stringify(sortedPaths));
return sortedPaths
}
function getClipperPaths(object) {
object.updateMatrix();
var grp = object;
var clipperPaths = [];
grp.traverse(function(child) {
// console.log('Traverse: ', child)
if (child.name == "inflatedGroup") {
console.log("this is the inflated path from a previous run. ignore.");
return;
} else if (child.type == "Line") {
// let's inflate the path for this line. it may not be closed
// so we need to check that.
var clipperArr = [];
// Fix world Coordinates
for (j = 0; j < child.geometry.vertices.length; j++) {
var localPt = child.geometry.vertices[j];
var worldPt = child.localToWorld(localPt.clone());
var xpos = worldPt.x; // + (sizexmax /2);
var ypos = worldPt.y; // + (sizeymax /2);
var xpos_offset = (parseFloat(child.position.x.toFixed(3)));
var ypos_offset = (parseFloat(child.position.y.toFixed(3)));
if (child.geometry.type == "CircleGeometry") {
xpos = (xpos + xpos_offset);
ypos = (ypos + ypos_offset);
}
clipperArr.push({
X: xpos,
Y: ypos
});
}
clipperPaths.push(clipperArr);
} else {
// console.log("type of ", child.type, " being skipped");
}
});
return clipperPaths
}