-
Notifications
You must be signed in to change notification settings - Fork 1
/
tiles.go
1283 lines (1144 loc) · 38.6 KB
/
tiles.go
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
package genworldvoronoi
import (
"fmt"
"image"
"image/color"
"log"
"math"
"sort"
"github.com/Flokey82/genbiome"
"github.com/Flokey82/genworldvoronoi/bio"
"github.com/Flokey82/genworldvoronoi/geo"
"github.com/Flokey82/genworldvoronoi/various"
"github.com/Flokey82/geoquad"
"github.com/Flokey82/go_gens/gameconstants"
"github.com/Flokey82/go_gens/vectors"
"github.com/davvo/mercator"
"github.com/llgcode/draw2d/draw2dimg"
"github.com/mazznoer/colorgrad"
geojson "github.com/paulmach/go.geojson"
)
// Display modes for tile rendering.
const (
DisplayModeDefault = 0
DisplayModeOceanPressure = 1
DisplayModeMoisture = 2
DisplayModeRainfall = 3
DisplayModeFlux = 4
DisplayModeCompression = 5
DisplayModeEarthquake = 6
DisplayModeVolcano = 7
DisplayModeRockSlide = 8
DisplayModeFlood = 9
DisplayModeErosion = 10
DisplayModeErosion2 = 11
DisplayModeSteepness = 12
DisplayModeSlope = 13
DisplayModeCityStates = 14
DisplayModeEmpires = 15
DisplayModeCultures = 16
DisplayModeReligions = 17
DisplayModeSpecies = 18
DisplayModePlates = 19
DisplayModeElevation = 20
DisplayModeAirTemperature = 21
DisplayModeOceanTemperature = 22
DisplayModeInsolation = 23
DisplayModePopulation = 24
DisplayModeSuitability = 25
DisplayModeSoilExhaustion = 26
DisplayModeTribes = 27
)
// GetTile returns the image of the tile at the given coordinates and zoom level.
func (m *Map) GetTile(x, y, zoom, displayMode, vectorMode int, drawRivers, drawTradeRoutes, drawLakes, drawShadows, aspectShading bool) image.Image {
// NOTE:
//
// For now we don't use the LOD logic until we have figured out how to handle triangles.
// While regions simply have n*step as their ID, triangles aren't stable as they are
// generated from the voronoi diagram from scratch. This means their order changes...
// Which also means we can't easily re-use the pre-computed triangle values from the
// primary mesh.
//
// mesh, step := m.getCoarseForZoom(zoom)
mesh := m.SphereMesh
step := 1
var colorFunc func(int, float64) color.Color
switch displayMode {
case DisplayModeCityStates, DisplayModeEmpires, DisplayModeCultures, DisplayModeReligions, DisplayModeSpecies, DisplayModePlates:
colorGrad := colorgrad.Rainbow()
terrToColor := make(map[int]int)
var territory []int
var terrLen int
if displayMode == DisplayModeCityStates {
terr := m.CityStates
terrLen = len(terr)
for i, c := range terr {
terrToColor[c.ID] = i
}
territory = m.RegionToCityState
} else if displayMode == DisplayModeEmpires {
terr := m.Empires
terrLen = len(terr)
for i, c := range terr {
terrToColor[c.ID] = i
}
territory = m.RegionToEmpire
} else if displayMode == DisplayModeCultures {
terr := m.Cultures
terrLen = len(terr)
for i, c := range terr {
terrToColor[c.ID] = i
}
territory = m.RegionToCulture
} else if displayMode == DisplayModeReligions {
terr := m.Religions
terrLen = len(terr)
for i, c := range terr {
terrToColor[c.ID] = i
}
territory = m.RegionToReligion
} else if displayMode == DisplayModeSpecies {
terr := m.Species
terrLen = len(terr)
for i, c := range terr {
terrToColor[c.Origin] = i
}
territory = m.SpeciesRegions
} else {
terr := m.PlateRegs
terrLen = len(terr)
for i, c := range terr {
terrToColor[c] = i
}
territory = m.RegionToPlate
}
min, max := minMax(m.Elevation)
_, maxMois := minMax(m.Moisture)
cols := colorGrad.Colors(uint(terrLen) + 1)
colorFunc = func(i int, n float64) color.Color {
// Calculate the color of the region.
elev := m.Elevation[i]
val := (elev - min) / (max - min)
// If we have a territory, return the color of the territory.
if territory[i] != -1 {
terrID := terrToColor[territory[i]]
return genColor(cols[terrID], math.Pow(val, 1/n))
}
// Return blue for water (oceans and lakes).
if elev <= 0 || (m.Waterpool[i] > 0 && drawLakes) {
return genBlue(val)
}
// Return the biome color for land.
rLat := m.LatLon[i][0]
valElev := elev / max
valMois := m.Moisture[i] / maxMois
return geo.GetWhittakerModBiomeColor(rLat, valElev, valMois, math.Pow(val, 1/n))
}
case DisplayModeElevation, DisplayModeAirTemperature, DisplayModeOceanTemperature: // Temperatures and elevation.
// Create a blue to red color gradient.
colorGrad := colorgrad.NewGradient()
colorGrad.Colors(
color.RGBA{0, 0, 255, 255},
color.RGBA{0, 255, 255, 255},
color.RGBA{0, 255, 0, 255},
color.RGBA{255, 255, 0, 255},
color.RGBA{255, 0, 0, 255},
)
cb, err := colorGrad.Build()
if err != nil {
log.Fatal(err)
}
if displayMode == DisplayModeElevation { // Elevation.
_, max := minMax(m.Elevation)
// Create the color function.
colorFunc = func(i int, n float64) color.Color {
// Calculate the color of the region.
val := m.Elevation[i] / max
return genColor(cb.At(val), math.Pow(val, 1/n))
}
} else if displayMode == DisplayModeAirTemperature { // Air temperature.
temp := m.AirTemperature
minTemp, maxTemp := minMax(temp)
// Create the color function.
colorFunc = func(i int, n float64) color.Color {
// Calculate the color of the region.
val := (temp[i] - minTemp) / (maxTemp - minTemp)
return genColor(cb.At(val), math.Pow(val, 1/n))
}
} else if displayMode == DisplayModeOceanTemperature { // Ocean temperature.
temp := m.OceanTemperature
minTemp, maxTemp := minMax(temp)
// Create the color function.
colorFunc = func(i int, n float64) color.Color {
// Calculate the color of the region.
val := (temp[i] - minTemp) / (maxTemp - minTemp)
return genColor(cb.At(val), math.Pow(val, 1/n))
}
}
default:
vals := m.Elevation
if displayMode == DisplayModeOceanPressure {
vals = m.CalcCurrentPressure(m.RegionToOceanVec)
} else if displayMode == DisplayModeMoisture {
vals = m.Moisture
} else if displayMode == DisplayModeRainfall {
vals = m.Rainfall
} else if displayMode == DisplayModeFlux {
vals = m.Flux
} else if displayMode == DisplayModeCompression {
vals = m.PropagateCompression(m.RegionCompression)
} else if displayMode == DisplayModeEarthquake {
vals = m.GetEarthquakeChance()
} else if displayMode == DisplayModeVolcano {
vals = m.GetVolcanoEruptionChance()
} else if displayMode == DisplayModeRockSlide {
vals = m.GetRockSlideAvalancheChance()
} else if displayMode == DisplayModeFlood {
vals = m.GetFloodChance()
} else if displayMode == DisplayModeErosion {
vals = m.GetErosionRate()
} else if displayMode == DisplayModeErosion2 {
vals = m.GetErosionRate2()
} else if displayMode == DisplayModeSteepness {
vals = m.GetSteepness()
} else if displayMode == DisplayModeSlope {
vals = m.GetSlope()
} else if displayMode == DisplayModeInsolation {
vals = m.Geo.AvgInsolation
} else if displayMode == DisplayModePopulation { // Population.
vals = make([]float64, m.NumRegions)
for i, pop := range m.Population {
if pop <= 0 {
vals[i] = 0
} else {
vals[i] = float64(pop)
}
}
} else if displayMode == DisplayModeSuitability {
vals = make([]float64, m.NumRegions)
for i, sus := range m.Suitability {
vals[i] = sus
}
} else if displayMode == DisplayModeSoilExhaustion {
vals = make([]float64, m.NumRegions)
for i, sus := range m.SoilExhaustion {
vals[i] = sus
}
} else if displayMode == DisplayModeTribes { // Tribes.
vals = make([]float64, m.NumRegions)
for _, tribe := range m.Tribes {
vals[tribe.RegionID] = float64(tribe.Population)
if tribe.Path != nil {
for _, p := range tribe.Path.Steps {
vals[p] = float64(tribe.Population) * 2
}
}
}
}
// Calculate the min and max elevation.
_, max := minMax(m.Elevation)
_, maxMois := minMax(m.Moisture)
minVal, maxVal := minMax(vals)
colorFunc = func(i int, n float64) color.Color {
// Calculate the color of the region.
elev := m.Elevation[i]
val := (vals[i] - minVal) / (maxVal - minVal)
// Return blue for water (oceans and lakes).
if elev <= 0 || (m.Waterpool[i] > 0 && drawLakes) {
return genBlue(val)
}
// Return the biome color for land.
rLat := m.LatLon[i][0]
valElev := elev / max
valMois := m.Moisture[i] / maxMois
return geo.GetWhittakerModBiomeColor(rLat, valElev, valMois, math.Pow(val, 1/n))
}
}
// Wrap the tile coordinates.
x, y = wrapTileCoordinates(x, y, zoom)
// Calculate an approximation of the distance between regions.
distRegion := math.Sqrt(4 * math.Pi / float64(m.NumRegions))
// Convert into degrees.
distRegionDeg := distRegion * 180 / math.Pi
// Calculate the bounds of the tile.
tbb := newTileBoundingBox(x, y, zoom)
la1, lo1, la2, lo2 := tbb.toLatLon()
latLonMargin := math.Max(20/float64(zoom), distRegionDeg*10)
// Calculate the bounds with margin for the tile.
la1Margin := la1 - latLonMargin //math.Max(-90, math.Min(90, la1-latLonMargin))
la2Margin := la2 + latLonMargin //math.Max(-90, math.Min(90, la2+latLonMargin))
lo1Margin := lo1 - latLonMargin
lo2Margin := lo2 + latLonMargin
// Check if we are within the tile with a small margin, taking
// into account that we might have wrapped around the world.
isLatLonInBounds := func(lat, lon float64) bool {
if lat < la1Margin || lat > la2Margin || lon < lo1Margin || lon > lo2Margin {
// Check if the tile and the region we are looking at is adjecent to +/- 180 degrees and
// NOTE: This could be improved by checking if one of the corners of the region is within the tile.
if lo1 > -175 && lo2 < 175 || lon < 175 && lon > -175 {
return false
}
}
return true
}
// Since our mercator conversion gives us absolute pixel coordinates, we need to
// remove the offset of the tile we are rendering from the path coordinates.
dx, _ := latLonToPixels(la1, lo1, zoom)
_, dy2 := latLonToPixels(la2, lo2, zoom)
// Create a new image to draw the tile on.
dest := image.NewRGBA(image.Rect(0, 0, tileSize, tileSize))
gc := draw2dimg.NewGraphicContext(dest)
// Get all regions that are within the tile bounds.
var inQuadTreeRegs []int
qds := mesh.RegQuadTree.FindPointsInRect(geoquad.Rect{
MinLat: la1Margin,
MaxLat: la2Margin,
MinLon: lo1Margin,
MaxLon: lo2Margin,
})
for _, qd := range qds {
inQuadTreeRegs = append(inQuadTreeRegs, qd.Data.(int))
}
// Draw the regions.
out_t := make([]int, 0, 6)
gc.SetLineWidth(1)
for _, i := range inQuadTreeRegs {
// rLat := m.LatLon[i][0]
rLon := mesh.LatLon[i][1]
// Draw the path that outlines the region.
var path [][2]float64
for _, j := range mesh.R_circulate_t(out_t, i) {
tLat := mesh.TriLatLon[j][0]
tLon := mesh.TriLatLon[j][1]
// Check if we have wrapped around the world.
if tLon-rLon > 120 {
tLon -= 360
} else if tLon-rLon < -120 {
tLon += 360
}
// Calculate the coordinates of the path point.
x, y := latLonToPixels(tLat, tLon, zoom)
path = append(path, [2]float64{(x - dx), (y - dy2)})
}
// Now check if the region we are looking at has wrapped around the world /
// +- 180 degrees. If so, we need to adjust the points in the path.
if lo1 < -175 && rLon > 175 {
for i := range path {
path[i][0] -= float64(sizeFromZoom(zoom))
}
} else if lo2 > 175 && rLon < -175 {
for i := range path {
path[i][0] += float64(sizeFromZoom(zoom))
}
}
// Calculate the color of the region.
col := colorFunc(i*step, 1.0)
// If the path is empty, we can skip it.
if len(path) == 0 {
continue
}
// Draw the path.
gc.SetStrokeColor(col)
gc.SetFillColor(col)
gc.BeginPath()
for i, p := range path {
if i == 0 {
gc.MoveTo(p[0], p[1])
} else {
gc.LineTo(p[0], p[1])
}
}
gc.Close()
gc.FillStroke()
}
if drawShadows {
// Get all triangles that are within the tile bounds.
var inQuadTreeTris []int
qds = m.TriQuadTree.FindPointsInRect(geoquad.Rect{
MinLat: la1Margin,
MaxLat: la2Margin,
MinLon: lo1Margin,
MaxLon: lo2Margin,
})
for _, qd := range qds {
inQuadTreeTris = append(inQuadTreeTris, qd.Data.(int))
}
// Set the global light direction (upper left when looking at the map)
lightDir := vectors.Vec3{X: -1.0, Y: 1.0, Z: 1.0}.Normalize()
// Set our initial line width.
gc.SetLineWidth(1)
Loop:
for _, i := range inQuadTreeTris {
// Hacky way to filter paths/triangles that wrap around the entire SVG.
triLat := m.TriLatLon[i][0]
triLon := m.TriLatLon[i][1]
// Check if we are within the tile with a small margin, taking
// into account that we might have wrapped around the world.
if !isLatLonInBounds(triLat, triLon) {
continue
}
// Draw the path that outlines the region.
var path [][2]float64
for _, j := range m.T_circulate_r(out_t, i) {
rLat := m.LatLon[j][0]
rLon := m.LatLon[j][1]
// Check if we the region is across the +/- 180 degrees longitude line
// compared to the triangle.
// In this case, the longitude is almost 360 degrees off, which means
// we need to adjust the longitude.
if rLon-triLon > 110 {
rLon -= 360
} else if rLon-triLon < -110 {
rLon += 360
}
// Calculate the coordinates of the path point.
x, y := latLonToPixels(rLat, rLon, zoom)
p := [2]float64{(x - dx), (y - dy2)}
// Check if we are way outside the tile.
if p[0] < -1000 || p[0] > 1000 || p[1] < -1000 || p[1] > 1000 {
continue Loop
}
path = append(path, p)
}
// Now check if the region we are looking at has wrapped around the world /
// +- 180 degrees. If so, we need to adjust the points in the path.
if lo1 < -175 && triLon > 175 {
for i := range path {
path[i][0] -= float64(sizeFromZoom(zoom))
}
} else if lo2 > 175 && triLon < -175 {
for i := range path {
path[i][0] += float64(sizeFromZoom(zoom))
}
}
// Get the 3 regions of the triangle.
regions := m.T_circulate_r(out_t, i)
// Get the normal of the triangle.
normal := m.RegTriNormal(i, regions)
// Now take the dot product of the slope and our global light
// direction to get the amount of light on the triangle.
diffuseShading := math.Max(0, vectors.Dot3(normal, lightDir))
// Brightness is the amount of light on the triangle.
var brightness float64
// If we have aspect shading enabled, calculate the aspect shading
// and mix it with the diffuse shading.
if aspectShading {
// Calculate the slope angle from the normal vector as
// a value between 0 and 1.
slope := math.Abs(math.Acos(normal.Y) / (math.Pi / 2))
// Get the azimuth of the light source vector3.
azimuth := math.Atan2(lightDir.Z, lightDir.X)
// Get the aspect of the triangle based on the normal vector.
aspect := math.Atan2(normal.Z, normal.X)
// Now calculate the aspect based shading.
aspectShading := math.Max(0, math.Cos(azimuth-aspect))
// Calculate the brightness of the triangle and mix
// brightness and shade based on the slope angle.
brightness = math.Min(1, math.Max(0, diffuseShading*(1-slope)+aspectShading*slope))
} else {
// Calculate the brightness of the triangle.
brightness = diffuseShading
}
// We have already the coordinates of all 3 regions, so we can just use them.
// We need to calculate the midpoint for each side of the triangle if one or two
// of the regions are below the sea level.
// We do this by calculating the intersection of the triangle segment
// with the sea level plane and then calculate the new midpoint for the triangle.
var midSides [3][2]float64
// Calculate the midpoints of each side of the triangle,
// given a possible intercept with the sea level plane.
// We need to do this for each side of the triangle where
// one of the regions is below the sea level.
var regsBelowSeaLevel [3]bool
var countBelowSeaLevel int
for j := 0; j < 3; j++ {
// Get the 2 regions of the triangle segment.
r1 := regions[j]
r2 := regions[(j+1)%3]
// Get the 2 points of the triangle segment.
x1, y1, z1 := path[j][0], path[j][1], m.Elevation[r1]
x2, y2, z2 := path[(j+1)%3][0], path[(j+1)%3][1], m.Elevation[r2]
if z1 <= 0 {
regsBelowSeaLevel[j] = true
countBelowSeaLevel++
}
// Check if we have a triangle segment that crosses the sea level plane.
if (z1 <= 0) != (z2 <= 0) {
// Calculate the intersection of the triangle segment with the sea level plane
// (when z becomes zero).
// We do this by calculating the ratio of the distance from the first point
// to the intersection point to the distance between the first and second point.
// We then use this ratio to calculate the coordinates of the intersection point.
ratio := math.Abs(z1) / (math.Abs(z1) + math.Abs(z2))
x := x1 + (x2-x1)*ratio
y := y1 + (y2-y1)*ratio
// Set the midpoint of the triangle segment to the intersection point.
midSides[j][0] = x
midSides[j][1] = y
} else {
// If the triangle segment does not cross the sea level plane,
// we can just use the midpoint of the triangle segment.
midSides[j][0] = (x1 + x2) / 2
midSides[j][1] = (y1 + y2) / 2
}
}
// Calculate the new midpoint of the triangle, which needs to be
// at sea level if one or two of the regions are below the sea level.
// - If one or two regions ar below the sea level, the midpoint of the triangle should
// be set at the midpoint between the two midpoints of the triangle segments that
// cross the sea level plane.
// - If all regions are above the sea level, the midpoint of the triangle should
// be set at the midpoint of the triangle.
var midTriangle [2]float64
// If only one region is below the sea level, the midpoint of the triangle should
// be set at the midpoint between the two midpoints of the triangle segments that
// cross the sea level plane.
if countBelowSeaLevel == 1 {
for j := 0; j < 3; j++ {
if regsBelowSeaLevel[j] {
midTriangle[0] = (midSides[(j+0)%3][0] + midSides[(j+2)%3][0]) / 2
midTriangle[1] = (midSides[(j+0)%3][1] + midSides[(j+2)%3][1]) / 2
break
}
}
} else if countBelowSeaLevel == 2 {
// If two regions are below the sea level, the midpoint of the triangle should
// be set at the midpoint between the two midpoints of the triangle segments that
// cross the sea level plane.
for j := 0; j < 3; j++ {
// If the current region is above the sea level, we can use the midpoint
// of the triangle segments, which are the current segment and the previous segment.
if !regsBelowSeaLevel[j] {
midTriangle[0] = (midSides[(j+0)%3][0] + midSides[(j+2)%3][0]) / 2
midTriangle[1] = (midSides[(j+0)%3][1] + midSides[(j+2)%3][1]) / 2
break
}
}
} else {
// If all regions are above the sea level, the midpoint of the triangle should
// be set at the midpoint of the triangle.
midTriangle[0] = (path[0][0] + path[1][0] + path[2][0]) / 3
midTriangle[1] = (path[0][1] + path[1][1] + path[2][1]) / 3
}
// Now we can draw the triangle using the adjusted midpoints.
for j := 0; j < 3; j++ {
// Set the color of the triangle shard.
col := colorFunc(regions[j], brightness)
gc.SetStrokeColor(col)
gc.SetFillColor(col)
// Get the 4 points of the triangle shard
// One region is the original point of the triangle,
// the other two are the midpoints of the triangle segment,
// and the midpoint of the triangle.
x1, y1 := path[j][0], path[j][1]
x2, y2 := midSides[(j+0)%3][0], midSides[(j+0)%3][1]
x3, y3 := midTriangle[0], midTriangle[1]
x4, y4 := midSides[(j+2)%3][0], midSides[(j+2)%3][1]
// Draw the triangle shard.
gc.BeginPath()
// First, we move to the first point of the triangle shard,
gc.MoveTo(x1, y1)
// then we draw a line to the midpoint of the first line segment,
gc.LineTo(x2, y2)
// then we draw a line to the midpoint of the triangle,
gc.LineTo(x3, y3)
// then we draw a line to the midpoint of the third line segment,
gc.LineTo(x4, y4)
// and finally we close the path.
gc.Close()
gc.FillStroke()
}
}
}
// Draw all the wind vectors on top.
if vectorMode > 0 {
vects := m.RegionToWindVec
if vectorMode == 2 {
vects = m.RegionToWindVecLocal
} else if vectorMode == 3 {
vects = m.RegionToOceanVec
}
// Set the color and line width of the wind vectors.
gc.SetStrokeColor(color.NRGBA{0, 0, 0, 255})
gc.SetLineWidth(1)
for _, i := range inQuadTreeRegs {
rLat := m.LatLon[i][0]
rLon := m.LatLon[i][1]
// Now draw the wind vector for the region.
// NOTE: I'm not 100% sure if this is correct, but it seems to work.
wLat, wLon := various.VectorToLatLong(various.Normalize2(vects[i]))
windVec := various.Normalize2([2]float64{wLat, wLon})
// Calculate the coordinates of the center of the region.
x, y := latLonToPixels(rLat, rLon, zoom)
x -= dx
y -= dy2
// Calculate the length of the wind vector.
length := various.Len2(windVec)
// Calculate the angle of the wind vector.
angle := math.Atan2(windVec[1], windVec[0])
// Calculate the coordinates of the end of the wind vector.
// Since we are on a computer screen, we need to flip the y-axis.
x2 := x + math.Cos(angle)*length*50
y2 := y - math.Sin(angle)*length*50
// Draw the wind vector.
gc.BeginPath()
gc.MoveTo(x, y)
gc.LineTo(x2, y2)
gc.Stroke()
// Draw the arrow head.
gc.BeginPath()
gc.MoveTo(x2, y2)
gc.LineTo(x2-math.Cos(angle+math.Pi/6)*5, y2+math.Sin(angle+math.Pi/6)*5)
gc.Stroke()
gc.BeginPath()
gc.MoveTo(x2, y2)
gc.LineTo(x2-math.Cos(angle-math.Pi/6)*5, y2+math.Sin(angle-math.Pi/6)*5)
gc.Stroke()
}
}
// Now we do something completely inefficient and
// fetch all the rivers and filter them by the tile.
// We should filter this stuff before we generate the rivers.
if drawRivers {
rivers := m.GetRiversInLatLonBB(0.001/float64(int(1)<<zoom), la1Margin, lo1Margin, la2Margin, lo2Margin)
_, maxFlux := minMax(m.Flux)
// Set our stroke color to a nice river blue.
gc.SetStrokeColor(color.NRGBA{0, 0, 255, 255})
for _, river := range rivers {
// Set the initial line width.
gc.SetLineWidth(1)
gc.BeginPath()
// Move to the first point.
rLat, rLon := m.LatLon[river[0]][0], m.LatLon[river[0]][1]
x, y := latLonToPixels(rLat, rLon, zoom)
gc.MoveTo(x-dx, y-dy2)
for i, p := range river[1:] {
// Set the line width based on the flux of the river, averaged with the previous flux.
gc.SetLineWidth(4 * math.Sqrt((m.Flux[p]+m.Flux[river[i]])/(2*maxFlux)))
// Set the line width based on the flux of the river.
rLat, rLon = m.LatLon[p][0], m.LatLon[p][1]
// Now compare the longitude to the previous longitude.
// If we have crossed the +- 180 degree boundary, we need to
// draw to a fake point at the same latitude but on the same side of the world.
if diff := rLon - m.LatLon[river[i]][1]; math.Abs(diff) > 110 {
rLonFake := rLon - 360
if diff < 0 {
rLonFake = rLon + 360
}
// Draw to the fake point.
x, y := latLonToPixels(rLat, rLonFake, zoom)
gc.LineTo(x-dx, y-dy2)
gc.Stroke()
// Move to the real point and start a new path.
x, y = latLonToPixels(rLat, rLon, zoom)
gc.BeginPath()
gc.MoveTo(x-dx, y-dy2)
}
x, y := latLonToPixels(rLat, rLon, zoom)
x -= dx
y -= dy2
// If both points are in a pool or below sea level, we end the path,
// move to the new point and start a new path.
// TODO: Calculate intercept of the river with the sea level.
if (m.Elevation[p] <= 0 || m.Waterpool[p] > 0 && drawLakes) &&
(m.Elevation[river[i]] <= 0 || m.Waterpool[river[i]] > 0 && drawLakes) {
// Draw from the last position to the midpoint.
// This will cause the river to end at the sea level.
gc.Stroke()
gc.Close()
// Move to the new point and start a new path.
gc.BeginPath()
gc.MoveTo(x, y)
} else if m.Elevation[p] <= 0 || (m.Waterpool[p] > 0 && drawLakes) {
// If we are below sea level, interpolate the point with the previous point.
// Draw from the last position to the midpoint.
// This will cause the river to end at the sea level.
lx, ly := gc.LastPoint()
gc.LineTo((x+lx)/2, (y+ly)/2)
// Move to the new point.
gc.MoveTo(x, y)
} else if m.Elevation[river[i]] <= 0 || (m.Waterpool[river[i]] > 0 && drawLakes) {
// If the previous point was below sea level, interpolate the point with the next point.
// This will cause the river to start at the sea level.
lx, ly := gc.LastPoint()
gc.MoveTo((x+lx)/2, (y+ly)/2)
// Draw to the new point.
gc.LineTo(x, y)
} else {
gc.LineTo(x, y)
}
// TODO: Use steepness to determine the amplitude of meandering.
// The less steep the river is, the more it meanders.
// lx, ly := gc.LastPoint()
// gc.CubicCurveTo((x+2*lx)/3, ly, lx, (ly+2*y)/3, x, y)
}
gc.Stroke()
gc.Close()
}
}
if drawTradeRoutes {
// Get all the trade routes.
traderoutes := m.getTradeRoutesInLatLonBB(la1Margin, lo1Margin, la2Margin, lo2Margin)
// Set our stroke color to a nice traderoute red.
gc.SetStrokeColor(color.NRGBA{255, 0, 0, 255})
for _, traderoute := range traderoutes {
// Set the initial line width.
gc.SetLineWidth(1)
gc.BeginPath()
for i, p := range traderoute {
rLat, rLon := m.LatLon[p][0], m.LatLon[p][1]
x, y := latLonToPixels(rLat, rLon, zoom)
if i == 0 {
// Move to the first point.
gc.MoveTo(x-dx, y-dy2)
} else {
// Now compare the longitude to the previous longitude.
// If we have crossed the +- 180 degree boundary, we need to
// draw to a fake point at the same latitude but on the same side of the world.
if diff := rLon - m.LatLon[traderoute[i-1]][1]; math.Abs(diff) > 110 {
rLonFake := rLon - 360
if diff < 0 {
rLonFake = rLon + 360
}
// Draw to the fake point.
x, y := latLonToPixels(rLat, rLonFake, zoom)
gc.LineTo(x-dx, y-dy2)
gc.Stroke()
// Move to the real point and start a new path.
x, y = latLonToPixels(rLat, rLon, zoom)
gc.BeginPath()
gc.MoveTo(x-dx, y-dy2)
}
// Draw to the next point.
gc.LineTo(x-dx, y-dy2)
}
}
gc.Stroke()
gc.Close()
}
}
return dest
}
func wrapTileCoordinates(x, y, zoom int) (int, int) {
// Wrap the tile coordinates.
x = x % (1 << uint(zoom))
if x < 0 {
x += 1 << uint(zoom)
}
y = y % (1 << uint(zoom))
if y < 0 {
y += 1 << uint(zoom)
}
return x, y
}
func wrapLatLon(la, lo float64) (float64, float64) {
// Wrap the lat lon coordinates.
la = math.Mod(la, 180)
if la < -90 {
la += 180
} else if la > 90 {
la -= 180
}
lo = math.Mod(lo, 360)
if lo < -180 {
lo += 360
} else if lo > 180 {
lo -= 360
}
return la, lo
}
func limitLatLon(la, lo float64) (float64, float64) {
// Limit the lat lon coordinates.
if la < -90 {
la = -90
} else if la > 90 {
la = 90
}
if lo < -180 {
lo = -180
} else if lo > 180 {
lo = 180
}
return la, lo
}
type latLonBounds struct {
la1, lo1, la2, lo2 float64
}
// InBounds checks if the given lat lon coordinates are within the bounds.
// NOTE: We need to take in account that the bounds might have wrapped around the world.
func (b latLonBounds) InBounds(la, lo float64) bool {
if b.la1 < b.la2 {
// We wrapped around north or south.
if la > b.la1 && la < b.la2 {
return false
}
} else {
if la > b.la1 || la < b.la2 {
return false
}
}
if b.lo1 > b.lo2 {
// We wrapped around east or west.
if lo < b.lo1 && lo > b.lo2 {
return false
}
} else {
if lo < b.lo1 || lo > b.lo2 {
return false
}
}
return true
}
func wrapLatitude(la float64) float64 {
// Wrap the latitude.
la = math.Mod(la, 180)
if la < -90 {
la += 180
} else if la > 90 {
la -= 180
}
return la
}
func wrapLongitude(lo float64) float64 {
// Wrap the longitude.
lo = math.Mod(lo, 360)
if lo < -180 {
lo += 360
} else if lo > 180 {
lo -= 360
}
return lo
}
func limitLatitude(la float64) float64 {
// Limit the latitude.
if la < -90 {
la = -90
} else if la > 90 {
la = 90
}
return la
}
func limitLongitude(lo float64) float64 {
// Limit the longitude.
if lo < -180 {
lo = -180
} else if lo > 180 {
lo = 180
}
return lo
}
// GetCitiesInTile returns all cities within the given tile coordinates and zoom level.
func (m *Map) GetCitiesInTile(x, y, zoom int) []*City {
// Wrap the tile coordinates.
x, y = wrapTileCoordinates(x, y, zoom)
// Calculate the bounds of the tile.
tbb := newTileBoundingBox(x, y, zoom)
la1, lo1, la2, lo2 := tbb.toLatLon()
// Wrap the lat lon coordinates.
la1, lo1 = wrapLatLon(la1, lo1)
la2, lo2 = wrapLatLon(la2, lo2)
// Get the cities within the tile.
var cities []*City
for _, c := range m.Cities {
cLatLon := m.LatLon[c.ID]
// Check if we are within the tile with a small margin.
if la1 < cLatLon[0] && cLatLon[0] < la2 && lo1 < cLatLon[1] && cLatLon[1] < lo2 {
continue
}
cities = append(cities, c)
}
return cities
}
// GetGeoJSONCities returns all cities as GeoJSON within the given bounds and zoom level.
func (m *Map) GetGeoJSONCities(la1, lo1, la2, lo2 float64, zoom int) ([]byte, error) {
geoJSON := geojson.NewFeatureCollection()
// Wrap the latitude only if we see less than 180 degrees, otherwise just limit it.
if math.Abs(la1-la2) < 180 {
la1 = wrapLatitude(la1)
la2 = wrapLatitude(la2)
} else {
la1 = limitLatitude(la1)
la2 = limitLatitude(la2)
}
// Wrap the longitude only if we see less than 360 degrees.
if math.Abs(lo1-lo2) < 360 {
lo1 = wrapLongitude(lo1)
lo2 = wrapLongitude(lo2)
} else {
lo1 = limitLongitude(lo1)
lo2 = limitLongitude(lo2)
}
lbb := latLonBounds{la1, lo1, la2, lo2}
// Get the last settled year.
_, maxSettled := minMax64(m.Settled)
distRegion := math.Sqrt(4 * math.Pi / float64(m.NumRegions))
biomeFunc := m.GetRegWhittakerModBiomeFunc()
_, maxElev := minMax(m.Elevation)
_, maxMois := minMax(m.Moisture)
regPropertyFunc := m.GetRegPropertyFunc()
// Depending on the zoom level we want to show more or less cities.
sortedCities := make([]*City, len(m.Cities))
copy(sortedCities, m.Cities)
// Sort the cities by population (descending).
sort.Slice(sortedCities, func(i, j int) bool {
return sortedCities[i].Population > sortedCities[j].Population
})
showNumCities := 0
// At zoom level 9 we want to show all cities.
if zoom >= 9 {
showNumCities = len(sortedCities)