File: mapimg.c

package info (click to toggle)
freeciv 2.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 212,508 kB
  • sloc: ansic: 443,831; cpp: 29,541; sh: 7,982; makefile: 7,886; python: 1,933; xml: 945
file content (3329 lines) | stat: -rw-r--r-- 105,323 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
/****************************************************************************
 Freeciv - Copyright (C) 2010 - The Freeciv Team
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
****************************************************************************/

#ifdef HAVE_CONFIG_H
#include <fc_config.h>
#endif

#include <stdarg.h>

#ifdef HAVE_MAPIMG_MAGICKWAND
  #include <wand/MagickWand.h>
#endif /* HAVE_MAPIMG_MAGICKWAND */

/* utility */
#include "astring.h"
#include "bitvector.h"
#include "fc_cmdline.h"
#include "fcintl.h"
#include "log.h"
#include "mem.h"
#include "string_vector.h"
#include "timing.h"

/* common */
#include "calendar.h"
#include "connection.h"
#include "fc_types.h"
#include "game.h"
#include "map.h"
#include "rgbcolor.h"
#include "terrain.h"
#include "tile.h"
#include "version.h"
#include "player.h"

#include "mapimg.h"

/* Some magick for ImageMagick - the interface has changed:
     ImageMagick-6.6.2-0: PixelGetNextIteratorRow(..., unsigned long *)
     ImageMagick-6.6.2-1: PixelGetNextIteratorRow(..., size_t *)
   Theoretically, "unsigned long" and "size_t" are pretty much the same but
   in practice the compiler will complain bitterly.
   (from Gem-0.93 ImageMAGICK plugin) */
#ifndef MagickLibInterface
# define MagickLibInterface 0
#endif
#ifndef MagickLibVersion
# define MagickLibVersion 0
#endif

/* This won't catch ImageMagick>=6.6.2-0.
   Another workaround: compile with "-fpermissive" */
#if (MagickLibInterface > 3) || (MagickLibVersion >= 0x662)
# define magickwand_size_t size_t
#else
# define magickwand_size_t unsigned long
#endif

/* == image colors == */
enum img_special {
  IMGCOLOR_ERROR,
  IMGCOLOR_OCEAN,
  IMGCOLOR_GROUND,
  IMGCOLOR_BACKGROUND,
  IMGCOLOR_TEXT
};

static const struct rgbcolor *imgcolor_special(enum img_special imgcolor);
static const struct rgbcolor *imgcolor_player(int plr_id);
static const struct rgbcolor
  *imgcolor_terrain(const struct terrain *pterrain);

/* == topologies == */
#define TILE_SIZE 6
#define NUM_PIXEL TILE_SIZE * TILE_SIZE

BV_DEFINE(bv_pixel, NUM_PIXEL);

struct tile_shape {
  int x[NUM_PIXEL];
  int y[NUM_PIXEL];
};

struct img;

typedef bv_pixel (*plot_func)(const struct tile *ptile,
                              const struct player *pplayer,
                              bool knowledge);
typedef void (*base_coor_func)(struct img *pimg, int *base_x, int *base_y,
                               int x, int y);

/* (isometric) rectangular topology */
static struct tile_shape tile_rect = {
  .x = {
    0, 1, 2, 3, 4, 5,
    0, 1, 2, 3, 4, 5,
    0, 1, 2, 3, 4, 5,
    0, 1, 2, 3, 4, 5,
    0, 1, 2, 3, 4, 5,
    0, 1, 2, 3, 4, 5
  },
  .y = {
    0, 0, 0, 0, 0, 0,
    1, 1, 1, 1, 1, 1,
    2, 2, 2, 2, 2, 2,
    3, 3, 3, 3, 3, 3,
    4, 4, 4, 4, 4, 4,
    5, 5, 5, 5, 5, 5
  }
};

static bv_pixel pixel_tile_rect(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge);
static bv_pixel pixel_city_rect(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge);
static bv_pixel pixel_unit_rect(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge);
static bv_pixel pixel_fogofwar_rect(const struct tile *ptile,
                                    const struct player *pplayer,
                                    bool knowledge);
static bv_pixel pixel_border_rect(const struct tile *ptile,
                                  const struct player *pplayer,
                                  bool knowledge);
static void base_coor_rect(struct img *pimg, int *base_x, int *base_y,
                           int x, int y);

/* hexa topology */
static struct tile_shape tile_hexa = {
  .x = {
          2, 3,
       1, 2, 3, 4,
    0, 1, 2, 3, 4, 5,
    0, 1, 2, 3, 4, 5,
    0, 1, 2, 3, 4, 5,
    0, 1, 2, 3, 4, 5,
       1, 2, 3, 4,
          2, 3,
  },
  .y = {
          0, 0,
       1, 1, 1, 1,
    2, 2, 2, 2, 2, 2,
    3, 3, 3, 3, 3, 3,
    4, 4, 4, 4, 4, 4,
    5, 5, 5, 5, 5, 5,
       6, 6, 6, 6,
          7, 7,
  }
};

static bv_pixel pixel_tile_hexa(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge);
static bv_pixel pixel_city_hexa(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge);
static bv_pixel pixel_unit_hexa(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge);
static bv_pixel pixel_fogofwar_hexa(const struct tile *ptile,
                                    const struct player *pplayer,
                                    bool knowledge);
static bv_pixel pixel_border_hexa(const struct tile *ptile,
                                  const struct player *pplayer,
                                  bool knowledge);
static void base_coor_hexa(struct img *pimg, int *base_x, int *base_y,
                           int x, int y);

/* isometric hexa topology */
static struct tile_shape tile_isohexa = {
  .x = {
          2, 3, 4, 5,
       1, 2, 3, 4, 5, 6,
    0, 1, 2, 3, 4, 5, 6, 7,
    0, 1, 2, 3, 4, 5, 6, 7,
       1, 2, 3, 4, 5, 6,
          2, 3, 4, 5
  },
  .y = {
          0, 0, 0, 0,
       1, 1, 1, 1, 1, 1,
    2, 2, 2, 2, 2, 2, 2, 2,
    3, 3, 3, 3, 3, 3, 3, 3,
       4, 4, 4, 4, 4, 4,
          5, 5, 5, 5
  }
};

static bv_pixel pixel_tile_isohexa(const struct tile *ptile,
                                   const struct player *pplayer,
                                   bool knowledge);
static bv_pixel pixel_city_isohexa(const struct tile *ptile,
                                   const struct player *pplayer,
                                   bool knowledge);
static bv_pixel pixel_unit_isohexa(const struct tile *ptile,
                                   const struct player *pplayer,
                                   bool knowledge);
static bv_pixel pixel_fogofwar_isohexa(const struct tile *ptile,
                                       const struct player *pplayer,
                                       bool knowledge);
static bv_pixel pixel_border_isohexa(const struct tile *ptile,
                                     const struct player *pplayer,
                                     bool knowledge);
static void base_coor_isohexa(struct img *pimg, int *base_x, int *base_y,
                              int x, int y);

/* == map images == */

#define ARG_PLRBV   "plrbv"
#define ARG_PLRID   "plrid"
#define ARG_PLRNAME "plrname"

/* mapimg definition */
#define SPECENUM_NAME mapdef_arg
#define SPECENUM_VALUE0     MAPDEF_FORMAT
#define SPECENUM_VALUE0NAME "format"
#define SPECENUM_VALUE1     MAPDEF_MAP
#define SPECENUM_VALUE1NAME "map"
#define SPECENUM_VALUE2     MAPDEF_PLRBV
#define SPECENUM_VALUE2NAME ARG_PLRBV
#define SPECENUM_VALUE3     MAPDEF_PLRID
#define SPECENUM_VALUE3NAME ARG_PLRID
#define SPECENUM_VALUE4     MAPDEF_PLRNAME
#define SPECENUM_VALUE4NAME ARG_PLRNAME
#define SPECENUM_VALUE5     MAPDEF_SHOW
#define SPECENUM_VALUE5NAME "show"
#define SPECENUM_VALUE6     MAPDEF_TURNS
#define SPECENUM_VALUE6NAME "turns"
#define SPECENUM_VALUE7     MAPDEF_ZOOM
#define SPECENUM_VALUE7NAME "zoom"
#define SPECENUM_COUNT      MAPDEF_COUNT
#include "specenum_gen.h"

BV_DEFINE(bv_mapdef_arg, MAPDEF_COUNT);

/* image format */
#define SPECENUM_NAME imageformat
#define SPECENUM_BITWISE
#define SPECENUM_VALUE0     IMGFORMAT_GIF
#define SPECENUM_VALUE0NAME "gif"
#define SPECENUM_VALUE1     IMGFORMAT_PNG
#define SPECENUM_VALUE1NAME "png"
#define SPECENUM_VALUE2     IMGFORMAT_PPM
#define SPECENUM_VALUE2NAME "ppm"
#define SPECENUM_VALUE3     IMGFORMAT_JPG
#define SPECENUM_VALUE3NAME "jpg"
#include "specenum_gen.h"

/* image format */
#define SPECENUM_NAME imagetool
#define SPECENUM_VALUE0     IMGTOOL_PPM
#define SPECENUM_VALUE0NAME "ppm"
#define SPECENUM_VALUE1     IMGTOOL_MAGICKWAND
#define SPECENUM_VALUE1NAME "magick"
#include "specenum_gen.h"

/* player definitions */
#define SPECENUM_NAME show_player
#define SPECENUM_VALUE0     SHOW_NONE
#define SPECENUM_VALUE0NAME "none"
#define SPECENUM_VALUE1     SHOW_EACH
#define SPECENUM_VALUE1NAME "each"
#define SPECENUM_VALUE2     SHOW_HUMAN
#define SPECENUM_VALUE2NAME "human"
#define SPECENUM_VALUE3     SHOW_ALL
#define SPECENUM_VALUE3NAME "all"
/* should be identical to MAPDEF_PLRNAME */
#define SPECENUM_VALUE4     SHOW_PLRNAME
#define SPECENUM_VALUE4NAME ARG_PLRNAME
/* should be identical to MAPDEF_PLRID */
#define SPECENUM_VALUE5     SHOW_PLRID
#define SPECENUM_VALUE5NAME ARG_PLRID
/* should be identical to MAPDEF_PLRBV */
#define SPECENUM_VALUE6     SHOW_PLRBV
#define SPECENUM_VALUE6NAME ARG_PLRBV
#include "specenum_gen.h"

#undef ARG_PLRBV
#undef ARG_PLRID
#undef ARG_PLRNAME

/* map definition status */
#define SPECENUM_NAME mapimg_status
#define SPECENUM_VALUE0     MAPIMG_STATUS_UNKNOWN
#define SPECENUM_VALUE0NAME _("not checked")
#define SPECENUM_VALUE1     MAPIMG_STATUS_OK
#define SPECENUM_VALUE1NAME _("OK")
#define SPECENUM_VALUE2     MAPIMG_STATUS_ERROR
#define SPECENUM_VALUE2NAME _("error")
#include "specenum_gen.h"

#define MAX_LEN_MAPARG MAX_LEN_MAPDEF
#define MAX_NUM_MAPIMG 10

static inline bool mapimg_initialised(void);
static bool mapimg_test(int id);
static bool mapimg_define_arg(struct mapdef *pmapdef, enum mapdef_arg arg,
                              const char *val, bool check);
static bool mapimg_def2str(struct mapdef *pmapdef, char *str, size_t str_len);
static bool mapimg_checkplayers(struct mapdef *pmapdef, bool recheck);
static char *mapimg_generate_name(struct mapdef *pmapdef);

/* == map definition == */
struct mapdef {
  char maparg[MAX_LEN_MAPARG];
  char error[MAX_LEN_MAPDEF];
  enum mapimg_status status;
  enum imageformat format;
  enum imagetool tool;
  int zoom;
  int turns;
  bool layers[MAPIMG_LAYER_COUNT];
  struct {
    enum show_player show;
    union {
      char name[MAX_LEN_NAME]; /* used by SHOW_PLRNAME */
      int id;                  /* used by SHOW_PLRID */
      bv_player plrbv;         /* used by SHOW_PLRBV */
    };
    bv_player checked_plrbv;   /* player bitvector used for the image
                                * creation */
  } player;

  bv_mapdef_arg args;
  bool colortest;
};

static struct mapdef *mapdef_new(bool colortest);
static void mapdef_destroy(struct mapdef *pmapdef);

/* List of map definitions. */
#define SPECLIST_TAG mapdef
#define SPECLIST_TYPE struct mapdef
#include "speclist.h"

#define mapdef_list_iterate(mapdef_list, pmapdef) \
  TYPED_LIST_ITERATE(struct mapdef, mapdef_list, pmapdef)
#define mapdef_list_iterate_end \
  LIST_ITERATE_END

/* == images == */
struct mapdef;

/* Some lengths used for the images created by the magickwand toolkit. */
#define IMG_BORDER_HEIGHT 5
#define IMG_BORDER_WIDTH IMG_BORDER_HEIGHT
#define IMG_SPACER_HEIGHT 5
#define IMG_LINE_HEIGHT 5
#define IMG_TEXT_HEIGHT 12

struct img {
  struct mapdef *def; /* map definition */
  int turn; /* save turn */
  char title[MAX_LEN_MAPDEF];

  /* topology definition */
  struct tile_shape *tileshape;
  plot_func pixel_tile;
  plot_func pixel_city;
  plot_func pixel_unit;
  plot_func pixel_fogofwar;
  plot_func pixel_border;
  base_coor_func base_coor;

  struct {
    int x;
    int y;
  } mapsize; /* map size */
  struct {
    int x;
    int y;
  } imgsize; /* image size */
  const struct rgbcolor **map;
};

static struct img *img_new(struct mapdef *mapdef, int topo, int xsize, int ysize);
static void img_destroy(struct img *pimg);
static inline void img_set_pixel(struct img *pimg, const int mindex,
                                 const struct rgbcolor *pcolor);
static inline int img_index(const int x, const int y,
                            const struct img *pimg);
static const char *img_playerstr(const struct player *pplayer);
static void img_plot(struct img *pimg, int x, int y,
                     const struct rgbcolor *pcolor, const bv_pixel pixel);
static void img_plot_tile(struct img *pimg, const struct tile *ptile,
                          const struct rgbcolor *pcolor, const bv_pixel pixel);
static bool img_save(const struct img *pimg, const char *mapimgfile,
                     const char *path);
static bool img_save_ppm(const struct img *pimg, const char *mapimgfile);
#ifdef HAVE_MAPIMG_MAGICKWAND
static bool img_save_magickwand(const struct img *pimg,
                                const char *mapimgfile);
#endif /* HAVE_MAPIMG_MAGICKWAND */
static bool img_filename(const char *mapimgfile, enum imageformat format,
                         char *filename, size_t filename_len);
static void img_createmap(struct img *pimg);

/* == image toolkits == */
typedef bool (*img_save_func)(const struct img *pimg,
                              const char *mapimgfile);

struct toolkit {
  enum imagetool tool;
  enum imageformat format_default;
  int formats;
  const img_save_func img_save;
  const char *help;
};

#define GEN_TOOLKIT(_tool, _format_default, _formats, _save_func, _help)    \
  {_tool, _format_default, _formats, _save_func, _help},

static struct toolkit img_toolkits[] = {
  GEN_TOOLKIT(IMGTOOL_PPM, IMGFORMAT_PPM, IMGFORMAT_PPM,
              img_save_ppm,
              N_("Standard ppm files"))
#ifdef HAVE_MAPIMG_MAGICKWAND
  GEN_TOOLKIT(IMGTOOL_MAGICKWAND, IMGFORMAT_GIF,
              IMGFORMAT_GIF + IMGFORMAT_PNG + IMGFORMAT_PPM + IMGFORMAT_JPG,
              img_save_magickwand,
              N_("ImageMagick"))
#endif /* HAVE_MAPIMG_MAGICKWAND */
};

static const int img_toolkits_count = ARRAY_SIZE(img_toolkits);

#ifdef HAVE_MAPIMG_MAGICKWAND
  #define MAPIMG_DEFAULT_IMGFORMAT IMGFORMAT_GIF
  #define MAPIMG_DEFAULT_IMGTOOL   IMGTOOL_MAGICKWAND
#else
  #define MAPIMG_DEFAULT_IMGFORMAT IMGFORMAT_PPM
  #define MAPIMG_DEFAULT_IMGTOOL   IMGTOOL_PPM
#endif /* HAVE_MAPIMG_MAGICKWAND */

static const struct toolkit *img_toolkit_get(enum imagetool tool);

#define img_toolkit_iterate(_toolkit)                                       \
  {                                                                         \
    int _i;                                                                 \
    for (_i = 0; _i < img_toolkits_count; _i++) {                           \
      const struct toolkit *_toolkit = &img_toolkits[_i];

#define img_toolkit_iterate_end                                             \
    }                                                                       \
  }

/* == logging == */
#define MAX_LEN_ERRORBUF 1024

static char error_buffer[MAX_LEN_ERRORBUF] = "\0";
static void mapimg_log(const char *file, const char *function, int line,
                       const char *format, ...)
                       fc__attribute((__format__(__printf__, 4, 5)));
#define MAPIMG_LOG(format, ...)                                             \
  mapimg_log(__FILE__, __FUNCTION__, __FC_LINE__, format, ## __VA_ARGS__)
#define MAPIMG_ASSERT_RET_VAL(cond, expr)                                   \
  fc_assert_action(cond, MAPIMG_LOG(_("internal error")); return (expr))

/* == additional functions == */

static int bvplayers_count(const struct mapdef *pmapdef);
static const char *bvplayers_str(const bv_player plrbv);

/* == map images data == */
static struct {
  bool init;
  struct mapdef_list *mapdef;

  mapimg_tile_known_func mapimg_tile_known;
  mapimg_tile_terrain_func mapimg_tile_terrain;
  mapimg_tile_player_func mapimg_tile_owner;
  mapimg_tile_player_func mapimg_tile_city;
  mapimg_tile_player_func mapimg_tile_unit;
  mapimg_plrcolor_count_func mapimg_plrcolor_count;
  mapimg_plrcolor_get_func mapimg_plrcolor_get;
} mapimg = { .init = FALSE };

/*
 * ==============================================
 * map images (external functions)
 * ==============================================
 */

/****************************************************************************
  Initialisation of the map image subsystem. The arguments are used to
  determine the map knowledge, the terrain type as well as the tile, city and
  unit owner.
****************************************************************************/
void mapimg_init(mapimg_tile_known_func mapimg_tile_known,
                 mapimg_tile_terrain_func mapimg_tile_terrain,
                 mapimg_tile_player_func mapimg_tile_owner,
                 mapimg_tile_player_func mapimg_tile_city,
                 mapimg_tile_player_func mapimg_tile_unit,
                 mapimg_plrcolor_count_func mapimg_plrcolor_count,
                 mapimg_plrcolor_get_func mapimg_plrcolor_get)
{
  if (mapimg_initialised()) {
    return;
  }

  mapimg.mapdef = mapdef_list_new();

  fc_assert_ret(mapimg_tile_known != NULL);
  mapimg.mapimg_tile_known = mapimg_tile_known;
  fc_assert_ret(mapimg_tile_terrain != NULL);
  mapimg.mapimg_tile_terrain = mapimg_tile_terrain;
  fc_assert_ret(mapimg_tile_owner != NULL);
  mapimg.mapimg_tile_owner = mapimg_tile_owner;
  fc_assert_ret(mapimg_tile_city != NULL);
  mapimg.mapimg_tile_city = mapimg_tile_city;
  fc_assert_ret(mapimg_tile_unit != NULL);
  mapimg.mapimg_tile_unit = mapimg_tile_unit;
  fc_assert_ret(mapimg_plrcolor_count != NULL);
  mapimg.mapimg_plrcolor_count = mapimg_plrcolor_count;
  fc_assert_ret(mapimg_plrcolor_get != NULL);
  mapimg.mapimg_plrcolor_get = mapimg_plrcolor_get;

  mapimg.init = TRUE;
}

/****************************************************************************
  Reset the map image subsystem.
****************************************************************************/
void mapimg_reset(void)
{
  if (!mapimg_initialised()) {
    return;
  }

  if (mapdef_list_size(mapimg.mapdef) > 0) {
    mapdef_list_iterate(mapimg.mapdef, pmapdef) {
      mapdef_list_remove(mapimg.mapdef, pmapdef);
      mapdef_destroy(pmapdef);
    } mapdef_list_iterate_end;
  }
}

/****************************************************************************
  Free all memory allocated by the map image subsystem.
****************************************************************************/
void mapimg_free(void)
{
  if (!mapimg_initialised()) {
    return;
  }

  mapimg_reset();
  mapdef_list_destroy(mapimg.mapdef);

  mapimg.init = FALSE;
}

/****************************************************************************
  Return the number of map image definitions.
****************************************************************************/
int mapimg_count(void)
{
  if (!mapimg_initialised()) {
    return 0;
  }

  return mapdef_list_size(mapimg.mapdef);
}

/****************************************************************************
  Describe the 'show' settings.
****************************************************************************/
static const char *showname_help(enum show_player showplr)
{
  switch (showplr) {
  case SHOW_NONE:     return _("no players, only terrain");
  case SHOW_EACH:     return _("one image per player");
  case SHOW_HUMAN:    return _("one image per human player");
  case SHOW_ALL:      return _("all players on a single image");
  case SHOW_PLRNAME:  return _("just the player named with 'plrname'");
  case SHOW_PLRID:    return _("just the player specified with 'plrid'");
  case SHOW_PLRBV:    return _("one image per player in 'plrbv'");
  }
  fc_assert(0);
  return "";
}

/****************************************************************************
  Return a help string for the 'mapimg' command.
****************************************************************************/
char *mapimg_help(const char *cmdname)
{
  enum imagetool tool;
  enum show_player showplr;
  enum mapimg_layer layer;
  struct astring defaults[MAPDEF_COUNT];
  struct astring str_format = ASTRING_INIT, str_showplr = ASTRING_INIT;
  struct mapdef *pmapdef = mapdef_new(FALSE);
  static struct astring help = ASTRING_INIT;

  if (astr_len(&help) > 0) {
    /* Help text was created already. */
    return fc_strdup(astr_str(&help));
  }

  /* Possible 'format' settings (toolkit + format). */
  for (tool = imagetool_begin(); tool != imagetool_end();
       tool = imagetool_next(tool)) {
    enum imageformat format;
    const struct toolkit *toolkit = img_toolkit_get(tool);

    if (!toolkit) {
      continue;
    }

    astr_add(&str_format, " - '%s': ", imagetool_name(tool));

    const char *separator = "";
    for (format = imageformat_begin(); format != imageformat_end();
         format = imageformat_next(format)) {
      if (toolkit->formats & format) {
        astr_add(&str_format, "%s'%s'", separator, imageformat_name(format));
        separator = ", ";
      }
    }

    if (tool != imagetool_max()) {
      astr_add(&str_format, "\n");
    }
  }

  /* Possible 'show' settings. */
  for (showplr = show_player_begin(); showplr != show_player_end();
       showplr = show_player_next(showplr)) {
    const char *nameptr = show_player_name(showplr);

    if (nameptr != NULL) {
      char name[10];

      fc_snprintf(name, sizeof(name), "'%s'", nameptr);
      astr_add(&str_showplr, " - %-9s %s", name, showname_help(showplr));
      if (showplr != show_player_max()) {
        astr_add(&str_showplr, "\n");
      }
    }
  }

  /* Default values. */
  astr_init(&defaults[MAPDEF_FORMAT]);
  astr_set(&defaults[MAPDEF_FORMAT],
           "(%s|%s)", imagetool_name(pmapdef->tool),
           imageformat_name(pmapdef->format));
  astr_init(&defaults[MAPDEF_SHOW]);
  astr_set(&defaults[MAPDEF_SHOW],
           "(%s)", show_player_name(pmapdef->player.show));
  astr_init(&defaults[MAPDEF_TURNS]);
  astr_set(&defaults[MAPDEF_TURNS], "(%d)", pmapdef->turns);
  astr_init(&defaults[MAPDEF_ZOOM]);
  astr_set(&defaults[MAPDEF_ZOOM], "(%d)", pmapdef->zoom);

  astr_init(&defaults[MAPDEF_MAP]);
  astr_set(&defaults[MAPDEF_MAP], "(");
  for (layer = mapimg_layer_begin(); layer != mapimg_layer_end();
       layer = mapimg_layer_next(layer)) {
    if (pmapdef->layers[layer]) {
      astr_add(&defaults[MAPDEF_MAP], "%c", mapimg_layer_name(layer)[0]);
    }
  }
  astr_add(&defaults[MAPDEF_MAP], ")");

  /* help text */
  astr_set(&help,
    /* TRANS: This is help for a server command, so keywords like
     * "define" in the first column are server keywords that must not
     * be translated. Do not translate keywords in single quotes, but
     * strings in <angle brackets> should be translated. */
    _("This command controls the creation of map images. Supported "
      "arguments:\n"
      "  define <mapdef>  - define a map image; returns numeric <id>\n"
      "  show <id>|all    - list map image definitions or show a specific one\n"
      "  create <id>|all  - manually save image(s) for current map state\n"
      "  delete <id>|all  - delete map image definition(s)\n"
      "  colortest        - create test image(s) showing all colors\n"
      "\n"
      "Multiple definitions can be active at once. "
      "A definition <mapdef> consists of colon-separated options:\n"
      "\n"
      "option                 (default)  description\n"
      "\n"
      "format=<[tool|]format> %-10s file format\n"
      "show=<show>            %-10s which players to show\n"
      "  plrname=<name>                    player name\n"
      "  plrid=<id>                        numeric player id\n"
      "  plrbv=<bit vector>                see example; first char = id 0\n"
      "turns=<turns>          %-10s save image each <turns> turns\n"
      "                                  (0=no autosave, save with 'create')\n"
      "zoom=<zoom>            %-10s magnification factor (1-5)\n"
      "map=<map>              %-10s which map layers to draw\n"
      "\n"
      "<[tool|]format> = use image format <format>, optionally specifying "
      "toolkit <tool>. The following toolkits and formats are compiled in:\n"
      "%s\n"
      "\n"
      "<show> determines which players are represented and how many "
      "images are saved by this definition:\n"
      "%s\n"
      "\n"
      "<map> can contain one or more of the following layers:\n"
      " - 'a' show area within borders of specified players\n"
      " - 'b' show borders of specified players\n"
      " - 'c' show cities of specified players\n"
      " - 'f' show fog of war (single-player images only)\n"
      " - 'k' show only player knowledge (single-player images only)\n"
      " - 't' full display of terrain types\n"
      " - 'u' show units of specified players\n"
      "\n"
      "Examples of <mapdef>:\n"
      " 'zoom=1:map=tcub:show=all:format=ppm|ppm'\n"
      " 'zoom=2:map=tcub:show=each:format=png'\n"
      " 'zoom=1:map=tcub:show=plrname:plrname=Otto:format=gif'\n"
      " 'zoom=3:map=cu:show=plrbv:plrbv=010011:format=jpg'\n"
      " 'zoom=1:map=t:show=none:format=magick|jpg'"),
    astr_str(&defaults[MAPDEF_FORMAT]), astr_str(&defaults[MAPDEF_SHOW]),
    astr_str(&defaults[MAPDEF_TURNS]), astr_str(&defaults[MAPDEF_ZOOM]),
    astr_str(&defaults[MAPDEF_MAP]),
    astr_str(&str_format), astr_str(&str_showplr));
  
  mapdef_destroy(pmapdef);
  astr_free(&str_format);
  astr_free(&str_showplr);
  astr_free(&defaults[MAPDEF_FORMAT]);
  astr_free(&defaults[MAPDEF_SHOW]);
  astr_free(&defaults[MAPDEF_TURNS]);
  astr_free(&defaults[MAPDEF_ZOOM]);
  astr_free(&defaults[MAPDEF_MAP]);

  return fc_strdup(astr_str(&help));
}

/****************************************************************************
  Returns the last error.
****************************************************************************/
const char *mapimg_error(void)
{
  return error_buffer;
}

/****************************************************************************
  Define on map image.
****************************************************************************/
#define NUM_MAX_MAPARGS 10
#define NUM_MAX_MAPOPTS 2
bool mapimg_define(const char *maparg, bool check)
{
  struct mapdef *pmapdef = NULL;
  char *mapargs[NUM_MAX_MAPARGS], *mapopts[NUM_MAX_MAPOPTS];
  int nmapargs, nmapopts, i;
  bool ret = TRUE;

  MAPIMG_ASSERT_RET_VAL(mapimg_initialised(), FALSE);

  if (maparg == NULL) {
    MAPIMG_LOG(_("no map definition"));
    return FALSE;
  }

  if (strlen(maparg) > MAX_LEN_MAPARG) {
    /* too long map definition string */
    MAPIMG_LOG(_("map definition string too long (max %d characters)"),
               MAX_LEN_MAPARG);
    return FALSE;
  }

  if (mapimg_count() == MAX_NUM_MAPIMG) {
    MAPIMG_LOG(_("maximum number of map definitions reached (%d)"),
               MAX_NUM_MAPIMG);
    return FALSE;
  }

  for (i = 0; i < mapimg_count(); i++) {
    pmapdef = mapdef_list_get(mapimg.mapdef, i);
    if (0 == fc_strcasecmp(pmapdef->maparg, maparg)) {
      MAPIMG_LOG(_("duplicate of map image definition %d ('%s')"), i,
                 maparg);
      return FALSE;
    }
  }

  pmapdef = mapdef_new(FALSE);

  /* get map options */
  nmapargs = get_tokens(maparg, mapargs, NUM_MAX_MAPARGS, ":");

  for (i = 0; i < nmapargs; i++) {
    /* split map options into variable and value */
    nmapopts = get_tokens(mapargs[i], mapopts, NUM_MAX_MAPOPTS, "=");

    if (nmapopts == 2) {
      enum mapdef_arg arg = mapdef_arg_by_name(mapopts[0], strcmp);
      if (mapdef_arg_is_valid(arg)) {
        /* If ret is FALSE an error message is set by mapimg_define_arg(). */
        ret = mapimg_define_arg(pmapdef, arg, mapopts[1], check);
      } else {
        MAPIMG_LOG(_("unknown map option: '%s'"), mapargs[i]);
        ret = FALSE;
      }
    } else {
      MAPIMG_LOG(_("unknown map option: '%s'"), mapargs[i]);
      ret = FALSE;
    }

    free_tokens(mapopts, nmapopts);

    if (!ret) {
      break;
    }
  }
  free_tokens(mapargs, nmapargs);

  /* sanity check */
  switch (pmapdef->player.show) {
  case SHOW_PLRNAME: /* display player given by name */
    if (!BV_ISSET(pmapdef->args, MAPDEF_PLRNAME)) {
      MAPIMG_LOG(_("'show=%s' but no player name 'plrname'"),
                 show_player_name(SHOW_PLRNAME));
      ret = FALSE;
    }
    break;
  case SHOW_PLRID:   /* display player given by id */
    if (!BV_ISSET(pmapdef->args, MAPDEF_PLRID)) {
      MAPIMG_LOG(_("'show=%s' but no player id 'plrid'"),
                 show_player_name(SHOW_PLRID));
      ret = FALSE;
    }
    break;
  case SHOW_PLRBV:   /* display players given by bitvector */
    if (!BV_ISSET(pmapdef->args, MAPDEF_PLRBV)) {
      MAPIMG_LOG(_("'show=%s' but no player bitvector 'plrbv'"),
                 show_player_name(SHOW_PLRBV));
      ret = FALSE;
    }
    break;
  case SHOW_NONE:    /* no player on the map */
    BV_CLR_ALL(pmapdef->player.checked_plrbv);
    break;
  case SHOW_ALL:     /* show all players in one map */
    BV_SET_ALL(pmapdef->player.checked_plrbv);
    break;
  case SHOW_EACH:    /* one map for each player */
  case SHOW_HUMAN:   /* one map for each human player */
    /* A loop for each player will be called at the time the image is
     * created. */
    BV_CLR_ALL(pmapdef->player.checked_plrbv);
    break;
  }

  if (ret && !check) {
    /* save map string */
    fc_strlcpy(pmapdef->maparg, maparg, MAX_LEN_MAPARG);

    /* add map definiton */
    mapdef_list_append(mapimg.mapdef, pmapdef);
  } else {
    mapdef_destroy(pmapdef);
  }

  return ret;
}
#undef NUM_MAX_MAPARGS
#undef NUM_MAX_MAPOPTS

/****************************************************************************
  Helper function for mapimg_define().
****************************************************************************/
#define NUM_MAX_FORMATARGS 2
static bool mapimg_define_arg(struct mapdef *pmapdef, enum mapdef_arg arg,
                              const char *val, bool check)
{
  if (BV_ISSET(pmapdef->args, arg)) {
    log_debug("Option '%s' for mapimg used more than once.",
              mapdef_arg_name(arg));
  }

  /* This argument was used. */
  BV_SET(pmapdef->args, arg);

  switch (arg) {
  case MAPDEF_FORMAT:
    /* file format */
    {
      char *formatargs[NUM_MAX_FORMATARGS];
      int nformatargs;
      enum imageformat format;
      enum imagetool tool;
      bool error = TRUE;

      /* get format options */
      nformatargs = get_tokens(val, formatargs, NUM_MAX_FORMATARGS, "|");

      if (nformatargs == 2) {
        tool = imagetool_by_name(formatargs[0], strcmp);
        format = imageformat_by_name(formatargs[1], strcmp);

        if (imageformat_is_valid(format) && imagetool_is_valid(tool)) {
          const struct toolkit *toolkit = img_toolkit_get(tool);

          if (toolkit && (toolkit->formats & format)) {
            pmapdef->tool = tool;
            pmapdef->format = format;

            error = FALSE;
          }
        }
      } else {
        /* Only one argument to format. */
        tool = imagetool_by_name(formatargs[0], strcmp);
        if (imagetool_is_valid(tool)) {
          /* toolkit defined */
          const struct toolkit *toolkit = img_toolkit_get(tool);

          if (toolkit) {
            pmapdef->tool = toolkit->tool;
            pmapdef->format = toolkit->format_default;

            error = FALSE;
          }
        } else {
          format = imageformat_by_name(formatargs[0], strcmp);
          if (imageformat_is_valid(format)) {
            /* format defined */
            img_toolkit_iterate(toolkit) {
              if ((toolkit->formats & format)) {
                pmapdef->tool = toolkit->tool;
                pmapdef->format = toolkit->format_default;

                error = FALSE;
                break;
              }
            } img_toolkit_iterate_end;
          }
        }
      }

      free_tokens(formatargs, nformatargs);

      if (error) {
        goto INVALID;
      }
    }
    break;

  case MAPDEF_MAP:
    /* map definition */
    {
      int len = strlen(val), l;
      enum mapimg_layer layer;
      bool error;

      for (layer = mapimg_layer_begin(); layer != mapimg_layer_end();
           layer = mapimg_layer_next(layer)) {
        pmapdef->layers[layer] = FALSE;
      }

      for (l = 0; l < len; l++) {
        error = TRUE;
        for (layer = mapimg_layer_begin(); layer != mapimg_layer_end();
             layer = mapimg_layer_next(layer)) {
          if (val[l] == mapimg_layer_name(layer)[0]) {
            pmapdef->layers[layer] = TRUE;
            error = FALSE;
            break;
          }
        }

        if (error) {
          goto INVALID;
        }
      }
    }
    break;

  case MAPDEF_PLRBV:
    /* player definition - bitvector */
    {
      int i;

      if (strlen(val) < MAX_NUM_PLAYER_SLOTS + 1) {
        BV_CLR_ALL(pmapdef->player.plrbv);
        for (i = 0; i < strlen(val); i++) {
          if (!strchr("01", val[i])) {
            MAPIMG_LOG(_("invalid character in bitvector: '%c' (%s)"),
                       val[i], val);
            return FALSE;
          } else if (val[i] == '1') {
            BV_SET(pmapdef->player.plrbv, i);
          }
        }
      } else {
        goto INVALID;
      }
    }
    break;

  case MAPDEF_PLRID:
    /* player definition - player id; will be checked by mapimg_isvalid()
     * which calls mapimg_checkplayers() */
    {
      int plrid;

      if (sscanf(val, "%d", &plrid) != 0) {
        if (plrid < 0 || plrid >= MAX_NUM_PLAYER_SLOTS) {
          MAPIMG_LOG(_("'plrid' should be between 0 and %d"),
                     MAX_NUM_PLAYER_SLOTS-1);
          return FALSE;
        }
        pmapdef->player.id = plrid;
      } else {
        goto INVALID;
      }
    }
    break;

  case MAPDEF_PLRNAME:
    /* player definition - player name; will be checked by mapimg_isvalid()
     * which calls mapimg_checkplayers() */
    {
      if (strlen(val) > sizeof(pmapdef->player.name)) {
        MAPIMG_LOG(_("player name too long: '%s' (max: %lu)"), val,
                   (unsigned long) sizeof(pmapdef->player.name));
        return FALSE;
      } else {
        sz_strlcpy(pmapdef->player.name, val);
      }
    }
    break;

  case MAPDEF_SHOW:
    /* player definition - basic definition */
    {
      enum show_player showplr;

      showplr = show_player_by_name(val, strcmp);
      if (show_player_is_valid(showplr)) {
        pmapdef->player.show = showplr;
      } else {
        goto INVALID;
      }
    }
    break;

  case MAPDEF_TURNS:
    /* save each <x> turns */
    {
      int turns;

      if (sscanf(val, "%d", &turns) != 0) {
        if (turns < 0 || turns > 99) {
          MAPIMG_LOG(_("'turns' should be between 0 and 99"));
          return FALSE;
        } else {
          pmapdef->turns = turns;
        }
      } else {
        goto INVALID;
      }
    }
    break;

  case MAPDEF_ZOOM:
    /* zoom factor */
    {
      int zoom;

      if (sscanf(val, "%d", &zoom) != 0) {
        if (zoom < 1 || zoom > 5) {
          MAPIMG_LOG(_("'zoom' factor should be between 1 and 5"));
          return FALSE;
        } else {
          pmapdef->zoom = zoom;
        }
      } else {
        goto INVALID;
      }
    }
    break;

  case MAPDEF_COUNT:
    fc_assert_ret_val(arg != MAPDEF_COUNT, FALSE);
    break;
  }

  return TRUE;

 INVALID:
  MAPIMG_LOG(_("invalid value for option '%s': '%s'"),
             mapdef_arg_name(arg), val);
  return FALSE;
}
#undef NUM_MAX_FORMATARGS

/****************************************************************************
  Check if a map image definition is valid. This function is a wrapper for
  mapimg_checkplayers().
****************************************************************************/
struct mapdef *mapimg_isvalid(int id)
{
  struct mapdef *pmapdef = NULL;

  if (!mapimg_test(id)) {
    /* The error message is set in mapimg_test(). */
    return NULL;
  }

  pmapdef = mapdef_list_get(mapimg.mapdef, id);
  mapimg_checkplayers(pmapdef, TRUE);

  switch (pmapdef->status) {
  case MAPIMG_STATUS_UNKNOWN:
    MAPIMG_LOG(_("map definition not checked (game not started)"));
    return NULL;
    break;
  case MAPIMG_STATUS_ERROR:
    MAPIMG_LOG(_("map definition deactivated: %s"), pmapdef->error);
    return NULL;
    break;
  case MAPIMG_STATUS_OK:
    /* nothing */
    break;
  }

  return pmapdef;
}

/****************************************************************************
  Return a list of all available tookits and formats for the client.
****************************************************************************/
const struct strvec *mapimg_get_format_list(void)
{
  static struct strvec *format_list = NULL;

  if (NULL == format_list) {
    enum imagetool tool;

    format_list = strvec_new();

    for (tool = imagetool_begin(); tool != imagetool_end();
         tool = imagetool_next(tool)) {
      enum imageformat format;
      const struct toolkit *toolkit = img_toolkit_get(tool);

      if (!toolkit) {
        continue;
      }

      for (format = imageformat_begin(); format != imageformat_end();
           format = imageformat_next(format)) {
        if (toolkit->formats & format) {
          char str_format[64];
          fc_snprintf(str_format, sizeof(str_format), "%s|%s",
                      imagetool_name(tool), imageformat_name(format));
          strvec_append(format_list, str_format);
        }
      }
    }
  }

  return format_list;
}

/****************************************************************************
  Return the default value of the tookit and the image format for the client.
****************************************************************************/
const char *mapimg_get_format_default(void)
{
  static char default_format[64];

  fc_snprintf(default_format, sizeof(default_format), "%s|%s",
              imagetool_name(MAPIMG_DEFAULT_IMGTOOL),
              imageformat_name(MAPIMG_DEFAULT_IMGFORMAT));

  return default_format;
}

/****************************************************************************
  Delete a map image definition.
****************************************************************************/
bool mapimg_delete(int id)
{
  struct mapdef *pmapdef = NULL;

  if (!mapimg_test(id)) {
    /* The error message is set in mapimg_test(). */
    return FALSE;
  }

  /* delete map definition */
  pmapdef = mapdef_list_get(mapimg.mapdef, id);
  mapdef_list_remove(mapimg.mapdef, pmapdef);

  return TRUE;
}

/****************************************************************************
  Show a map image definition.
****************************************************************************/
bool mapimg_show(int id, char *str, size_t str_len, bool detail)
{
  struct mapdef *pmapdef = NULL;

  if (!mapimg_test(id)) {
    /* The error message is set in mapimg_test(). */
    return FALSE;
  }

  pmapdef = mapdef_list_get(mapimg.mapdef, id);

  /* Clear string ... */
  fc_assert_ret_val(str_len > 0, FALSE);
  str[0] = '\0';

  if (detail) {
    cat_snprintf(str, str_len, _("Detailed information for map image "
                                 "definition %d\n"), id);
    if (pmapdef->status == MAPIMG_STATUS_ERROR) {
      cat_snprintf(str, str_len, _("  - status:                   %s (%s)\n"),
                   mapimg_status_name(pmapdef->status), pmapdef->error);
    } else {
      cat_snprintf(str, str_len, _("  - status:                   %s\n"),
                   mapimg_status_name(pmapdef->status));
    }
    cat_snprintf(str, str_len, _("  - file name string:         %s\n"),
                 mapimg_generate_name(pmapdef));
    cat_snprintf(str, str_len, _("  - image toolkit:            %s\n"),
                 imagetool_name(pmapdef->tool));
    cat_snprintf(str, str_len, _("  - image format:             %s\n"),
                 imageformat_name(pmapdef->format));
    cat_snprintf(str, str_len, _("  - zoom factor:              %d\n"),
                 pmapdef->zoom);
    cat_snprintf(str, str_len, _("  - show area within borders: %s\n"),
                 pmapdef->layers[MAPIMG_LAYER_AREA] ? _("yes") : _("no"));
    cat_snprintf(str, str_len, _("  - show borders:             %s\n"),
                 pmapdef->layers[MAPIMG_LAYER_BORDERS] ? _("yes") : _("no"));
    cat_snprintf(str, str_len, _("  - show cities:              %s\n"),
                 pmapdef->layers[MAPIMG_LAYER_CITIES] ? _("yes") : _("no"));
    cat_snprintf(str, str_len, _("  - show fog of war:          %s\n"),
                 pmapdef->layers[MAPIMG_LAYER_FOGOFWAR] ? _("yes") : _("no"));
    cat_snprintf(str, str_len, _("  - show player knowledge:    %s\n"),
                 pmapdef->layers[MAPIMG_LAYER_KNOWLEDGE] ? _("yes") : _("no"));
    cat_snprintf(str, str_len, _("  - show terrain:             %s\n"),
                 pmapdef->layers[MAPIMG_LAYER_TERRAIN] ? _("full") :_("basic"));
    cat_snprintf(str, str_len, _("  - show units:               %s\n"),
                 pmapdef->layers[MAPIMG_LAYER_UNITS] ? _("yes") : _("no"));
    cat_snprintf(str, str_len, _("  - players included:         %s"),
                 show_player_name(pmapdef->player.show));
    switch (pmapdef->player.show) {
    case SHOW_NONE:
    case SHOW_HUMAN:
    case SHOW_EACH:
    case SHOW_ALL:
      /* nothing */
      break;
    case SHOW_PLRNAME:
      cat_snprintf(str, str_len, _("\n  - player name:              %s"),
                   pmapdef->player.name);
      break;
    case SHOW_PLRID:
      cat_snprintf(str, str_len, _("\n  - player id:                %d"),
                   pmapdef->player.id);
      break;
    case SHOW_PLRBV:
      cat_snprintf(str, str_len, _("\n  - players:                  %s"),
                   bvplayers_str(pmapdef->player.plrbv));
      break;
    }
  } else {
    char str_def[MAX_LEN_MAPDEF];
    mapimg_def2str(pmapdef, str_def, sizeof(str_def));
    if (pmapdef->status == MAPIMG_STATUS_ERROR) {
      cat_snprintf(str, str_len, "'%s' (%s: %s)", str_def,
                   mapimg_status_name(pmapdef->status), pmapdef->error);
    } else {
      cat_snprintf(str, str_len, "'%s' (%s)", str_def,
                   mapimg_status_name(pmapdef->status));
    }
  }

  return TRUE;
}

/****************************************************************************
  Return the map image definition 'id' as a mapdef string. This function is
  a wrapper for mapimg_def2str().
****************************************************************************/
bool mapimg_id2str(int id, char *str, size_t str_len)
{
  struct mapdef *pmapdef = NULL;

  if (!mapimg_test(id)) {
    /* The error message is set in mapimg_test(). */
    return FALSE;
  }

  pmapdef = mapdef_list_get(mapimg.mapdef, id);

  return mapimg_def2str(pmapdef, str, str_len);
}

/****************************************************************************
  Create the requested map image. The filename is created as
  <basename as used for savegames>-<mapstr>.<mapext> where <mapstr>
  contains the map definition and <mapext> the selected image extension.
  If 'force' is FALSE, the image is only created if game.info.turn is a
  multiple of the map setting turns.
****************************************************************************/
bool mapimg_create(struct mapdef *pmapdef, bool force, const char *savename,
                   const char *path)
{
  struct img *pimg;
  char mapimgfile[MAX_LEN_PATH];
  bool ret = TRUE;
#ifdef DEBUG
  struct timer *timer_cpu, *timer_user;
#endif

  if (map_is_empty()) {
    MAPIMG_LOG(_("map not yet created"));

    return FALSE;
  }

  mapimg_checkplayers(pmapdef, FALSE);

  if (pmapdef->status != MAPIMG_STATUS_OK) {
    MAPIMG_LOG(_("map definition not checked or error"));
    return FALSE;
  }

  /* An image should be saved if:
   * - force is set to TRUE
   * - it is the first turn
   * - turns is set to a value not zero and the current turn can be devided
   *   by this number */
  if (!force && game.info.turn != 0
      && !(pmapdef->turns != 0 && game.info.turn % pmapdef->turns == 0)) {
    return TRUE;
  }

#ifdef DEBUG
  timer_cpu = timer_new(TIMER_CPU, TIMER_ACTIVE);
  timer_start(timer_cpu);
  timer_user = timer_new(TIMER_USER, TIMER_ACTIVE);
  timer_start(timer_user);
#endif

  /* create map */
  switch (pmapdef->player.show) {
  case SHOW_PLRNAME: /* display player given by name */
  case SHOW_PLRID:   /* display player given by id */
  case SHOW_NONE:    /* no player one the map */
  case SHOW_ALL:     /* show all players in one map */
  case SHOW_PLRBV:   /* display player(s) given by bitvector */
    generate_save_name(savename, mapimgfile, sizeof(mapimgfile),
                       mapimg_generate_name(pmapdef));

    pimg = img_new(pmapdef, CURRENT_TOPOLOGY, game.map.xsize, game.map.ysize);
    img_createmap(pimg);
    if (!img_save(pimg, mapimgfile, path)) {
      ret = FALSE;
    }
    img_destroy(pimg);
    break;
  case SHOW_EACH:    /* one map for each player */
  case SHOW_HUMAN:   /* one map for each human player */
    players_iterate(pplayer) {
      if (!pplayer->is_alive || (pmapdef->player.show == SHOW_HUMAN
                                 && pplayer->ai_controlled)) {
        /* no map image for dead players
         * or AI players if only human players should be shown */
        continue;
      }

      BV_CLR_ALL(pmapdef->player.checked_plrbv);
      BV_SET(pmapdef->player.checked_plrbv, player_index(pplayer));

      generate_save_name(savename, mapimgfile, sizeof(mapimgfile),
                         mapimg_generate_name(pmapdef));

      pimg = img_new(pmapdef, CURRENT_TOPOLOGY, game.map.xsize, game.map.ysize);
      img_createmap(pimg);
      if (!img_save(pimg, mapimgfile, path)) {
        ret = FALSE;
      }
      img_destroy(pimg);

      if (!ret) {
        break;
      }
    } players_iterate_end;
    break;
  }

#ifdef DEBUG
  log_debug("Image generation time: %g seconds (%g apparent)",
            timer_read_seconds(timer_cpu),
            timer_read_seconds(timer_user));

  timer_destroy(timer_cpu);
  timer_destroy(timer_user);
#endif

  return ret;
}

/****************************************************************************
  Create images which shows all map colors (playercolor, terrain colors). One
  image is created for each supported toolkit and image format. The filename
  will be <basename as used for savegames>-colortest-<tookit>.<format>.
****************************************************************************/
bool mapimg_colortest(const char *savename, const char *path)
{
  struct img *pimg;
  const struct rgbcolor *pcolor;
  struct mapdef *pmapdef = mapdef_new(TRUE);
  char mapimgfile[MAX_LEN_PATH];
  bv_pixel pixel;
  int i, nat_x, nat_y;
  int max_playercolor = mapimg.mapimg_plrcolor_count();
  int max_terraincolor = terrain_count();
  bool ret = TRUE;
  enum imagetool tool;

#define SIZE_X 16
#define SIZE_Y 5

  pimg = img_new(pmapdef, 0, SIZE_X + 2,
                 SIZE_Y * (max_playercolor / SIZE_X) + 2);

  pixel = pimg->pixel_tile(NULL, NULL, FALSE);

  pcolor = imgcolor_special(IMGCOLOR_OCEAN);
  for (i = 0; i < MAX(max_playercolor, max_terraincolor); i++) {
    nat_x = 1 + i % SIZE_X;
    nat_y = 1 + (i / SIZE_X) * SIZE_Y;

    img_plot(pimg, nat_x, nat_y, pcolor, pixel);
  }

  for (i = 0; i < MAX(max_playercolor, max_terraincolor); i++) {
    if (i >= max_playercolor) {
      break;
    }

    nat_x = 1 + i % SIZE_X;
    nat_y = 2 + (i / SIZE_X) * SIZE_Y;
    pcolor = mapimg.mapimg_plrcolor_get(i);

    img_plot(pimg, nat_x, nat_y, pcolor, pixel);
  }

  pcolor = imgcolor_special(IMGCOLOR_GROUND);
  for (i = 0; i < MAX(max_playercolor, max_terraincolor); i++) {
    nat_x = 1 + i % SIZE_X;
    nat_y = 3 + (i / SIZE_X) * SIZE_Y;

    img_plot(pimg, nat_x, nat_y, pcolor, pixel);
  }

  for (i = 0; i < MAX(max_playercolor, max_terraincolor); i++) {
    if (i >= max_terraincolor) {
      break;
    }

    nat_x = 1 + i % SIZE_X;
    nat_y = 4 + (i / SIZE_X) * SIZE_Y;
    pcolor = imgcolor_terrain(terrain_by_number(i));

    img_plot(pimg, nat_x, nat_y, pcolor, pixel);
  }

#undef SIZE_X
#undef SIZE_Y

  for (tool = imagetool_begin(); tool != imagetool_end();
       tool = imagetool_next(tool)) {
    enum imageformat format;
    const struct toolkit *toolkit = img_toolkit_get(tool);

    if (!toolkit) {
      continue;
    }

    /* Set the toolkit. */
    pmapdef->tool = tool;

    for (format = imageformat_begin(); format != imageformat_end();
         format = imageformat_next(format)) {
      if (toolkit->formats & format) {
        char buf[128];

        /* Set the image format. */
        pmapdef->format = format;

        fc_snprintf(buf, sizeof(buf), "colortest-%s", imagetool_name(tool));
        /* filename for color test */
        generate_save_name(savename, mapimgfile, sizeof(mapimgfile), buf);

        if (!img_save(pimg, mapimgfile, path)) {
          /* If one of the mapimg format/toolkit combination fail, return
           * FALSE, i.e. an error occurred. */
          ret = FALSE;
        }
      }
    }
  }

  img_destroy(pimg);
  mapdef_destroy(pmapdef);

  return ret;
}

/*
 * ==============================================
 * map images (internal functions)
 * ==============================================
 */

/****************************************************************************
  Check if the map image subsustem is initialised.
****************************************************************************/
static inline bool mapimg_initialised(void)
{
  return mapimg.init;
}

/****************************************************************************
  Check if the map image subsystem is initialised and the given ID is valid.
  In case of an error, the error message is saved via MAPIMG_LOG().
****************************************************************************/
static bool mapimg_test(int id)
{
  MAPIMG_ASSERT_RET_VAL(mapimg_initialised(), FALSE);

  if (id < 0 || id >= mapimg_count()) {
    MAPIMG_LOG(_("no map definition with id %d"), id);
    return FALSE;
  }

  return TRUE;
}

/****************************************************************************
  Return a mapdef string for the map image definition given by 'pmapdef'.
****************************************************************************/
static bool mapimg_def2str(struct mapdef *pmapdef, char *str, size_t str_len)
{
  enum mapimg_layer layer;
  char buf[MAPIMG_LAYER_COUNT + 1];
  int i;

  if (pmapdef->status != MAPIMG_STATUS_OK) {
    MAPIMG_LOG(_("map definition not checked or error"));
    fc_strlcpy(str, pmapdef->maparg, str_len);
    return FALSE;
  }

  str[0] = '\0';
  cat_snprintf(str, str_len, "format=%s|%s:",
               imagetool_name(pmapdef->tool),
               imageformat_name(pmapdef->format));
  cat_snprintf(str, str_len, "turns=%d:", pmapdef->turns);

  i = 0;
  for (layer = mapimg_layer_begin(); layer != mapimg_layer_end();
       layer = mapimg_layer_next(layer)) {
    if (pmapdef->layers[layer]) {
      buf[i++] = mapimg_layer_name(layer)[0];
    }
  }
  buf[i++] = '\0';
  cat_snprintf(str, str_len, "map=%s:", buf);

  switch (pmapdef->player.show) {
  case SHOW_NONE:
  case SHOW_EACH:
  case SHOW_HUMAN:
  case SHOW_ALL:
    cat_snprintf(str, str_len, "show=%s:",
                 show_player_name(pmapdef->player.show));
    break;
  case SHOW_PLRBV:
    cat_snprintf(str, str_len, "show=%s:", show_player_name(SHOW_PLRBV));
    cat_snprintf(str, str_len, "plrbv=%s:",
                 bvplayers_str(pmapdef->player.plrbv));
    break;
  case SHOW_PLRNAME:
    cat_snprintf(str, str_len, "show=%s:", show_player_name(SHOW_PLRNAME));
    cat_snprintf(str, str_len, "plrname=%s:", pmapdef->player.name);
    break;
  case SHOW_PLRID:
    cat_snprintf(str, str_len, "show=%s:", show_player_name(SHOW_PLRID));
    cat_snprintf(str, str_len, "plrid=%d:", pmapdef->player.id);
    break;
  }
  cat_snprintf(str, str_len, "zoom=%d", pmapdef->zoom);

  return TRUE;
}

/****************************************************************************
  Check the player selection. This needs to be done befor _each_ image
  creationcall (see mapimg_create()) to test the the selection is still
  valid as players can be added or removed during the game.
****************************************************************************/
static bool mapimg_checkplayers(struct mapdef *pmapdef, bool recheck)
{
  struct player *pplayer;
  enum m_pre_result result;

  if (!recheck && pmapdef->status == MAPIMG_STATUS_ERROR) {
    return FALSE;
  }

  /* game started - generate / check bitvector for players */
  switch (pmapdef->player.show) {
  case SHOW_NONE:
    /* nothing */
    break;
  case SHOW_PLRBV:
    pmapdef->player.checked_plrbv = pmapdef->player.plrbv;
    break;
  case SHOW_EACH:
  case SHOW_HUMAN:
    /* A map for each player will be created in a loop. */
    BV_CLR_ALL(pmapdef->player.checked_plrbv);
    break;
  case SHOW_ALL:
    BV_SET_ALL(pmapdef->player.checked_plrbv);
    break;
  case SHOW_PLRNAME:
    /* display players as requested in the map definition */
    BV_CLR_ALL(pmapdef->player.checked_plrbv);
    pplayer = player_by_name_prefix(pmapdef->player.name, &result);

    if (pplayer != NULL) {
      BV_SET(pmapdef->player.checked_plrbv, player_index(pplayer));
    } else {
      pmapdef->status = MAPIMG_STATUS_ERROR;
      /* Save the error message in map definition. */
      fc_snprintf(pmapdef->error, sizeof(pmapdef->error),
                  _("unknown player name: '%s'"), pmapdef->player.name);
      MAPIMG_LOG("%s", pmapdef->error);
      return FALSE;
    }
    break;
  case SHOW_PLRID:
    /* display players as requested in the map definition */
    BV_CLR_ALL(pmapdef->player.checked_plrbv);
    pplayer = player_by_number(pmapdef->player.id);

    if (pplayer != NULL) {
      BV_SET(pmapdef->player.checked_plrbv, player_index(pplayer));
    } else {
      pmapdef->status = MAPIMG_STATUS_ERROR;
      /* Save the error message in map definition. */
      fc_snprintf(pmapdef->error, sizeof(pmapdef->error),
                  _("invalid player id: %d"), pmapdef->player.id);
      MAPIMG_LOG("%s", pmapdef->error);
      return FALSE;
    }
    break;
  }

  pmapdef->status = MAPIMG_STATUS_OK;

  return TRUE;
}

/****************************************************************************
  Edit the error_buffer.
  Strings should not have a terminating period.
****************************************************************************/
static void mapimg_log(const char *file, const char *function, int line,
                       const char *format, ...)
{
  va_list args;

  va_start(args, format);
  fc_vsnprintf(error_buffer, sizeof(error_buffer), format, args);
  va_end(args);

#ifdef DEBUG
  log_debug("In %s() [%s:%d]: %s", function, file, line, error_buffer);
#endif
}

/****************************************************************************
  Generate an identifier for a map image.

  M<map options>Z<zoom factor>P<players>

  <map options>    map options
  <zoom factor>    zoom factor
  <players>        player ID or vector of size MAX_NUM_PLAYER_SLOTS [0/1]

  For the player bitvector all MAX_NUM_PLAYER_SLOTS values are used due to
  the possibility of additional players during the game (civil war,
  barbarians).
****************************************************************************/
static char *mapimg_generate_name(struct mapdef *pmapdef)
{
  static char mapstr[256];
  char str_show[MAX_NUM_PLAYER_SLOTS + 1];
  enum mapimg_layer layer;
  int i, count = 0, plr_id = -1;

  switch (pmapdef->player.show) {
  case SHOW_NONE:
    /* no player on the map */
    sz_strlcpy(str_show, "none");
    break;
  case SHOW_ALL:
    /* show all players in one map */
    sz_strlcpy(str_show, "all");
    break;
  case SHOW_PLRBV:
  case SHOW_PLRNAME:
  case SHOW_PLRID:
  case SHOW_HUMAN:
  case SHOW_EACH:
    /* one map for each selected player; iterate over all possible player ids
     * to generate unique strings even if civil wars occur */
    for (i = 0; i < MAX_NUM_PLAYER_SLOTS; i++) {
      str_show[i] = BV_ISSET(pmapdef->player.checked_plrbv, i) ? '1' : '0';
      if (BV_ISSET(pmapdef->player.checked_plrbv, i)) {
        count++;
        plr_id = i;
      }
    }
    str_show[MAX_NUM_PLAYER_SLOTS] = '\0';

    /* Return the option name if no player is selected or the player id if
     * there is only one player selected. */
    if (count == 0) {
      fc_snprintf(str_show, sizeof(str_show), "---%s",
                  show_player_name(pmapdef->player.show));
    } else if (count == 1 && plr_id != -1) {
      fc_snprintf(str_show, sizeof(str_show), "%03d%s", plr_id,
                  show_player_name(pmapdef->player.show));
    }
    break;
  }

  fc_snprintf(mapstr, sizeof(mapstr), "M");
  for (layer = mapimg_layer_begin(); layer != mapimg_layer_end();
       layer = mapimg_layer_next(layer)) {
    if (pmapdef->layers[layer]) {
      const char *lname = mapimg_layer_name(layer);

      if (lname != NULL) {
        cat_snprintf(mapstr, sizeof(mapstr), "%s", lname);
      } else {
        cat_snprintf(mapstr, sizeof(mapstr), "-");
      }
    } else {
      cat_snprintf(mapstr, sizeof(mapstr), "-");
    }
  }
  cat_snprintf(mapstr, sizeof(mapstr), "Z%dP%s", pmapdef->zoom, str_show);

  return mapstr;
}

/*
 * ==============================================
 * map definitions (internal functions)
 * ==============================================
 */

/****************************************************************************
  Create a new map image definition with default values.
****************************************************************************/
static struct mapdef *mapdef_new(bool colortest)
{
  struct mapdef *pmapdef;

  pmapdef = fc_malloc(sizeof(*pmapdef));

  /* default values */
  pmapdef->maparg[0] = '\0';
  pmapdef->error[0] = '\0';
  pmapdef->status = MAPIMG_STATUS_UNKNOWN;
  pmapdef->format = MAPIMG_DEFAULT_IMGFORMAT;
  pmapdef->tool = MAPIMG_DEFAULT_IMGTOOL;
  pmapdef->zoom = 2;
  pmapdef->turns = 1;
  pmapdef->layers[MAPIMG_LAYER_TERRAIN] = FALSE;
  pmapdef->layers[MAPIMG_LAYER_CITIES] = TRUE;
  pmapdef->layers[MAPIMG_LAYER_UNITS] = TRUE;
  pmapdef->layers[MAPIMG_LAYER_BORDERS] = TRUE;
  pmapdef->layers[MAPIMG_LAYER_FOGOFWAR] = FALSE;
  pmapdef->layers[MAPIMG_LAYER_KNOWLEDGE] = TRUE;
  pmapdef->layers[MAPIMG_LAYER_AREA] = FALSE;
  pmapdef->player.show = SHOW_ALL;
  /* The union is not set at this point (player.id, player.name and
   * player.plrbv). */
  BV_CLR_ALL(pmapdef->player.checked_plrbv);
  BV_CLR_ALL(pmapdef->args);
  pmapdef->colortest = colortest;

  return pmapdef;
}

/****************************************************************************
  Destroy a map image definition.
****************************************************************************/
static void mapdef_destroy(struct mapdef *pmapdef)
{
  if (pmapdef == NULL) {
    return;
  }

  free(pmapdef);
}

/*
 * ==============================================
 * images (internal functions)
 * ==============================================
 */

/****************************************************************************
  Return the definition of the requested toolkit (or NULL).
****************************************************************************/
static const struct toolkit *img_toolkit_get(enum imagetool tool)
{
  img_toolkit_iterate(toolkit) {
    if (toolkit->tool == tool) {
      return toolkit;
    }
  } img_toolkit_iterate_end;

  return NULL;
}

/****************************************************************************
  Create a new image.
****************************************************************************/
static struct img *img_new(struct mapdef *mapdef, int topo, int xsize, int ysize)
{
  struct img *pimg;

  pimg = fc_malloc(sizeof(*pimg));

  pimg->def = mapdef;
  pimg->turn = game.info.turn;
  fc_snprintf(pimg->title, sizeof(pimg->title),
              _("Turn: %4d - Year: %10s"), game.info.turn,
              calendar_text());

  pimg->mapsize.x = xsize; /* x size of the map */
  pimg->mapsize.y = ysize; /* y size of the map */

  pimg->imgsize.x = 0; /* x size of the map image */
  pimg->imgsize.y = 0; /* y size of the map image */

  if (topo_has_flag(topo, TF_HEX)) {
    /* additional space for hex maps */
    pimg->imgsize.x += TILE_SIZE / 2;
    pimg->imgsize.y += TILE_SIZE / 2;

    if (topo_has_flag(topo, TF_ISO)) {
      /* iso-hex */
      pimg->imgsize.x += (pimg->mapsize.x + pimg->mapsize.y / 2)
                         * TILE_SIZE;
      pimg->imgsize.y += (pimg->mapsize.x + pimg->mapsize.y / 2)
                         * TILE_SIZE;

      /* magic for isohexa: change size if wrapping in only one direction */
      if ((topo_has_flag(topo, TF_WRAPX) && !topo_has_flag(topo, TF_WRAPY))
          || (!topo_has_flag(topo, TF_WRAPX) && topo_has_flag(topo, TF_WRAPY))) {
        pimg->imgsize.y += (pimg->mapsize.x - pimg->mapsize.y / 2) / 2
                           * TILE_SIZE;
      }

      pimg->tileshape = &tile_isohexa;

      pimg->pixel_tile = pixel_tile_isohexa;
      pimg->pixel_city = pixel_city_isohexa;
      pimg->pixel_unit = pixel_unit_isohexa;
      pimg->pixel_fogofwar = pixel_fogofwar_isohexa;
      pimg->pixel_border = pixel_border_isohexa;

      pimg->base_coor = base_coor_isohexa;
    } else {
      /* hex */
      pimg->imgsize.x += pimg->mapsize.x * TILE_SIZE;
      pimg->imgsize.y += pimg->mapsize.y * TILE_SIZE;

      pimg->tileshape = &tile_hexa;

      pimg->pixel_tile = pixel_tile_hexa;
      pimg->pixel_city = pixel_city_hexa;
      pimg->pixel_unit = pixel_unit_hexa;
      pimg->pixel_fogofwar = pixel_fogofwar_hexa;
      pimg->pixel_border = pixel_border_hexa;

      pimg->base_coor = base_coor_hexa;
    }
  } else {
    if (topo_has_flag(topo, TF_ISO)) {
      /* isometric rectangular */
      pimg->imgsize.x += (pimg->mapsize.x + pimg->mapsize.y / 2) * TILE_SIZE;
      pimg->imgsize.y += (pimg->mapsize.x + pimg->mapsize.y / 2) * TILE_SIZE;
    } else {
      /* rectangular */
      pimg->imgsize.x += pimg->mapsize.x * TILE_SIZE;
      pimg->imgsize.y += pimg->mapsize.y * TILE_SIZE;
    }

    pimg->tileshape = &tile_rect;

    pimg->pixel_tile = pixel_tile_rect;
    pimg->pixel_city = pixel_city_rect;
    pimg->pixel_unit = pixel_unit_rect;
    pimg->pixel_fogofwar = pixel_fogofwar_rect;
    pimg->pixel_border = pixel_border_rect;

    pimg->base_coor = base_coor_rect;
  }

  /* Here the map image is saved as an array of RGB color values. */
  pimg->map = fc_calloc(pimg->imgsize.x * pimg->imgsize.y,
                        sizeof(*pimg->map));
  /* Initialise map. */
  memset(pimg->map, 0, pimg->imgsize.x * pimg->imgsize.y);

  return pimg;
}

/****************************************************************************
  Destroy a image.
****************************************************************************/
static void img_destroy(struct img *pimg)
{
  if (pimg != NULL) {
    /* do not free pimg->def */
    free(pimg->map);
    free(pimg);
  }
}

/****************************************************************************
  Set the color of one pixel.
****************************************************************************/
static inline void img_set_pixel(struct img *pimg, const int mindex,
                                 const struct rgbcolor *pcolor)
{
  if (mindex < 0 || mindex > pimg->imgsize.x * pimg->imgsize.y) {
    log_error("invalid index: 0 <= %d < %d", mindex,
              pimg->imgsize.x * pimg->imgsize.y);
    return;
  }

  pimg->map[mindex] = pcolor;
}

/****************************************************************************
  Get the index for an (x,y) image coordinate.
****************************************************************************/
static inline int img_index(const int x, const int y,
                            const struct img *pimg)
{
  fc_assert_ret_val(x >= 0 && x < pimg->imgsize.x, -1);
  fc_assert_ret_val(y >= 0 && y < pimg->imgsize.y, -1);

  return pimg->imgsize.x * y + x;
}

/****************************************************************************
  Plot one tile at (x,y). Only the pixel of the tile set within 'pixel' are ploted.
****************************************************************************/
static void img_plot(struct img *pimg, int x, int y,
                     const struct rgbcolor *pcolor, const bv_pixel pixel)
{
  int base_x, base_y, i, mindex;

  if (!BV_ISSET_ANY(pixel)) {
    return;
  }

  pimg->base_coor(pimg, &base_x, &base_y, x, y);

  for (i = 0; i < NUM_PIXEL; i++) {
    if (BV_ISSET(pixel, i)) {
      mindex = img_index(base_x + pimg->tileshape->x[i],
                         base_y + pimg->tileshape->y[i], pimg);
      img_set_pixel(pimg, mindex, pcolor);
    }
  }
}

/****************************************************************************
  Plot one tile. Only the pixel of the tile set within 'pixel' are ploted.
****************************************************************************/
static void img_plot_tile(struct img *pimg, const struct tile *ptile,
                          const struct rgbcolor *pcolor, const bv_pixel pixel)
{
  int x, y;

  index_to_map_pos(&x, &y, tile_index(ptile));

  img_plot(pimg, x, y, pcolor, pixel);
}

/****************************************************************************
  Save an image as ppm file.
****************************************************************************/
static bool img_save(const struct img *pimg, const char *mapimgfile,
                     const char *path)
{
  enum imagetool tool = pimg->def->tool;
  const struct toolkit *toolkit = img_toolkit_get(tool);
  char tmpname[600];

  if (!toolkit) {
    MAPIMG_LOG(_("toolkit not defined"));
    return FALSE;
  }

  if (!path_is_absolute(mapimgfile) && path != NULL) {
    make_dir(path);

    sz_strlcpy(tmpname, path);
    if (tmpname[0] != '\0') {
      sz_strlcat(tmpname, "/");
    }
  } else {
    tmpname[0] = '\0';
  }

  sz_strlcat(tmpname, mapimgfile);

  MAPIMG_ASSERT_RET_VAL(toolkit->img_save, FALSE);

  return toolkit->img_save(pimg, tmpname);
}

/****************************************************************************
  Save an image using magickwand as toolkit. This allows different file
  formats.

  Image structure:

  [             0]
                    border
  [+IMG_BORDER_HEIGHT]
                    title
  [+  IMG_TEXT_HEIGHT]
                    space (only if count(displayed players) > 0)
  [+IMG_SPACER_HEIGHT]
                    player line (only if count(displayed players) > 0)
  [+  IMG_LINE_HEIGHT]
                    space
  [+IMG_SPACER_HEIGHT]
                    map
  [+   map_height]
                    border
  [+IMG_BORDER_HEIGHT]

****************************************************************************/
#ifdef HAVE_MAPIMG_MAGICKWAND
#define SET_COLOR(str, pcolor)                                              \
  fc_snprintf(str, sizeof(str), "rgb(%d,%d,%d)",                            \
              pcolor->r, pcolor->g, pcolor->b);
static bool img_save_magickwand(const struct img *pimg,
                                const char *mapimgfile)
{
  const struct rgbcolor *pcolor = NULL;
  struct player *pplr_now = NULL, *pplr_only = NULL;
  bool ret = TRUE;
  char imagefile[MAX_LEN_PATH];
  char str_color[32], comment[2048] = "", title[258];
  magickwand_size_t img_width, img_height, map_width, map_height;
  int x, y, xxx, yyy, row, i, mindex, plrwidth, plroffset, textoffset;
  bool withplr = BV_ISSET_ANY(pimg->def->player.checked_plrbv);

  if (!img_filename(mapimgfile, pimg->def->format, imagefile,
                    sizeof(imagefile))) {
    MAPIMG_LOG(_("error generating the file name"));
    return FALSE;
  }

  MagickWand *mw;
  PixelIterator *imw;
  PixelWand **pmw, *pw;
  DrawingWand *dw;

  MagickWandGenesis();

  mw = NewMagickWand();
  dw = NewDrawingWand();
  pw = NewPixelWand();

  map_width = pimg->imgsize.x * pimg->def->zoom;
  map_height = pimg->imgsize.y * pimg->def->zoom;

  img_width = map_width + 2 * IMG_BORDER_WIDTH;
  img_height = map_height + 2 * IMG_BORDER_HEIGHT + IMG_TEXT_HEIGHT
               + IMG_SPACER_HEIGHT + (withplr ? 2 * IMG_SPACER_HEIGHT : 0);

  fc_snprintf(title, sizeof(title), "%s (%s)", pimg->title, mapimgfile);

  SET_COLOR(str_color, imgcolor_special(IMGCOLOR_BACKGROUND));
  PixelSetColor(pw, str_color);
  MagickNewImage(mw, img_width, img_height, pw);

  textoffset = 0;
  if (withplr) {
    if (bvplayers_count(pimg->def) == 1) {
      /* only one player */
      for (i = 0; i < player_slot_count(); i++) {
        if (BV_ISSET(pimg->def->player.checked_plrbv, i)) {
          pplr_only = player_by_number(i);
          break;
        }
      }
    }

    if (pplr_only) {
      magickwand_size_t plr_color_square = IMG_TEXT_HEIGHT;

      textoffset += IMG_TEXT_HEIGHT + IMG_BORDER_HEIGHT;

      pcolor = imgcolor_player(player_index(pplr_only));
      SET_COLOR(str_color, pcolor);

      /* Show the color of the selected player. */
      imw = NewPixelRegionIterator(mw, IMG_BORDER_WIDTH, IMG_BORDER_HEIGHT,
                                   IMG_TEXT_HEIGHT, IMG_TEXT_HEIGHT);
      /* y coordinate */
      for (y = 0; y < IMG_TEXT_HEIGHT; y++) {
        pmw = PixelGetNextIteratorRow(imw, &plr_color_square);
        /* x coordinate */
        for (x = 0; x < IMG_TEXT_HEIGHT; x++) {
          PixelSetColor(pmw[x], str_color);
        }
        PixelSyncIterator(imw);
      }
      DestroyPixelIterator(imw);
    }

    /* Show a line displaying the colors of alive players */
    plrwidth = map_width / MIN(map_width, player_count());
    plroffset = (map_width - MIN(map_width, plrwidth * player_count())) / 2;

    imw = NewPixelRegionIterator(mw, IMG_BORDER_WIDTH,
                                 IMG_BORDER_HEIGHT + IMG_TEXT_HEIGHT
                                 + IMG_SPACER_HEIGHT, map_width,
                                 IMG_LINE_HEIGHT);
    /* y coordinate */
    for (y = 0; y < IMG_LINE_HEIGHT; y++) {
      pmw = PixelGetNextIteratorRow(imw, &map_width);

      /* x coordinate */
      for (x = plroffset; x < map_width; x++) {
        i = (x - plroffset) / plrwidth;
        pplr_now = player_by_number(i);

        if (i > player_count() || pplr_now == NULL || !pplr_now->is_alive) {
          continue;
        }

        if (BV_ISSET(pimg->def->player.checked_plrbv, i)) {
          /* The selected player is alive - display it. */
          pcolor = imgcolor_player(i);
          SET_COLOR(str_color, pcolor);
          PixelSetColor(pmw[x], str_color);
        } else if (pplr_only != NULL) {
          /* Display the state between pplr_only and pplr_now:
           *  - if allied:
           *      - show each second pixel
           *  - if pplr_now does shares map with pplr_onlyus:
           *      - show every other line of pixels
           * This results in the following patterns (# = color):
           *   ######      # # #       ######
           *                # # #       # # #
           *   ######      # # #       ######
           *                # # #       # # #
           *   shared      allied      shared vision
           *   vision                   + allied */
          if ((pplayers_allied(pplr_now, pplr_only) && (x + y) % 2 == 0)
              || (y % 2 == 0 && gives_shared_vision(pplr_now, pplr_only))) {
            pcolor = imgcolor_player(i);
            SET_COLOR(str_color, pcolor);
            PixelSetColor(pmw[x], str_color);
          }
        }
      }
      PixelSyncIterator(imw);
    }
    DestroyPixelIterator(imw);
  }

  /* Display the image name. */
  SET_COLOR(str_color, imgcolor_special(IMGCOLOR_TEXT));
  PixelSetColor(pw, str_color);
  DrawSetFillColor(dw, pw);
  DrawSetFont(dw, "Times-New-Roman");
  DrawSetFontSize(dw, IMG_TEXT_HEIGHT);
  DrawAnnotation(dw, IMG_BORDER_WIDTH + textoffset,
                 IMG_TEXT_HEIGHT + IMG_BORDER_HEIGHT,
                 (unsigned char *)title);
  MagickDrawImage(mw, dw);

  /* Display the map. */
  imw = NewPixelRegionIterator(mw, IMG_BORDER_WIDTH,
                               IMG_BORDER_HEIGHT + IMG_TEXT_HEIGHT
                               + IMG_SPACER_HEIGHT
                               + (withplr ? (IMG_LINE_HEIGHT + IMG_SPACER_HEIGHT)
                                          : 0), map_width, map_height);
  /* y coordinate */
  for (y = 0; y < pimg->imgsize.y; y++) {
    /* zoom for y */
    for (yyy = 0; yyy < pimg->def->zoom; yyy++) {

      pmw = PixelGetNextIteratorRow(imw, &map_width);

      /* x coordinate */
      for (x = 0; x < pimg->imgsize.x; x++) {
        mindex = img_index(x, y, pimg);
        pcolor = pimg->map[mindex];

        if (pcolor != NULL) {
          SET_COLOR(str_color, pcolor);

          /* zoom for x */
          for (xxx = 0; xxx < pimg->def->zoom; xxx++) {
            row = x * pimg->def->zoom + xxx;
            PixelSetColor(pmw[row], str_color);
          }
        }
      }
      PixelSyncIterator(imw);
    }
  }
  DestroyPixelIterator(imw);

  cat_snprintf(comment, sizeof(comment), "map definition: %s\n",
               pimg->def->maparg);
  if (BV_ISSET_ANY(pimg->def->player.checked_plrbv)) {
    players_iterate(pplayer) {
      if (!BV_ISSET(pimg->def->player.checked_plrbv, player_index(pplayer))) {
        continue;
      }

      pcolor = imgcolor_player(player_index(pplayer));
      cat_snprintf(comment, sizeof(comment), "%s\n", img_playerstr(pplayer));
    } players_iterate_end;
  }
  MagickCommentImage(mw, comment);

  if (!MagickWriteImage(mw, imagefile)) {
    MAPIMG_LOG(_("error saving map image '%s'"), imagefile);
    ret = FALSE;
  } else {
    log_verbose("Map image saved as '%s'.", imagefile);
  }

  DestroyDrawingWand(dw);
  DestroyPixelWand(pw);
  DestroyMagickWand(mw);

  MagickWandTerminus();

  return ret;
}
#undef SET_COLOR
#endif /* HAVE_MAPIMG_MAGICKWAND */

/****************************************************************************
  Save an image as ppm file (toolkit: ppm).
****************************************************************************/
static bool img_save_ppm(const struct img *pimg, const char *mapimgfile)
{
  char ppmname[MAX_LEN_PATH];
  FILE *fp;
  int x, y, xxx, yyy, mindex;
  const struct rgbcolor *pcolor;

  if (pimg->def->format != IMGFORMAT_PPM) {
    MAPIMG_LOG(_("the ppm toolkit can only create images in the ppm "
                 "format"));
    return FALSE;
  }

  if (!img_filename(mapimgfile, IMGFORMAT_PPM, ppmname, sizeof(ppmname))) {
    MAPIMG_LOG(_("error generating the file name"));
    return FALSE;
  }

  fp = fopen(ppmname, "w");
  if (!fp) {
    MAPIMG_LOG(_("could not open file: %s"), ppmname);
    return FALSE;
  }

  fprintf(fp, "P3\n");
  fprintf(fp, "# version:2\n");
  fprintf(fp, "# map definition: %s\n", pimg->def->maparg);

  if (pimg->def->colortest) {
    fprintf(fp, "# color test\n");
  } else if (BV_ISSET_ANY(pimg->def->player.checked_plrbv)) {
    players_iterate(pplayer) {
      if (!BV_ISSET(pimg->def->player.checked_plrbv, player_index(pplayer))) {
        continue;
      }

      pcolor = imgcolor_player(player_index(pplayer));
      fprintf(fp, "# %s\n", img_playerstr(pplayer));
    } players_iterate_end;
  } else {
    fprintf(fp, "# no players\n");
  }

  fprintf(fp, "%d %d\n", pimg->imgsize.x * pimg->def->zoom,
          pimg->imgsize.y * pimg->def->zoom);
  fprintf(fp, "255\n");

  /* y coordinate */
  for (y = 0; y < pimg->imgsize.y; y++) {
    /* zoom for y */
    for (yyy = 0; yyy < pimg->def->zoom; yyy++) {
      /* x coordinate */
      for (x = 0; x < pimg->imgsize.x; x++) {
        mindex = img_index(x, y, pimg);
        pcolor = pimg->map[mindex];

        /* zoom for x */
        for (xxx = 0; xxx < pimg->def->zoom; xxx++) {
          if (pcolor == NULL) {
            pcolor = imgcolor_special(IMGCOLOR_BACKGROUND);
          }
          fprintf(fp, "%d %d %d\n", pcolor->r, pcolor->g, pcolor->b);
        }
      }
    }
  }

  log_verbose("Map image saved as '%s'.", ppmname);
  fclose(fp);

  return TRUE;
}

/****************************************************************************
  Generate the final filename.
****************************************************************************/
static bool img_filename(const char *mapimgfile, enum imageformat format,
                         char *filename, size_t filename_len)
{
  fc_assert_ret_val(imageformat_is_valid(format) , FALSE);

  fc_snprintf(filename, filename_len, "%s.map.%s", mapimgfile,
              imageformat_name(format));

  return TRUE;
}

/****************************************************************************
  Return a definition string for the player.
****************************************************************************/
static const char *img_playerstr(const struct player *pplayer)
{
  static char buf[512];
  const struct rgbcolor *pcolor = imgcolor_player(player_index(pplayer));

  fc_snprintf(buf, sizeof(buf),
              "playerno:%d:color:(%3d, %3d, %3d):name:\"%s\"",
              player_number(pplayer), pcolor->r, pcolor->g, pcolor->b,
              player_name(pplayer));

  return buf;
}

/****************************************************************************
  Create the map considering the options (terrain, player(s), cities,
  units, borders, known, fogofwar, ...).
****************************************************************************/
static void img_createmap(struct img *pimg)
{
  const struct rgbcolor *pcolor;
  bv_pixel pixel;
  int player_id;
  struct player *pplayer = NULL;
  struct player *plr_tile = NULL, *plr_city = NULL, *plr_unit = NULL;
  enum known_type tile_knowledge = TILE_UNKNOWN;
  struct terrain *pterrain = NULL;
  bool plr_knowledge = pimg->def->layers[MAPIMG_LAYER_KNOWLEDGE];

  whole_map_iterate(ptile) {
    if (bvplayers_count(pimg->def) == 1) {
      /* only one player; get player id for 'known' and 'fogofwar' */
      players_iterate(aplayer) {
        if (BV_ISSET(pimg->def->player.checked_plrbv,
                     player_index(aplayer))) {
          pplayer = aplayer;
          tile_knowledge = mapimg.mapimg_tile_known(ptile, pplayer,
                                                    plr_knowledge);
          break;
        }
      } players_iterate_end;
    }

    /* known tiles */
    if (plr_knowledge && pplayer != NULL && tile_knowledge == TILE_UNKNOWN) {
      /* plot nothing iff tile is not known */
      continue;
    }

    /* terrain */
    pterrain = mapimg.mapimg_tile_terrain(ptile, pplayer, plr_knowledge);
    if (pimg->def->layers[MAPIMG_LAYER_TERRAIN]) {
      /* full terrain */
      pixel = pimg->pixel_tile(ptile, pplayer, plr_knowledge);
      pcolor = imgcolor_terrain(pterrain);
      img_plot_tile(pimg, ptile, pcolor, pixel);
    } else {
      /* basic terrain */
      pixel = pimg->pixel_tile(ptile, pplayer, plr_knowledge);
      if (is_ocean(pterrain)) {
        img_plot_tile(pimg, ptile, imgcolor_special(IMGCOLOR_OCEAN), pixel);
      } else {
        img_plot_tile(pimg, ptile, imgcolor_special(IMGCOLOR_GROUND), pixel);
      }
    }

    /* (land) area within borders and borders */
    plr_tile = mapimg.mapimg_tile_owner(ptile, pplayer, plr_knowledge);
    if (game.info.borders > 0 && NULL != plr_tile) {
      player_id = player_index(plr_tile);
      if (pimg->def->layers[MAPIMG_LAYER_AREA] && !is_ocean(pterrain)
          && BV_ISSET(pimg->def->player.checked_plrbv, player_id)) {
        /* the tile is land and inside the players borders */
        pixel = pimg->pixel_tile(ptile, pplayer, plr_knowledge);
        pcolor = imgcolor_player(player_id);
        img_plot_tile(pimg, ptile, pcolor, pixel);
      } else if (pimg->def->layers[MAPIMG_LAYER_BORDERS]
                 && (BV_ISSET(pimg->def->player.checked_plrbv, player_id)
                     || (plr_knowledge && pplayer != NULL))) {
        /* plot borders if player is selected or view range of the one
         * displayed player */
        pixel = pimg->pixel_border(ptile, pplayer, plr_knowledge);
        pcolor = imgcolor_player(player_id);
        img_plot_tile(pimg, ptile, pcolor, pixel);
      }
    }

    /* cities and units */
    plr_city = mapimg.mapimg_tile_city(ptile, pplayer, plr_knowledge);
    plr_unit = mapimg.mapimg_tile_unit(ptile, pplayer, plr_knowledge);
    if (pimg->def->layers[MAPIMG_LAYER_CITIES] && plr_city) {
      player_id = player_index(plr_city);
      if (BV_ISSET(pimg->def->player.checked_plrbv, player_id)
          || (plr_knowledge && pplayer != NULL)) {
        /* plot cities if player is selected or view range of the one
         * displayed player */
        pixel = pimg->pixel_city(ptile, pplayer, plr_knowledge);
        pcolor = imgcolor_player(player_id);
        img_plot_tile(pimg, ptile, pcolor, pixel);
      }
    } else if (pimg->def->layers[MAPIMG_LAYER_UNITS] && plr_unit) {
      player_id = player_index(plr_unit);
      if (BV_ISSET(pimg->def->player.checked_plrbv, player_id)
          || (plr_knowledge && pplayer != NULL)) {
        /* plot units if player is selected or view range of the one
         * displayed player */
        pixel = pimg->pixel_unit(ptile, pplayer, plr_knowledge);
        pcolor = imgcolor_player(player_id);
        img_plot_tile(pimg, ptile, pcolor, pixel);
      }
    }

    /* fogofwar; if only 1 player is plotted */
    if (game.info.fogofwar && pimg->def->layers[MAPIMG_LAYER_FOGOFWAR]
        && pplayer != NULL
        && tile_knowledge == TILE_KNOWN_UNSEEN) {
      pixel = pimg->pixel_fogofwar(ptile, pplayer, plr_knowledge);
      pcolor = NULL;
      img_plot_tile(pimg, ptile, pcolor, pixel);
    }
  } whole_map_iterate_end;
}

/*
 * ==============================================
 * topology (internal functions)
 * ==============================================
 * With these functions the pixels corresponding to the different elements
 * (tile, city, unit) for each map topology are defined.
 *
 * The bv_pixel_fogofwar_*() functions are special as they defines where
 * the color should be removed.
 *
 * The functions for a rectangular and an isometric rectangular topology
 * are identical.
 */

/****************************************************************************
   0  1  2  3  3  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
****************************************************************************/
static bv_pixel pixel_tile_rect(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge)
{
  bv_pixel pixel;

  BV_SET_ALL(pixel);

  return pixel;
}

/****************************************************************************
  -- -- -- -- -- --
  --  7  8  9 10 --
  -- 13 14 15 16 --
  -- 19 20 21 22 --
  -- 25 26 27 28 --
  -- -- -- -- -- --
****************************************************************************/
static bv_pixel pixel_city_rect(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge)
{
  bv_pixel pixel;

  BV_CLR_ALL(pixel);
  BV_SET(pixel, 7);
  BV_SET(pixel, 8);
  BV_SET(pixel, 9);
  BV_SET(pixel, 10);
  BV_SET(pixel, 13);
  BV_SET(pixel, 14);
  BV_SET(pixel, 15);
  BV_SET(pixel, 16);
  BV_SET(pixel, 19);
  BV_SET(pixel, 20);
  BV_SET(pixel, 21);
  BV_SET(pixel, 22);
  BV_SET(pixel, 21);
  BV_SET(pixel, 25);
  BV_SET(pixel, 26);
  BV_SET(pixel, 27);
  BV_SET(pixel, 28);

  return pixel;
}

/****************************************************************************
  -- -- -- -- -- --
  -- -- -- -- -- --
  -- -- 14 15 -- --
  -- -- 20 21 -- --
  -- -- -- -- -- --
  -- -- -- -- -- --
****************************************************************************/
static bv_pixel pixel_unit_rect(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge)
{
  bv_pixel pixel;

  BV_CLR_ALL(pixel);
  BV_SET(pixel, 14);
  BV_SET(pixel, 15);
  BV_SET(pixel, 20);
  BV_SET(pixel, 21);

  return pixel;
}

/****************************************************************************
   0 --  2 --  4 --
  --  7 --  9 -- 11
  12 -- 14 -- 16 --
  -- 19 -- 21 -- 23
  24 -- 26 -- 28 --
  -- 31 -- 33 -- 35
****************************************************************************/
static bv_pixel pixel_fogofwar_rect(const struct tile *ptile,
                                    const struct player *pplayer,
                                    bool knowledge)
{
  bv_pixel pixel;

  BV_CLR_ALL(pixel);

  BV_SET(pixel,  0);
  BV_SET(pixel,  2);
  BV_SET(pixel,  4);
  BV_SET(pixel,  7);
  BV_SET(pixel,  9);
  BV_SET(pixel, 11);
  BV_SET(pixel, 12);
  BV_SET(pixel, 14);
  BV_SET(pixel, 16);
  BV_SET(pixel, 19);
  BV_SET(pixel, 21);
  BV_SET(pixel, 23);
  BV_SET(pixel, 24);
  BV_SET(pixel, 26);
  BV_SET(pixel, 28);
  BV_SET(pixel, 31);
  BV_SET(pixel, 33);
  BV_SET(pixel, 35);

  return pixel;
}

/****************************************************************************
             [N]

       0  1  2  3  3  5
       6 -- -- -- -- 11
  [W] 12 -- -- -- -- 17 [E]
      18 -- -- -- -- 23
      24 -- -- -- -- 29
      30 31 32 33 34 35

             [S]
****************************************************************************/
static bv_pixel pixel_border_rect(const struct tile *ptile,
                                  const struct player *pplayer,
                                  bool knowledge)
{
  bv_pixel pixel;
  struct tile *pnext;
  struct player *owner;

  BV_CLR_ALL(pixel);

  fc_assert_ret_val(ptile != NULL, pixel);

  if (NULL == ptile) {
    /* no tile */
    return pixel;
  }

  owner = mapimg.mapimg_tile_owner(ptile, pplayer, knowledge);
  if (NULL == owner) {
    /* no border */
    return pixel;
  }

  pnext = mapstep(ptile, DIR8_NORTH);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 0);
    BV_SET(pixel, 1);
    BV_SET(pixel, 2);
    BV_SET(pixel, 3);
    BV_SET(pixel, 4);
    BV_SET(pixel, 5);
  }

  pnext = mapstep(ptile, DIR8_EAST);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 5);
    BV_SET(pixel, 11);
    BV_SET(pixel, 17);
    BV_SET(pixel, 23);
    BV_SET(pixel, 29);
    BV_SET(pixel, 35);
  }

  pnext = mapstep(ptile, DIR8_SOUTH);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 30);
    BV_SET(pixel, 31);
    BV_SET(pixel, 32);
    BV_SET(pixel, 33);
    BV_SET(pixel, 34);
    BV_SET(pixel, 35);
  }

  pnext = mapstep(ptile, DIR8_WEST);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 0);
    BV_SET(pixel, 6);
    BV_SET(pixel, 12);
    BV_SET(pixel, 18);
    BV_SET(pixel, 24);
    BV_SET(pixel, 30);
  }

  return pixel;
}

/****************************************************************************
  Base coordinates for the tiles on a (isometric) rectange topology,
****************************************************************************/
static void base_coor_rect(struct img *pimg, int *base_x, int *base_y,
                           int x, int y)
{
  *base_x = x * TILE_SIZE;
  *base_y = y * TILE_SIZE;
}

/****************************************************************************
         0  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
****************************************************************************/
static bv_pixel pixel_tile_hexa(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge)
{
  bv_pixel pixel;

  BV_SET_ALL(pixel);

  return pixel;
}

/****************************************************************************
        -- --
     --  3  4 --
  --  7  8  9 10 --
  -- 13 14 15 16 --
  -- 19 20 21 22 --
  -- 25 26 27 28 --
     -- 31 32 --
        -- --
****************************************************************************/
static bv_pixel pixel_city_hexa(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge)
{
  bv_pixel pixel;

  BV_CLR_ALL(pixel);
  BV_SET(pixel, 3);
  BV_SET(pixel, 4);
  BV_SET(pixel, 7);
  BV_SET(pixel, 8);
  BV_SET(pixel, 9);
  BV_SET(pixel, 10);
  BV_SET(pixel, 13);
  BV_SET(pixel, 14);
  BV_SET(pixel, 15);
  BV_SET(pixel, 16);
  BV_SET(pixel, 19);
  BV_SET(pixel, 20);
  BV_SET(pixel, 21);
  BV_SET(pixel, 22);
  BV_SET(pixel, 25);
  BV_SET(pixel, 26);
  BV_SET(pixel, 27);
  BV_SET(pixel, 28);
  BV_SET(pixel, 31);
  BV_SET(pixel, 32);

  return pixel;
}

/****************************************************************************
        -- --
     -- -- -- --
  -- -- -- -- -- --
  -- -- 14 15 -- --
  -- -- 20 21 -- --
  -- -- -- -- -- --
     -- -- -- --
        -- --
****************************************************************************/
static bv_pixel pixel_unit_hexa(const struct tile *ptile,
                                const struct player *pplayer,
                                bool knowledge)
{
  bv_pixel pixel;

  BV_CLR_ALL(pixel);
  BV_SET(pixel, 14);
  BV_SET(pixel, 15);
  BV_SET(pixel, 20);
  BV_SET(pixel, 21);

  return pixel;
}

/****************************************************************************
         0 --
     --  3 --  5
  --  7 --  9 -- 11
  -- 13 -- 15 -- 17
  18 -- 20 -- 22 --
  24 -- 26 -- 28 --
     30 -- 32 --
        -- 35
****************************************************************************/
static bv_pixel pixel_fogofwar_hexa(const struct tile *ptile,
                                    const struct player *pplayer,
                                    bool knowledge)
{
  bv_pixel pixel;

  BV_CLR_ALL(pixel);
  BV_SET(pixel,  0);
  BV_SET(pixel,  3);
  BV_SET(pixel,  5);
  BV_SET(pixel,  7);
  BV_SET(pixel,  9);
  BV_SET(pixel, 11);
  BV_SET(pixel, 13);
  BV_SET(pixel, 15);
  BV_SET(pixel, 17);
  BV_SET(pixel, 18);
  BV_SET(pixel, 20);
  BV_SET(pixel, 22);
  BV_SET(pixel, 24);
  BV_SET(pixel, 26);
  BV_SET(pixel, 28);
  BV_SET(pixel, 30);
  BV_SET(pixel, 32);
  BV_SET(pixel, 35);

  return pixel;
}

/****************************************************************************
   [W]        0  1       [N]
           2 -- --  5
        6 -- -- -- -- 11
  [SW] 12 -- -- -- -- 17 [NE]
       18 -- -- -- -- 23
       24 -- -- -- -- 29
          30 -- -- 33
   [S]       34 35       [E]
****************************************************************************/
static bv_pixel pixel_border_hexa(const struct tile *ptile,
                                  const struct player *pplayer,
                                  bool knowledge)
{
  bv_pixel pixel;
  struct tile *pnext;
  struct player *owner;

  BV_CLR_ALL(pixel);

  fc_assert_ret_val(ptile != NULL, pixel);

  if (NULL == ptile) {
    /* no tile */
    return pixel;
  }

  owner = mapimg.mapimg_tile_owner(ptile, pplayer, knowledge);
  if (NULL == owner) {
    /* no border */
    return pixel;
  }

  pnext = mapstep(ptile, DIR8_WEST);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 0);
    BV_SET(pixel, 2);
    BV_SET(pixel, 6);
  }

  /* not used: DIR8_NORTHWEST */

  pnext = mapstep(ptile, DIR8_NORTH);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 1);
    BV_SET(pixel, 5);
    BV_SET(pixel, 11);
  }

  pnext = mapstep(ptile, DIR8_NORTHEAST);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 11);
    BV_SET(pixel, 17);
    BV_SET(pixel, 23);
    BV_SET(pixel, 29);
  }

  pnext = mapstep(ptile, DIR8_EAST);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 29);
    BV_SET(pixel, 33);
    BV_SET(pixel, 35);
  }

  /* not used. DIR8_SOUTHEAST */

  pnext = mapstep(ptile, DIR8_SOUTH);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 24);
    BV_SET(pixel, 30);
    BV_SET(pixel, 34);
  }

  pnext = mapstep(ptile, DIR8_SOUTHWEST);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 6);
    BV_SET(pixel, 12);
    BV_SET(pixel, 18);
    BV_SET(pixel, 24);
  }

  return pixel;
}

/****************************************************************************
  Base coordinates for the tiles on a hexa topology,
****************************************************************************/
static void base_coor_hexa(struct img *pimg, int *base_x, int *base_y,
                           int x, int y)
{
  int nat_x, nat_y;
  MAP_TO_NATIVE_POS(&nat_x, &nat_y, x, y);

  *base_x = nat_x * TILE_SIZE + ((nat_y % 2) ? TILE_SIZE / 2 : 0);
  *base_y = nat_y * TILE_SIZE;
}

/****************************************************************************
         0  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
****************************************************************************/
static bv_pixel pixel_tile_isohexa(const struct tile *ptile,
                                   const struct player *pplayer,
                                   bool knowledge)
{
  bv_pixel pixel;

  BV_SET_ALL(pixel);

  return pixel;
}

/****************************************************************************
        -- -- -- --
     --  5  6  7  8 --
  -- 11 12 13 14 15 16 --
  -- 19 20 21 22 23 24 --
     -- 27 28 29 30 --
        -- -- -- --
****************************************************************************/
static bv_pixel pixel_city_isohexa(const struct tile *ptile,
                                   const struct player *pplayer,
                                   bool knowledge)
{
  bv_pixel pixel;

  BV_CLR_ALL(pixel);
  BV_SET(pixel, 5);
  BV_SET(pixel, 6);
  BV_SET(pixel, 7);
  BV_SET(pixel, 8);
  BV_SET(pixel, 11);
  BV_SET(pixel, 12);
  BV_SET(pixel, 13);
  BV_SET(pixel, 14);
  BV_SET(pixel, 15);
  BV_SET(pixel, 16);
  BV_SET(pixel, 19);
  BV_SET(pixel, 20);
  BV_SET(pixel, 21);
  BV_SET(pixel, 22);
  BV_SET(pixel, 23);
  BV_SET(pixel, 24);
  BV_SET(pixel, 27);
  BV_SET(pixel, 28);
  BV_SET(pixel, 29);
  BV_SET(pixel, 30);

  return pixel;
}

/****************************************************************************
        -- -- -- --
     -- -- -- -- -- --
  -- -- -- 13 14 -- -- --
  -- -- -- 21 22 -- -- --
     -- -- -- -- -- --
        -- -- -- --
****************************************************************************/
static bv_pixel pixel_unit_isohexa(const struct tile *ptile,
                                   const struct player *pplayer,
                                   bool knowledge)
{
  bv_pixel pixel;

  BV_CLR_ALL(pixel);
  BV_SET(pixel, 13);
  BV_SET(pixel, 14);
  BV_SET(pixel, 21);
  BV_SET(pixel, 22);

  return pixel;
}

/****************************************************************************
         0  1 -- --
      4 -- --  7  8 --
  -- -- 12 13 -- -- 16 17
  18 19 -- -- 22 23 -- --
     -- 27 28 -- -- 31
        -- -- 34 35
****************************************************************************/
static bv_pixel pixel_fogofwar_isohexa(const struct tile *ptile,
                                       const struct player *pplayer,
                                       bool knowledge)
{
  bv_pixel pixel;

  BV_CLR_ALL(pixel);
  BV_SET(pixel,  0);
  BV_SET(pixel,  1);
  BV_SET(pixel,  4);
  BV_SET(pixel,  7);
  BV_SET(pixel,  8);
  BV_SET(pixel, 12);
  BV_SET(pixel, 13);
  BV_SET(pixel, 16);
  BV_SET(pixel, 17);
  BV_SET(pixel, 18);
  BV_SET(pixel, 19);
  BV_SET(pixel, 22);
  BV_SET(pixel, 23);
  BV_SET(pixel, 27);
  BV_SET(pixel, 28);
  BV_SET(pixel, 31);
  BV_SET(pixel, 34);
  BV_SET(pixel, 35);

  return pixel;
}

/****************************************************************************

               [N]

  [NW]       0  1  2  3      [E]
          4 -- -- -- --  9
      10 -- -- -- -- -- -- 17
      18 -- -- -- -- -- -- 25
         26 -- -- -- -- 31
  [W]       32 33 34 35      [SE]

               [S]
****************************************************************************/
static bv_pixel pixel_border_isohexa(const struct tile *ptile,
                                     const struct player *pplayer,
                                     bool knowledge)
{
  bv_pixel pixel;
  struct tile *pnext;
  struct player *owner;

  BV_CLR_ALL(pixel);

  fc_assert_ret_val(ptile != NULL, pixel);

  if (NULL == ptile) {
    /* no tile */
    return pixel;
  }

  owner = mapimg.mapimg_tile_owner(ptile, pplayer, knowledge);
  if (NULL == owner) {
    /* no border */
    return pixel;
  }

  pnext = mapstep(ptile, DIR8_NORTH);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 0);
    BV_SET(pixel, 1);
    BV_SET(pixel, 2);
    BV_SET(pixel, 3);
  }

  /* not used: DIR8_NORTHEAST */

  pnext = mapstep(ptile, DIR8_EAST);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 3);
    BV_SET(pixel, 9);
    BV_SET(pixel, 17);
  }

  pnext = mapstep(ptile, DIR8_SOUTHEAST);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 25);
    BV_SET(pixel, 31);
    BV_SET(pixel, 35);
  }

  pnext = mapstep(ptile, DIR8_SOUTH);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 32);
    BV_SET(pixel, 33);
    BV_SET(pixel, 34);
    BV_SET(pixel, 35);
  }

  /* not used: DIR8_SOUTHWEST */

  pnext = mapstep(ptile, DIR8_WEST);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 18);
    BV_SET(pixel, 26);
    BV_SET(pixel, 32);
  }

  pnext = mapstep(ptile, DIR8_NORTHWEST);
  if (!pnext || (mapimg.mapimg_tile_known(pnext, pplayer,
                                          knowledge) != TILE_UNKNOWN
                 && mapimg.mapimg_tile_owner(pnext, pplayer,
                                             knowledge) != owner)) {
    BV_SET(pixel, 0);
    BV_SET(pixel, 4);
    BV_SET(pixel, 10);
  }

  return pixel;
}

/****************************************************************************
  Base coordinates for the tiles on a isometric hexa topology,
****************************************************************************/
static void base_coor_isohexa(struct img *pimg, int *base_x, int *base_y,
                              int x, int y)
{
  /* magic for iso-hexa */
  y -= x / 2;
  y += (pimg->mapsize.x - 1)/2;

  *base_x = x * TILE_SIZE;
  *base_y = y * TILE_SIZE + ((x % 2) ? 0 : TILE_SIZE / 2);
}

/*
 * ==============================================
 * additional functions (internal functions)
 * ==============================================
 */

/****************************************************************************
  Convert the player bitvector to a string.
****************************************************************************/
static const char *bvplayers_str(const bv_player plrbv)
{
  static char buf[MAX_NUM_PLAYER_SLOTS + 1];
  int i;

  /* Don't print lots of unnecessary trailing zeroes */
  for (i = MAX_NUM_PLAYER_SLOTS-1; i >= 0; i--) {
    if (BV_ISSET(plrbv, i) || player_by_number(i)) {
      buf[i+1] = '\0';
      break;
    }
  }

  for (; i >= 0; i--) {
    buf[i] = BV_ISSET(plrbv, i) ? '1' : '0';
  }

  return buf;
}

/****************************************************************************
  Return the number of players defined in a map image definition.
****************************************************************************/
static int bvplayers_count(const struct mapdef *pmapdef)
{
  int i, count = 0;

  switch (pmapdef->player.show) {
  case SHOW_NONE:    /* no player on the map */
    count = 0;
    break;
  case SHOW_HUMAN:   /* one map for each human player */
  case SHOW_EACH:    /* one map for each player */
  case SHOW_PLRNAME: /* the map of one selected player */
  case SHOW_PLRID:
    count = 1;
    break;
  case SHOW_PLRBV:   /* map showing only players given by a bitvector */
    count = 0;
    for (i = 0; i < MAX_NUM_PLAYER_SLOTS; i++) {
      if (BV_ISSET(pmapdef->player.plrbv, i)) {
        count++;
      }
    }
    break;
  case SHOW_ALL:     /* show all players in one map */
    count = player_count();
    break;
  }

  return count;
}

/*
 * ==============================================
 * image colors (internal functions)
 * ==============================================
 */

/****************************************************************************
  Return rgbcolor for img_special
****************************************************************************/
static const struct rgbcolor *imgcolor_special(enum img_special imgcolor)
{
  static struct rgbcolor rgb_special[] = {
    { 255,   0,   0, NULL}, /* IMGCOLOR_ERROR */
    /* FIXME: 'ocean' and 'ground' colors are also used in the overview; the
     *        values are defined in colors.tilespec. */
    {   0,   0, 200, NULL}, /* IMGCOLOR_OCEAN */
    {   0, 200,   0, NULL}, /* IMGCOLOR_GROUND */
    {   0,   0,   0, NULL}, /* IMGCOLOR_BACKGROUND */
    { 255, 255, 255, NULL}, /* IMGCOLOR_TEXT */
  };

  fc_assert_ret_val(imgcolor >= 0 && imgcolor < ARRAY_SIZE(rgb_special),
                    &rgb_special[0]);

  return &rgb_special[imgcolor];
}

/****************************************************************************
  Return rgbcolor for player.

  FIXME: nearly identical with get_player_color() in colors_common.c.
****************************************************************************/
static const struct rgbcolor *imgcolor_player(int plr_id)
{
  struct player *pplayer = player_by_number(plr_id);

  fc_assert_ret_val(pplayer != NULL, imgcolor_special(IMGCOLOR_ERROR));
  fc_assert_ret_val(pplayer->rgb != NULL,
                    imgcolor_special(IMGCOLOR_ERROR));

  return pplayer->rgb;
}

/****************************************************************************
  Return rgbcolor for terrain.

  FIXME: nearly identical with get_terrain_color() in colors_common.c.
****************************************************************************/
static const struct rgbcolor
  *imgcolor_terrain(const struct terrain *pterrain)
{
  fc_assert_ret_val(pterrain != NULL, imgcolor_special(IMGCOLOR_ERROR));
  fc_assert_ret_val(pterrain->rgb != NULL, imgcolor_special(IMGCOLOR_ERROR));

  return pterrain->rgb;
}