-
Notifications
You must be signed in to change notification settings - Fork 354
/
terrain.js
1073 lines (1001 loc) · 30 KB
/
terrain.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";
function runif(lo, hi) {
return lo + Math.random() * (hi - lo);
}
var rnorm = (function () {
var z2 = null;
function rnorm() {
if (z2 != null) {
var tmp = z2;
z2 = null;
return tmp;
}
var x1 = 0;
var x2 = 0;
var w = 2.0;
while (w >= 1) {
x1 = runif(-1, 1);
x2 = runif(-1, 1);
w = x1 * x1 + x2 * x2;
}
w = Math.sqrt(-2 * Math.log(w) / w);
z2 = x2 * w;
return x1 * w;
}
return rnorm;
})();
function randomVector(scale) {
return [scale * rnorm(), scale * rnorm()];
}
var defaultExtent = {
width: 1,
height: 1
};
function generatePoints(n, extent) {
extent = extent || defaultExtent;
var pts = [];
for (var i = 0; i < n; i++) {
pts.push([(Math.random() - 0.5) * extent.width, (Math.random() - 0.5) * extent.height]);
}
return pts;
}
function centroid(pts) {
var x = 0;
var y = 0;
for (var i = 0; i < pts.length; i++) {
x += pts[i][0];
y += pts[i][1];
}
return [x/pts.length, y/pts.length];
}
function improvePoints(pts, n, extent) {
n = n || 1;
extent = extent || defaultExtent;
for (var i = 0; i < n; i++) {
pts = voronoi(pts, extent)
.polygons(pts)
.map(centroid);
}
return pts;
}
function generateGoodPoints(n, extent) {
extent = extent || defaultExtent;
var pts = generatePoints(n, extent);
pts = pts.sort(function (a, b) {
return a[0] - b[0];
});
return improvePoints(pts, 1, extent);
}
function voronoi(pts, extent) {
extent = extent || defaultExtent;
var w = extent.width/2;
var h = extent.height/2;
return d3.voronoi().extent([[-w, -h], [w, h]])(pts);
}
function makeMesh(pts, extent) {
extent = extent || defaultExtent;
var vor = voronoi(pts, extent);
var vxs = [];
var vxids = {};
var adj = [];
var edges = [];
var tris = [];
for (var i = 0; i < vor.edges.length; i++) {
var e = vor.edges[i];
if (e == undefined) continue;
var e0 = vxids[e[0]];
var e1 = vxids[e[1]];
if (e0 == undefined) {
e0 = vxs.length;
vxids[e[0]] = e0;
vxs.push(e[0]);
}
if (e1 == undefined) {
e1 = vxs.length;
vxids[e[1]] = e1;
vxs.push(e[1]);
}
adj[e0] = adj[e0] || [];
adj[e0].push(e1);
adj[e1] = adj[e1] || [];
adj[e1].push(e0);
edges.push([e0, e1, e.left, e.right]);
tris[e0] = tris[e0] || [];
if (!tris[e0].includes(e.left)) tris[e0].push(e.left);
if (e.right && !tris[e0].includes(e.right)) tris[e0].push(e.right);
tris[e1] = tris[e1] || [];
if (!tris[e1].includes(e.left)) tris[e1].push(e.left);
if (e.right && !tris[e1].includes(e.right)) tris[e1].push(e.right);
}
var mesh = {
pts: pts,
vor: vor,
vxs: vxs,
adj: adj,
tris: tris,
edges: edges,
extent: extent
}
mesh.map = function (f) {
var mapped = vxs.map(f);
mapped.mesh = mesh;
return mapped;
}
return mesh;
}
function generateGoodMesh(n, extent) {
extent = extent || defaultExtent;
var pts = generateGoodPoints(n, extent);
return makeMesh(pts, extent);
}
function isedge(mesh, i) {
return (mesh.adj[i].length < 3);
}
function isnearedge(mesh, i) {
var x = mesh.vxs[i][0];
var y = mesh.vxs[i][1];
var w = mesh.extent.width;
var h = mesh.extent.height;
return x < -0.45 * w || x > 0.45 * w || y < -0.45 * h || y > 0.45 * h;
}
function neighbours(mesh, i) {
var onbs = mesh.adj[i];
var nbs = [];
for (var i = 0; i < onbs.length; i++) {
nbs.push(onbs[i]);
}
return nbs;
}
function distance(mesh, i, j) {
var p = mesh.vxs[i];
var q = mesh.vxs[j];
return Math.sqrt((p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1]));
}
function quantile(h, q) {
var sortedh = [];
for (var i = 0; i < h.length; i++) {
sortedh[i] = h[i];
}
sortedh.sort(d3.ascending);
return d3.quantile(sortedh, q);
}
function zero(mesh) {
var z = [];
for (var i = 0; i < mesh.vxs.length; i++) {
z[i] = 0;
}
z.mesh = mesh;
return z;
}
function slope(mesh, direction) {
return mesh.map(function (x) {
return x[0] * direction[0] + x[1] * direction[1];
});
}
function cone(mesh, slope) {
return mesh.map(function (x) {
return Math.pow(x[0] * x[0] + x[1] * x[1], 0.5) * slope;
});
}
function map(h, f) {
var newh = h.map(f);
newh.mesh = h.mesh;
return newh;
}
function normalize(h) {
var lo = d3.min(h);
var hi = d3.max(h);
return map(h, function (x) {return (x - lo) / (hi - lo)});
}
function peaky(h) {
return map(normalize(h), Math.sqrt);
}
function add() {
var n = arguments[0].length;
var newvals = zero(arguments[0].mesh);
for (var i = 0; i < n; i++) {
for (var j = 0; j < arguments.length; j++) {
newvals[i] += arguments[j][i];
}
}
return newvals;
}
function mountains(mesh, n, r) {
r = r || 0.05;
var mounts = [];
for (var i = 0; i < n; i++) {
mounts.push([mesh.extent.width * (Math.random() - 0.5), mesh.extent.height * (Math.random() - 0.5)]);
}
var newvals = zero(mesh);
for (var i = 0; i < mesh.vxs.length; i++) {
var p = mesh.vxs[i];
for (var j = 0; j < n; j++) {
var m = mounts[j];
newvals[i] += Math.pow(Math.exp(-((p[0] - m[0]) * (p[0] - m[0]) + (p[1] - m[1]) * (p[1] - m[1])) / (2 * r * r)), 2);
}
}
return newvals;
}
function relax(h) {
var newh = zero(h.mesh);
for (var i = 0; i < h.length; i++) {
var nbs = neighbours(h.mesh, i);
if (nbs.length < 3) {
newh[i] = 0;
continue;
}
newh[i] = d3.mean(nbs.map(function (j) {return h[j]}));
}
return newh;
}
function downhill(h) {
if (h.downhill) return h.downhill;
function downfrom(i) {
if (isedge(h.mesh, i)) return -2;
var best = -1;
var besth = h[i];
var nbs = neighbours(h.mesh, i);
for (var j = 0; j < nbs.length; j++) {
if (h[nbs[j]] < besth) {
besth = h[nbs[j]];
best = nbs[j];
}
}
return best;
}
var downs = [];
for (var i = 0; i < h.length; i++) {
downs[i] = downfrom(i);
}
h.downhill = downs;
return downs;
}
function findSinks(h) {
var dh = downhill(h);
var sinks = [];
for (var i = 0; i < dh.length; i++) {
var node = i;
while (true) {
if (isedge(h.mesh, node)) {
sinks[i] = -2;
break;
}
if (dh[node] == -1) {
sinks[i] = node;
break;
}
node = dh[node];
}
}
}
function fillSinks(h, epsilon) {
epsilon = epsilon || 1e-5;
var infinity = 999999;
var newh = zero(h.mesh);
for (var i = 0; i < h.length; i++) {
if (isnearedge(h.mesh, i)) {
newh[i] = h[i];
} else {
newh[i] = infinity;
}
}
while (true) {
var changed = false;
for (var i = 0; i < h.length; i++) {
if (newh[i] == h[i]) continue;
var nbs = neighbours(h.mesh, i);
for (var j = 0; j < nbs.length; j++) {
if (h[i] >= newh[nbs[j]] + epsilon) {
newh[i] = h[i];
changed = true;
break;
}
var oh = newh[nbs[j]] + epsilon;
if ((newh[i] > oh) && (oh > h[i])) {
newh[i] = oh;
changed = true;
}
}
}
if (!changed) return newh;
}
}
function getFlux(h) {
var dh = downhill(h);
var idxs = [];
var flux = zero(h.mesh);
for (var i = 0; i < h.length; i++) {
idxs[i] = i;
flux[i] = 1/h.length;
}
idxs.sort(function (a, b) {
return h[b] - h[a];
});
for (var i = 0; i < h.length; i++) {
var j = idxs[i];
if (dh[j] >= 0) {
flux[dh[j]] += flux[j];
}
}
return flux;
}
function getSlope(h) {
var dh = downhill(h);
var slope = zero(h.mesh);
for (var i = 0; i < h.length; i++) {
var s = trislope(h, i);
slope[i] = Math.sqrt(s[0] * s[0] + s[1] * s[1]);
continue;
if (dh[i] < 0) {
slope[i] = 0;
} else {
slope[i] = (h[i] - h[dh[i]]) / distance(h.mesh, i, dh[i]);
}
}
return slope;
}
function erosionRate(h) {
var flux = getFlux(h);
var slope = getSlope(h);
var newh = zero(h.mesh);
for (var i = 0; i < h.length; i++) {
var river = Math.sqrt(flux[i]) * slope[i];
var creep = slope[i] * slope[i];
var total = 1000 * river + creep;
total = total > 200 ? 200 : total;
newh[i] = total;
}
return newh;
}
function erode(h, amount) {
var er = erosionRate(h);
var newh = zero(h.mesh);
var maxr = d3.max(er);
for (var i = 0; i < h.length; i++) {
newh[i] = h[i] - amount * (er[i] / maxr);
}
return newh;
}
function doErosion(h, amount, n) {
n = n || 1;
h = fillSinks(h);
for (var i = 0; i < n; i++) {
h = erode(h, amount);
h = fillSinks(h);
}
return h;
}
function setSeaLevel(h, q) {
var newh = zero(h.mesh);
var delta = quantile(h, q);
for (var i = 0; i < h.length; i++) {
newh[i] = h[i] - delta;
}
return newh;
}
function cleanCoast(h, iters) {
for (var iter = 0; iter < iters; iter++) {
var changed = 0;
var newh = zero(h.mesh);
for (var i = 0; i < h.length; i++) {
newh[i] = h[i];
var nbs = neighbours(h.mesh, i);
if (h[i] <= 0 || nbs.length != 3) continue;
var count = 0;
var best = -999999;
for (var j = 0; j < nbs.length; j++) {
if (h[nbs[j]] > 0) {
count++;
} else if (h[nbs[j]] > best) {
best = h[nbs[j]];
}
}
if (count > 1) continue;
newh[i] = best / 2;
changed++;
}
h = newh;
newh = zero(h.mesh);
for (var i = 0; i < h.length; i++) {
newh[i] = h[i];
var nbs = neighbours(h.mesh, i);
if (h[i] > 0 || nbs.length != 3) continue;
var count = 0;
var best = 999999;
for (var j = 0; j < nbs.length; j++) {
if (h[nbs[j]] <= 0) {
count++;
} else if (h[nbs[j]] < best) {
best = h[nbs[j]];
}
}
if (count > 1) continue;
newh[i] = best / 2;
changed++;
}
h = newh;
}
return h;
}
function trislope(h, i) {
var nbs = neighbours(h.mesh, i);
if (nbs.length != 3) return [0,0];
var p0 = h.mesh.vxs[nbs[0]];
var p1 = h.mesh.vxs[nbs[1]];
var p2 = h.mesh.vxs[nbs[2]];
var x1 = p1[0] - p0[0];
var x2 = p2[0] - p0[0];
var y1 = p1[1] - p0[1];
var y2 = p2[1] - p0[1];
var det = x1 * y2 - x2 * y1;
var h1 = h[nbs[1]] - h[nbs[0]];
var h2 = h[nbs[2]] - h[nbs[0]];
return [(y2 * h1 - y1 * h2) / det,
(-x2 * h1 + x1 * h2) / det];
}
function cityScore(h, cities) {
var score = map(getFlux(h), Math.sqrt);
for (var i = 0; i < h.length; i++) {
if (h[i] <= 0 || isnearedge(h.mesh, i)) {
score[i] = -999999;
continue;
}
score[i] += 0.01 / (1e-9 + Math.abs(h.mesh.vxs[i][0]) - h.mesh.extent.width/2)
score[i] += 0.01 / (1e-9 + Math.abs(h.mesh.vxs[i][1]) - h.mesh.extent.height/2)
for (var j = 0; j < cities.length; j++) {
score[i] -= 0.02 / (distance(h.mesh, cities[j], i) + 1e-9);
}
}
return score;
}
function placeCity(render) {
render.cities = render.cities || [];
var score = cityScore(render.h, render.cities);
var newcity = d3.scan(score, d3.descending);
render.cities.push(newcity);
}
function placeCities(render) {
var params = render.params;
var h = render.h;
var n = params.ncities;
for (var i = 0; i < n; i++) {
placeCity(render);
}
}
function contour(h, level) {
level = level || 0;
var edges = [];
for (var i = 0; i < h.mesh.edges.length; i++) {
var e = h.mesh.edges[i];
if (e[3] == undefined) continue;
if (isnearedge(h.mesh, e[0]) || isnearedge(h.mesh, e[1])) continue;
if ((h[e[0]] > level && h[e[1]] <= level) ||
(h[e[1]] > level && h[e[0]] <= level)) {
edges.push([e[2], e[3]]);
}
}
return mergeSegments(edges);
}
function getRivers(h, limit) {
var dh = downhill(h);
var flux = getFlux(h);
var links = [];
var above = 0;
for (var i = 0; i < h.length; i++) {
if (h[i] > 0) above++;
}
limit *= above / h.length;
for (var i = 0; i < dh.length; i++) {
if (isnearedge(h.mesh, i)) continue;
if (flux[i] > limit && h[i] > 0 && dh[i] >= 0) {
var up = h.mesh.vxs[i];
var down = h.mesh.vxs[dh[i]];
if (h[dh[i]] > 0) {
links.push([up, down]);
} else {
links.push([up, [(up[0] + down[0])/2, (up[1] + down[1])/2]]);
}
}
}
return mergeSegments(links).map(relaxPath);
}
function getTerritories(render) {
var h = render.h;
var cities = render.cities;
var n = render.params.nterrs;
if (n > render.cities.length) n = render.cities.length;
var flux = getFlux(h);
var terr = [];
var queue = new PriorityQueue({comparator: function (a, b) {return a.score - b.score}});
function weight(u, v) {
var horiz = distance(h.mesh, u, v);
var vert = h[v] - h[u];
if (vert > 0) vert /= 10;
var diff = 1 + 0.25 * Math.pow(vert/horiz, 2);
diff += 100 * Math.sqrt(flux[u]);
if (h[u] <= 0) diff = 100;
if ((h[u] > 0) != (h[v] > 0)) return 1000;
return horiz * diff;
}
for (var i = 0; i < n; i++) {
terr[cities[i]] = cities[i];
var nbs = neighbours(h.mesh, cities[i]);
for (var j = 0; j < nbs.length; j++) {
queue.queue({
score: weight(cities[i], nbs[j]),
city: cities[i],
vx: nbs[j]
});
}
}
while (queue.length) {
var u = queue.dequeue();
if (terr[u.vx] != undefined) continue;
terr[u.vx] = u.city;
var nbs = neighbours(h.mesh, u.vx);
for (var i = 0; i < nbs.length; i++) {
var v = nbs[i];
if (terr[v] != undefined) continue;
var newdist = weight(u.vx, v);
queue.queue({
score: u.score + newdist,
city: u.city,
vx: v
});
}
}
terr.mesh = h.mesh;
return terr;
}
function getBorders(render) {
var terr = render.terr;
var h = render.h;
var edges = [];
for (var i = 0; i < terr.mesh.edges.length; i++) {
var e = terr.mesh.edges[i];
if (e[3] == undefined) continue;
if (isnearedge(terr.mesh, e[0]) || isnearedge(terr.mesh, e[1])) continue;
if (h[e[0]] < 0 || h[e[1]] < 0) continue;
if (terr[e[0]] != terr[e[1]]) {
edges.push([e[2], e[3]]);
}
}
return mergeSegments(edges).map(relaxPath);
}
function mergeSegments(segs) {
var adj = {};
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
var a0 = adj[seg[0]] || [];
var a1 = adj[seg[1]] || [];
a0.push(seg[1]);
a1.push(seg[0]);
adj[seg[0]] = a0;
adj[seg[1]] = a1;
}
var done = [];
var paths = [];
var path = null;
while (true) {
if (path == null) {
for (var i = 0; i < segs.length; i++) {
if (done[i]) continue;
done[i] = true;
path = [segs[i][0], segs[i][1]];
break;
}
if (path == null) break;
}
var changed = false;
for (var i = 0; i < segs.length; i++) {
if (done[i]) continue;
if (adj[path[0]].length == 2 && segs[i][0] == path[0]) {
path.unshift(segs[i][1]);
} else if (adj[path[0]].length == 2 && segs[i][1] == path[0]) {
path.unshift(segs[i][0]);
} else if (adj[path[path.length - 1]].length == 2 && segs[i][0] == path[path.length - 1]) {
path.push(segs[i][1]);
} else if (adj[path[path.length - 1]].length == 2 && segs[i][1] == path[path.length - 1]) {
path.push(segs[i][0]);
} else {
continue;
}
done[i] = true;
changed = true;
break;
}
if (!changed) {
paths.push(path);
path = null;
}
}
return paths;
}
function relaxPath(path) {
var newpath = [path[0]];
for (var i = 1; i < path.length - 1; i++) {
var newpt = [0.25 * path[i-1][0] + 0.5 * path[i][0] + 0.25 * path[i+1][0],
0.25 * path[i-1][1] + 0.5 * path[i][1] + 0.25 * path[i+1][1]];
newpath.push(newpt);
}
newpath.push(path[path.length - 1]);
return newpath;
}
function visualizePoints(svg, pts) {
var circle = svg.selectAll('circle').data(pts);
circle.enter()
.append('circle');
circle.exit().remove();
d3.selectAll('circle')
.attr('cx', function (d) {return 1000*d[0]})
.attr('cy', function (d) {return 1000*d[1]})
.attr('r', 100 / Math.sqrt(pts.length));
}
function makeD3Path(path) {
var p = d3.path();
p.moveTo(1000*path[0][0], 1000*path[0][1]);
for (var i = 1; i < path.length; i++) {
p.lineTo(1000*path[i][0], 1000*path[i][1]);
}
return p.toString();
}
function visualizeVoronoi(svg, field, lo, hi) {
if (hi == undefined) hi = d3.max(field) + 1e-9;
if (lo == undefined) lo = d3.min(field) - 1e-9;
var mappedvals = field.map(function (x) {return x > hi ? 1 : x < lo ? 0 : (x - lo) / (hi - lo)});
var tris = svg.selectAll('path.field').data(field.mesh.tris)
tris.enter()
.append('path')
.classed('field', true);
tris.exit()
.remove();
svg.selectAll('path.field')
.attr('d', makeD3Path)
.style('fill', function (d, i) {
return d3.interpolateViridis(mappedvals[i]);
});
}
function visualizeDownhill(h) {
var links = getRivers(h, 0.01);
drawPaths('river', links);
}
function drawPaths(svg, cls, paths) {
var paths = svg.selectAll('path.' + cls).data(paths)
paths.enter()
.append('path')
.classed(cls, true)
paths.exit()
.remove();
svg.selectAll('path.' + cls)
.attr('d', makeD3Path);
}
function visualizeSlopes(svg, render) {
var h = render.h;
var strokes = [];
var r = 0.25 / Math.sqrt(h.length);
for (var i = 0; i < h.length; i++) {
if (h[i] <= 0 || isnearedge(h.mesh, i)) continue;
var nbs = neighbours(h.mesh, i);
nbs.push(i);
var s = 0;
var s2 = 0;
for (var j = 0; j < nbs.length; j++) {
var slopes = trislope(h, nbs[j]);
s += slopes[0] / 10;
s2 += slopes[1];
}
s /= nbs.length;
s2 /= nbs.length;
if (Math.abs(s) < runif(0.1, 0.4)) continue;
var l = r * runif(1, 2) * (1 - 0.2 * Math.pow(Math.atan(s), 2)) * Math.exp(s2/100);
var x = h.mesh.vxs[i][0];
var y = h.mesh.vxs[i][1];
if (Math.abs(l*s) > 2 * r) {
var n = Math.floor(Math.abs(l*s/r));
l /= n;
if (n > 4) n = 4;
for (var j = 0; j < n; j++) {
var u = rnorm() * r;
var v = rnorm() * r;
strokes.push([[x+u-l, y+v+l*s], [x+u+l, y+v-l*s]]);
}
} else {
strokes.push([[x-l, y+l*s], [x+l, y-l*s]]);
}
}
var lines = svg.selectAll('line.slope').data(strokes)
lines.enter()
.append('line')
.classed('slope', true);
lines.exit()
.remove();
svg.selectAll('line.slope')
.attr('x1', function (d) {return 1000*d[0][0]})
.attr('y1', function (d) {return 1000*d[0][1]})
.attr('x2', function (d) {return 1000*d[1][0]})
.attr('y2', function (d) {return 1000*d[1][1]})
}
function visualizeContour(h, level) {
level = level || 0;
var links = contour(h, level);
drawPaths('coast', links);
}
function visualizeBorders(h, cities, n) {
var links = getBorders(h, getTerritories(h, cities, n));
drawPaths('border', links);
}
function visualizeCities(svg, render) {
var cities = render.cities;
var h = render.h;
var n = render.params.nterrs;
var circs = svg.selectAll('circle.city').data(cities);
circs.enter()
.append('circle')
.classed('city', true);
circs.exit()
.remove();
svg.selectAll('circle.city')
.attr('cx', function (d) {return 1000*h.mesh.vxs[d][0]})
.attr('cy', function (d) {return 1000*h.mesh.vxs[d][1]})
.attr('r', function (d, i) {return i >= n ? 4 : 10})
.style('fill', 'white')
.style('stroke-width', 5)
.style('stroke-linecap', 'round')
.style('stroke', 'black')
.raise();
}
function dropEdge(h, p) {
p = p || 4
var newh = zero(h.mesh);
for (var i = 0; i < h.length; i++) {
var v = h.mesh.vxs[i];
var x = 2.4*v[0] / h.mesh.extent.width;
var y = 2.4*v[1] / h.mesh.extent.height;
newh[i] = h[i] - Math.exp(10*(Math.pow(Math.pow(x, p) + Math.pow(y, p), 1/p) - 1));
}
return newh;
}
function generateCoast(params) {
var mesh = generateGoodMesh(params.npts, params.extent);
var h = add(
slope(mesh, randomVector(4)),
cone(mesh, runif(-1, -1)),
mountains(mesh, 50)
);
for (var i = 0; i < 10; i++) {
h = relax(h);
}
h = peaky(h);
h = doErosion(h, runif(0, 0.1), 5);
h = setSeaLevel(h, runif(0.2, 0.6));
h = fillSinks(h);
h = cleanCoast(h, 3);
return h;
}
function terrCenter(h, terr, city, landOnly) {
var x = 0;
var y = 0;
var n = 0;
for (var i = 0; i < terr.length; i++) {
if (terr[i] != city) continue;
if (landOnly && h[i] <= 0) continue;
x += terr.mesh.vxs[i][0];
y += terr.mesh.vxs[i][1];
n++;
}
return [x/n, y/n];
}
function drawLabels(svg, render) {
var params = render.params;
var h = render.h;
var terr = render.terr;
var cities = render.cities;
var nterrs = render.params.nterrs;
var avoids = [render.rivers, render.coasts, render.borders];
var lang = makeRandomLanguage();
var citylabels = [];
function penalty(label) {
var pen = 0;
if (label.x0 < -0.45 * h.mesh.extent.width) pen += 100;
if (label.x1 > 0.45 * h.mesh.extent.width) pen += 100;
if (label.y0 < -0.45 * h.mesh.extent.height) pen += 100;
if (label.y1 > 0.45 * h.mesh.extent.height) pen += 100;
for (var i = 0; i < citylabels.length; i++) {
var olabel = citylabels[i];
if (label.x0 < olabel.x1 && label.x1 > olabel.x0 &&
label.y0 < olabel.y1 && label.y1 > olabel.y0) {
pen += 100;
}
}
for (var i = 0; i < cities.length; i++) {
var c = h.mesh.vxs[cities[i]];
if (label.x0 < c[0] && label.x1 > c[0] && label.y0 < c[1] && label.y1 > c[1]) {
pen += 100;
}
}
for (var i = 0; i < avoids.length; i++) {
var avoid = avoids[i];
for (var j = 0; j < avoid.length; j++) {
var avpath = avoid[j];
for (var k = 0; k < avpath.length; k++) {
var pt = avpath[k];
if (pt[0] > label.x0 && pt[0] < label.x1 && pt[1] > label.y0 && pt[1] < label.y1) {
pen++;
}
}
}
}
return pen;
}
for (var i = 0; i < cities.length; i++) {
var x = h.mesh.vxs[cities[i]][0];
var y = h.mesh.vxs[cities[i]][1];
var text = makeName(lang, 'city');
var size = i < nterrs ? params.fontsizes.city : params.fontsizes.town;
var sx = 0.65 * size/1000 * text.length;
var sy = size/1000;
var posslabels = [
{
x: x + 0.8 * sy,
y: y + 0.3 * sy,
align: 'start',
x0: x + 0.7 * sy,
y0: y - 0.6 * sy,
x1: x + 0.7 * sy + sx,
y1: y + 0.6 * sy
},
{
x: x - 0.8 * sy,
y: y + 0.3 * sy,
align: 'end',
x0: x - 0.9 * sy - sx,
y0: y - 0.7 * sy,
x1: x - 0.9 * sy,
y1: y + 0.7 * sy
},
{
x: x,
y: y - 0.8 * sy,
align: 'middle',
x0: x - sx/2,
y0: y - 1.9*sy,
x1: x + sx/2,
y1: y - 0.7 * sy
},
{
x: x,
y: y + 1.2 * sy,
align: 'middle',
x0: x - sx/2,
y0: y + 0.1*sy,
x1: x + sx/2,
y1: y + 1.3*sy
}
];
var label = posslabels[d3.scan(posslabels, function (a, b) {return penalty(a) - penalty(b)})];
label.text = text;
label.size = size;
citylabels.push(label);
}
var texts = svg.selectAll('text.city').data(citylabels);
texts.enter()
.append('text')
.classed('city', true);
texts.exit()
.remove();
svg.selectAll('text.city')
.attr('x', function (d) {return 1000*d.x})
.attr('y', function (d) {return 1000*d.y})
.style('font-size', function (d) {return d.size})
.style('text-anchor', function (d) {return d.align})
.text(function (d) {return d.text})
.raise();
var reglabels = [];
for (var i = 0; i < nterrs; i++) {
var city = cities[i];
var text = makeName(lang, 'region');
var sy = params.fontsizes.region / 1000;
var sx = 0.6 * text.length * sy;
var lc = terrCenter(h, terr, city, true);
var oc = terrCenter(h, terr, city, false);
var best = 0;
var bestscore = -999999;
for (var j = 0; j < h.length; j++) {
var score = 0;
var v = h.mesh.vxs[j];
score -= 3000 * Math.sqrt((v[0] - lc[0]) * (v[0] - lc[0]) + (v[1] - lc[1]) * (v[1] - lc[1]));
score -= 1000 * Math.sqrt((v[0] - oc[0]) * (v[0] - oc[0]) + (v[1] - oc[1]) * (v[1] - oc[1]));
if (terr[j] != city) score -= 3000;
for (var k = 0; k < cities.length; k++) {
var u = h.mesh.vxs[cities[k]];
if (Math.abs(v[0] - u[0]) < sx &&
Math.abs(v[1] - sy/2 - u[1]) < sy) {
score -= k < nterrs ? 4000 : 500;
}
if (v[0] - sx/2 < citylabels[k].x1 &&
v[0] + sx/2 > citylabels[k].x0 &&
v[1] - sy < citylabels[k].y1 &&
v[1] > citylabels[k].y0) {
score -= 5000;
}
}
for (var k = 0; k < reglabels.length; k++) {
var label = reglabels[k];
if (v[0] - sx/2 < label.x + label.width/2 &&
v[0] + sx/2 > label.x - label.width/2 &&
v[1] - sy < label.y &&
v[1] > label.y - label.size) {
score -= 20000;
}
}
if (h[j] <= 0) score -= 500;
if (v[0] + sx/2 > 0.5 * h.mesh.extent.width) score -= 50000;