-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch-voronoi-manhattan.js
362 lines (317 loc) · 13.6 KB
/
sketch-voronoi-manhattan.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
// npx canvas-sketch-cli sketch-voronoi-manhattan.js --open --output=export/
//const clustering = require('density-clustering');
//const convexHull = require('convex-hull');
const canvasSketch = require('canvas-sketch');
const load = require('load-asset');
const loadsvg = require('load-svg');
const segments = require('svg-line-segments');
const linearize = require('svg-linearize');
const { polylinesToSVG } = require('canvas-sketch-util/penplot');
import { generatePoints, segmentsEqual, pointsEqual, addSegmentsFromPolys,
getBMPColor, pointInBMPMask, findMedianDir, directionFromTo, intersectEdges, fitLinesToCanvas } from "./utils.js";
import { voronoiPolysFromPointsAndMask } from "./utils-voronoi.js";
import { fillManhNodesPoints, fillManhCellsLines } from "./utils-manh-voronoi.js";
import { generateL1Voronoi } from "./libs/voronoi.js";
import { config } from "./config.js";
const lines = [];
let manhAllPointsSeed;
const generateManhattanVoronoi = (width, height) => {
manhAllPointsSeed = generatePoints(config.showManh ? config.randomPointsCount : 0, width, height, config.margin);
const manhattan = generateL1Voronoi(manhAllPointsSeed, width, height, true);
manhattan.forEach(mi =>
{
const manhFilteredPolygonPoints = mi.polygonPoints.filter((item, index) => mi.polygonPoints.indexOf(item) == index);
mi.polygonPoints = manhFilteredPolygonPoints;
});
return manhattan;
};
const generateIrisVoronoi = (width, height, bmpMask, eyeOffset) => {
const randomPoints = generatePoints(config.irisVoroGenPointsCount, width, height, config.margin);
const irisMaskFunc = entry => pointInBMPMask(entry, width, height, config.margin, bmpMask, [0], eyeOffset);
const irisPolys = voronoiPolysFromPointsAndMask(randomPoints, width, height, config.margin, irisMaskFunc);
const maskedPoints = randomPoints.filter(entry => pointInBMPMask(entry, width, height, config.margin, bmpMask, [0], eyeOffset));
return { allPoints: randomPoints, maskedPoints: maskedPoints, polys: irisPolys };
};
const addLinesCutWithContourAndMask = (linesToCut, contourLines, maskFunc, linesOut) => {
for (let i = 0; i < linesToCut.length; ++i)
{
let intersection = false;
for (let j = 0; j < contourLines.length; ++j)
{
intersection = intersectEdges(linesToCut[i], contourLines[j]);
if (intersection) break;
}
const p0InMask = maskFunc(linesToCut[i][0]);
const p1InMask = maskFunc(linesToCut[i][1]);
if (!p0InMask && !p1InMask && !intersection)
{
linesOut.push(linesToCut[i]);
}
else if (intersection)
{
if (!p0InMask && p1InMask) linesOut.push([linesToCut[i][0], intersection]);
else if (!p1InMask && p0InMask) linesOut.push([linesToCut[i][1], intersection]);
}
}
};
const distSq = (a, b) =>
{
const d = [a[0] - b[0], a[1] - b[1]];
return d[0]*d[0] + d[1]*d[1];
}
const dist = (a, b) =>
{
return Math.sqrt(distSq(a, b));
}
const fancyIrisMaths = (linesIn, linesOut, tearCenterPolyline, tearMaskFunc) =>
{
const sexyEyeLines = [];
const allPoints = [];
let center = [0, 0];
linesIn.forEach(l => {
allPoints.push(l[0]);
allPoints.push(l[1]);
center[0] += l[0][0];
center[0] += l[1][0];
center[1] += l[0][1];
center[1] += l[1][1];
})
center[0] /= allPoints.length;
center[1] /= allPoints.length;
let maxRSq = 0;
let minRSq = 66666666.1;
allPoints.forEach(p => {
const d = distSq(p, center);
maxRSq = Math.max(maxRSq, d);
minRSq = Math.min(minRSq, d);
});
const rMax = Math.sqrt(maxRSq);
const rMin = Math.sqrt(minRSq);
const r = rMax - rMin;
let edgeCircleDist = 0;
let innerCirclePointsCount = 0;
linesIn.forEach(l => {
const d1 = dist(l[0], center) - rMin;
const d2 = dist(l[1], center) - rMin;
const minD = Math.min(d1, d2);
const maxD = Math.max(d1, d2);
const toCenter = directionFromTo(l[0], center);
const dir = directionFromTo(l[0], l[1]);
const isDirTangent = Math.abs(toCenter[0] * dir[0] + toCenter[1] * dir[1]) < 0.4;
if (isDirTangent && minD > r * 0.4 && maxD < r * 0.66)
{
edgeCircleDist += (d1 + d2);
innerCirclePointsCount += 2;
}
});
edgeCircleDist /= innerCirclePointsCount;
const distToEdge = edgeCircleDist + 0.0 * r;
if (config.debugShowIrisOrigVoro)
{
linesIn.forEach(l => linesOut.push(l));
return;
}
if (config.debugShowIrisOrigVoroCutWithContour || config.debugShowIrisOrigVoroUnmasked)
{
linesIn.forEach(l => sexyEyeLines.push(l));
addLinesCutWithContourAndMask(sexyEyeLines, tearCenterPolyline, tearMaskFunc, linesOut);
return;
}
linesIn.forEach(l => {
const d1 = dist(l[0], center) - rMin;
const d2 = dist(l[1], center) - rMin;
const minD = Math.min(d1, d2);
const maxD = Math.max(d1, d2);
const toCenter1 = directionFromTo(l[0], center);
const toCenter2 = directionFromTo(l[1], center);
const dir = directionFromTo(l[0], l[1]);
const isDirTangent = Math.abs(toCenter1[0] * dir[0] + toCenter1[1] * dir[1]) < 0.4;
const d1ToEdge = Math.abs(d1 - edgeCircleDist);
const d2ToEdge = Math.abs(d2 - edgeCircleDist);
const offsettedP1 = [l[0][0] + toCenter1[0] * distToEdge, l[0][1] + toCenter1[1] * distToEdge - 0.08];
const offsettedP2 = [l[1][0] + toCenter2[0] * distToEdge, l[1][1] + toCenter2[1] * distToEdge - 0.08];
if (isDirTangent && d1ToEdge < r*0.1 && d2ToEdge < r*0.1) // center edge - not needed
{
return;
}
if (d1ToEdge > r * 0.1 && d2ToEdge > r * 0.1 && minD > distToEdge) // outer decor
{
sexyEyeLines.push(l);
return;
}
const rngDist = Math.random() * distToEdge * 0.8;
const outerOffsettedP1 = [
l[0][0] + toCenter1[0] * rngDist,
l[0][1] + toCenter1[1] * rngDist - 0.08
];
const outerOffsettedP2 = [
l[1][0] + toCenter2[0] * rngDist,
l[1][1] + toCenter2[1] * rngDist - 0.08
];
if (minD > distToEdge - 0.1 && maxD > distToEdge + 0.1) // onEdge-outer
{
if (d1 < d2) sexyEyeLines.push([outerOffsettedP1, l[1]]);
else sexyEyeLines.push([outerOffsettedP2, l[0]]);
return;
}
if (maxD < r * 0.4)
{
sexyEyeLines.push(l);
}
});
addLinesCutWithContourAndMask(sexyEyeLines, tearCenterPolyline, tearMaskFunc, linesOut);
};
let eye_contour_svg;
let tear_center_svg;
let tear_edge_svg;
let decor_svg;
loadsvg('assets/eye_contour.svg', async(err, svg) => {
eye_contour_svg = await segments(await linearize(svg, { tolerance: 0 }));
});
loadsvg('assets/tear_center.svg', async(err, svg) => {
tear_center_svg = await segments(await linearize(svg, { tolerance: 0 }));
});
loadsvg('assets/tear_edge.svg', async(err, svg) => {
tear_edge_svg = await segments(await linearize(svg, { tolerance: 0 }));
});
loadsvg('assets/decor.svg', async(err, svg) => {
decor_svg = await segments(await linearize(svg, { tolerance: 0 }));
});
const sketch = async ({ width, height, units, render }) => {
const img_eye_base = await load('assets/eye_base.png');
const canvas = document.createElement('canvas');
canvas.width = config.img_size;
canvas.height = config.img_size;
const tmpContext = canvas.getContext('2d');
tmpContext.imageSmoothingEnabled = false;
tmpContext.clearRect(0, 0, config.img_size, config.img_size);
tmpContext.drawImage(img_eye_base, 0, 0, config.img_size, config.img_size);
const eye_base_bmp = tmpContext.getImageData(0, 0, config.img_size, config.img_size);
const img_eye_iris = await load('assets/eye_iris.png');
tmpContext.clearRect(0, 0, config.img_size, config.img_size);
tmpContext.drawImage(img_eye_iris, 0, 0, config.img_size, config.img_size);
const eye_iris_bmp = tmpContext.getImageData(0, 0, config.img_size, config.img_size);
const eye_base_contour = [];
const tear_center_polyline = [];
const mapSegCoords = (seg, offset) => {
const x = (seg[0] / config.img_size) * (width - config.eye_outer_margin*2) + config.eye_outer_margin + offset[0];
const y = (seg[1] / config.img_size) * (height - config.eye_outer_margin*2) + config.eye_outer_margin + offset[1];
return [x, y];
}
eye_contour_svg.forEach(seg => {
for (let i = 0; i < seg.length; ++i)
{
const contourLine = [mapSegCoords(seg[i], config.eye_offset), mapSegCoords(seg[(i + 1) % seg.length], config.eye_offset)];
if (config.showSvgContours) lines.push(contourLine);
eye_base_contour.push(contourLine);
}
});
tear_center_svg.forEach(seg => {
for (let i = 0; i < seg.length - 1; ++i)
{
const contourLine = [mapSegCoords(seg[i], config.eye_offset), mapSegCoords(seg[(i + 1) % seg.length], config.eye_offset)];
if (config.showSvgContours) lines.push(contourLine);
tear_center_polyline.push(contourLine);
}
});
tear_edge_svg.forEach(seg => {
for (let i = 0; i < seg.length - 1; ++i)
{
if (config.showSvgContours) lines.push([mapSegCoords(seg[i], config.eye_offset), mapSegCoords(seg[(i + 1) % seg.length], config.eye_offset)]);
}
});
decor_svg.forEach(seg => {
for (let i = 0; i < seg.length - 1; ++i)
{
if (config.showSvgContours) lines.push([mapSegCoords(seg[i], config.eye_offset), mapSegCoords(seg[(i + 1) % seg.length], config.eye_offset)]);
}
});
const pointsManh = [];
const linesManh = [];
const manh = generateManhattanVoronoi(width, height);
if (config.debugShowManhIntersectionFilteredPoints) fillManhNodesPoints(manh, pointsManh);
fillManhCellsLines(manh, config.innerCellRadiusMargin, linesManh, width, height);
if (config.cutManhWithContourAndMask)
{
const manhMaskFunc = point => pointInBMPMask(point, width, height, config.eye_outer_margin, eye_base_bmp, [0, 1], config.eye_offset);
addLinesCutWithContourAndMask(linesManh, eye_base_contour, manhMaskFunc, lines);
}
else
{
const manhMaskFunc = point => false;
addLinesCutWithContourAndMask(linesManh, [], manhMaskFunc, lines);
}
let irisVoroGenResult;
const genIrisLines = config.showIris || config.debugShowIrisOrigVoro || config.debugShowIrisOrigVoroCutWithContour || config.debugShowIrisOrigVoroUnmasked;
if (genIrisLines || config.debugShowIrisAllPoints || config.debugShowIrisMaskedPoints)
{
const linesIrisBase = [];
const linesIris = [];
irisVoroGenResult = generateIrisVoronoi(width, height, eye_iris_bmp, config.eye_offset);
const irisPolys = irisVoroGenResult.polys;
if (genIrisLines)
{
const debug = {
duplicateSegments: 0
};
addSegmentsFromPolys(irisVoroGenResult.polys.partiallyInside, linesIrisBase, [0, 0], debug);
addSegmentsFromPolys(irisVoroGenResult.polys.fullyOutside, linesIrisBase, [0, 0], debug);
if (config.debugShowIrisOrigVoroUnmasked)
{
addSegmentsFromPolys(irisVoroGenResult.polys.fullyInside, linesIrisBase, [0, 0], debug);
}
const irisMaskFunc = point => !pointInBMPMask(point, width, height, config.eye_outer_margin, eye_base_bmp, [2], config.eye_offset);
const tearMaskFunc = point => pointInBMPMask(point, width, height, config.eye_outer_margin, eye_base_bmp, [1], config.eye_offset);
addLinesCutWithContourAndMask(linesIrisBase, eye_base_contour, irisMaskFunc, linesIris);
const linesIrisToUse = config.debugShowIrisOrigVoroUnmasked ? linesIrisBase : linesIris;
if (config.debugShowIrisOrigVoroUnmasked) fancyIrisMaths(linesIrisToUse, lines, [], (p) => {return false;});
else if (config.debugShowIrisSolo) fancyIrisMaths(linesIrisToUse, lines, eye_base_contour, irisMaskFunc);
else fancyIrisMaths(linesIrisToUse, lines, tear_center_polyline, tearMaskFunc);
}
}
let linesToDraw = lines;
if (config.shrinkToCanvas)
{
linesToDraw = fitLinesToCanvas(lines, width, height);
}
return ({ context }) => {
context.clearRect(0, 0, width, height);
context.fillStyle = 'white';
context.fillRect(0, 0, width, height);
linesToDraw.forEach(line => {
context.beginPath();
line.forEach(p => context.lineTo(p[0], p[1]));
context.strokeStyle = 'black';
context.lineWidth = config.penThicknessCm;
context.lineJoin = 'round';
context.lineCap = 'round';
context.stroke();
});
const drawPoints = (pp, col) =>
{
pp.forEach(p => {
context.beginPath();
context.arc(p[0], p[1], 0.02, 0, Math.PI * 2);
context.strokeStyle = context.fillStyle = col;
context.lineWidth = config.penThicknessCm;
context.fill();
});
};
if (config.debugShowManhAllPoints) drawPoints(manhAllPointsSeed, 'red');
if (config.debugShowManhIntersectionFilteredPoints) drawPoints(pointsManh, 'blue');
if (config.debugShowIrisAllPoints) drawPoints(irisVoroGenResult.allPoints, 'red');
if (config.debugShowIrisMaskedPoints) drawPoints(irisVoroGenResult.maskedPoints, 'green');
return [
context.canvas,
{
data: polylinesToSVG(linesToDraw, { width, height, units } ),
extension: '.svg'
}
];
};
};
canvasSketch(sketch, {
dimensions: [ 13, 13 ],
pixelsPerInch: 300,
units: 'cm',
});