forked from ParadoxGameConverters/oldProvinceMapper
/
MapReader.cs
78 lines (70 loc) · 2.61 KB
/
MapReader.cs
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
using System.Collections.Generic;
using System.Drawing;
namespace ProvinceMapper
{
class MapReader
{
public MapReader(Bitmap _map, List<Province> provinces, bool invert, StatusUpdate su)
{
su(0.0);
SortedList<int, Province> sortedProvs = new SortedList<int, Province>();
foreach (Province p in provinces)
{
sortedProvs.Add(p.rgb.ToArgb(), p);
}
map = _map;
bounds = new Rectangle(Point.Empty, map.Size);
if (invert)
{
map.RotateFlip(RotateFlipType.RotateNoneFlipY);
}
UnsafeBitmap bmp = new UnsafeBitmap(map);
bmp.LockBitmap();
#if WRITE_UNRECOGNIZED
Bitmap unrecognizedOverlay = new Bitmap(map.Width, map.Height, map.PixelFormat);
UnsafeBitmap unrecognizedBmp = new UnsafeBitmap(unrecognizedOverlay);
unrecognizedBmp.LockBitmap();
#endif
Province lastProvince = null;
int lastColor = 0;
for (int x = 0; x < map.Width; ++x)
{
for (int y = 0; y < map.Height; ++y)
{
Pixel pix = bmp.GetPixel(x, y);
int argb = (pix.alpha << 24) | (pix.red << 16) | (pix.green << 8) | pix.blue;
if (lastProvince != null && lastColor == argb) // optimize contiguous regions
{
lastProvince.area.Add(new Point(x, y));
}
else if (argb != (pix.alpha << 24)) // ignore black pixels
{
Province match = null;
if (sortedProvs.TryGetValue(argb, out match))
{
match.area.Add(new Point(x, y));
lastProvince = match;
lastColor = argb;
}
else
{
#if WRITE_UNRECOGNIZED
unrecognizedBmp.SetPixel(x, y, new Pixel() { alpha = 0xff, blue = 0xff, green = 0xff, red = 0xff });
#endif
lastColor = 0;
lastProvince = null;
}
}
}
su(100.0 * x / map.Width);
}
bmp.UnlockBitmap();
#if WRITE_UNRECOGNIZED
unrecognizedBmp.UnlockBitmap();
unrecognizedBmp.Bitmap.Save((string)_map.Tag + "_unrecognized.png");
#endif
}
public Bitmap map;
public Rectangle bounds;
}
}