-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsquash_groups.js
350 lines (228 loc) · 8.5 KB
/
squash_groups.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
var shapes = require('svg-path-shapes')
var normalize = require('normalize-svg-path')
var parse = require('parse-svg-path')
var _ = require('lodash')
var simplify = require('simplify-js')
var cheerio = require('cheerio')
var minimist = require('minimist')
var abs = require('abs-svg-path')
var thr = require('throw')
var fs = require('fs');
const pointDistance = require("point-distance");
const { count } = require('console')
//Getting the filename arg
var argv = minimist(process.argv.slice(2))
var argv = require('minimist')(process.argv.slice(2))
var args = argv._
var opts = _.omit(argv, '_')
var fileName = args[0];
if(fileName == '' || fileName == undefined) thr('Enter a relative file path')
var bezierOutput = (opts.b ? true : false)
//Hardcoded filepath, to be replaced with command line arguments
var filePath = __dirname + '/' + fileName
//1. Get all GROUP elements within the file
//2. For each group element
//3. Gather array of all PATH elements
//4. For each path element
//5 Retain each color & width - Should all be the same per group
//6. Separate each path from multipath <path> elements
//7 When collecting path array elements, gather START XY and END XY
//8. Create a new path element with every subpath from the group
//9. Apply color / width to new single path element
//10. Output SVG of single elements
let groups = parseSVGGroups(filePath);
let output = parseGroupPaths(groups);
//console.log(groups);
//console.log(output);
console.log('done');
//Old Logic Series
//var svgPaths = parseSVGPaths(filePath)
//var seperatedPaths = seperatePaths(svgPaths)
//console.log(wrapSVG(seperatedPaths))
//Takes in multi-shape path(s) and outputs an array of paths
function seperatePaths(paths){
var pathElements = [];
_(paths).forEach(function(layer){
_(shapes(layer)).forEach(function(shape){
var pathPoints = _.reduce(parse(shape), function (items, points) {
//if(points[0] == 'M') items.push({ x: values[0], y: values[1]})
if(points[0].toUpperCase() == 'M'){
//console.log('m path')
items.push('M' + points.slice(1))
}
else if(points[0].toUpperCase() == 'C'){
//console.log('c path')
items.push('C' + points.slice(1))
}
else if(points[0].toUpperCase() == 'L'){
//console.log('c path')
items.push('L' + points.slice(1))
}
else if(points[0].toUpperCase() == 'Z') items.push(['Z'])
else {
console.log('Unsupported SVG path token')
console.log(points)
process.exit()
}
return items
}, [])
pathElements.push(_.join(pathPoints,' '))
}) // end foreach multipath shapes
}) // end foreach path
return pathElements
}
//Wraps the pathData array of x,y coords in a line or bezier <path> element
function wrapPath(pathData){
var linePathString = pointPath(pathData)
//console.log(pathData);
//console.log(pathPointsToBezier(pathDataString))
var pathDataString = (bezierOutput ? pathStringToBezier(linePathString) : linePathString)
return '<path d="' + pathDataString + '" stroke="#000000" fill="none"/>'
}
function simpleWrapPath(pathString){
return '<path d="' + pathString + '" stroke="#000000" fill="none"/>'
}
function wrapSVG(paths){
var strOutput = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
strOutput += '<svg id="workspace" xmlns="http://www.w3.org/2000/svg" version="1.1">'
_(paths).forEach(function(element){
strOutput += simpleWrapPath(element)
})
strOutput += '</svg>'
return strOutput
}
//Takes in an SVG file, returns an array of paths elements
function parseSVGPaths(filePath){
$ = cheerio.load(fs.readFileSync(filePath));
var paths = _.reduce($('path'), function (items, path) {
items.push($(path).attr('d'))
return items
}, [])
return paths
}
//Takes in an array of path objects including first, last and coord pieces
//For each element in the array (choose active shape, first item sequentially in list)
//Store LAST point (x,y) of the active shape
//Add LAST path to the top of the stack
//Iterate through all other items
//Compare the distance from last point of active shape to first/last of the next FIFO shape in the array
//https://www.npmjs.com/package/point-distance
//For the shape with the lowest distance score from ACTIVE LAST X,Y to NEXT SHAPE X,Y
//Add shape to the top of the stack, set shape to be active shape, remove shape from array of items for next cycle
function orderPaths(paths){
let newPathArray = [];
//let activePath = _.first(paths); //first path of pathArray
//_.drop(paths[0]); // remove first item
let activePath = paths[0];
let pathStack = _.without(paths, paths[0]);
let nextPath = findClosestPath(activePath, pathStack);
}
function findClosestPath(targetPath,pathArray){
let targetPathCoords = targetPath.first.split(',');
// let targetPathX = parseFloat(targetPathCoords[0]);
// let targetPathY = parseFloat(targetPathCoords[1]);
let targetXY = [parseFloat(targetPathCoords[0]), parseFloat(targetPathCoords[1])];
let pathScores = _.map(pathArray, (eachPath) => {
//make sure duplicate paths not being processed
if(eachPath.d !== targetPath.d){
let eachPathCoordsStart = eachPath.first.split(',');
let eachPathCoordsEnd = eachPath.last.split(',');
let eachStartXY = [parseFloat(eachPathCoordsStart[0]), parseFloat(eachPathCoordsStart[1])];
let eachEndXY = [parseFloat(eachPathCoordsEnd[0]), parseFloat(eachPathCoordsEnd[1])];
let comparisonValues = [targetXY, eachStartXY, eachEndXY];
console.log(comparisonValues,[[1,1],[100,100]]);
let score = {
target: _.omit(targetPath,['d']),
test: _.omit(eachPath,['d']),
//values: comparisonValues,
comparisonValues: comparisonValues,
distanceStart: pointDistance(targetXY, eachStartXY),
distanceEnd: pointDistance(targetXY, eachEndXY)
}
//console.log(eachPath);
//console.log(targetPath);
console.log(score);
return score;
}
}); //end map
console.log(pathScores);
}
//Takes in an array of groups, returns an array of paths elements with color, stroke, first/last
function parseGroupPaths(group){
let pathArray = group.children;
console.log('processing group');
let groupId = $(group).attr('id')
var paths = _.reduce($('path'), function (items, path, key) {
//Trim and explode, then turn multipath pathstrings into array of paths
let pathPieces = _.without(_.split($(path).attr('d'),' '),'')
let separatedPaths = seperatePaths(pathPieces)
let firstPiece = _.first(separatedPaths);
let lastPiece = _.last(separatedPaths);
let pathObj = {
id: `${groupId}-${key}`,
//separated: separatedPaths,
points: separatedPaths.length,
d: $(path).attr('d'),
stroke: $(path).attr('stroke'),
strokeWidth: $(path).attr('stroke-width'),
first: firstPiece.replace(/[A-Z]+/,''),
last: lastPiece.replace(/[A-Z]+/,''),
}
//console.log(pathObj)
//process.exit();
items.push(pathObj);
return items
}, [])
//Collect all groups paths together into one array
// let groupPaths = _.reduce(paths, function(allPaths, group){
// //console.log(group.separated);
// //allPaths.push(group.separated);
// //return allPaths;
// })
//Arrange paths in sequence optimal for pen plotter
let orderedPaths = orderPaths(paths);
let groupObj = {
strokeColor : paths[0].stroke,
strokeWidth : paths[0].strokeWidth,
paths: paths
}
//console.log(groupObj);
process.exit();
return paths
}
//Takes in an SVG file, returns an array of paths elements
function parseSVGGroups(filepath){
$ = cheerio.load(fs.readFileSync(filepath));
var groups = _.reduce($('g'), function (items, group) {
//console.log(group);
items.push(group)
return items
}, [])
return groups
}
function pointPath(pathPointsArr){
console.log(pathPointsArr)
process.exit()
var pathDataString = 'M ' + pathPointsArr[0].x + ' ' + pathPointsArr[0].y + ' '
_(pathPointsArr.slice(1)).forEach(function(element){
console.log('element')
console.log(element)
pathDataString += ' L ' + element.x + ' ' + element.y + ' '
})
console.log(pathDataString)
console.log('debugg')
process.exit()
return pathDataString
}
function pathStringToBezier(pathPointString){
var pathPieces = _.without(_.split(pathPointString,' '),'')
var pathChunks = abs(_.chunk(pathPieces,3))
var bezierPathArr = normalize(pathChunks)
var bezierPathString = ''
_(bezierPathArr).forEach(function(element){
bezierPathString += ' ' + _.join(element,' ')
});
//var bezierPathString = _.join([bezierPathArr],' ')
//return _.replace(bezierPathString,',',' ')
return bezierPathString
}