-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDemo.hx
635 lines (549 loc) · 17.2 KB
/
Demo.hx
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
package;
import com.nodename.delaunay.Voronoi;
import com.nodename.geom.LineSegment;
import com.nodename.geom.Point;
import com.nodename.geom.Rectangle;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.filters.GlowFilter;
import flash.system.System;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import flash.ui.Keyboard;
import haxe.Timer;
import openfl.Assets;
using StringTools;
@:bitmap("assets/mona-lisa.png")
class Picture extends flash.display.BitmapData {}
@:bitmap("assets/mona-lisa-mini.png")
class PictureMini extends flash.display.BitmapData {}
/**
* hxDelaunay openFL demo.
*
* @author azrafe7
*/
class Demo extends Sprite {
private var g:Graphics;
private var POINT_COLOR:Int = 0x00F000;
private var REGION_COLOR:Int = 0x4000F0;
private var MIN_FILL_COLOR:Int = 0x200040;
private var MAX_FILL_COLOR:Int = 0x4000A0;
private var TRIANGLE_COLOR:Int = 0xF00000;
private var HULL_COLOR:Int = 0x30F090;
private var TREE_COLOR:Int = 0xF0C020;
private var ONION_COLOR:Int = 0x10A0FF;
private var SELECTED_COLOR:Int = 0x8020F0;
private var CENTROID_COLOR:Int = 0x111111;
private var PICTURE:String = "assets/mona-lisa.png";
private var PICTURE_MINI:String = "assets/mona-lisa-mini.png";
private var THICKNESS:Float = 1.5;
private var ALPHA:Float = 1.;
private var FILL_ALPHA:Float = 1.;
private var SAMPLE_FILL_ALPHA:Float = .8;
private var CENTROID_ALPHA:Float = .5;
private var TEXT_COLOR:Int = 0xFFFFFF;
private var TEXT_FONT:String = "_typewriter";
private var TEXT_SIZE:Int = 12;
private var TEXT_OUTLINE:GlowFilter = new GlowFilter(0xFF000000, 1, 2, 2, 6);
private var BOUNDS:Rectangle = new Rectangle(0, 0, 500, 500);
private var voronoi:Voronoi;
private var nPoints:Int = 25;
private var points:Array<Point>;
private var centroids:Array<Point>;
private var directions:Array<Point>;
private var regions:Array<Array<Point>>;
private var sortedRegions:Array<Array<Point>>;
private var fillColors:Array<Int>;
private var triangles:Array<LineSegment>;
private var hull:Array<LineSegment>;
private var tree:Array<LineSegment>;
private var onion:Array<Array<Point>>;
private var proxymitySprite:Sprite;
private var proxymityMap:BitmapData;
private var selectedRegion:Array<Point>;
private var pictureBMD:BitmapData;
private var pictureBitmap:Bitmap;
private var pictureMiniBMD:BitmapData; // downscaled by a factor of 4
private var isMouseDown:Bool = false;
private var prevMousePos:Point = new Point();
private var mousePos:Point = new Point();
private var showPoints:Bool = true;
private var showRegions:Bool = true;
private var fillRegions:Bool = false;
private var showTriangles:Bool = false;
private var fillTriangles:Bool = false;
private var showHull:Bool = false;
private var showTree:Bool = false;
private var showOnion:Bool = false;
private var showProximityMap:Bool = false;
private var relax:Bool = false;
private var animate:Bool = false;
private var sampleImage:Bool = false;
private var startTime:Float = 0;
private var dt:Float = 0;
private var text:TextField;
private var TEXT:String =
" hxDelaunay \n" +
" (ported by azrafe7)\n" +
"\n" +
" TOGGLE:\n\n" +
" 1 points : |POINTS|\n" +
" 2 regions : |REGIONS|\n" +
" 3 fill regions : |FILL_REGIONS|\n" +
" 4 triangles : |TRIANGLES|\n" +
" 5 fill tris : |FILL_TRIANGLES|\n" +
" 6 convex hull : |HULL|\n" +
" 7 spanning tree : |TREE|\n" +
" 8 onion : |ONION|\n" +
" 9 proximity map : |PROXIMITY|\n" +
"\n" +
" X relax : |RELAX|\n" +
" A animate : |ANIMATE|\n" +
" P picture : |PICTURE|\n" +
"\n" +
" POINTS: (|NPOINTS|)\n\n" +
" [SHIFT] + \n" +
" ▲ add point/s\n" +
" ▼ remove point/s\n" +
"\n" +
" R randomize\n" +
#if (openfl && !nme)
"\n" +
" S save png\n" +
#end
"\n" +
" click & drag to\n" +
" move region point" +
"\n";
var sprite:Sprite;
public function new () {
super ();
sprite = new Sprite();
addChild(sprite);
g = sprite.graphics;
g.lineStyle(THICKNESS, TEXT_COLOR, ALPHA);
addChild(text = getTextField(TEXT, BOUNDS.width + 10, 15));
text.height = stage.stageHeight - text.y; // makes sure it's _fully_ visible
// picture
#if (!jsprime)
pictureBMD = new Picture(0, 0);
pictureMiniBMD = new PictureMini(0, 0);
#else
pictureBMD = Assets.getBitmapData(PICTURE);
pictureMiniBMD = Assets.getBitmapData(PICTURE_MINI);
#end
pictureBitmap = new Bitmap(pictureBMD);
addChildAt(pictureBitmap, 0);
// generate fill colors
var MAX_COLORS = 10;
fillColors = [for (i in 0...MAX_COLORS) colorLerp(MIN_FILL_COLOR, MAX_FILL_COLOR, i / MAX_COLORS)];
centroids = new Array<Point>();
directions = new Array<Point>();
// first random set of points
points = new Array<Point>();
for (i in 0...nPoints) {
points.push(new Point(Math.random() * BOUNDS.width, Math.random() * BOUNDS.height));
}
update(); // recalc
render(); // draw
updateText(); // info
startTime = Timer.stamp();
//stage.addChild(new FPS(5, 5, 0xFFFFFF));
stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}
public function update():Void
{
if (voronoi != null) {
voronoi.dispose();
voronoi = null;
}
voronoi = new Voronoi(points, null, BOUNDS);
regions = [for (p in points) voronoi.region(p)];
sortedRegions = voronoi.regions();
triangles = voronoi.delaunayTriangulation();
hull = voronoi.hull();
tree = voronoi.spanningTree();
onion = calcOnion(voronoi);
updateProximityMap();
}
public function updateText():Void
{
text.text = TEXT
.replace("|POINTS|", bool2OnOff(showPoints))
.replace("|REGIONS|", bool2OnOff(showRegions))
.replace("|FILL_REGIONS|", bool2OnOff(fillRegions))
.replace("|TRIANGLES|", bool2OnOff(showTriangles))
.replace("|FILL_TRIANGLES|", bool2OnOff(fillTriangles))
.replace("|HULL|", bool2OnOff(showHull))
.replace("|TREE|", bool2OnOff(showTree))
.replace("|ONION|", bool2OnOff(showOnion))
.replace("|PROXIMITY|", bool2OnOff(showProximityMap))
.replace("|NPOINTS|", Std.string(nPoints))
.replace("|RELAX|", bool2OnOff(relax))
.replace("|ANIMATE|", bool2OnOff(animate))
.replace("|PICTURE|", bool2OnOff(sampleImage));
}
public function render():Void {
g.clear();
if (showRegions || fillRegions) drawRegions();
pictureBitmap.visible = (sampleImage && (!fillRegions || SAMPLE_FILL_ALPHA < FILL_ALPHA));
if (showProximityMap) {
g.beginBitmapFill(proxymityMap);
g.drawRect(0, 0, BOUNDS.width, BOUNDS.height);
g.endFill();
}
if (showTriangles || fillTriangles) drawTriangles();
if (showTree) drawTree();
if (showOnion) drawOnion();
if (showHull) drawHull();
if (showPoints) drawSiteCoords();
if (selectedRegion != null) drawPoints(selectedRegion, SELECTED_COLOR);
if (relax && showPoints) drawCentroids();
}
inline function bool2OnOff(v:Bool):String
{
return (v ? "[ON]" : "[OFF]");
}
public function updateProximityMap():Void {
if (proxymityMap == null) {
proxymityMap = new BitmapData(Std.int(BOUNDS.width), Std.int(BOUNDS.height), false);
proxymitySprite = new Sprite();
}
var graphics = proxymitySprite.graphics;
proxymityMap.fillRect(proxymityMap.rect, 0xFFFFFFFF);
graphics.clear();
for (i in 0...sortedRegions.length) {
graphics.lineStyle(1, i, 1); // no borders
graphics.beginFill(i);
var points = sortedRegions[i];
for (p in points) {
if (p == points[0]) graphics.moveTo(p.x, p.y);
else graphics.lineTo(p.x, p.y);
}
graphics.endFill();
}
proxymityMap.draw(proxymitySprite);
}
public function calcOnion(voronoi:Voronoi):Array<Array<Point>>
{
var res = new Array<Array<Point>>();
var points = voronoi.siteCoords();
while (points.length > 2) {
var v:Voronoi = new Voronoi(points, null, BOUNDS);
var peel = v.hullPointsInOrder();
for (p in peel) points.remove(p);
res.push(peel);
v.dispose();
v = null;
}
if (points.length > 0) res.push(points);
return res;
}
public function drawSiteCoords():Void
{
g.lineStyle(THICKNESS, POINT_COLOR, ALPHA);
for (p in points) {
g.drawCircle(p.x, p.y, 2);
}
}
public function drawCentroids():Void
{
if (centroids.length < points.length) return; // wait next frame
for (i in 0...points.length) {
var c = centroids[i];
c.x = Math.round(c.x); c.y = Math.round(c.y);
g.lineStyle(THICKNESS, CENTROID_COLOR, CENTROID_ALPHA);
g.moveTo(c.x - 2, c.y); g.lineTo(c.x + 2, c.y);
g.moveTo(c.x, c.y - 2); g.lineTo(c.x, c.y + 2);
}
}
public function drawRegions():Void
{
if (!sampleImage) {
var fillIdx = -1;
for (region in regions) {
fillIdx = (fillIdx + 1) % fillColors.length;
var fillColor = fillRegions ? fillColors[fillIdx] : null;
drawPoints(region, fillRegions && !showRegions ? fillColors[fillIdx] : REGION_COLOR, fillColor);
}
} else {
for (p in points) {
//var sampledColor = pictureBMD.getPixel(Std.int(p.x), Std.int(p.y)); // use fullscale bitmap for sampling
var sampledColor = pictureMiniBMD.getPixel(Std.int(p.x / 4), Std.int(p.y / 4)); // use downscaled bitmap for sampling
drawPoints(voronoi.region(p), fillRegions && showRegions ? REGION_COLOR : sampledColor, fillRegions ? sampledColor: null);
}
}
}
inline public function drawTriangles():Void
{
if (!sampleImage) {
var fillIdx = -1;
for (tri in voronoi.triangles()) {
fillIdx = (fillIdx + 1) % fillColors.length;
var fillColor = fillTriangles ? fillColors[fillIdx] & 0xFF0000 : null;
drawPoints(tri.points, fillTriangles && !showTriangles ? fillColors[fillIdx] & 0xFF0000 : TRIANGLE_COLOR, fillColor);
}
} else {
for (tri in voronoi.triangles()) {
var p = getCentroid(tri.points);
var sampledColor = pictureBMD.getPixel(Std.int(p.x), Std.int(p.y)); // use fullscale bitmap for sampling
//var sampledColor = pictureMiniBMD.getPixel(Std.int(p.x / 4), Std.int(p.y / 4)); // use downscaled bitmap for sampling
drawPoints(tri.points, fillTriangles && showTriangles ? TRIANGLE_COLOR: sampledColor, fillTriangles ? sampledColor: null);
}
}
}
inline public function drawHull():Void
{
drawSegments(hull, HULL_COLOR);
}
inline public function drawTree():Void
{
drawSegments(tree, TREE_COLOR);
}
public function drawOnion():Void
{
for (peel in onion) {
drawPoints(peel, ONION_COLOR);
}
}
// generic draw function for segments
public function drawSegments(segments:Array<LineSegment>, color:Int, ?fillColor:Int = null) {
g.lineStyle(THICKNESS, color, ALPHA);
if (fillColor != null) g.beginFill(fillColor, FILL_ALPHA);
else g.beginFill(0, 0);
for (segment in segments) {
g.moveTo(segment.p0.x, segment.p0.y);
g.lineTo(segment.p1.x, segment.p1.y);
}
g.endFill();
}
// generic draw function for points
public function drawPoints(points:Array<Point>, color:Int, ?fillColor:Int = null) {
if (points == null || points.length == 0) return;
g.lineStyle(THICKNESS, color, sampleImage ? SAMPLE_FILL_ALPHA : ALPHA);
if (fillColor != null) g.beginFill(fillColor, sampleImage ? SAMPLE_FILL_ALPHA : FILL_ALPHA);
else g.beginFill(0, 0);
var q = points[0];
g.moveTo(q.x, q.y);
for (i in 1...points.length) {
var p = points[i];
g.lineTo(p.x, p.y);
}
g.lineTo(q.x, q.y);
g.endFill();
}
public function getCentroid(region:Array<Point>):Point
{
var c = new Point();
var len = region.length;
for (i in 0...len) {
var p0 = region[i];
var p1 = region[(i + 1) % len];
var m = p0.x * p1.y - p1.x * p0.y;
c.x += (p0.x + p1.x) * m;
c.y += (p0.y + p1.y) * m;
}
var area = getArea(region);
c.x /= 6 * area;
c.y /= 6 * area;
return c;
}
public function getArea(region:Array<Point>):Float
{
var area = 0.0;
var len = region.length;
for (i in 0...len) {
var p0 = region[i];
var p1 = region[(i + 1) % len];
area += p0.x * p1.y - p1.x * p0.y;
}
return area = .5 * area;
}
public function getTextField(text:String = "", x:Float, y:Float):TextField
{
var tf:TextField = new TextField();
var fmt:TextFormat = new TextFormat(TEXT_FONT, null, TEXT_COLOR);
fmt.align = TextFormatAlign.LEFT;
fmt.size = TEXT_SIZE;
tf.defaultTextFormat = fmt;
tf.autoSize = TextFieldAutoSize.LEFT;
tf.selectable = false;
tf.x = x;
tf.y = y;
#if (flash || html5)
tf.filters = [TEXT_OUTLINE];
#end
tf.text = text;
return tf;
}
public function onKeyDown(e:KeyboardEvent):Void
{
var deltaPoints = e.shiftKey ? 20 : 1;
switch (e.keyCode)
{
// TOGGLE
case Keyboard.NUMBER_1: showPoints = !showPoints;
case Keyboard.NUMBER_2: showRegions = !showRegions;
case Keyboard.NUMBER_3: fillRegions = !fillRegions;
case Keyboard.NUMBER_4: showTriangles = !showTriangles;
case Keyboard.NUMBER_5: fillTriangles = !fillTriangles;
case Keyboard.NUMBER_6: showHull = !showHull;
case Keyboard.NUMBER_7: showTree = !showTree;
case Keyboard.NUMBER_8: showOnion = !showOnion;
case Keyboard.NUMBER_9: showProximityMap = !showProximityMap;
// POINTS
case Keyboard.UP:
for (i in 0...deltaPoints) points.push(new Point(Math.random() * BOUNDS.width, Math.random() * BOUNDS.height));
nPoints = points.length;
update();
case Keyboard.DOWN:
while (deltaPoints-- > 0 && nPoints > 3) {
points.pop();
nPoints = points.length;
}
update();
case Keyboard.R:
for (p in points) p.setTo(Math.random() * BOUNDS.width, Math.random() * BOUNDS.height);
update();
case Keyboard.X:
relax = !relax;
animate = false;
case Keyboard.A:
animate = !animate;
relax = false;
case Keyboard.P: sampleImage = !sampleImage;
case Keyboard.S:
#if (openfl && !nme)
update();
var oldSampleFillAlpha = SAMPLE_FILL_ALPHA;
SAMPLE_FILL_ALPHA = sampleImage ? .97 : oldSampleFillAlpha;
render();
SAMPLE_FILL_ALPHA = oldSampleFillAlpha;
var tempBMD = new BitmapData(pictureBMD.width, pictureBMD.height, false, 0);
tempBMD.draw(sprite);
//var tempBMP = new Bitmap(tempBMD);
//addChild(tempBMP);
//sprite.visible = false;
savePNG(tempBMD, "voronoi.png");
#end
}
updateText();
render();
if (e.keyCode == 27) {
#if (flash || html5)
System.exit(1);
#else
Sys.exit(1);
#end
}
}
public function savePNG(bmd:BitmapData, filename:String)
{
#if (openfl && !nme)
var ba:openfl.utils.ByteArray = bmd.encode(bmd.rect, new openfl.display.PNGEncoderOptions());
var fileRef = new openfl.net.FileReference();
fileRef.save(ba, filename);
#end
}
public function onMouseDown(e:MouseEvent):Void
{
isMouseDown = true;
}
public function onMouseUp(e:MouseEvent):Void
{
isMouseDown = false;
selectedRegion = null;
render();
}
public function onMouseMove(e:MouseEvent):Void
{
mousePos.setTo(e.stageX, e.stageY);
}
public function onEnterFrame(e:Event):Void {
dt = Timer.stamp() - startTime;
startTime = Timer.stamp();
var mousePosChanged = !(mousePos.x == prevMousePos.x && mousePos.y == prevMousePos.y);
if (relax) {
for (i in 0...points.length) {
var p = points[i];
var r = voronoi.region(p);
var c = getCentroid(r);
(i == centroids.length) ? centroids.push(c) : centroids[i] = c;
var changed = false;
if (nPoints < 100) {
var distSquared = Point.distanceSquared(c, p);
if (distSquared > 4.5) { // slow down things a bit
c.x -= p.x; c.y -= p.y;
c.normalize(.75);
p.x += c.x; p.y += c.y;
changed = true;
}
}
if (!changed) {
p.x = c.x; p.y = c.y;
}
}
}
if (animate) {
for (i in 0...points.length) {
if (i == directions.length) {
directions.push(new Point(30 * (Math.random() < .5 ? -1 : 1) * (Math.random() * .8 + .4), 30 * (Math.random() < .5 ? -1 : 1) * (Math.random() * .8 + .4)));
}
var p = points[i];
var d = directions[i];
var dx = d.x * dt;
var dy = d.y * dt;
if (p.x + dx < 0 || p.x + dx > BOUNDS.width) {
d.x *= -1;
dx *= -1;
}
if (p.y + dy < 0 || p.y + dy > BOUNDS.height) {
d.y *= -1;
dy *= -1;
}
p.x += dx;
p.y += dy;
}
}
if (relax || animate) {
update();
render();
}
if (isMouseDown && mousePos.x > 0 && mousePos.x < BOUNDS.width && mousePos.y > 0 && mousePos.y < BOUNDS.height) {
var p = voronoi.nearestSitePoint(Std.int(mousePos.x), Std.int(mousePos.y));
if (p != null) {
points[points.indexOf(p)].setTo(mousePos.x, mousePos.y);
if (mousePosChanged) update();
selectedRegion = voronoi.region(p);
render();
}
prevMousePos.setTo(mousePos.x, mousePos.y);
}
}
public function colorLerp(fromColor:Int, toColor:Int, t:Float = 1):Int
{
if (t <= 0) { return fromColor; }
if (t >= 1) { return toColor; }
var r:Int = fromColor >> 16 & 0xFF,
g:Int = fromColor >> 8 & 0xFF,
b:Int = fromColor & 0xFF,
dR:Int = (toColor >> 16 & 0xFF) - r,
dG:Int = (toColor >> 8 & 0xFF) - g,
dB:Int = (toColor & 0xFF) - b;
r += Std.int(dR * t);
g += Std.int(dG * t);
b += Std.int(dB * t);
return r << 16 | g << 8 | b;
}
}